diff --git a/chips/yosys/frontends/blif/blifparse.h b/chips/yosys/frontends/blif/blifparse.h new file mode 100644 index 0000000000000000000000000000000000000000..534ab98ebde7d6287cbda1315b7a281b01f35017 --- /dev/null +++ b/chips/yosys/frontends/blif/blifparse.h @@ -0,0 +1,32 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#ifndef ABC_BLIFPARSE +#define ABC_BLIFPARSE + +#include "kernel/yosys.h" + +YOSYS_NAMESPACE_BEGIN + +extern void parse_blif(RTLIL::Design *design, std::istream &f, IdString dff_name, int autoidx_base, + bool run_clean = false, bool sop_mode = false, bool wideports = false); + +YOSYS_NAMESPACE_END + +#endif diff --git a/chips/yosys/frontends/json/CMakeLists.txt b/chips/yosys/frontends/json/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..9d3beb60be907ffa02e9308427168be450ae7299 --- /dev/null +++ b/chips/yosys/frontends/json/CMakeLists.txt @@ -0,0 +1,3 @@ +yosys_frontend(json + jsonparse.cc +) diff --git a/chips/yosys/frontends/json/jsonparse.cc b/chips/yosys/frontends/json/jsonparse.cc new file mode 100644 index 0000000000000000000000000000000000000000..40e52d272241b13e3a460a2c2f6837e94aac5bd3 --- /dev/null +++ b/chips/yosys/frontends/json/jsonparse.cc @@ -0,0 +1,675 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" + +YOSYS_NAMESPACE_BEGIN + +struct JsonNode +{ + char type; // S=String, N=Number, A=Array, D=Dict + string data_string; + int64_t data_number; + vector data_array; + dict data_dict; + vector data_dict_keys; + + JsonNode(std::istream &f) + { + type = 0; + data_number = 0; + + while (1) + { + int ch = f.get(); + + if (ch == EOF) + log_error("Unexpected EOF in JSON file.\n"); + + if (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n') + continue; + + if (ch == '"') + { + type = 'S'; + + while (1) + { + ch = f.get(); + + if (ch == EOF) + log_error("Unexpected EOF in JSON string.\n"); + + if (ch == '"') + break; + + if (ch == '\\') { + ch = f.get(); + + switch (ch) { + case EOF: log_error("Unexpected EOF in JSON string.\n"); break; + case '"': + case '/': + case '\\': break; + case 'b': ch = '\b'; break; + case 'f': ch = '\f'; break; + case 'n': ch = '\n'; break; + case 'r': ch = '\r'; break; + case 't': ch = '\t'; break; + case 'u': + int val = 0; + for (int i = 0; i < 4; i++) { + ch = f.get(); + val <<= 4; + if (ch >= '0' && '9' >= ch) { + val += ch - '0'; + } else if (ch >= 'A' && 'F' >= ch) { + val += 10 + ch - 'A'; + } else if (ch >= 'a' && 'f' >= ch) { + val += 10 + ch - 'a'; + } else + log_error("Unexpected non-digit character in \\uXXXX sequence: %c.\n", ch); + } + if (val < 128) + ch = val; + else + log_error("Unsupported \\uXXXX sequence in JSON string: %04X.\n", val); + break; + } + } + + data_string += ch; + } + + break; + } + + if (('0' <= ch && ch <= '9') || ch == '-') + { + bool negative = false; + type = 'N'; + if (ch == '-') { + data_number = 0; + negative = true; + } else { + data_number = ch - '0'; + } + + data_string += ch; + + while (1) + { + ch = f.get(); + + if (ch == EOF) + break; + + if (ch == '.') + goto parse_real; + + if (ch < '0' || '9' < ch) { + f.unget(); + break; + } + + data_number = data_number*10 + (ch - '0'); + data_string += ch; + } + + data_number = negative ? -data_number : data_number; + data_string = ""; + break; + + parse_real: + type = 'S'; + data_number = 0; + data_string += ch; + + while (1) + { + ch = f.get(); + + if (ch == EOF) + break; + + if (ch < '0' || '9' < ch) { + f.unget(); + break; + } + + data_string += ch; + } + + break; + } + + if (ch == '[') + { + type = 'A'; + + while (1) + { + ch = f.get(); + + if (ch == EOF) + log_error("Unexpected EOF in JSON file.\n"); + + if (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' || ch == ',') + continue; + + if (ch == ']') + break; + + f.unget(); + data_array.push_back(new JsonNode(f)); + } + + break; + } + + if (ch == '{') + { + type = 'D'; + + while (1) + { + ch = f.get(); + + if (ch == EOF) + log_error("Unexpected EOF in JSON file.\n"); + + if (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' || ch == ',') + continue; + + if (ch == '}') + break; + + f.unget(); + JsonNode key(f); + + while (1) + { + ch = f.get(); + + if (ch == EOF) + log_error("Unexpected EOF in JSON file.\n"); + + if (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' || ch == ':') + continue; + + f.unget(); + break; + } + + JsonNode *value = new JsonNode(f); + + if (key.type != 'S') + log_error("Unexpected non-string key in JSON dict.\n"); + + data_dict[key.data_string] = value; + data_dict_keys.push_back(key.data_string); + } + + break; + } + + log_error("Unexpected character in JSON file: '%c'\n", ch); + } + } + + ~JsonNode() + { + for (auto it : data_array) + delete it; + for (auto &it : data_dict) + delete it.second; + } +}; + +Const json_parse_attr_param_value(JsonNode *node) +{ + Const value; + + if (node->type == 'S') { + string &s = node->data_string; + size_t cursor = s.find_first_not_of("01xz"); + if (cursor == string::npos) { + value = Const::from_string(s); + } else if (s.find_first_not_of(' ', cursor) == string::npos) { + value = Const(s.substr(0, GetSize(s)-1)); + } else { + value = Const(s); + } + } else + if (node->type == 'N') { + value = Const(node->data_number); + if (node->data_number < 0) + value.flags |= RTLIL::CONST_FLAG_SIGNED; + } else + if (node->type == 'A') { + log_error("JSON attribute or parameter value is an array.\n"); + } else + if (node->type == 'D') { + log_error("JSON attribute or parameter value is a dict.\n"); + } else { + log_abort(); + } + + return value; +} + +void json_parse_attr_param(RTLIL::Design *design, dict &results, JsonNode *node) +{ + if (node->type != 'D') + log_error("JSON attributes or parameters node is not a dictionary.\n"); + + for (auto it : node->data_dict) + { + IdString key = design->twines().add(RTLIL::escape_id(it.first.c_str())); + Const value = json_parse_attr_param_value(it.second); + results[key] = value; + } +} + +void json_import(Design *design, string &modname, JsonNode *node) +{ + log("Importing module %s from JSON tree.\n", modname); + + Module *module = new RTLIL::Module(design); + module->name = design->twines().add(RTLIL::escape_id(modname)); + + if (design->module(module->name)) + log_error("Re-definition of module %s.\n", module); + + design->add(module); + + if (node->data_dict.count("attributes")) + json_parse_attr_param(design, module->attributes, node->data_dict.at("attributes")); + + if (node->data_dict.count("parameter_default_values")) + json_parse_attr_param(design, module->parameter_default_values, node->data_dict.at("parameter_default_values")); + + dict signal_bits; + + if (node->data_dict.count("ports")) + { + JsonNode *ports_node = node->data_dict.at("ports"); + + if (ports_node->type != 'D') + log_error("JSON ports node is not a dictionary.\n"); + + for (int port_id = 1; port_id <= GetSize(ports_node->data_dict_keys); port_id++) + { + IdString port_ref = design->twines().add(RTLIL::escape_id(ports_node->data_dict_keys[port_id-1])); + JsonNode *port_node = ports_node->data_dict.at(ports_node->data_dict_keys[port_id-1]); + + if (port_node->type != 'D') + log_error("JSON port node '%s' is not a dictionary.\n", PooledName(design, port_ref).unescape()); + + if (port_node->data_dict.count("direction") == 0) + log_error("JSON port node '%s' has no direction attribute.\n", PooledName(design, port_ref).unescape()); + + if (port_node->data_dict.count("bits") == 0) + log_error("JSON port node '%s' has no bits attribute.\n", PooledName(design, port_ref).unescape()); + + JsonNode *port_direction_node = port_node->data_dict.at("direction"); + JsonNode *port_bits_node = port_node->data_dict.at("bits"); + + if (port_direction_node->type != 'S') + log_error("JSON port node '%s' has non-string direction attribute.\n", PooledName(design, port_ref).unescape()); + + if (port_bits_node->type != 'A') + log_error("JSON port node '%s' has non-array bits attribute.\n", PooledName(design, port_ref).unescape()); + + Wire *port_wire = module->wire(port_ref); + + if (port_wire == nullptr) + port_wire = module->addWire(port_ref, GetSize(port_bits_node->data_array)); + + if (port_node->data_dict.count("upto") != 0) { + JsonNode *val = port_node->data_dict.at("upto"); + if (val->type == 'N') + port_wire->upto = val->data_number != 0; + } + + if (port_node->data_dict.count("signed") != 0) { + JsonNode *val = port_node->data_dict.at("signed"); + if (val->type == 'N') + port_wire->is_signed = val->data_number != 0; + } + + if (port_node->data_dict.count("offset") != 0) { + JsonNode *val = port_node->data_dict.at("offset"); + if (val->type == 'N') + port_wire->start_offset = val->data_number; + } + + if (port_direction_node->data_string == "input") { + port_wire->port_input = true; + } else + if (port_direction_node->data_string == "output") { + port_wire->port_output = true; + } else + if (port_direction_node->data_string == "inout") { + port_wire->port_input = true; + port_wire->port_output = true; + } else + log_error("JSON port node '%s' has invalid '%s' direction attribute.\n", PooledName(design, port_ref).unescape(), port_direction_node->data_string); + + port_wire->port_id = port_id; + + for (int i = 0; i < GetSize(port_bits_node->data_array); i++) + { + JsonNode *bitval_node = port_bits_node->data_array.at(i); + SigBit sigbit(port_wire, i); + + if (bitval_node->type == 'S') { + if (bitval_node->data_string == "0") + module->connect(sigbit, State::S0); + else if (bitval_node->data_string == "1") + module->connect(sigbit, State::S1); + else if (bitval_node->data_string == "x") + module->connect(sigbit, State::Sx); + else if (bitval_node->data_string == "z") + module->connect(sigbit, State::Sz); + else + log_error("JSON port node '%s' has invalid '%s' bit string value on bit %d.\n", + PooledName(design, port_ref).unescape(), bitval_node->data_string, i); + } else + if (bitval_node->type == 'N') { + int bitidx = bitval_node->data_number; + if (signal_bits.count(bitidx)) { + if (port_wire->port_output) { + module->connect(sigbit, signal_bits.at(bitidx)); + } else { + module->connect(signal_bits.at(bitidx), sigbit); + signal_bits[bitidx] = sigbit; + } + } else { + signal_bits[bitidx] = sigbit; + } + } else + log_error("JSON port node '%s' has invalid bit value on bit %d.\n", PooledName(design, port_ref).unescape(), i); + } + } + + module->fixup_ports(); + } + + if (node->data_dict.count("netnames")) + { + JsonNode *netnames_node = node->data_dict.at("netnames"); + + if (netnames_node->type != 'D') + log_error("JSON netnames node is not a dictionary.\n"); + + for (auto &net : netnames_node->data_dict) + { + IdString net_ref = design->twines().add(RTLIL::escape_id(net.first)); + JsonNode *net_node = net.second; + + if (net_node->type != 'D') + log_error("JSON netname node '%s' is not a dictionary.\n", PooledName(design, net_ref).unescape()); + + if (net_node->data_dict.count("bits") == 0) + log_error("JSON netname node '%s' has no bits attribute.\n", PooledName(design, net_ref).unescape()); + + JsonNode *bits_node = net_node->data_dict.at("bits"); + + if (bits_node->type != 'A') + log_error("JSON netname node '%s' has non-array bits attribute.\n", PooledName(design, net_ref).unescape()); + + Wire *wire = module->wire(net_ref); + + if (wire == nullptr) + wire = module->addWire(net_ref, GetSize(bits_node->data_array)); + + if (net_node->data_dict.count("upto") != 0) { + JsonNode *val = net_node->data_dict.at("upto"); + if (val->type == 'N') + wire->upto = val->data_number != 0; + } + + if (net_node->data_dict.count("offset") != 0) { + JsonNode *val = net_node->data_dict.at("offset"); + if (val->type == 'N') + wire->start_offset = val->data_number; + } + + if (net_node->data_dict.count("signed") != 0) { + JsonNode *val = net_node->data_dict.at("signed"); + if (val->type == 'N') + wire->is_signed = val->data_number != 0; + } + + for (int i = 0; i < GetSize(bits_node->data_array); i++) + { + JsonNode *bitval_node = bits_node->data_array.at(i); + SigBit sigbit(wire, i); + + if (bitval_node->type == 'S') { + if (bitval_node->data_string == "0") + module->connect(sigbit, State::S0); + else if (bitval_node->data_string == "1") + module->connect(sigbit, State::S1); + else if (bitval_node->data_string == "x") + module->connect(sigbit, State::Sx); + else if (bitval_node->data_string == "z") + module->connect(sigbit, State::Sz); + else + log_error("JSON netname node '%s' has invalid '%s' bit string value on bit %d.\n", + PooledName(design, net_ref).unescape(), bitval_node->data_string, i); + } else + if (bitval_node->type == 'N') { + int bitidx = bitval_node->data_number; + if (signal_bits.count(bitidx)) { + if (sigbit != signal_bits.at(bitidx)) + module->connect(sigbit, signal_bits.at(bitidx)); + } else { + signal_bits[bitidx] = sigbit; + } + } else + log_error("JSON netname node '%s' has invalid bit value on bit %d.\n", PooledName(design, net_ref).unescape(), i); + } + + if (net_node->data_dict.count("attributes")) + json_parse_attr_param(design, wire->attributes, net_node->data_dict.at("attributes")); + } + } + + if (node->data_dict.count("cells")) + { + JsonNode *cells_node = node->data_dict.at("cells"); + + if (cells_node->type != 'D') + log_error("JSON cells node is not a dictionary.\n"); + + for (auto &cell_node_it : cells_node->data_dict) + { + IdString cell_ref = design->twines().add(RTLIL::escape_id(cell_node_it.first)); + JsonNode *cell_node = cell_node_it.second; + + if (cell_node->type != 'D') + log_error("JSON cells node '%s' is not a dictionary.\n", PooledName(design, cell_ref).unescape()); + + if (cell_node->data_dict.count("type") == 0) + log_error("JSON cells node '%s' has no type attribute.\n", PooledName(design, cell_ref).unescape()); + + JsonNode *type_node = cell_node->data_dict.at("type"); + + if (type_node->type != 'S') + log_error("JSON cells node '%s' has a non-string type.\n", PooledName(design, cell_ref).unescape()); + + IdString cell_type = design->twines().add(RTLIL::escape_id(type_node->data_string)); + + Cell *cell = module->addCell(cell_ref, cell_type); + + if (cell_node->data_dict.count("connections") == 0) + log_error("JSON cells node '%s' has no connections attribute.\n", PooledName(design, cell_ref).unescape()); + + JsonNode *connections_node = cell_node->data_dict.at("connections"); + + if (connections_node->type != 'D') + log_error("JSON cells node '%s' has non-dictionary connections attribute.\n", PooledName(design, cell_ref).unescape()); + + for (auto &conn_it : connections_node->data_dict) + { + IdString conn_ref = design->twines().add(RTLIL::escape_id(conn_it.first)); + JsonNode *conn_node = conn_it.second; + + if (conn_node->type != 'A') + log_error("JSON cells node '%s' connection '%s' is not an array.\n", PooledName(design, cell_ref).unescape(), PooledName(design, conn_ref).unescape()); + + SigSpec sig; + + for (int i = 0; i < GetSize(conn_node->data_array); i++) + { + JsonNode *bitval_node = conn_node->data_array.at(i); + + if (bitval_node->type == 'S') { + if (bitval_node->data_string == "0") + sig.append(State::S0); + else if (bitval_node->data_string == "1") + sig.append(State::S1); + else if (bitval_node->data_string == "x") + sig.append(State::Sx); + else if (bitval_node->data_string == "z") + sig.append(State::Sz); + else + log_error("JSON cells node '%s' connection '%s' has invalid '%s' bit string value on bit %d.\n", + PooledName(design, cell_ref).unescape(), PooledName(design, conn_ref).unescape(), bitval_node->data_string, i); + } else + if (bitval_node->type == 'N') { + int bitidx = bitval_node->data_number; + if (signal_bits.count(bitidx) == 0) + signal_bits[bitidx] = module->addWire(NEW_ID); + sig.append(signal_bits.at(bitidx)); + } else + log_error("JSON cells node '%s' connection '%s' has invalid bit value on bit %d.\n", + PooledName(design, cell_ref).unescape(), PooledName(design, conn_ref).unescape(), i); + + } + + cell->setPort(conn_ref, sig); + } + + if (cell_node->data_dict.count("attributes")) + json_parse_attr_param(design, cell->attributes, cell_node->data_dict.at("attributes")); + + if (cell_node->data_dict.count("parameters")) + json_parse_attr_param(design, cell->parameters, cell_node->data_dict.at("parameters")); + } + } + + if (node->data_dict.count("memories")) + { + JsonNode *memories_node = node->data_dict.at("memories"); + + if (memories_node->type != 'D') + log_error("JSON memories node is not a dictionary.\n"); + + for (auto &memory_node_it : memories_node->data_dict) + { + JsonNode *memory_node = memory_node_it.second; + + RTLIL::Memory *mem = new RTLIL::Memory(module); + mem->name = design->twines().add(RTLIL::escape_id(memory_node_it.first)); + + if (memory_node->type != 'D') + log_error("JSON memory node '%s' is not a dictionary.\n", mem); + + if (memory_node->data_dict.count("width") == 0) + log_error("JSON memory node '%s' has no width attribute.\n", mem); + JsonNode *width_node = memory_node->data_dict.at("width"); + if (width_node->type != 'N') + log_error("JSON memory node '%s' has a non-number width.\n", mem); + mem->width = width_node->data_number; + + if (memory_node->data_dict.count("size") == 0) + log_error("JSON memory node '%s' has no size attribute.\n", mem); + JsonNode *size_node = memory_node->data_dict.at("size"); + if (size_node->type != 'N') + log_error("JSON memory node '%s' has a non-number size.\n", mem); + mem->size = size_node->data_number; + + mem->start_offset = 0; + if (memory_node->data_dict.count("start_offset") != 0) { + JsonNode *val = memory_node->data_dict.at("start_offset"); + if (val->type == 'N') + mem->start_offset = val->data_number; + } + + if (memory_node->data_dict.count("attributes")) + json_parse_attr_param(design, mem->attributes, memory_node->data_dict.at("attributes")); + + module->memories[mem->name] = mem; + } + } + + // remove duplicates from connections array + pool unique_connections(module->connections_.begin(), module->connections_.end()); + module->connections_ = std::vector(unique_connections.begin(), unique_connections.end()); +} + +struct JsonFrontend : public Frontend { + JsonFrontend() : Frontend("json", "read JSON file") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" read_json [filename]\n"); + log("\n"); + log("Load modules from a JSON file into the current design See \"help write_json\"\n"); + log("for a description of the file format.\n"); + log("\n"); + } + void execute(std::istream *&f, std::string filename, std::vector args, RTLIL::Design *design) override + { + log_header(design, "Executing JSON frontend.\n"); + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) { + // std::string arg = args[argidx]; + // if (arg == "-sop") { + // sop_mode = true; + // continue; + // } + break; + } + extra_args(f, filename, args, argidx); + + JsonNode root(*f); + + if (root.type != 'D') + log_error("JSON root node is not a dictionary.\n"); + + if (root.data_dict.count("modules") != 0) + { + JsonNode *modules = root.data_dict.at("modules"); + + if (modules->type != 'D') + log_error("JSON modules node is not a dictionary.\n"); + + for (auto &it : modules->data_dict) + json_import(design, it.first, it.second); + } + } +} JsonFrontend; + +YOSYS_NAMESPACE_END diff --git a/chips/yosys/frontends/liberty/CMakeLists.txt b/chips/yosys/frontends/liberty/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..3301504ff2b76054782ee2f3fd2fec3e42fc0c1d --- /dev/null +++ b/chips/yosys/frontends/liberty/CMakeLists.txt @@ -0,0 +1,5 @@ +yosys_frontend(liberty + liberty.cc + REQUIRES + libparse +) diff --git a/chips/yosys/frontends/liberty/liberty.cc b/chips/yosys/frontends/liberty/liberty.cc new file mode 100644 index 0000000000000000000000000000000000000000..f32b0a0865e793632d43e427d53c13e28fd5cdf9 --- /dev/null +++ b/chips/yosys/frontends/liberty/liberty.cc @@ -0,0 +1,796 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "passes/techmap/libparse.h" +#include "kernel/register.h" +#include "kernel/log.h" +#include + +YOSYS_NAMESPACE_BEGIN + +struct token_t { + char type; + RTLIL::SigSpec sig; + token_t (char t) : type(t) { } + token_t (char t, RTLIL::SigSpec s) : type(t), sig(s) { } +}; + +static RTLIL::SigSpec parse_func_identifier(RTLIL::Module *module, const char *&expr) +{ + log_assert(*expr != 0); + + int id_len = 0; + while (('a' <= expr[id_len] && expr[id_len] <= 'z') || ('A' <= expr[id_len] && expr[id_len] <= 'Z') || + ('0' <= expr[id_len] && expr[id_len] <= '9') || expr[id_len] == '.' || + expr[id_len] == '_' || expr[id_len] == '[' || expr[id_len] == ']') id_len++; + + if (id_len == 0) + log_error("Expected identifier at `%s' in %s.\n", expr, module); + + if (id_len == 1 && (*expr == '0' || *expr == '1')) + return *(expr++) == '0' ? RTLIL::State::S0 : RTLIL::State::S1; + + std::string id = RTLIL::escape_id(std::string(expr, id_len)); + IdString wire_ref = module->twines().find(id); + RTLIL::Wire *w = module->wire(wire_ref); + if (!w) + log_error("Can't resolve wire name %s in %s.\n", RTLIL::unescape_id(id), module); + + expr += id_len; + return w; +} + +static bool parse_func_reduce(RTLIL::Module *module, std::vector &stack, token_t next_token) +{ + int top = int(stack.size())-1; + + if (0 <= top-1 && stack[top].type == 0 && stack[top-1].type == '!') { + token_t t = token_t(0, module->NotGate(NEW_ID, stack[top].sig)); + stack.pop_back(); + stack.pop_back(); + stack.push_back(t); + return true; + } + + if (0 <= top-1 && stack[top].type == '\'' && stack[top-1].type == 0) { + token_t t = token_t(0, module->NotGate(NEW_ID, stack[top-1].sig)); + stack.pop_back(); + stack.pop_back(); + stack.push_back(t); + return true; + } + + if (0 <= top && stack[top].type == 0) { + if (next_token.type == '\'') + return false; + stack[top].type = 1; + return true; + } + + if (0 <= top-2 && stack[top-2].type == 1 && stack[top-1].type == '^' && stack[top].type == 1) { + token_t t = token_t(1, module->XorGate(NEW_ID, stack[top-2].sig, stack[top].sig)); + stack.pop_back(); + stack.pop_back(); + stack.pop_back(); + stack.push_back(t); + return true; + } + + if (0 <= top && stack[top].type == 1) { + if (next_token.type == '^') + return false; + stack[top].type = 2; + return true; + } + + if (0 <= top-1 && stack[top-1].type == 2 && stack[top].type == 2) { + token_t t = token_t(2, module->AndGate(NEW_ID, stack[top-1].sig, stack[top].sig)); + stack.pop_back(); + stack.pop_back(); + stack.push_back(t); + return true; + } + + if (0 <= top-2 && stack[top-2].type == 2 && (stack[top-1].type == '*' || stack[top-1].type == '&') && stack[top].type == 2) { + token_t t = token_t(2, module->AndGate(NEW_ID, stack[top-2].sig, stack[top].sig)); + stack.pop_back(); + stack.pop_back(); + stack.pop_back(); + stack.push_back(t); + return true; + } + + if (0 <= top && stack[top].type == 2) { + if (next_token.type == '*' || next_token.type == '&' || next_token.type == 0 || next_token.type == '(' || next_token.type == '!') + return false; + stack[top].type = 3; + return true; + } + + if (0 <= top-2 && stack[top-2].type == 3 && (stack[top-1].type == '+' || stack[top-1].type == '|') && stack[top].type == 3) { + token_t t = token_t(3, module->OrGate(NEW_ID, stack[top-2].sig, stack[top].sig)); + stack.pop_back(); + stack.pop_back(); + stack.pop_back(); + stack.push_back(t); + return true; + } + + if (0 <= top-2 && stack[top-2].type == '(' && stack[top-1].type == 3 && stack[top].type == ')') { + token_t t = token_t(0, stack[top-1].sig); + stack.pop_back(); + stack.pop_back(); + stack.pop_back(); + stack.push_back(t); + return true; + } + + return false; +} + +static RTLIL::SigSpec parse_func_expr(RTLIL::Module *module, const char *expr) +{ + const char *orig_expr = expr; + std::vector stack; + + while (*expr) + { + if (*expr == ' ' || *expr == '\t' || *expr == '\r' || *expr == '\n' || *expr == '"') { + expr++; + continue; + } + + token_t next_token(0); + if (*expr == '(' || *expr == ')' || *expr == '\'' || *expr == '!' || *expr == '^' || *expr == '*' || *expr == '+' || *expr == '|' || *expr == '&') + next_token = token_t(*(expr++)); + else + next_token = token_t(0, parse_func_identifier(module, expr)); + + while (parse_func_reduce(module, stack, next_token)) {} + stack.push_back(next_token); + } + + while (parse_func_reduce(module, stack, token_t('.'))) {} + +#if 0 + for (size_t i = 0; i < stack.size(); i++) + if (stack[i].type < 16) + log("%3d: %d %s\n", int(i), stack[i].type, log_signal(stack[i].sig)); + else + log("%3d: %c\n", int(i), stack[i].type); +#endif + + if (stack.size() != 1 || stack.back().type != 3) + log_error("Parser error in function expr `%s'in %s.\n", orig_expr, module); + + return stack.back().sig; +} + +static RTLIL::SigSpec create_tristate(RTLIL::Module *module, RTLIL::SigSpec func, const char *three_state_expr) +{ + RTLIL::SigSpec three_state = parse_func_expr(module, three_state_expr); + + auto cell = module->addTribuf(NEW_ID, func, module->NotGate(NEW_ID, three_state), module->addWire(NEW_ID)); + return cell->getPort(ID::Y); +} + +static void create_latch_ff_wires(RTLIL::Module *module, const LibertyAst *node) +{ + module->addWire(RTLIL::escape_id(node->args.at(0))); + module->addWire(RTLIL::escape_id(node->args.at(1))); +} + +static std::pair find_latch_ff_wires(RTLIL::Module *module, const LibertyAst *node) +{ + IdString iq_ref = module->twines().find(RTLIL::escape_id(node->args.at(0))); + IdString iqn_ref = module->twines().find(RTLIL::escape_id(node->args.at(1))); + auto* iq_wire = module->wire(iq_ref); + auto* iqn_wire = module->wire(iqn_ref); + log_assert(iq_wire && iqn_wire); + return std::make_pair(iq_wire, iqn_wire); +} + +static void create_ff(RTLIL::Module *module, const LibertyAst *node) +{ + auto [iq_sig, iqn_sig] = find_latch_ff_wires(module, node); + RTLIL::SigSpec clk_sig, data_sig, clear_sig, preset_sig; + const std::string name = module->name.unescape(); + + std::optional clear_preset_var1; + std::optional clear_preset_var2; + for (auto child : node->children) { + if (child->id == "clocked_on") + clk_sig = parse_func_expr(module, child->value.c_str()); + if (child->id == "next_state") + data_sig = parse_func_expr(module, child->value.c_str()); + if (child->id == "clear") + clear_sig = parse_func_expr(module, child->value.c_str()); + if (child->id == "preset") + preset_sig = parse_func_expr(module, child->value.c_str()); + + for (auto& [id, var] : {pair{"clear_preset_var1", &clear_preset_var1}, {"clear_preset_var2", &clear_preset_var2}}) + if (child->id == id) { + if (child->value.size() != 1) + log_error("Unexpected length of clear_preset_var* value %s in FF cell %s\n", child->value, name); + *var = child->value[0]; + } + + } + + if (clk_sig.size() == 0 || data_sig.size() == 0) + log_error("FF cell %s has no next_state and/or clocked_on attribute.\n", name); + + for (auto& [out_sig, cp_var, neg] : {tuple{iq_sig, clear_preset_var1, false}, {iqn_sig, clear_preset_var2, true}}) { + SigSpec q_sig = out_sig; + if (neg) { + q_sig = module->addWire(NEW_ID, out_sig.as_wire()); + module->addNotGate(NEW_ID, q_sig, out_sig); + } + + RTLIL::Cell* cell = module->addCell(NEW_ID, IdString::Null); + cell->setPort(ID::D, data_sig); + cell->setPort(ID::Q, q_sig); + cell->setPort(ID::C, clk_sig); + + if (clear_sig.size() == 0 && preset_sig.size() == 0) { + cell->type = ID::$_DFF_P_; + } + + if (clear_sig.size() == 1 && preset_sig.size() == 0) { + cell->type = ID::$_DFF_PP0_; + cell->setPort(ID::R, clear_sig); + } + + if (clear_sig.size() == 0 && preset_sig.size() == 1) { + cell->type = ID::$_DFF_PP1_; + cell->setPort(ID::R, preset_sig); + } + + if (clear_sig.size() == 1 && preset_sig.size() == 1) { + cell->type = ID::$_DFFSR_PPP_; + + SigBit s_sig = preset_sig; + SigBit r_sig = clear_sig; + if (cp_var && *cp_var != 'X') { + // Either set or reset dominates + bool set_dominates; + if (*cp_var == 'L') { + set_dominates = neg; + } else if (*cp_var == 'H') { + set_dominates = !neg; + } else { + log_error("FF cell %s has unsupported clear&preset behavior \'%c\'.\n", name, *cp_var); + } + log_debug("cell %s variable %d cp_var %c set dominates? %d\n", name, (int)neg + 1, *cp_var, set_dominates); + // S&R priority is well-defined now + if (set_dominates) { + r_sig = module->AndnotGate(NEW_ID, r_sig, s_sig); + } else { + s_sig = module->AndnotGate(NEW_ID, s_sig, r_sig); + } + } else { + log_debug("cell %s variable %d undef c&p behavior\n", name, (int)neg + 1); + } + + cell->setPort(ID::S, s_sig); + cell->setPort(ID::R, r_sig); + } + + log_assert(!cell->type.empty()); + } +} + +static bool create_latch(RTLIL::Module *module, const LibertyAst *node, bool flag_ignore_miss_data_latch) +{ + auto [iq_sig, iqn_sig] = find_latch_ff_wires(module, node); + RTLIL::SigSpec enable_sig, data_sig, clear_sig, preset_sig; + const std::string name = module->name.unescape(); + + std::optional clear_preset_var1; + std::optional clear_preset_var2; + for (auto child : node->children) { + if (child->id == "enable") + enable_sig = parse_func_expr(module, child->value.c_str()); + if (child->id == "data_in") + data_sig = parse_func_expr(module, child->value.c_str()); + if (child->id == "clear") + clear_sig = parse_func_expr(module, child->value.c_str()); + if (child->id == "preset") + preset_sig = parse_func_expr(module, child->value.c_str()); + + for (auto& [id, var] : {pair{"clear_preset_var1", &clear_preset_var1}, {"clear_preset_var2", &clear_preset_var2}}) { + if (child->id == id) { + if (child->value.size() != 1) + log_error("Unexpected length of clear_preset_var* value %s in latch cell %s\n", child->value, name); + *var = child->value[0]; + } + } + } + + if (enable_sig.size() == 0 || data_sig.size() == 0) { + if (!flag_ignore_miss_data_latch) + log_error("Latch cell %s has no data_in and/or enable attribute.\n", name); + else + log("Ignored latch cell %s with no data_in and/or enable attribute.\n", name); + + return false; + } + + for (auto& [out_sig, cp_var, neg] : {tuple{iq_sig, clear_preset_var1, false}, {iqn_sig, clear_preset_var2, true}}) { + SigSpec q_sig = out_sig; + if (neg) { + q_sig = module->addWire(NEW_ID, out_sig.as_wire()); + module->addNotGate(NEW_ID, q_sig, out_sig); + } + + RTLIL::Cell* cell = module->addCell(NEW_ID, ""); + cell->setPort(ID::D, data_sig); + cell->setPort(ID::Q, q_sig); + cell->setPort(ID::E, enable_sig); + + if (clear_sig.size() == 0 && preset_sig.size() == 0) { + cell->type = ID::$_DLATCH_P_; + } + + if (clear_sig.size() == 1 && preset_sig.size() == 0) { + cell->type = ID::$_DLATCH_PP0_; + cell->setPort(ID::R, clear_sig); + } + + if (clear_sig.size() == 0 && preset_sig.size() == 1) { + cell->type = ID::$_DLATCH_PP1_; + cell->setPort(ID::R, preset_sig); + } + + if (clear_sig.size() == 1 && preset_sig.size() == 1) { + cell->type = ID::$_DLATCHSR_PPP_; + + SigBit s_sig = preset_sig; + SigBit r_sig = clear_sig; + if (cp_var && *cp_var != 'X') { + // Either set or reset dominates + bool set_dominates; + if (*cp_var == 'L') { + set_dominates = neg; + } else if (*cp_var == 'H') { + set_dominates = !neg; + } else { + log_error("Latch cell %s has unsupported clear&preset behavior \'%c\'.\n", name, *cp_var); + } + log_debug("cell %s variable %d cp_var %c set dominates? %d\n", name, (int)neg + 1, *cp_var, set_dominates); + // S&R priority is well-defined now + if (set_dominates) { + r_sig = module->AndnotGate(NEW_ID, r_sig, s_sig); + } else { + s_sig = module->AndnotGate(NEW_ID, s_sig, r_sig); + } + } else { + log_debug("cell %s variable %d undef c&p behavior\n", name, (int)neg + 1); + } + + cell->setPort(ID::S, s_sig); + cell->setPort(ID::R, r_sig); + } + + log_assert(!cell->type.empty()); + } + + return true; +} + +void parse_type_map(std::map> &type_map, const LibertyAst *ast) +{ + for (auto type_node : ast->children) + { + if (type_node->id != "type" || type_node->args.size() != 1) + continue; + + std::string type_name = type_node->args.at(0); + int bit_width = -1, bit_from = -1, bit_to = -1; + bool upto = false; + + for (auto child : type_node->children) + { + if (child->id == "base_type" && child->value != "array") + goto next_type; + + if (child->id == "data_type" && child->value != "bit") + goto next_type; + + if (child->id == "bit_width") + bit_width = atoi(child->value.c_str()); + + if (child->id == "bit_from") + bit_from = atoi(child->value.c_str()); + + if (child->id == "bit_to") + bit_to = atoi(child->value.c_str()); + + if (child->id == "downto" && (child->value == "0" || child->value == "false" || child->value == "FALSE")) + upto = true; + } + + if (bit_width != (std::max(bit_from, bit_to) - std::min(bit_from, bit_to) + 1)) + log_error("Incompatible array type '%s': bit_width=%d, bit_from=%d, bit_to=%d.\n", + type_name, bit_width, bit_from, bit_to); + + type_map[type_name] = std::tuple(bit_width, std::min(bit_from, bit_to), upto); + next_type:; + } +} + +struct LibertyFrontend : public Frontend { + LibertyFrontend() : Frontend("liberty", "read cells from liberty file") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" read_liberty [filename]\n"); + log("\n"); + log("Read cells from liberty file as modules into current design.\n"); + log("\n"); + log(" -lib\n"); + log(" only create empty blackbox modules\n"); + log("\n"); + log(" -wb\n"); + log(" mark imported cells as whiteboxes\n"); + log("\n"); + log(" -nooverwrite\n"); + log(" ignore re-definitions of modules. (the default behavior is to\n"); + log(" create an error message if the existing module is not a blackbox\n"); + log(" module, and overwrite the existing module if it is a blackbox module.)\n"); + log("\n"); + log(" -overwrite\n"); + log(" overwrite existing modules with the same name\n"); + log("\n"); + log(" -ignore_miss_func\n"); + log(" ignore cells with missing function specification of outputs\n"); + log("\n"); + log(" -ignore_miss_dir\n"); + log(" ignore cells with a missing or invalid direction\n"); + log(" specification on a pin\n"); + log("\n"); + log(" -ignore_miss_data_latch\n"); + log(" ignore latches with missing data and/or enable pins\n"); + log("\n"); + log(" -ignore_buses\n"); + log(" ignore cells with bus interfaces (wide ports)\n"); + log("\n"); + log(" -setattr \n"); + log(" set the specified attribute (to the value 1) on all loaded modules\n"); + log("\n"); + log(" -unit_delay\n"); + log(" import combinational timing arcs under the unit delay model\n"); + log("\n"); + } + void execute(std::istream *&f, std::string filename, std::vector args, RTLIL::Design *design) override + { + bool flag_lib = false; + bool flag_wb = false; + bool flag_nooverwrite = false; + bool flag_overwrite = false; + bool flag_ignore_miss_func = false; + bool flag_ignore_miss_dir = false; + bool flag_ignore_miss_data_latch = false; + bool flag_ignore_buses = false; + bool flag_unit_delay = false; + std::vector attributes; + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) { + std::string arg = args[argidx]; + if (arg == "-lib") { + flag_lib = true; + continue; + } + if (arg == "-wb") { + flag_wb = true; + continue; + } + if (arg == "-ignore_redef" || arg == "-nooverwrite") { + flag_nooverwrite = true; + flag_overwrite = false; + continue; + } + if (arg == "-overwrite") { + flag_nooverwrite = false; + flag_overwrite = true; + continue; + } + if (arg == "-ignore_miss_func") { + flag_ignore_miss_func = true; + continue; + } + if (arg == "-ignore_miss_dir") { + flag_ignore_miss_dir = true; + continue; + } + if (arg == "-ignore_miss_data_latch") { + flag_ignore_miss_data_latch = true; + continue; + } + if (arg == "-ignore_buses") { + flag_ignore_buses = true; + continue; + } + if (arg == "-setattr" && argidx+1 < args.size()) { + attributes.push_back(RTLIL::escape_id(args[++argidx])); + continue; + } + if (arg == "-unit_delay") { + flag_unit_delay = true; + continue; + } + break; + } + extra_args(f, filename, args, argidx); + + if (flag_wb && flag_lib) + log_error("-wb and -lib cannot be specified together!\n"); + + log_header(design, "Executing Liberty frontend: %s\n", filename); + + LibertyParser parser(*f, filename, liberty_synth_filter); + int cell_count = 0; + + std::map> global_type_map; + parse_type_map(global_type_map, parser.ast); + + for (auto cell : parser.ast->children) + { + if (cell->id != "cell" || cell->args.size() != 1) + continue; + + // log("Processing cell type %s.\n", RTLIL::unescape_id(cell_name)); + + std::map> type_map = global_type_map; + parse_type_map(type_map, cell); + + RTLIL::Module *module = new RTLIL::Module(design); + std::string cell_name = RTLIL::escape_id(cell->args.at(0)); + IdString cell_name_ref = design->twines().add(cell_name); + module->name = cell_name_ref; + + if (flag_lib) + module->set_bool_attribute(ID::blackbox); + + if (flag_wb) + module->set_bool_attribute(ID::whitebox); + + const LibertyAst *area = cell->find("area"); + if (area) + module->attributes[ID::area] = area->value; + + for (auto &attr : attributes) + module->attributes[design->twines().add(attr)] = 1; + + bool simple_comb_cell = true, has_inputs = false, has_outputs = false; + + for (auto node : cell->children) + { + if (node->id == "pin" && node->args.size() == 1) { + const LibertyAst *dir = node->find("direction"); + if (!dir || (dir->value != "input" && dir->value != "output" && dir->value != "inout" && dir->value != "internal")) + { + if (!flag_ignore_miss_dir) + { + log_error("Missing or invalid direction for pin %s on cell %s.\n", node->args.at(0), module); + } else { + log("Ignoring cell %s with missing or invalid direction for pin %s.\n", module, node->args.at(0)); + delete module; + goto skip_cell; + } + } + if (!flag_lib || dir->value != "internal") + module->addWire(RTLIL::escape_id(node->args.at(0))); + } + + if (node->id == "bus" && node->args.size() == 1) + { + if (flag_ignore_buses) { + log("Ignoring cell %s with a bus interface %s.\n", module, node->args.at(0)); + delete module; + goto skip_cell; + } + + if (!flag_lib) + log_error("Error in cell %s: bus interfaces are only supported in -lib mode.\n", RTLIL::unescape_id(cell_name)); + + const LibertyAst *dir = node->find("direction"); + + if (dir == nullptr) { + const LibertyAst *pin = node->find("pin"); + if (pin != nullptr) + dir = pin->find("direction"); + } + + if (!dir || (dir->value != "input" && dir->value != "output" && dir->value != "inout" && dir->value != "internal")) + log_error("Missing or invalid direction for bus %s on cell %s.\n", node->args.at(0), module); + + simple_comb_cell = false; + + if (dir->value == "internal") + continue; + + const LibertyAst *bus_type_node = node->find("bus_type"); + + if (!bus_type_node || !type_map.count(bus_type_node->value)) + log_error("Unknown or unsupported type for bus interface %s on cell %s.\n", + node->args.at(0), RTLIL::unescape_id(cell_name)); + + int bus_type_width = std::get<0>(type_map.at(bus_type_node->value)); + int bus_type_offset = std::get<1>(type_map.at(bus_type_node->value)); + bool bus_type_upto = std::get<2>(type_map.at(bus_type_node->value)); + + Wire *wire = module->addWire(RTLIL::escape_id(node->args.at(0)), bus_type_width); + wire->start_offset = bus_type_offset; + wire->upto = bus_type_upto; + + if (dir->value == "input" || dir->value == "inout") + wire->port_input = true; + + if (dir->value == "output" || dir->value == "inout") + wire->port_output = true; + } + } + + if (!flag_lib) + { + // some liberty files do not put ff/latch at the beginning of a cell + // try to find "ff" or "latch" and create FF/latch _before_ processing all other nodes + // but first, in case of balloon retention cells, we need all ff/latch output wires + // defined before we add ff/latch cells + for (auto node : cell->children) + { + if ((node->id == "ff" && node->args.size() == 2) || (node->id == "latch" && node->args.size() == 2)) + create_latch_ff_wires(module, node); + } + for (auto node : cell->children) + { + if (node->id == "ff" && node->args.size() == 2) + create_ff(module, node); + if (node->id == "latch" && node->args.size() == 2) + if (!create_latch(module, node, flag_ignore_miss_data_latch)) { + delete module; + goto skip_cell; + } + } + } + + for (auto node : cell->children) + { + if (node->id == "pin" && node->args.size() == 1) + { + const LibertyAst *dir = node->find("direction"); + + if (dir->value == "internal" || dir->value == "inout") + simple_comb_cell = false; + + if (flag_lib && dir->value == "internal") + continue; + + IdString wire_ref = module->twines().find(RTLIL::escape_id(node->args.at(0))); + RTLIL::Wire *wire = module->wire(wire_ref); + log_assert(wire); + + const LibertyAst *capacitance = node->find("capacitance"); + if (capacitance) + wire->attributes[ID::capacitance] = capacitance->value; + + if (dir && dir->value == "inout") { + wire->port_input = true; + wire->port_output = true; + } + + if (dir && dir->value == "input") { + has_inputs = true; + wire->port_input = true; + continue; + } + + if (dir && dir->value == "output") { + has_outputs = true; + wire->port_output = true; + } + + if (flag_lib) + continue; + + const LibertyAst *func = node->find("function"); + if (func == NULL) + { + if (dir->value != "inout") { // allow inout with missing function, can be used for power pins + if (!flag_ignore_miss_func) + { + log_error("Missing function on output %s of cell %s.\n", wire, module); + } else { + log("Ignoring cell %s with missing function on output %s.\n", module, wire); + delete module; + goto skip_cell; + } + } + simple_comb_cell = false; + } else { + RTLIL::SigSpec out_sig = parse_func_expr(module, func->value.c_str()); + const LibertyAst *three_state = node->find("three_state"); + if (three_state) { + out_sig = create_tristate(module, out_sig, three_state->value.c_str()); + simple_comb_cell = false; + } + module->connect(RTLIL::SigSig(wire, out_sig)); + } + } + + if (node->id == "ff" || node->id == "ff_bank" || + node->id == "latch" || node->id == "latch_bank" || + node->id == "statetable") + simple_comb_cell = false; + } + + if (simple_comb_cell && has_inputs && has_outputs && flag_unit_delay) { + module->set_bool_attribute(ID::abc9_box); + + for (auto wi : module->wires()) + if (wi->port_input) { + for (auto wo : module->wires()) + if (wo->port_output) { + RTLIL::Cell *spec = module->addCell(NEW_ID, ID($specify2)); + spec->setParam(ID::SRC_WIDTH, wi->width); + spec->setParam(ID::DST_WIDTH, wo->width); + spec->setParam(ID::T_FALL_MAX, 1000); + spec->setParam(ID::T_FALL_TYP, 1000); + spec->setParam(ID::T_FALL_MIN, 1000); + spec->setParam(ID::T_RISE_MAX, 1000); + spec->setParam(ID::T_RISE_TYP, 1000); + spec->setParam(ID::T_RISE_MIN, 1000); + spec->setParam(ID::SRC_DST_POL, false); + spec->setParam(ID::SRC_DST_PEN, false); + spec->setParam(ID::FULL, true); + spec->setPort(ID::EN, Const(1, 1)); + spec->setPort(ID::SRC, wi); + spec->setPort(ID::DST, wo); + } + } + } + + if (design->has(cell_name_ref)) { + Module *existing_mod = design->module(cell_name_ref); + if (!flag_nooverwrite && !flag_overwrite && !existing_mod->get_bool_attribute(ID::blackbox)) { + log_error("Re-definition of cell/module %s!\n", RTLIL::unescape_id(cell_name)); + } else if (flag_nooverwrite) { + log("Ignoring re-definition of module %s.\n", RTLIL::unescape_id(cell_name)); + delete module; + goto skip_cell; + } else { + log("Replacing existing%s module %s.\n", existing_mod->get_bool_attribute(ID::blackbox) ? " blackbox" : "", RTLIL::unescape_id(cell_name)); + design->remove(existing_mod); + } + } + + module->fixup_ports(); + design->add(module); + cell_count++; +skip_cell:; + } + + log("Imported %d cell types from liberty file.\n", cell_count); + } +} LibertyFrontend; + +YOSYS_NAMESPACE_END diff --git a/chips/yosys/frontends/rpc/CMakeLists.txt b/chips/yosys/frontends/rpc/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..4e1136cf363e70c9ae4ae4c82cd0aba3405af8ce --- /dev/null +++ b/chips/yosys/frontends/rpc/CMakeLists.txt @@ -0,0 +1,8 @@ +yosys_frontend(rpc + rpc_frontend.cc + REQUIRES + json11 + sha1 + ENABLE_IF + YOSYS_ENABLE_SPAWN +) diff --git a/chips/yosys/frontends/rpc/rpc_frontend.cc b/chips/yosys/frontends/rpc/rpc_frontend.cc new file mode 100644 index 0000000000000000000000000000000000000000..96aa18995522f5716f8430adbaf413301fb90346 --- /dev/null +++ b/chips/yosys/frontends/rpc/rpc_frontend.cc @@ -0,0 +1,597 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2019 whitequark + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +// The reason the -path mode of connect_rpc uses byte-oriented and not message-oriented sockets, even though +// it is a message-oriented interface, is that the system can place various limits on the message size, which +// are not always transparent or easy to change. Given that generated HDL code get be extremely large, it is +// unwise to rely on those limits being large enough, and using byte-oriented sockets is guaranteed to work. + +#ifndef _WIN32 +#include +#include +#include +#include +#include +extern char **environ; +#endif + +#include "libs/json11/json11.hpp" +#include "libs/sha1/sha1.h" +#include "kernel/yosys.h" + +YOSYS_NAMESPACE_BEGIN + +#if defined(_WIN32) +static std::wstring str2wstr(const std::string &in) { + if(in == "") return L""; + std::wstring out; + out.resize(MultiByteToWideChar(/*CodePage=*/CP_UTF8, /*dwFlags=*/0, /*lpMultiByteStr=*/&in[0], /*cbMultiByte=*/(int)in.length(), /*lpWideCharStr=*/NULL, /*cchWideChar=*/0)); + int written = MultiByteToWideChar(/*CodePage=*/CP_UTF8, /*dwFlags=*/0, /*lpMultiByteStr=*/&in[0], /*cbMultiByte=*/(int)in.length(), /*lpWideCharStr=*/&out[0], /*cchWideChar=*/(int)out.length()); + log_assert(written == (int)out.length()); + return out; +} + +static std::string wstr2str(const std::wstring &in) { + if(in == L"") return ""; + std::string out; + out.resize(WideCharToMultiByte(/*CodePage=*/CP_UTF8, /*dwFlags=*/0, /*lpWideCharStr=*/&in[0], /*cchWideChar=*/(int)in.length(), /*lpMultiByteStr=*/NULL, /*cbMultiByte=*/0, /*lpDefaultChar=*/NULL, /*lpUsedDefaultChar=*/NULL)); + int written = WideCharToMultiByte(/*CodePage=*/CP_UTF8, /*dwFlags=*/0, /*lpWideCharStr=*/&in[0], /*cchWideChar=*/(int)in.length(), /*lpMultiByteStr=*/&out[0], /*cbMultiByte=*/(int)out.length(), /*lpDefaultChar=*/NULL, /*lpUsedDefaultChar=*/NULL); + log_assert(written == (int)out.length()); + return out; +} + +static std::string get_last_error_str() { + DWORD last_error = GetLastError(); + LPWSTR out_w; + DWORD size_w = FormatMessageW(/*dwFlags=*/FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_IGNORE_INSERTS, /*lpSource=*/NULL, /*dwMessageId=*/last_error, /*dwLanguageId=*/0, /*lpBuffer=*/(LPWSTR)&out_w, /*nSize=*/0, /*Arguments=*/NULL); + if (size_w == 0) + return std::to_string(last_error); + std::string out = wstr2str(std::wstring(out_w, size_w)); + LocalFree(out_w); + return out; +} +#endif + +using json11::Json; + +struct RpcServer { + std::string name; + + RpcServer(const std::string &name) : name(name) { } + virtual ~RpcServer() { } + + virtual void write(const std::string &data) = 0; + virtual std::string read() = 0; + + Json call(const Json &json_request) { + std::string request; + json_request.dump(request); + request += '\n'; + log_debug("RPC frontend request: %s", request); + write(request); + + std::string response = read(); + log_debug("RPC frontend response: %s", response); + std::string error; + Json json_response = Json::parse(response, error); + if (json_response.is_null()) + log_cmd_error("parsing JSON failed: %s\n", error); + if (json_response["error"].is_string()) + log_cmd_error("RPC frontend returned an error: %s\n", json_response["error"].string_value()); + return json_response; + } + + std::vector get_module_names() { + Json response = call(Json::object { + { "method", "modules" }, + }); + bool is_valid = true; + std::vector modules; + if (response["modules"].is_array()) { + for (auto &json_module : response["modules"].array_items()) { + if (json_module.is_string()) + modules.push_back(json_module.string_value()); + else is_valid = false; + } + } else is_valid = false; + if (!is_valid) + log_cmd_error("RPC frontend returned malformed response: %s\n", response.dump()); + return modules; + } + + std::pair derive_module(const RTLIL::Design *design, const std::string &module, const dict ¶meters) { + Json::object json_parameters; + for (auto ¶m : parameters) { + std::string type, value; + if (param.second.flags & RTLIL::CONST_FLAG_REAL) { + type = "real"; + value = param.second.decode_string(); + } else if (param.second.flags & RTLIL::CONST_FLAG_STRING) { + type = "string"; + value = param.second.decode_string(); + } else if ((param.second.flags & ~RTLIL::CONST_FLAG_SIGNED) == RTLIL::CONST_FLAG_NONE) { + type = (param.second.flags & RTLIL::CONST_FLAG_SIGNED) ? "signed" : "unsigned"; + value = param.second.as_string(); + } else + log_cmd_error("Unserializable constant flags 0x%x\n", param.second.flags); + json_parameters[design->twines().str(param.first)] = Json::object { + { "type", type }, + { "value", value }, + }; + } + Json response = call(Json::object { + { "method", "derive" }, + { "module", module }, + { "parameters", json_parameters }, + }); + bool is_valid = true; + std::string frontend, source; + if (response["frontend"].is_string()) + frontend = response["frontend"].string_value(); + else is_valid = false; + if (response["source"].is_string()) + source = response["source"].string_value(); + else is_valid = false; + if (!is_valid) + log_cmd_error("RPC frontend returned malformed response: %s\n", response.dump()); + return std::make_pair(frontend, source); + } +}; + +struct RpcModule : RTLIL::Module { + using RTLIL::Module::Module; + + std::shared_ptr server; + + RTLIL::IdString derive(RTLIL::Design *design, const dict ¶meters, bool /*mayfail*/) override { + std::string stripped_name = name.str(); + if (stripped_name.compare(0, 9, "$abstract") == 0) + stripped_name = stripped_name.substr(9); + log_assert(stripped_name[0] == '\\'); + + log_header(design, "Executing RPC frontend `%s' for module `%s'.\n", server->name, stripped_name); + + std::string parameter_info; + for (auto ¶m : parameters) { + log("Parameter %s = %s\n", PooledName(design, param.first).unescape(), log_signal(RTLIL::SigSpec(param.second))); + parameter_info += stringf("%s=%s", PooledName(design, param.first).unescape(), log_signal(RTLIL::SigSpec(param.second))); + } + + std::string derived_name; + if (parameters.empty()) + derived_name = stripped_name; + else if (parameter_info.size() > 60) + derived_name = "$paramod$" + sha1(parameter_info) + stripped_name; + else + derived_name = "$paramod" + stripped_name + parameter_info; + + IdString derived_ref = design->twines().find(derived_name); + if (design->has(derived_ref)) { + log("Found cached RTLIL representation for module `%s'.\n", derived_name); + } else { + std::string command, input; + std::tie(command, input) = server->derive_module(design, stripped_name.substr(1), parameters); + + std::istringstream input_stream(input); + RTLIL::Design derived_design; + Frontend::frontend_call(&derived_design, &input_stream, "" + derived_name.substr(8), command); + derived_design.check(); + + dict name_mangling; + bool found_derived_top = false; + for (auto module : derived_design.modules()) { + std::string original_name = module->name.str(); + if (original_name == stripped_name) { + found_derived_top = true; + name_mangling[original_name] = derived_name; + } else { + name_mangling[original_name] = derived_name + module->name.str(); + } + } + if (!found_derived_top) + log_cmd_error("RPC frontend did not return requested module `%s`!\n", stripped_name); + + for (auto module : derived_design.modules()) + for (auto cell : module->cells()) + if (name_mangling.count(cell->type.str())) + cell->type = cell->twines().add(name_mangling[cell->type.str()]); + + for (auto module : derived_design.modules_) { + std::string mangled_name = name_mangling[derived_design.twines().str(module.first)]; + + log("Importing `%s' as `%s'.\n", PooledName(&derived_design, module.first).unescape(), mangled_name); + + IdString original_name = module.first; + RTLIL::Module *t = module.second->clone(design, design->twines().add(mangled_name)); + t->attributes.erase(ID::top); + if (!t->has_attribute(ID::hdlname)) + t->set_string_attribute(ID::hdlname, derived_design.twines().str(original_name)); + } + } + + return design->twines().add(derived_name); + } + + RTLIL::Module *clone() const override { + RpcModule *new_mod = new RpcModule(design); + new_mod->server = server; + cloneInto(new_mod); + return new_mod; + } +}; + +#if defined(_WIN32) + +#if defined(_MSC_VER) +#include +typedef SSIZE_T ssize_t; +#endif + +struct HandleRpcServer : RpcServer { + HANDLE hsend, hrecv; + + HandleRpcServer(const std::string &name, HANDLE hsend, HANDLE hrecv) + : RpcServer(name), hsend(hsend), hrecv(hrecv) { } + + void write(const std::string &data) override { + log_assert(data.length() >= 1 && data.find('\n') == data.length() - 1); + ssize_t offset = 0; + do { + DWORD data_written; + if (!WriteFile(hsend, &data[offset], data.length() - offset, &data_written, /*lpOverlapped=*/NULL)) + log_cmd_error("WriteFile failed: %s\n", get_last_error_str()); + offset += data_written; + } while(offset < (ssize_t)data.length()); + } + + std::string read() override { + std::string data; + ssize_t offset = 0; + while (data.length() == 0 || data[data.length() - 1] != '\n') { + data.resize(data.length() + 1024); + DWORD data_read; + if (!ReadFile(hrecv, &data[offset], data.length() - offset, &data_read, /*lpOverlapped=*/NULL)) + log_cmd_error("ReadFile failed: %s\n", get_last_error_str()); + offset += data_read; + data.resize(offset); + size_t term_pos = data.find('\n', offset); + if (term_pos != data.length() - 1 && term_pos != std::string::npos) + log_cmd_error("read failed: more than one response\n"); + } + return data; + } + + ~HandleRpcServer() { + CloseHandle(hsend); + if (hrecv != hsend) + CloseHandle(hrecv); + } +}; + +#else + +struct FdRpcServer : RpcServer { + int fdsend, fdrecv; + pid_t pid; + + FdRpcServer(const std::string &name, int fdsend, int fdrecv, pid_t pid = -1) + : RpcServer(name), fdsend(fdsend), fdrecv(fdrecv), pid(pid) { } + + void check_pid() { + if (pid == -1) return; + // If we're communicating with a process, check that it's still running, or we may get killed with SIGPIPE. + pid_t wait_result = ::waitpid(pid, NULL, WNOHANG); + if (wait_result == -1) + log_cmd_error("waitpid failed: %s\n", strerror(errno)); + if (wait_result == pid) + log_cmd_error("RPC frontend terminated unexpectedly\n"); + } + + void write(const std::string &data) override { + log_assert(data.length() >= 1 && data.find('\n') == data.length() - 1); + ssize_t offset = 0; + do { + check_pid(); + ssize_t result = ::write(fdsend, &data[offset], data.length() - offset); + if (result == -1) + log_cmd_error("write failed: %s\n", strerror(errno)); + offset += result; + } while(offset < (ssize_t)data.length()); + } + + std::string read() override { + std::string data; + ssize_t offset = 0; + while (data.length() == 0 || data[data.length() - 1] != '\n') { + data.resize(data.length() + 1024); + check_pid(); + ssize_t result = ::read(fdrecv, &data[offset], data.length() - offset); + if (result == -1) + log_cmd_error("read failed: %s\n", strerror(errno)); + offset += result; + data.resize(offset); + size_t term_pos = data.find('\n', offset); + if (term_pos != data.length() - 1 && term_pos != std::string::npos) + log_cmd_error("read failed: more than one response\n"); + } + return data; + } + + ~FdRpcServer() { + close(fdsend); + if (fdrecv != fdsend) + close(fdrecv); + } +}; + +#endif + +// RpcFrontend does not inherit from Frontend since it does not read files. +struct RpcFrontend : public Pass { + RpcFrontend() : Pass("connect_rpc", "connect to RPC frontend") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" connect_rpc -exec [args...]\n"); + log(" connect_rpc -path \n"); + log("\n"); + log("Load modules using an out-of-process frontend.\n"); + log("\n"); + log(" -exec [args...]\n"); + log(" run with arguments [args...]. send requests on stdin, read\n"); + log(" responses from stdout.\n"); + log("\n"); + log(" -path \n"); + log(" connect to Unix domain socket at . (Unix)\n"); + log(" connect to bidirectional byte-type named pipe at . (Windows)\n"); + log("\n"); + log("A simple JSON-based, newline-delimited protocol is used for communicating with\n"); + log("the frontend. Yosys requests data from the frontend by sending exactly 1 line\n"); + log("of JSON. Frontend responds with data or error message by replying with exactly\n"); + log("1 line of JSON as well.\n"); + log("\n"); + log(" -> {\"method\": \"modules\"}\n"); + log(" <- {\"modules\": [\"\", ...]}\n"); + log(" <- {\"error\": \"\"}\n"); + log(" request for the list of modules that can be derived by this frontend.\n"); + log(" the 'hierarchy' command will call back into this frontend if a cell\n"); + log(" with type is instantiated in the design.\n"); + log("\n"); + log(" -> {\"method\": \"derive\", \"module\": \", \"parameters\": {\n"); + log(" \"\": {\"type\": \"[unsigned|signed|string|real]\",\n"); + log(" \"value\": \"\"}, ...}}\n"); + log(" <- {\"frontend\": \"[rtlil|verilog|...]\",\"source\": \"\"}}\n"); + log(" <- {\"error\": \"\"}\n"); + log(" request for the module to be derived for a specific set of\n"); + log(" parameters. starts with \\ for named parameters, and with $\n"); + log(" for unnamed parameters, which are numbered starting at 1.\n"); + log(" for integer parameters is always specified as a binary string of\n"); + log(" unlimited precision. the returned by the frontend is\n"); + log(" hygienically parsedby a built-in Yosys , allowing the RPC\n"); + log(" frontend to return anyconvenient representation of the module. the\n"); + log(" derived module is cached,so the response should be the same whenever the\n"); + log(" same set of parameters is provided.\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + log_header(design, "Connecting to RPC frontend.\n"); + + std::vector command; + std::string path; + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) { + std::string arg = args[argidx]; + if (arg == "-exec" && argidx+1 < args.size()) { + command.insert(command.begin(), args.begin() + argidx + 1, args.end()); + argidx = args.size()-1; + continue; + } + if (arg == "-path" && argidx+1 < args.size()) { + path = args[++argidx]; + continue; + } + break; + } + extra_args(args, argidx, design); + + if ((!command.empty()) + (!path.empty()) != 1) + log_cmd_error("Exactly one of -exec, -unix must be specified.\n"); + + std::shared_ptr server; + if (!command.empty()) { + std::string command_line; + bool first = true; + for (auto &arg : command) { + if (!first) command_line += ' '; + command_line += arg; + first = false; + } + +#ifdef _WIN32 + std::wstring command_w = str2wstr(command[0]); + std::wstring command_path_w; + std::wstring command_line_w = str2wstr(command_line); + DWORD command_path_len_w; + SECURITY_ATTRIBUTES pipe_attr = {}; + HANDLE send_r = NULL, send_w = NULL, recv_r = NULL, recv_w = NULL; + STARTUPINFOW startup_info = {}; + PROCESS_INFORMATION proc_info = {}; + + command_path_len_w = SearchPathW(/*lpPath=*/NULL, /*lpFileName=*/command_w.c_str(), /*lpExtension=*/L".exe", /*nBufferLength=*/0, /*lpBuffer=*/NULL, /*lpFilePart=*/NULL); + if (command_path_len_w == 0) { + log_error("SearchPathW failed: %s\n", get_last_error_str()); + goto cleanup_exec; + } + command_path_w.resize(command_path_len_w - 1); + command_path_len_w = SearchPathW(/*lpPath=*/NULL, /*lpFileName=*/command_w.c_str(), /*lpExtension=*/L".exe", /*nBufferLength=*/command_path_len_w, /*lpBuffer=*/&command_path_w[0], /*lpFilePart=*/NULL); + log_assert(command_path_len_w == command_path_w.length()); + + pipe_attr.nLength = sizeof(pipe_attr); + pipe_attr.bInheritHandle = TRUE; + pipe_attr.lpSecurityDescriptor = NULL; + if (!CreatePipe(&send_r, &send_w, &pipe_attr, /*nSize=*/0)) { + log_error("CreatePipe failed: %s\n", get_last_error_str()); + goto cleanup_exec; + } + if (!SetHandleInformation(send_w, HANDLE_FLAG_INHERIT, 0)) { + log_error("SetHandleInformation failed: %s\n", get_last_error_str()); + goto cleanup_exec; + } + if (!CreatePipe(&recv_r, &recv_w, &pipe_attr, /*nSize=*/0)) { + log_error("CreatePipe failed: %s\n", get_last_error_str()); + goto cleanup_exec; + } + if (!SetHandleInformation(recv_r, HANDLE_FLAG_INHERIT, 0)) { + log_error("SetHandleInformation failed: %s\n", get_last_error_str()); + goto cleanup_exec; + } + + startup_info.cb = sizeof(startup_info); + startup_info.hStdInput = send_r; + startup_info.hStdOutput = recv_w; + startup_info.hStdError = GetStdHandle(STD_ERROR_HANDLE); + startup_info.dwFlags |= STARTF_USESTDHANDLES; + if (!CreateProcessW(/*lpApplicationName=*/command_path_w.c_str(), /*lpCommandLine=*/&command_line_w[0], /*lpProcessAttributes=*/NULL, /*lpThreadAttributes=*/NULL, /*bInheritHandles=*/TRUE, /*dwCreationFlags=*/0, /*lpEnvironment=*/NULL, /*lpCurrentDirectory=*/NULL, &startup_info, &proc_info)) { + log_error("CreateProcessW failed: %s\n", get_last_error_str()); + goto cleanup_exec; + } + CloseHandle(proc_info.hProcess); + CloseHandle(proc_info.hThread); + + server = std::make_shared(path, send_w, recv_r); + send_w = NULL; + recv_r = NULL; + +cleanup_exec: + if (send_r != NULL) CloseHandle(send_r); + if (send_w != NULL) CloseHandle(send_w); + if (recv_r != NULL) CloseHandle(recv_r); + if (recv_w != NULL) CloseHandle(recv_w); +#else + std::vector argv; + int send[2] = {-1,-1}, recv[2] = {-1,-1}; + posix_spawn_file_actions_t file_actions, *file_actions_p = NULL; + pid_t pid; + + for (auto &arg : command) + argv.push_back(&arg[0]); + argv.push_back(nullptr); + + if (pipe(send) != 0) { + log_error("pipe failed: %s\n", strerror(errno)); + goto cleanup_exec; + } + if (pipe(recv) != 0) { + log_error("pipe failed: %s\n", strerror(errno)); + goto cleanup_exec; + } + + if (posix_spawn_file_actions_init(&file_actions) != 0) { + log_error("posix_spawn_file_actions_init failed: %s\n", strerror(errno)); + goto cleanup_exec; + } + file_actions_p = &file_actions; + if (posix_spawn_file_actions_adddup2(file_actions_p, send[0], STDIN_FILENO) != 0) { + log_error("posix_spawn_file_actions_adddup2 failed: %s\n", strerror(errno)); + goto cleanup_exec; + } + if (posix_spawn_file_actions_addclose(file_actions_p, send[1]) != 0) { + log_error("posix_spawn_file_actions_addclose failed: %s\n", strerror(errno)); + goto cleanup_exec; + } + if (posix_spawn_file_actions_adddup2(file_actions_p, recv[1], STDOUT_FILENO) != 0) { + log_error("posix_spawn_file_actions_adddup2 failed: %s\n", strerror(errno)); + goto cleanup_exec; + } + if (posix_spawn_file_actions_addclose(file_actions_p, recv[0]) != 0) { + log_error("posix_spawn_file_actions_addclose failed: %s\n", strerror(errno)); + goto cleanup_exec; + } + + if (posix_spawnp(&pid, argv[0], file_actions_p, /*attrp=*/NULL, argv.data(), environ) != 0) { + log_error("posix_spawnp failed: %s\n", strerror(errno)); + goto cleanup_exec; + } + + server = std::make_shared(command_line, send[1], recv[0], pid); + send[1] = -1; + recv[0] = -1; + +cleanup_exec: + if (send[0] != -1) close(send[0]); + if (send[1] != -1) close(send[1]); + if (recv[0] != -1) close(recv[0]); + if (recv[1] != -1) close(recv[1]); + if (file_actions_p != NULL) + posix_spawn_file_actions_destroy(file_actions_p); +#endif + } else if (!path.empty()) { +#ifdef _WIN32 + std::wstring path_w = str2wstr(path); + HANDLE h; + + h = CreateFileW(path_w.c_str(), GENERIC_READ|GENERIC_WRITE, /*dwShareMode=*/0, /*lpSecurityAttributes=*/NULL, /*dwCreationDisposition=*/OPEN_EXISTING, /*dwFlagsAndAttributes=*/0, /*hTemplateFile=*/NULL); + if (h == INVALID_HANDLE_VALUE) { + log_error("CreateFileW failed: %s\n", get_last_error_str()); + goto cleanup_path; + } + + server = std::make_shared(path, h, h); + +cleanup_path: + ; +#else + struct sockaddr_un addr; + addr.sun_family = AF_UNIX; + strncpy(addr.sun_path, path.c_str(), sizeof(addr.sun_path) - 1); + + int fd = socket(AF_UNIX, SOCK_STREAM, 0); + if (fd == -1) { + log_error("socket failed: %s\n", strerror(errno)); + goto cleanup_path; + } + + if (connect(fd, (struct sockaddr *)&addr, sizeof(addr)) != 0) { + log_error("connect failed: %s\n", strerror(errno)); + goto cleanup_path; + } + + server = std::make_shared(path, fd, fd); + fd = -1; + +cleanup_path: + if (fd != -1) close(fd); +#endif + } + + if (!server) + log_cmd_error("Failed to connect to RPC frontend.\n"); + + for (auto &module_name : server->get_module_names()) { + log("Linking module `%s'.\n", module_name); + RpcModule *module = new RpcModule(design); + module->name = design->twines().add("$abstract\\" + module_name); + module->server = server; + design->add(module); + } + } +} RpcFrontend; + +YOSYS_NAMESPACE_END diff --git a/chips/yosys/frontends/rtlil/.gitignore b/chips/yosys/frontends/rtlil/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..d4a3227560601923d512a8e1c4e19885f0466f88 --- /dev/null +++ b/chips/yosys/frontends/rtlil/.gitignore @@ -0,0 +1,4 @@ +rtlil_lexer.cc +rtlil_parser.output +rtlil_parser.tab.cc +rtlil_parser.tab.hh diff --git a/chips/yosys/frontends/rtlil/CMakeLists.txt b/chips/yosys/frontends/rtlil/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..57f9d9284875e33aa2d12fe8c1c23d0c74c6c9bc --- /dev/null +++ b/chips/yosys/frontends/rtlil/CMakeLists.txt @@ -0,0 +1,3 @@ +yosys_frontend(rtlil + rtlil_frontend.cc +) diff --git a/chips/yosys/frontends/rtlil/rtlil_frontend.cc b/chips/yosys/frontends/rtlil/rtlil_frontend.cc new file mode 100644 index 0000000000000000000000000000000000000000..8f9da0e6f12300e13cfe5454fe38ef53461d3baa --- /dev/null +++ b/chips/yosys/frontends/rtlil/rtlil_frontend.cc @@ -0,0 +1,1139 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * --- + * + * A handwritten recursive-descent parser for the RTLIL text representation. + * + */ + +#include "kernel/register.h" +#include "kernel/log.h" +#include "kernel/rtlil.h" +#include "kernel/utils.h" +#include "kernel/twine.h" +#include +#include +#include + +YOSYS_NAMESPACE_BEGIN + +struct RTLILFrontendWorker { + std::istream *f = nullptr; + RTLIL::Design *design; + bool flag_nooverwrite = false; + bool flag_overwrite = false; + bool flag_lib = false; + bool flag_legalize = false; + + int line_num; + std::string line_buf; + // Substring of line_buf. Always newline-terminated, thus never empty. + std::string_view line; + + RTLIL::Module *current_module; + dict attrbuf; + std::vector*> switch_stack; + std::vector case_stack; + + dict twine_remap; + std::vector twine_parser_holds; + + struct TwineDesc { + enum Kind { Root, Suffix } kind; + std::string text; + size_t parent = 0; + bool materializing = false; + }; + dict twine_descs; + + + + template + [[noreturn]] + void error(FmtString...> fmt, const Args &... args) + { + log_error("Parser error in line %d: %s\n", line_num, fmt.format(args...)); + } + + template + void warning(FmtString...> fmt, const Args &... args) + { + log_warning("In line %d: %s\n", line_num, fmt.format(args...)); + } + + // May return an empty line if the stream is not good(). + void advance_to_next_nonempty_line() + { + if (!f->good()) { + line = "\n"; + return; + } + while (true) { + std::getline(*f, line_buf); + line_num++; + if (line_buf.empty() || line_buf[line_buf.size() - 1] != '\n') + line_buf += '\n'; + line = line_buf; + consume_whitespace_and_comments(); + if (line[0] != '\n' || !f->good()) + break; + } + } + + void consume_whitespace_and_comments() + { + while (true) { + switch (line[0]) { + case ' ': + case '\t': + line = line.substr(1); + break; + case '#': + line = "\n"; + return; + default: + return; + } + } + } + + bool try_parse_keyword(std::string_view keyword) + { + int keyword_size = keyword.size(); + if (keyword != line.substr(0, keyword_size)) + return false; + // This index is safe because `line` is always newline-terminated + // and `keyword` never contains a newline. + char ch = line[keyword_size]; + if (ch >= 'a' && ch <= 'z') + return false; + line = line.substr(keyword_size); + consume_whitespace_and_comments(); + return true; + } + + std::string error_token() + { + std::string result; + for (char ch : line) { + if (ch == '\n' || ch == ' ' || ch == '\t') + break; + result += ch; + } + return result; + } + + void expect_keyword(std::string_view keyword) + { + if (!try_parse_keyword(keyword)) + error("Expected token `%s', got `%s'.", keyword, error_token()); + } + + bool try_parse_char(char ch) + { + if (line[0] != ch) + return false; + line = line.substr(1); + consume_whitespace_and_comments(); + return true; + } + + void expect_char(char ch) + { + if (!try_parse_char(ch)) + error("Expected `%c', got `%s'.", ch, error_token()); + } + + bool try_parse_eol() + { + if (line[0] != '\n') + return false; + advance_to_next_nonempty_line(); + return true; + } + + void expect_eol() + { + if (!try_parse_eol()) + error("Expected EOL, got `%s'.", error_token()); + } + + std::optional try_parse_id() + { + char ch = line[0]; + if (ch != '\\' && ch != '$') + return std::nullopt; + int idx = 1; + while (true) { + ch = line[idx]; + if (ch <= ' ' && (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r')) + break; + ++idx; + } + std::string result(line.substr(0, idx)); + line = line.substr(idx); + consume_whitespace_and_comments(); + return result; + } + + std::string parse_id() + { + std::optional id = try_parse_id(); + if (!id.has_value()) + error("Expected ID, got `%s'.", error_token()); + return std::move(*id); + } + + long long parse_integer() + { + long long result = parse_integer_alone(); + consume_whitespace_and_comments(); + return result; + } + + long long parse_integer_alone() + { + int idx = 0; + if (line[idx] == '-') + ++idx; + while (true) { + char ch = line[idx]; + if (ch < '0' || ch > '9') + break; + ++idx; + } + long long result; + if (std::from_chars(line.data(), line.data() + idx, result, 10).ec != std::errc{}) + error("Invalid integer `%s'.", error_token()); + line = line.substr(idx); + return result; + } + + std::string parse_string() + { + if (line[0] != '\"') + error("Expected string, got `%s'.", error_token()); + std::string str; + int idx = 1; + while (true) { + int start_idx = idx; + char ch; + while (true) { + ch = line[idx]; + if (ch == '"' || ch == '\n' || ch == '\\' || ch == 0) + break; + ++idx; + } + str.append(line.data() + start_idx, line.data() + idx); + ++idx; + if (ch == '"') + break; + if (ch == 0) + error("Null byte in string literal: `%s'.", line); + if (ch == '\n') + error("Unterminated string literal: `%s'.", line); + ch = line[idx++]; + if (ch == 'n') { + ch = '\n'; + } else if (ch == 't') { + ch = '\t'; + } else if (ch >= '0' && ch <= '7') { + int v = ch - '0'; + char next_ch = line[idx + 1]; + if (next_ch >= '0' && next_ch <= '7') { + ++idx; + v = v*8 + (next_ch - '0'); + next_ch = line[idx + 1]; + if (next_ch >= '0' && next_ch <= '7') { + ++idx; + v = v*8 + (next_ch - '0'); + } + } + ch = v; + } + str += ch; + } + line = line.substr(idx); + consume_whitespace_and_comments(); + return str; + } + + RTLIL::Const parse_const() + { + if (line[0] == '"') + return RTLIL::Const(parse_string()); + + bool negative_value = line[0] == '-'; + long long width = parse_integer_alone(); + // Can't test value<0 here because we need to stop parsing after '-0' + if (negative_value || line[0] != '\'') { + if (width < INT_MIN || width > INT_MAX) + error("Integer %lld out of range before `%s'.", width, error_token()); + consume_whitespace_and_comments(); + return RTLIL::Const(width); + } + + int idx = 1; + bool is_signed = line[1] == 's'; + if (is_signed) + ++idx; + + std::vector bits; + if (width >= RTLIL::WIDTH_LIMIT) + error("Constant width %lld out of range before `%s`.", width, error_token()); + bits.reserve(width); + int start_idx = idx; + while (true) { + RTLIL::State bit; + switch (line[idx]) { + case '0': bit = RTLIL::S0; break; + case '1': bit = RTLIL::S1; break; + case 'x': bit = RTLIL::Sx; break; + case 'z': bit = RTLIL::Sz; break; + case 'm': bit = RTLIL::Sm; break; + case '-': bit = RTLIL::Sa; break; + default: goto done; + } + bits.push_back(bit); + ++idx; + } + done: + if (start_idx < idx) + std::reverse(bits.begin(), bits.end()); + + if (GetSize(bits) > width) + bits.resize(width); + else if (GetSize(bits) < width) { + RTLIL::State extbit = RTLIL::Sx; + if (!bits.empty()) { + extbit = bits.back(); + if (extbit == RTLIL::S1) + extbit = RTLIL::S0; + } + bits.resize(width, extbit); + } + + RTLIL::Const val(std::move(bits)); + if (is_signed) + val.flags |= RTLIL::CONST_FLAG_SIGNED; + line = line.substr(idx); + consume_whitespace_and_comments(); + return val; + } + + RTLIL::Wire *legalize_wire(RTLIL::IdString id) + { + int wires_size = current_module->wires_size(); + if (wires_size == 0) + error("No wires found for legalization"); + int hash = hash_ops::hash(id).yield(); + RTLIL::Wire *wire = current_module->wire_at(abs(hash % wires_size)); + log("Legalizing wire `%s' to `%s'.\n", PooledName(current_module->design, id).unescape(), wire); + return wire; + } + + RTLIL::SigSpec parse_sigspec() + { + RTLIL::SigSpec sig; + + if (try_parse_char('{')) { + std::vector parts; + while (!try_parse_char('}')) + parts.push_back(parse_sigspec()); + for (auto it = parts.rbegin(); it != parts.rend(); ++it) + sig.append(std::move(*it)); + } else if (std::optional handle = try_parse_twine_handle()) { + IdString ref = *handle; + RTLIL::Wire *wire = current_module->wire(ref); + if (wire == nullptr) { + if (flag_legalize) + wire = legalize_wire(ref); + else + error("Wire %s not found.", design->twines().str(ref).c_str()); + } + sig = RTLIL::SigSpec(wire); + } else { + // We could add a special path for parsing IdStrings that must already exist, + // as here. + // We don't need to addref/release in this case. + std::optional id = try_parse_id(); + if (id.has_value()) { + RTLIL::Wire *wire = current_module->wire(design->twines().find(*id)); + if (wire == nullptr) { + if (flag_legalize) + wire = legalize_wire(design->twines().add(*id)); + else + error("Wire `%s' not found.", *id); + } + sig = RTLIL::SigSpec(wire); + } else { + sig = RTLIL::SigSpec(parse_const()); + } + } + + while (try_parse_char('[')) { + int left = parse_integer(); + if (left >= sig.size() || left < 0) { + if (flag_legalize) { + int legalized; + if (sig.size() == 0) + legalized = 0; + else + legalized = std::max(0, std::min(left, sig.size() - 1)); + log("Legalizing bit index %d to %d.\n", left, legalized); + left = legalized; + } else { + error("bit index %d out of range", left); + } + } + if (try_parse_char(':')) { + int right = parse_integer(); + if (right < 0) { + if (flag_legalize) { + log("Legalizing bit index %d to %d.\n", right, 0); + right = 0; + } else + error("bit index %d out of range", right); + } + if (left < right) { + if (flag_legalize) { + log("Legalizing bit index %d to %d.\n", left, right); + left = right; + } else + error("invalid slice [%d:%d]", left, right); + } + if (flag_legalize && left >= sig.size()) + log("Legalizing slice %d:%d by igoring it\n", left, right); + else + sig = sig.extract(right, left - right + 1); + } else { + if (flag_legalize && left >= sig.size()) + log("Legalizing slice %d by igoring it\n", left); + else + sig = sig.extract(left); + } + expect_char(']'); + } + + return sig; + } + + void parse_module() + { + IdString module_name = parse_twine(); + expect_eol(); + + bool delete_current_module = false; + if (design->has(module_name)) { + RTLIL::Module *existing_mod = design->module(module_name); + if (!flag_overwrite && (flag_lib || (attrbuf.count(ID::blackbox) && attrbuf.at(ID::blackbox).as_bool()))) { + log("Ignoring blackbox re-definition of module %s.\n", design->twines().str(module_name)); + delete_current_module = true; + } else if (!flag_nooverwrite && !flag_overwrite && !existing_mod->get_bool_attribute(ID::blackbox)) { + error("RTLIL error: redefinition of module %s.", design->twines().str(module_name).c_str()); + } else if (flag_nooverwrite) { + log("Ignoring re-definition of module %s.\n", design->twines().str(module_name)); + delete_current_module = true; + } else { + log("Replacing existing%s module %s.\n", existing_mod->get_bool_attribute(ID::blackbox) ? " blackbox" : "", design->twines().str(module_name)); + design->remove(existing_mod); + } + } + + current_module = new RTLIL::Module(design); + current_module->name = std::move(module_name); + current_module->attributes = std::move(attrbuf); + if (!delete_current_module) + design->add(current_module); + + while (true) + { + if (try_parse_keyword("attribute")) { + parse_attribute(); + continue; + } + if (try_parse_keyword("parameter")) { + parse_parameter(); + continue; + } + if (try_parse_keyword("connect")) { + parse_connect(); + continue; + } + if (try_parse_keyword("wire")) { + parse_wire(); + continue; + } + if (try_parse_keyword("cell")) { + parse_cell(); + continue; + } + if (try_parse_keyword("memory")) { + parse_memory(); + continue; + } + if (try_parse_keyword("process")) { + parse_process(); + continue; + } + if (try_parse_keyword("end")) { + expect_eol(); + break; + } + error("Unexpected token in module body: %s", error_token()); + } + + if (attrbuf.size() != 0) + error("dangling attribute"); + current_module->fixup_ports(); + if (delete_current_module) + delete current_module; + else if (flag_lib) + current_module->makeblackbox(); + current_module = nullptr; + } + + void parse_attribute() + { + IdString id = parse_twine(); + RTLIL::Const c = parse_const(); + attrbuf.insert({std::move(id), std::move(c)}); + expect_eol(); + } + + bool static_ids_match(const std::vector &ordered_ids) + { + for (size_t id : ordered_ids) { + if (id >= STATIC_TWINE_END) + continue; + const TwineDesc &desc = twine_descs.at(id); + IdString found; + if (desc.kind == TwineDesc::Root) + found = design->twines().find(TwineSpec{TwineSpec::Root{desc.text}}); + else + found = design->twines().find(TwineSpec{TwineSpec::Suffix{ + IdString(desc.parent), desc.text}}); + if (found == IdString::Null || found.untag().raw() != id) + return false; + } + return true; + } + + IdString resolve_file_twine(size_t id, bool is_public = false) + { + return materialize_file_twine(id).tag(is_public); + } + + IdString materialize_file_twine(size_t id) + { + auto rit = twine_remap.find(id); + if (rit != twine_remap.end()) + return rit->second; + auto dit = twine_descs.find(id); + if (dit == twine_descs.end()) { + if (id < STATIC_TWINE_END) + return IdString(id); + error("Unknown twine reference @%zu at line %d", id, line_num); + } + TwineDesc &desc = dit->second; + if (desc.materializing) + error("Cyclic twine reference @%zu at line %d", id, line_num); + desc.materializing = true; + IdString ref; + switch (desc.kind) { + case TwineDesc::Root: + ref = design->twines().add(TwineSpec::Root{desc.text}); + break; + case TwineDesc::Suffix: + ref = design->twines().add(TwineSpec::Suffix{ + materialize_file_twine(desc.parent), + desc.text}); + break; + } + desc.materializing = false; + twine_remap[id] = ref; + return ref; + } + + std::optional try_parse_twine_handle() + { + bool is_public; + size_t prefix = IdString::handle_token_prefix(line, is_public); + if (prefix == 0) + return std::nullopt; + line = line.substr(prefix); + return resolve_file_twine(parse_integer(), is_public); + } + + std::optional try_parse_twine() + { + if (std::optional handle = try_parse_twine_handle()) + return handle; + std::optional id = try_parse_id(); + if (!id) + return std::nullopt; + return design->twines().add(std::move(*id)); + } + + IdString parse_twine() + { + std::optional t = try_parse_twine(); + if (!t) + error("Expected twine reference or ID, got `%s'.", error_token()); + return *t; + } + + void parse_twines() + { + expect_eol(); + while (true) { + if (try_parse_keyword("end")) + break; + if (try_parse_keyword("root")) { + size_t file_id = parse_integer(); + TwineDesc &desc = twine_descs[file_id]; + desc.kind = TwineDesc::Root; + desc.text = parse_string(); + expect_eol(); + continue; + } + if (try_parse_keyword("suffix")) { + size_t file_id = parse_integer(); + TwineDesc &desc = twine_descs[file_id]; + desc.kind = TwineDesc::Suffix; + desc.parent = parse_integer(); + desc.text = parse_string(); + expect_eol(); + continue; + } + error("Expected `root` or `suffix` inside twines block, got `%s'.", + error_token()); + } + std::vector ordered_ids; + ordered_ids.reserve(twine_descs.size()); + for (auto &it : twine_descs) + ordered_ids.push_back(it.first); + std::sort(ordered_ids.begin(), ordered_ids.end()); + if (static_ids_match(ordered_ids)) { + std::vector dynamic_ids; + dynamic_ids.reserve(ordered_ids.size()); + for (size_t id : ordered_ids) { + if (id < STATIC_TWINE_END) + twine_descs.erase(id); + else + dynamic_ids.push_back(id); + } + ordered_ids.swap(dynamic_ids); + } + for (size_t id : ordered_ids) + materialize_file_twine(id); + twine_descs.clear(); + expect_eol(); + } + + void parse_metadata() + { + expect_eol(); + while (!try_parse_keyword("end")) { + if (try_parse_keyword("twines")) + parse_twines(); + else + error("Unexpected section `%s' in metadata block.", error_token()); + } + expect_eol(); + } + + void parse_parameter() + { + IdString id = parse_twine(); + current_module->avail_parameters(id); + if (try_parse_eol()) + return; + RTLIL::Const c = parse_const(); + current_module->parameter_default_values.insert({std::move(id), std::move(c)}); + expect_eol(); + } + + void parse_wire() + { + RTLIL::Wire *wire; + int width = 1; + int start_offset = 0; + int port_id = 0; + bool port_input = false; + bool port_output = false; + bool upto = false; + bool is_signed = false; + + while (true) + { + std::optional name = try_parse_twine(); + if (name) { + IdString wire_name = *name; + if (current_module->wire(wire_name) != nullptr) { + if (flag_legalize) { + log("Legalizing redefinition of wire %s.\n", design->twines().str(wire_name)); + pool wires = {current_module->wire(wire_name)}; + current_module->remove(wires); + } else + error("RTLIL error: redefinition of wire %s.", design->twines().str(wire_name).c_str()); + } + wire = current_module->addWire(wire_name); + break; + } + if (try_parse_keyword("width")){ + long long width_val = parse_integer(); + if (width_val < 0 || width_val >= RTLIL::WIDTH_LIMIT) + error("Wire width %lld out of range before `%s`.", width_val, error_token()); + width = width_val; + } + else if (try_parse_keyword("upto")) + upto = true; + else if (try_parse_keyword("signed")) + is_signed = true; + else if (try_parse_keyword("offset")) { + long long offset_val = parse_integer(); + if (offset_val < INT_MIN || offset_val > INT_MAX) + error("Wire offset %lld out of range before `%s`.", offset_val, error_token()); + start_offset = offset_val; + } + else if (try_parse_keyword("input")) { + port_id = parse_integer(); + port_input = true; + } else if (try_parse_keyword("output")) { + port_id = parse_integer(); + port_output = true; + } else if (try_parse_keyword("inout")) { + port_id = parse_integer(); + port_input = true; + port_output = true; + } else if (try_parse_eol()) + error("Missing wire ID"); + else + error("Unexpected wire option: %s", error_token()); + } + + wire->attributes = std::move(attrbuf); + wire->width = width; + wire->upto = upto; + wire->start_offset = start_offset; + wire->is_signed = is_signed; + wire->port_id = port_id; + wire->port_input = port_input; + wire->port_output = port_output; + expect_eol(); + } + + void parse_memory() + { + RTLIL::Memory *memory = new RTLIL::Memory(current_module); + memory->attributes = std::move(attrbuf); + + int width = 1; + int start_offset = 0; + int size = 0; + IdString mem_name; + while (true) + { + std::optional name = try_parse_twine(); + if (name.has_value()) { + mem_name = *name; + if (current_module->memories.count(mem_name) != 0) { + if (flag_legalize) { + log("Legalizing redefinition of memory %s.\n", design->twines().str(mem_name)); + current_module->remove(current_module->memories.at(mem_name)); + } else + error("RTLIL error: redefinition of memory %s.", design->twines().str(mem_name).c_str()); + } + memory->name = mem_name; + break; + } + if (try_parse_keyword("width")){ + long long width_val = parse_integer(); + if (width_val < 0 || width_val >= RTLIL::WIDTH_LIMIT) + error("Memory width %lld out of range before `%s`.", width_val, error_token()); + width = width_val; + } + else if (try_parse_keyword("size")) { + long long size_val = parse_integer(); + if (size_val < INT_MIN || size_val > INT_MAX) + error("Memory size %lld out of range before `%s`.", size_val, error_token()); + size = size_val; + } + else if (try_parse_keyword("offset")) { + long long offset_val = parse_integer(); + if (offset_val < INT_MIN || offset_val > INT_MAX) + error("Memory offset %lld out of range before `%s`.", offset_val, error_token()); + start_offset = offset_val; + } + else if (try_parse_eol()) + error("Missing memory ID"); + else + error("Unexpected memory option: %s", error_token()); + } + memory->width = width; + memory->start_offset = start_offset; + memory->size = size; + memory->module = current_module; + current_module->memories.insert({mem_name, memory}); + expect_eol(); + } + + void legalize_width_parameter(RTLIL::Cell *cell, RTLIL::IdString port_name) + { + IdString width_param = design->twines().find(design->twines().str(port_name) + "_WIDTH"); + if (width_param == IdString::Null || cell->parameters.count(width_param) == 0) + return; + RTLIL::Const ¶m = cell->parameters.at(width_param); + if (param.as_int() != 0) + return; + cell->parameters[width_param] = RTLIL::Const(cell->getPort(port_name).size()); + } + + void parse_cell() + { + IdString cell_type_ref = parse_twine(); + IdString cell_name_ref = parse_twine(); + expect_eol(); + + if (current_module->cell(cell_name_ref) != nullptr) { + if (flag_legalize) { + std::string base = design->twines().str(cell_name_ref); + std::string new_name_str; + int suffix = 1; + do { + new_name_str = base + "_" + std::to_string(suffix); + cell_name_ref = design->twines().add(new_name_str); + ++suffix; + } while (current_module->cell(cell_name_ref) != nullptr); + log("Legalizing redefinition of cell %s by renaming to %s.\n", base, new_name_str); + } else + error("RTLIL error: redefinition of cell %s.", design->twines().str(cell_name_ref).c_str()); + } + RTLIL::Cell *cell = current_module->addCell(cell_name_ref, cell_type_ref); + cell->attributes = std::move(attrbuf); + + while (true) + { + if (try_parse_keyword("parameter")) { + bool is_signed = false; + bool is_real = false; + bool is_unsized = false; + if (try_parse_keyword("signed")) { + is_signed = true; + } else if (try_parse_keyword("real")) { + is_real = true; + } else if (try_parse_keyword("unsized")) { + is_unsized = true; + } + IdString param_name = parse_twine(); + RTLIL::Const val = parse_const(); + if (is_signed) + val.flags |= RTLIL::CONST_FLAG_SIGNED; + if (is_real) + val.flags |= RTLIL::CONST_FLAG_REAL; + if (is_unsized) + val.flags |= RTLIL::CONST_FLAG_UNSIZED; + cell->parameters.insert({std::move(param_name), std::move(val)}); + expect_eol(); + } else if (try_parse_keyword("connect")) { + IdString port_name = parse_twine(); + if (cell->hasPort(port_name)) { + if (flag_legalize) + log("Legalizing redefinition of cell port %s.\n", design->twines().str(port_name)); + else + error("RTLIL error: redefinition of cell port %s.", design->twines().str(port_name).c_str()); + } + cell->setPort(port_name, parse_sigspec()); + if (flag_legalize) + legalize_width_parameter(cell, port_name); + expect_eol(); + } else if (try_parse_keyword("end")) { + expect_eol(); + break; + } else { + error("Unexpected token in cell body: %s", error_token()); + } + } + } + + void parse_connect() + { + if (attrbuf.size() != 0) + error("dangling attribute"); + RTLIL::SigSpec s1 = parse_sigspec(); + RTLIL::SigSpec s2 = parse_sigspec(); + if (flag_legalize) { + int min_size = std::min(s1.size(), s2.size()); + s1 = s1.extract(0, min_size); + s2 = s2.extract(0, min_size); + } + current_module->connect(std::move(s1), std::move(s2)); + expect_eol(); + } + + void parse_case_body(RTLIL::CaseRule *current_case) + { + while (true) + { + if (try_parse_keyword("attribute")) + parse_attribute(); + else if (try_parse_keyword("switch")) + parse_switch(); + else if (try_parse_keyword("assign")) { + if (attrbuf.size() != 0) + error("dangling attribute"); + // See https://github.com/YosysHQ/yosys/pull/4765 for discussion on this + // warning + if (!switch_stack.back()->empty()) + warning("case rule assign statements after switch statements may cause unexpected behaviour. " + "The assign statement is reordered to come before all switch statements."); + RTLIL::SigSpec s1 = parse_sigspec(); + RTLIL::SigSpec s2 = parse_sigspec(); + current_case->actions.push_back({std::move(s1), std::move(s2)}); + expect_eol(); + } else + return; + } + } + + void parse_switch() + { + RTLIL::SwitchRule *rule = new RTLIL::SwitchRule; + rule->signal = parse_sigspec(); + rule->attributes = std::move(attrbuf); + switch_stack.back()->push_back(rule); + expect_eol(); + + while (true) { + if (try_parse_keyword("attribute")) { + parse_attribute(); + continue; + } + + if (try_parse_keyword("end")) { + expect_eol(); + break; + } + + expect_keyword("case"); + RTLIL::CaseRule *case_rule = new RTLIL::CaseRule; + case_rule->attributes = std::move(attrbuf); + rule->cases.push_back(case_rule); + switch_stack.push_back(&case_rule->switches); + case_stack.push_back(case_rule); + + if (!try_parse_eol()) { + while (true) { + case_rule->compare.push_back(parse_sigspec()); + if (try_parse_eol()) + break; + expect_char(','); + } + } + + parse_case_body(case_rule); + + switch_stack.pop_back(); + case_stack.pop_back(); + } + } + + void parse_process() + { + IdString proc_name = parse_twine(); + expect_eol(); + + if (current_module->processes.count(proc_name) != 0) { + if (flag_legalize) { + log("Legalizing redefinition of process %s.\n", design->twines().str(proc_name)); + current_module->remove(current_module->processes.at(proc_name)); + } else + error("RTLIL error: redefinition of process %s.", design->twines().str(proc_name).c_str()); + } + RTLIL::Process *proc = current_module->addProcess(std::move(proc_name)); + proc->attributes = std::move(attrbuf); + + switch_stack.clear(); + switch_stack.push_back(&proc->root_case.switches); + case_stack.clear(); + case_stack.push_back(&proc->root_case); + + parse_case_body(&proc->root_case); + + while (try_parse_keyword("sync")) + { + RTLIL::SyncRule *rule = new RTLIL::SyncRule; + + if (try_parse_keyword("low")) rule->type = RTLIL::ST0; + else if (try_parse_keyword("high")) rule->type = RTLIL::ST1; + else if (try_parse_keyword("posedge")) rule->type = RTLIL::STp; + else if (try_parse_keyword("negedge")) rule->type = RTLIL::STn; + else if (try_parse_keyword("edge")) rule->type = RTLIL::STe; + else if (try_parse_keyword("always")) rule->type = RTLIL::STa; + else if (try_parse_keyword("global")) rule->type = RTLIL::STg; + else if (try_parse_keyword("init")) rule->type = RTLIL::STi; + else error("Unexpected sync type: %s", error_token()); + + if (rule->type != RTLIL::STa && rule->type != RTLIL::STg && rule->type != RTLIL::STi) + rule->signal = parse_sigspec(); + proc->syncs.push_back(rule); + expect_eol(); + + bool attributes_in_update_list = false; + while (true) + { + if (try_parse_keyword("update")) { + RTLIL::SigSpec s1 = parse_sigspec(); + RTLIL::SigSpec s2 = parse_sigspec(); + rule->actions.push_back({std::move(s1), std::move(s2)}); + expect_eol(); + continue; + } + + if (try_parse_keyword("attribute")) { + attributes_in_update_list = true; + parse_attribute(); + continue; + } + + if (!try_parse_keyword("memwr")) + break; + + RTLIL::MemWriteAction act; + act.attributes = std::move(attrbuf); + act.memid = parse_twine(); + act.address = parse_sigspec(); + act.data = parse_sigspec(); + act.enable = parse_sigspec(); + act.priority_mask = parse_const(); + rule->mem_write_actions.push_back(std::move(act)); + expect_eol(); + } + // The old parser allowed dangling attributes before a "sync" to carry through + // the "sync", so we will too, for now. + if (attributes_in_update_list && attrbuf.size() > 0) + error("dangling attribute"); + } + + expect_keyword("end"); + expect_eol(); + } + + RTLILFrontendWorker(RTLIL::Design *design) : design(design) {} + + void parse(std::istream *f) + { + this->f = f; + line_num = 0; + advance_to_next_nonempty_line(); + while (f->good()) + { + if (try_parse_keyword("attribute")) { + parse_attribute(); + continue; + } + if (try_parse_keyword("module")) { + parse_module(); + continue; + } + if (try_parse_keyword("autoidx")) { + design->twines().ensure_autoidx(parse_integer()); + expect_eol(); + continue; + } + if (try_parse_keyword("metadata")) { + parse_metadata(); + continue; + } + error("Unexpected token: %s", error_token()); + } + if (attrbuf.size() != 0) + error("dangling attribute"); + + twine_parser_holds.clear(); + twine_remap.clear(); + } +}; + +struct RTLILFrontend : public Frontend { + RTLILFrontend() : Frontend("rtlil", "read modules from RTLIL file") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" read_rtlil [filename]\n"); + log("\n"); + log("Load modules from an RTLIL file to the current design. (RTLIL is a text\n"); + log("representation of a design in yosys's internal format.)\n"); + log("\n"); + log(" -nooverwrite\n"); + log(" ignore re-definitions of modules. (the default behavior is to\n"); + log(" create an error message if the existing module is not a blackbox\n"); + log(" module, and overwrite the existing module if it is a blackbox module.)\n"); + log("\n"); + log(" -overwrite\n"); + log(" overwrite existing modules with the same name\n"); + log("\n"); + log(" -lib\n"); + log(" only create empty blackbox modules\n"); + log("\n"); + log(" -legalize\n"); + log(" prevent semantic errors (e.g. reference to unknown wire, redefinition of wire/cell)\n"); + log(" by deterministically rewriting the input into something valid. Useful when using\n"); + log(" fuzzing to generate random but valid RTLIL.\n"); + log("\n"); + } + void execute(std::istream *&f, std::string filename, std::vector args, RTLIL::Design *design) override + { + RTLILFrontendWorker worker(design); + + log_header(design, "Executing RTLIL frontend.\n"); + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) { + std::string arg = args[argidx]; + if (arg == "-nooverwrite") { + worker.flag_nooverwrite = true; + worker.flag_overwrite = false; + continue; + } + if (arg == "-overwrite") { + worker.flag_nooverwrite = false; + worker.flag_overwrite = true; + continue; + } + if (arg == "-lib") { + worker.flag_lib = true; + continue; + } + if (arg == "-legalize") { + worker.flag_legalize = true; + continue; + } + break; + } + extra_args(f, filename, args, argidx); + + log("Input filename: %s\n", filename); + + worker.parse(f); + } +} RTLILFrontend; + +YOSYS_NAMESPACE_END diff --git a/chips/yosys/frontends/slang/CMakeLists.txt b/chips/yosys/frontends/slang/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..6fc02e24d16a6b486d3c71c0a34ebd014a057c13 --- /dev/null +++ b/chips/yosys/frontends/slang/CMakeLists.txt @@ -0,0 +1,47 @@ +include(lib/cmake/GitRevision.cmake) +git_rev_parse(YOSYS_SLANG_REVISION ${CMAKE_CURRENT_SOURCE_DIR}/lib) +git_rev_parse(SLANG_REVISION ${PROJECT_SOURCE_DIR}/libs/slang) +configure_file(${CMAKE_CURRENT_SOURCE_DIR}/lib/src/version.h.in ${CMAKE_CURRENT_BINARY_DIR}/version.h) + +yosys_frontend(slang + lib/src/yosys_plugin/abort_helpers.cc + lib/src/yosys_plugin/backend_builder.cc + lib/src/yosys_plugin/backend_builder.h + lib/src/yosys_plugin/blackboxes.cc + lib/src/yosys_plugin/cases.cc + lib/src/yosys_plugin/cases.h + lib/src/yosys_plugin/driver.cc + lib/src/yosys_plugin/ir.cc + lib/src/yosys_plugin/ir.h + lib/src/yosys_plugin/sva.cc + lib/src/addressing.cc + lib/src/async_pattern.cc + lib/src/async_pattern.h + lib/src/builder.cc + lib/src/diag.cc + lib/src/diag.h + lib/src/initialization.cc + lib/src/lvalue.cc + lib/src/memory.h + lib/src/naming.cc + lib/src/procedural.cc + lib/src/slang_frontend.cc + lib/src/slang_frontend.h + lib/src/statements.h + lib/src/variables.cc + lib/src/variables.h + ${CMAKE_CURRENT_BINARY_DIR}/version.h + DEFINITIONS + YOSYS_MAJOR=${YOSYS_VERSION_MAJOR} + YOSYS_MINOR=${YOSYS_VERSION_MINOR} + YOSYS_COMMIT=${YOSYS_VERSION_COMMIT} + ENABLE_IF + YOSYS_ENABLE_SLANG + INCLUDE_DIRS + ${CMAKE_CURRENT_SOURCE_DIR}/lib/src + ${CMAKE_CURRENT_SOURCE_DIR}/lib/third_party/hashlib + ${CMAKE_CURRENT_SOURCE_DIR}/lib/src/yosys_plugin + ${CMAKE_CURRENT_BINARY_DIR} + LIBRARIES + $<${YOSYS_ENABLE_SLANG}:slang::slang> +) diff --git a/chips/yosys/frontends/verific/CMakeLists.txt b/chips/yosys/frontends/verific/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..82e4fcf19c91ddf4481ba744906888bba78b9744 --- /dev/null +++ b/chips/yosys/frontends/verific/CMakeLists.txt @@ -0,0 +1,79 @@ +if (NOT YOSYS_ENABLE_VERIFIC) + # Stub interface library. + add_library(verific INTERFACE) + set(verific_data_files) +else() + if (NOT YOSYS_VERIFIC_COMPONENTS) + get_verific_components(YOSYS_VERIFIC_COMPONENTS) + endif() + + if (NOT YOSYS_VERIFIC_FEATURES) + foreach (component ${YOSYS_VERIFIC_COMPONENTS}) + if (component MATCHES "^(hier_tree|vhdl|edif|extensions)$") + list(APPEND YOSYS_VERIFIC_FEATURES ${component}) + elseif (component STREQUAL "verilog") + list(APPEND YOSYS_VERIFIC_FEATURES systemverilog) + elseif (component STREQUAL "synlib") + list(APPEND YOSYS_VERIFIC_FEATURES liberty) + endif() + endforeach() + endif() + + message(STATUS "Verific library components: ${YOSYS_VERIFIC_COMPONENTS}") + message(STATUS "Verific frontend features: ${YOSYS_VERIFIC_FEATURES}") + + get_verific_options(verific_include_dirs verific_libraries ${YOSYS_VERIFIC_COMPONENTS}) + add_library(verific INTERFACE) + target_include_directories(verific INTERFACE + ${verific_include_dirs} + ) + target_link_libraries(verific INTERFACE + $ + PkgConfig::zlib + ) + + set(verific_data_files) + if ("vhdl" IN_LIST YOSYS_VERIFIC_FEATURES) + foreach (vdb_std 1987 1993 2008 2019) + set(vdb_std_root ${YOSYS_VERIFIC_DIR}/vhdl_packages/vdbs_${vdb_std}) + file(GLOB_RECURSE vdb_files RELATIVE ${vdb_std_root} ${vdb_std_root}/*) + foreach (vdb_file ${vdb_files}) + list(APPEND verific_data_files + verific/vhdl_vdbs_${vdb_std}/${vdb_file} + ${YOSYS_VERIFIC_DIR}/vhdl_packages/vdbs_${vdb_std}/${vdb_file} + ) + endforeach() + endforeach() + endif() +endif() + +yosys_frontend(verific + read.cc + verific.cc + verific.h + verific_pass.cc + $<${YOSYS_ENABLE_VERIFIC}:verific_clocking.cc> + $<${YOSYS_ENABLE_VERIFIC}:verific_clocking.h> + $<${YOSYS_ENABLE_VERIFIC}:verific_command.cc> + $<${YOSYS_ENABLE_VERIFIC}:verific_command.h> + $<${YOSYS_ENABLE_VERIFIC}:verific_extnets.cc> + $<${YOSYS_ENABLE_VERIFIC}:verific_importer.cc> + $<${YOSYS_ENABLE_VERIFIC}:verific_importer.h> + $<${YOSYS_ENABLE_VERIFIC}:verificsva.cc> + DEFINITIONS + $<$:VERIFIC_HIER_TREE_SUPPORT> + $<$:VERIFIC_SYSTEMVERILOG_SUPPORT> + $<$:VERIFIC_VHDL_SUPPORT> + $<$:VERIFIC_EDIF_SUPPORT> + $<$:VERIFIC_LIBERTY_SUPPORT> + $<$:YOSYSHQ_VERIFIC_EXTENSIONS> + LIBRARIES + verific + REQUIRES + sha1 + read_verilog + PROVIDES + read + DATA_EXPLICIT + ${verific_data_files} +) diff --git a/chips/yosys/frontends/verific/README b/chips/yosys/frontends/verific/README new file mode 100644 index 0000000000000000000000000000000000000000..84afaa9fde6e91590f89d3846234eb35da2f4e0a --- /dev/null +++ b/chips/yosys/frontends/verific/README @@ -0,0 +1,36 @@ + +This directory contains Verific bindings for Yosys. + +Use Tabby CAD Suite from YosysHQ if you need Yosys+Verific. +https://www.yosyshq.com/ + +Contact YosysHQ at contact@yosyshq.com for free evaluation +binaries of Tabby CAD Suite. + + +Verific Features that should be enabled in your Verific library +=============================================================== + +database/DBCompileFlags.h: + DB_PRESERVE_INITIAL_VALUE + + +Testing Verific+Yosys+SBY for formal verification +======================================================== + +Install Yosys+Verific, SBY, and Yices2. Install instructions: +https://yosyshq.readthedocs.io/projects/sby/en/latest/install.html + +Then run in the following command in this directory: + + sby -f example.sby + +This will generate approximately one page of text output. The last lines +should be something like this: + + SBY [example] summary: Elapsed clock time [H:MM:SS (secs)]: 0:00:00 (0) + SBY [example] summary: Elapsed process time [H:MM:SS (secs)]: 0:00:00 (0) + SBY [example] summary: engine_0 (smtbmc yices) returned PASS for basecase + SBY [example] summary: engine_0 (smtbmc yices) returned PASS for induction + SBY [example] summary: successful proof by k-induction. + SBY [example] DONE (PASS, rc=0) diff --git a/chips/yosys/frontends/verific/example.sby b/chips/yosys/frontends/verific/example.sby new file mode 100644 index 0000000000000000000000000000000000000000..69d56d2dd236280a508ac41d1047b6651ec8d854 --- /dev/null +++ b/chips/yosys/frontends/verific/example.sby @@ -0,0 +1,16 @@ +# Simple SBY example job utilizing Verific + +[options] +mode prove +depth 10 + +[engines] +smtbmc yices + +[script] +verific -sv example.sv +verific -import top +prep -top top + +[files] +example.sv diff --git a/chips/yosys/frontends/verific/example.sv b/chips/yosys/frontends/verific/example.sv new file mode 100644 index 0000000000000000000000000000000000000000..21a5d42c85c1100c5013bfa02244defd62f74295 --- /dev/null +++ b/chips/yosys/frontends/verific/example.sv @@ -0,0 +1,18 @@ +module top ( + input clk, rst, + output reg [3:0] cnt +); + initial cnt = 0; + + always @(posedge clk) begin + if (rst) + cnt <= 0; + else + cnt <= cnt + 4'd 1; + end + + always @(posedge clk) begin + assume (cnt != 10); + assert (cnt != 15); + end +endmodule diff --git a/chips/yosys/frontends/verific/read.cc b/chips/yosys/frontends/verific/read.cc new file mode 100644 index 0000000000000000000000000000000000000000..9393eb0c876b3ff7425a96281d974b3cd903f3b9 --- /dev/null +++ b/chips/yosys/frontends/verific/read.cc @@ -0,0 +1,235 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" + +#include "frontends/verific/verific.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct ReadPass : public Pass { + ReadPass() : Pass("read", "load HDL designs") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" read {-vlog95|-vlog2k|-sv2005|-sv2009|-sv2012|\n"); + log(" -sv2017|-sv2023|-sv|-formal} ..\n"); + log("\n"); + log("Load the specified Verilog/SystemVerilog files. (Full SystemVerilog support\n"); + log("is only available via Verific.)\n"); + log("\n"); + log("Additional -D[=] options may be added after the option indicating\n"); + log("the language version (and before file names) to set additional verilog defines.\n"); + log("\n"); + log("\n"); +#ifdef VERIFIC_VHDL_SUPPORT + log(" read {-vhdl87|-vhdl93|-vhdl2k|-vhdl2008|-vhdl2019|-vhdl} ..\n"); + log("\n"); + log("Load the specified VHDL files. (Requires Verific.)\n"); + log("\n"); + log("\n"); +#endif +#ifdef VERIFIC_EDIF_SUPPORT + log(" read {-edif} ..\n"); + log("\n"); + log("Load the specified EDIF files. (Requires Verific.)\n"); + log("\n"); + log("\n"); +#endif + log(" read {-liberty} ..\n"); + log("\n"); + log("Load the specified Liberty files.\n"); + log("\n"); + log(" -lib\n"); + log(" only create empty blackbox modules\n"); + log("\n"); + log("\n"); + log(" read {-f|-F} \n"); + log("\n"); + log("Load and execute the specified command file.\n"); + log("Check verific command for more information about supported commands in file.\n"); + log("\n"); + log("\n"); + log(" read -define [=]..\n"); + log("\n"); + log("Set global Verilog/SystemVerilog defines.\n"); + log("\n"); + log("\n"); + log(" read -undef ..\n"); + log("\n"); + log("Unset global Verilog/SystemVerilog defines.\n"); + log("\n"); + log("\n"); + log(" read -incdir \n"); + log("\n"); + log("Add directory to global Verilog/SystemVerilog include directories.\n"); + log("\n"); + log("\n"); + log(" read -verific\n"); + log(" read -noverific\n"); + log("\n"); + log("Subsequent calls to 'read' will either use or not use Verific. Calling 'read'\n"); + log("with -verific will result in an error on Yosys binaries that are built without\n"); + log("Verific support. The default is to use Verific if it is available.\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { +#ifdef YOSYS_ENABLE_VERIFIC + static bool verific_available = !check_noverific_env(); +#else + static bool verific_available = false; +#endif + static bool use_verific = verific_available; + + if (args.size() < 2 || args[1][0] != '-') + cmd_error(args, 1, "Missing mode parameter.\n"); + + if (args[1] == "-verific" || args[1] == "-noverific") { + if (args.size() != 2) + cmd_error(args, 1, "Additional arguments to -verific/-noverific.\n"); + if (args[1] == "-verific") { + if (!verific_available) + cmd_error(args, 1, "This version of Yosys is built without Verific support.\n"); + use_verific = true; + } else { + use_verific = false; + } + return; + } + + if (args.size() < 3) + cmd_error(args, 3, "Missing file name parameter.\n"); + + if (args[1] == "-vlog95" || args[1] == "-vlog2k") { + if (use_verific) { + args[0] = "verific"; + } else { + args[0] = "read_verilog"; + args[1] = "-defer"; + } + Pass::call(design, args); + return; + } + + if (args[1] == "-sv2005" || args[1] == "-sv2009" || args[1] == "-sv2012" || + args[1] == "-sv2017" || args[1] == "-sv2023" || args[1] == "-sv" || args[1] == "-formal") { + if (use_verific) { + args[0] = "verific"; + } else { + args[0] = "read_verilog"; + if (args[1] == "-formal") + args.insert(args.begin()+1, std::string()); + args[1] = "-sv"; + args.insert(args.begin()+1, "-defer"); + } + Pass::call(design, args); + return; + } + +#ifdef VERIFIC_VHDL_SUPPORT + if (args[1] == "-vhdl87" || args[1] == "-vhdl93" || args[1] == "-vhdl2k" || args[1] == "-vhdl2008" || args[1] == "-vhdl2019" || args[1] == "-vhdl") { + if (use_verific) { + args[0] = "verific"; + Pass::call(design, args); + } else { + cmd_error(args, 1, "This version of Yosys is built without Verific support.\n"); + } + return; + } +#endif +#ifdef VERIFIC_EDIF_SUPPORT + if (args[1] == "-edif") { + if (use_verific) { + args[0] = "verific"; + Pass::call(design, args); + } else { + cmd_error(args, 1, "This version of Yosys is built without Verific support.\n"); + } + return; + } +#endif + if (args[1] == "-liberty") { + if (use_verific) { + args[0] = "verific"; + } else { + args[0] = "read_liberty"; + } + Pass::call(design, args); + return; + } + if (args[1] == "-f" || args[1] == "-F") { + if (use_verific) { + args[0] = "verific"; + } else { + args[0] = "read_verilog_file_list"; + } + Pass::call(design, args); + return; + } + + if (args[1] == "-define") { + if (use_verific) { + args[0] = "verific"; + args[1] = "-vlog-define"; + Pass::call(design, args); + } + args[0] = "verilog_defines"; + args.erase(args.begin()+1, args.begin()+2); + for (int i = 1; i < GetSize(args); i++) + args[i] = "-D" + args[i]; + Pass::call(design, args); + return; + } + + if (args[1] == "-undef") { + if (use_verific) { + args[0] = "verific"; + args[1] = "-vlog-undef"; + Pass::call(design, args); + } + args[0] = "verilog_defines"; + args.erase(args.begin()+1, args.begin()+2); + for (int i = 1; i < GetSize(args); i++) + args[i] = "-U" + args[i]; + Pass::call(design, args); + return; + } + + if (args[1] == "-incdir") { + if (use_verific) { + args[0] = "verific"; + args[1] = "-vlog-incdir"; + Pass::call(design, args); + } + args[0] = "verilog_defaults"; + args[1] = "-add"; + for (int i = 2; i < GetSize(args); i++) + args[i] = "-I" + args[i]; + Pass::call(design, args); + return; + } + + cmd_error(args, 1, "Missing or unsupported mode parameter.\n"); + } +} ReadPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/frontends/verific/verific.cc b/chips/yosys/frontends/verific/verific.cc new file mode 100644 index 0000000000000000000000000000000000000000..afde411a93ee4ef2567416f858a13913680fc0b5 --- /dev/null +++ b/chips/yosys/frontends/verific/verific.cc @@ -0,0 +1,653 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" +#include "kernel/log.h" +#include +#include + +#include "frontends/verific/verific.h" +#include "frontends/verific/verific_command.h" + +USING_YOSYS_NAMESPACE + +#ifdef YOSYS_ENABLE_VERIFIC + +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Woverloaded-virtual" +#endif + +#include "Array.h" +#include "RuntimeFlags.h" +#ifdef VERIFIC_HIER_TREE_SUPPORT +#include "hier_tree.h" +#endif + +#ifdef VERIFIC_SYSTEMVERILOG_SUPPORT +#include "veri_file.h" +#include "VeriModule.h" +#include "VeriLibrary.h" +#include "VeriExpression.h" +#endif + +#ifdef VERIFIC_VHDL_SUPPORT +#include "vhdl_file.h" +#include "VhdlIdDef.h" +#include "VhdlUnits.h" +#endif + +#ifdef VERIFIC_EDIF_SUPPORT +#include "edif_file.h" +#endif + +#ifdef VERIFIC_LIBERTY_SUPPORT +#include "synlib_file.h" +#endif + +#include "VerificStream.h" +#include "FileSystem.h" + +#ifdef YOSYSHQ_VERIFIC_EXTENSIONS +#include "VerificExtensions.h" +#endif + +#ifndef YOSYSHQ_VERIFIC_API_VERSION +#warning "Only YosysHQ flavored Verific is fully supported. Please contact office@yosyshq.com for commercial support for Yosys+Verific." +#else +#if YOSYSHQ_VERIFIC_API_VERSION < 20230901 +# error "Please update your version of YosysHQ flavored Verific." +#endif +#endif + +#if !defined(VERIFIC_VHDL_SUPPORT) && !defined(VERIFIC_SYSTEMVERILOG_SUPPORT) +#error "At least one of HDL languages must be enabled." +#endif + +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + +#ifdef VERIFIC_NAMESPACE +using namespace Verific; +#endif + +#endif + +#ifdef YOSYS_ENABLE_VERIFIC +YOSYS_NAMESPACE_BEGIN + +// Verific use internally static data structures to keep current +// state, we can not mix new design with existing until current +// design is imported + +void verific_cleanup(); + +void VerificSession::begin(Design *design) +{ + std::unique_lock lock(mutex); + while (owner != nullptr && owner != design) + cv.wait(lock); + owner = design; +} + +std::unique_ptr VerificSession::deferred_end(Design *design) +{ + std::lock_guard lock(mutex); + if (owner != design) + return nullptr; + return std::make_unique(); +} + +VerificSession::~VerificSession() +{ + verific_cleanup(); + std::lock_guard lock(mutex); + owner = nullptr; + cv.notify_all(); +} + +int verific_verbose; +bool verific_import_pending; +string verific_error_msg; +int verific_sva_fsm_limit; + +const char *get_message_type(msg_type_t msg_type) +{ + switch (msg_type) { + case VERIFIC_NONE: + return "VERIFIC-NONE"; + case VERIFIC_ERROR: + return "VERIFIC-ERROR"; + case VERIFIC_WARNING: + return "VERIFIC-WARNING"; + case VERIFIC_IGNORE: + return "VERIFIC-IGNORE"; + case VERIFIC_INFO: + return "VERIFIC-INFO"; + case VERIFIC_COMMENT: + return "VERIFIC-COMMENT"; + case VERIFIC_PROGRAM_ERROR: + return "VERIFIC-PROGRAM_ERROR"; + default: + return "VERIFIC-UNKNOWN"; + } +} + +void msg_func(msg_type_t msg_type, const char *message_id, linefile_type linefile, const char *msg, va_list args) +{ + std::string id = message_id ? stringf("[%s] ",message_id) : ""; + string message = stringf("%s%s\n", id, vstringf(msg, args)); + auto src = !linefile ? LogSourceLocation{} : LogSourceLocation{LineFile::GetFileName(linefile), +#ifdef VERIFIC_LINEFILE_INCLUDES_COLUMNS + int(linefile->GetLeftLine()), int(linefile->GetLeftCol()), int(linefile->GetRightLine()), int(linefile->GetRightCol())}; +#else + int(LineFile::GetLineNo(linefile))}; +#endif + + if (log_verific_callback) { + log_verific_callback(int(msg_type), message_id, src, message.c_str()); + } else { + string message_prefix = stringf("%s: ",get_message_type(msg_type)); + if (msg_type == VERIFIC_ERROR || msg_type == VERIFIC_PROGRAM_ERROR) { + logger().formatted_nonfatal_error(src, message_prefix, "%s%s\n", message); + } else if (msg_type == VERIFIC_WARNING) { + logger().formatted_warning(src, message_prefix, "%s%s\n", message); + } else { + logger().formatted_string(LogSeverity::Info, src, message_prefix, "%s%s\n", message); + } + } + if (msg_type == VERIFIC_ERROR || msg_type == VERIFIC_PROGRAM_ERROR) + verific_error_msg = "Design elaboration failed; see full log for details"; +} + +void set_verific_logging(void (*cb)(int msg_type, const char *message_id, LogSourceLocation src, const char *msg)) +{ + Message::SetConsoleOutput(0); + Message::RegisterCallBackMsg(msg_func); + log_verific_callback = cb; +} + +string get_full_netlist_name(Netlist *nl) +{ + if (nl->NumOfRefs() == 1) { + Instance *inst = (Instance*)nl->GetReferences()->GetLast(); + return get_full_netlist_name(inst->Owner()) + "." + inst->Name(); + } + + return nl->CellBaseName(); +} + +#ifdef VERIFIC_SYSTEMVERILOG_SUPPORT +class YosysStreamCallBackHandler : public VerificStreamCallBackHandler +{ +public: + YosysStreamCallBackHandler() : VerificStreamCallBackHandler() { } + virtual ~YosysStreamCallBackHandler() { } + + virtual verific_stream *GetSysCallStream(const char *file_path) + { + if (!file_path) return nullptr; + + linefile_type src_loc = GetFromLocation(); + + char *this_file_name = nullptr; + if (src_loc && !FileSystem::IsAbsolutePath(file_path)) { + const char *src_file_name = LineFile::GetFileName(src_loc); + char *dir_name = FileSystem::DirectoryPath(src_file_name); + if (dir_name) { + this_file_name = Strings::save(dir_name, "/", file_path); + Strings::free(dir_name); + file_path = this_file_name; + } + } + verific_stream *strm = new verific_ifstream(file_path); + Strings::free(this_file_name); + return strm; + } +}; + +YosysStreamCallBackHandler verific_read_cb; +#endif + +#ifdef VERIFIC_SYSTEMVERILOG_SUPPORT +static msg_type_t prev_1063; +#endif +#ifdef VERIFIC_VHDL_SUPPORT +static msg_type_t prev_1240 ; +static msg_type_t prev_1241 ; +#endif +void save_blackbox_msg_state() +{ +#ifdef VERIFIC_SYSTEMVERILOG_SUPPORT + prev_1063 = Message::GetMessageType("VERI-1063") ; + Message::SetMessageType("VERI-1063", VERIFIC_INFO); +#endif +#ifdef VERIFIC_VHDL_SUPPORT + prev_1240 = Message::GetMessageType("VHDL-1240") ; + prev_1241 = Message::GetMessageType("VHDL-1241") ; + Message::SetMessageType("VHDL-1240", VERIFIC_INFO); + Message::SetMessageType("VHDL-1241", VERIFIC_INFO); +#endif +} + +void restore_blackbox_msg_state() +{ +#ifdef VERIFIC_SYSTEMVERILOG_SUPPORT + Message::ClearMessageType("VERI-1063") ; + if (Message::GetMessageType("VERI-1063")!=prev_1063) + Message::SetMessageType("VERI-1063", prev_1063); +#endif +#ifdef VERIFIC_VHDL_SUPPORT + Message::ClearMessageType("VHDL-1240") ; + Message::ClearMessageType("VHDL-1241") ; + if (Message::GetMessageType("VHDL-1240")!=prev_1240) + Message::SetMessageType("VHDL-1240", prev_1240); + if (Message::GetMessageType("VHDL-1241")!=prev_1241) + Message::SetMessageType("VHDL-1241", prev_1241); +#endif +} + +void import_all(const char* work, std::map *nl_todo, Map *parameters, bool show_message, std::string ppfile YS_MAYBE_UNUSED) +{ +#ifdef YOSYSHQ_VERIFIC_EXTENSIONS + save_blackbox_msg_state(); + VerificExtensions::ElaborateAndRewrite(work, parameters); + verific_error_msg.clear(); + restore_blackbox_msg_state(); +#endif +#ifdef VERIFIC_SYSTEMVERILOG_SUPPORT + if (!ppfile.empty()) + veri_file::PrettyPrint(ppfile.c_str(), nullptr, work); +#endif + + Array vhdl_libs; +#ifdef VERIFIC_VHDL_SUPPORT + VhdlLibrary *vhdl_lib = vhdl_file::GetLibrary(work, 1); + if (vhdl_lib) vhdl_libs.InsertLast(vhdl_lib); +#endif + Array veri_libs; +#ifdef VERIFIC_SYSTEMVERILOG_SUPPORT + VeriLibrary *veri_lib = veri_file::GetLibrary(work, 1); + if (veri_lib) veri_libs.InsertLast(veri_lib); +#endif + +#ifdef VERIFIC_HIER_TREE_SUPPORT + if (show_message) + log("Running hier_tree::ElaborateAll().\n"); + Array *netlists = hier_tree::ElaborateAll(&veri_libs, &vhdl_libs, parameters); + Netlist *nl; + int i; + + FOREACH_ARRAY_ITEM(netlists, i, nl) + nl_todo->emplace(nl->CellBaseName(), nl); + delete netlists; +#else + if (parameters->Size()) + log_warning("Please note that parameters are not propagated during import.\n"); +#ifdef VERIFIC_SYSTEMVERILOG_SUPPORT + if (show_message) + log("Running veri_file::ElaborateAll().\n"); + veri_file::ElaborateAll(work); +#endif +#ifdef VERIFIC_VHDL_SUPPORT + if (show_message) + log("Running vhdl_file::ElaborateAll().\n"); + vhdl_file::ElaborateAll(work); +#endif + MapIter mi ; + Verific::Cell *c ; + MapIter it ; + Library *l ; + FOREACH_LIBRARY_OF_LIBSET(Libset::Global(),it,l) { + if (l == Library::Primitives() || l == Library::Operators()) continue; + FOREACH_CELL_OF_LIBRARY(l,mi,c) { + MapIter ni ; + Netlist *nl; + FOREACH_NETLIST_OF_CELL(c, ni, nl) { + if (nl) + nl_todo->emplace(nl->CellBaseName(), nl); + } + } + } +#endif +} + +std::set import_tops(const char* work, std::map *nl_todo, Map *parameters, bool show_message, std::string ppfile YS_MAYBE_UNUSED, std::vector &tops, std::string *top) +{ + std::set top_mod_names; + Array *netlists = nullptr; + (void)top; + +#ifdef VERIFIC_VHDL_SUPPORT + VhdlLibrary *vhdl_lib = vhdl_file::GetLibrary(work, 1); +#endif +#ifdef VERIFIC_SYSTEMVERILOG_SUPPORT + VeriLibrary* veri_lib = veri_file::GetLibrary(work, 1); +#endif + +#ifdef YOSYSHQ_VERIFIC_EXTENSIONS + for (int static_elaborate = 1; static_elaborate >= 0; static_elaborate--) +#endif + { + Array vhdl_units; + Array veri_modules; + for (std::string n : tops) + { + const char *name = n.c_str(); + top_mod_names.insert(name); + +#ifdef VERIFIC_SYSTEMVERILOG_SUPPORT + VeriModule *veri_module = veri_lib ? veri_lib->GetModule(name, 1) : nullptr; + if (veri_module) { + if (veri_module->IsConfiguration()) { + if (show_message) + log("Adding Verilog configuration '%s' to elaboration queue.\n", name); + veri_modules.InsertLast(veri_module); + top_mod_names.erase(name); + VeriConfiguration *cfg = (VeriConfiguration*)veri_module; + VeriName *module_name; + int i; + FOREACH_ARRAY_ITEM(cfg->GetTopModuleNames(), i, module_name) { + VeriLibrary *lib = veri_module->GetLibrary() ; + if (module_name && module_name->IsHierName()) { + VeriName *prefix = module_name->GetPrefix() ; + const char *lib_name = (prefix) ? prefix->GetName() : 0 ; + if (work != lib_name) lib = veri_file::GetLibrary(lib_name, 1) ; + } + if (lib && module_name) + top_mod_names.insert(lib->GetModule(module_name->GetName(), 1)->GetName()); + } + } else { + if (show_message) + log("Adding Verilog module '%s' to elaboration queue.\n", name); + veri_modules.InsertLast(veri_module); + } + continue; + } +#endif +#ifdef VERIFIC_VHDL_SUPPORT + VhdlDesignUnit *vhdl_unit = vhdl_lib ? vhdl_lib->GetPrimUnit(name) : nullptr; + if (vhdl_unit) { + if (show_message) + log("Adding VHDL unit '%s' to elaboration queue.\n", name); + vhdl_units.InsertLast(vhdl_unit); + if (strcmp(name, vhdl_unit->Id()->OrigName()) != 0) { + top_mod_names.erase(name); + top_mod_names.insert(vhdl_unit->Id()->OrigName()); + if (top && *top == name) + *top = vhdl_unit->Id()->OrigName(); + } + continue; + } +#endif + log_error("Can't find module/unit '%s'.\n", name); + } + +#ifdef YOSYSHQ_VERIFIC_EXTENSIONS + if (static_elaborate) { + save_blackbox_msg_state(); + VerificExtensions::ElaborateAndRewrite(work, &veri_modules, &vhdl_units, parameters); + verific_error_msg.clear(); + restore_blackbox_msg_state(); +#endif +#ifdef VERIFIC_SYSTEMVERILOG_SUPPORT + if (!ppfile.empty()) + veri_file::PrettyPrint(ppfile.c_str(), nullptr, work); +#endif +#ifdef YOSYSHQ_VERIFIC_EXTENSIONS + continue; + } +#endif +#ifdef VERIFIC_SYSTEMVERILOG_SUPPORT + const char *lib_name = nullptr; + SetIter si; + FOREACH_SET_ITEM(veri_file::GetAllLOptions(), si, &lib_name) { + VeriLibrary* veri_lib = veri_file::GetLibrary(lib_name, 0); + if (veri_lib) { + // Also elaborate all root modules since they may contain bind statements + MapIter mi; + VeriModule *veri_module; + FOREACH_VERILOG_MODULE_IN_LIBRARY(veri_lib, mi, veri_module) { + if (!veri_module->IsRootModule()) continue; + veri_modules.InsertLast(veri_module); + } + } + } +#endif +#ifdef VERIFIC_HIER_TREE_SUPPORT + if (show_message) + log("Running hier_tree::Elaborate().\n"); + netlists = hier_tree::Elaborate(&veri_modules, &vhdl_units, parameters); +#else +#if defined(VERIFIC_SYSTEMVERILOG_SUPPORT) && !defined(VERIFIC_VHDL_SUPPORT) + if (show_message) + log("Running veri_file::ElaborateMultipleTop().\n"); + // SystemVerilog support only + netlists = veri_file::ElaborateMultipleTop(&veri_modules, parameters); +#elif defined(VERIFIC_VHDL_SUPPORT) && !defined(VERIFIC_SYSTEMVERILOG_SUPPORT) + if (show_message) + log("Running vhdl_file::Elaborate().\n"); + // VHDL support only + netlists = new Array(top_mod_names.size()); + for (auto &name : top_mod_names) { + vhdl_file::Elaborate(name.c_str(), work, 0, parameters); + netlists->InsertLast(Netlist::PresentDesign()); + } +#elif defined(VERIFIC_SYSTEMVERILOG_SUPPORT) && defined(VERIFIC_VHDL_SUPPORT) + // Both SystemVerilog and VHDL support + if (veri_modules.Size()>0) { + if (show_message) + log("Running veri_file::ElaborateMultipleTop().\n"); + netlists = veri_file::ElaborateMultipleTop(&veri_modules, parameters); + } else + netlists = new Array(1); + if (vhdl_units.Size()>0) { + if (show_message) + log("Running vhdl_file::Elaborate().\n"); + for (auto &name : top_mod_names) { + vhdl_file::Elaborate(name.c_str(), work, 0, parameters); + netlists->InsertLast(Netlist::PresentDesign()); + } + } +#else +#endif +#endif + } + Netlist *nl; + int i; + + FOREACH_ARRAY_ITEM(netlists, i, nl) { + if (!nl) continue; + if (!top_mod_names.count(nl->CellBaseName())) + continue; + nl->AddAtt(new Att(" \\top", NULL)); + nl_todo->emplace(nl->CellBaseName(), nl); + } + delete netlists; + return top_mod_names; +} + +static bool set_verific_global_flags = true; + +static void set_global_flags() +{ + if (!set_verific_global_flags) + return; + + Message::SetConsoleOutput(0); + Message::RegisterCallBackMsg(msg_func); + + RuntimeFlags::SetVar("db_preserve_user_instances", 1); + RuntimeFlags::SetVar("db_preserve_user_nets", 1); + RuntimeFlags::SetVar("db_preserve_x", 1); + + RuntimeFlags::SetVar("db_allow_external_nets", 1); + RuntimeFlags::SetVar("db_infer_wide_operators", 1); + RuntimeFlags::SetVar("db_infer_set_reset_registers", 0); + + // Properly respect order of read and write for rams + RuntimeFlags::SetVar("db_change_inplace_ram_blocking_write_before_read", 1); + +#ifdef VERIFIC_SYSTEMVERILOG_SUPPORT + RuntimeFlags::SetVar("veri_extract_dualport_rams", 0); + RuntimeFlags::SetVar("veri_extract_multiport_rams", 1); + RuntimeFlags::SetVar("veri_allow_any_ram_in_loop", 1); + RuntimeFlags::SetVar("veri_replace_const_exprs", 1); +#endif +#ifdef VERIFIC_VHDL_SUPPORT + RuntimeFlags::SetVar("vhdl_extract_dualport_rams", 0); + RuntimeFlags::SetVar("vhdl_extract_multiport_rams", 1); + RuntimeFlags::SetVar("vhdl_allow_any_ram_in_loop", 1); + RuntimeFlags::SetVar("vhdl_replace_const_exprs", 1); + + RuntimeFlags::SetVar("vhdl_support_variable_slice", 1); + RuntimeFlags::SetVar("vhdl_ignore_assertion_statements", 0); + + RuntimeFlags::SetVar("vhdl_preserve_assignments", 1); + //RuntimeFlags::SetVar("vhdl_preserve_comments", 1); + RuntimeFlags::SetVar("vhdl_preserve_drivers", 1); +#endif +#ifdef VERIFIC_SYSTEMVERILOG_SUPPORT + RuntimeFlags::SetVar("veri_preserve_assignments", 1); + RuntimeFlags::SetVar("veri_preserve_comments", 1); + RuntimeFlags::SetVar("veri_preserve_drivers", 1); + + // Workaround for VIPER #13851 + RuntimeFlags::SetVar("veri_create_name_for_unnamed_gen_block", 1); + + // WARNING: instantiating unknown module 'XYZ' (VERI-1063) + Message::SetMessageType("VERI-1063", VERIFIC_ERROR); + + // Downgrade warnings about things that are normal + // VERIFIC-WARNING [VERI-1209] foo.sv:98: expression size 7 truncated to fit in target size 6 + Message::SetMessageType("VERI-1209", VERIFIC_INFO); + // VERIFIC-WARNING [VERI-1142] foo.sv:55: system task 'display' is ignored for synthesis + Message::SetMessageType("VERI-1142", VERIFIC_INFO); + // VERIFIC-WARNING [VERI-2418] foo.svh:503: parameter 'all_cfgs_gp' declared inside package 'bp_common_pkg' shall be treated as localparam + Message::SetMessageType("VERI-2418", VERIFIC_INFO); + + // https://github.com/YosysHQ/yosys/issues/1055 + RuntimeFlags::SetVar("veri_elaborate_top_level_modules_having_interface_ports", 1) ; +#endif + RuntimeFlags::SetVar("verific_produce_verbose_syntax_error_message", 1); + +#ifndef DB_PRESERVE_INITIAL_VALUE +# warning Verific was built without DB_PRESERVE_INITIAL_VALUE. +#endif + + set_verific_global_flags = false; +} + +void verific_setup() +{ + set_global_flags(); +#ifdef VERIFIC_SYSTEMVERILOG_SUPPORT + veri_file::RegisterCallBackVerificStream(&verific_read_cb); +#endif +} + +void verific_cleanup() +{ +#ifdef YOSYSHQ_VERIFIC_EXTENSIONS + VerificExtensions::Reset(); +#endif +#ifdef VERIFIC_HIER_TREE_SUPPORT + hier_tree::DeleteHierarchicalTree(); +#endif +#ifdef VERIFIC_SYSTEMVERILOG_SUPPORT + veri_file::Reset(); +#endif +#ifdef VERIFIC_VHDL_SUPPORT + vhdl_file::Reset(); +#endif +#ifdef VERIFIC_EDIF_SUPPORT + edif_file::Reset(); +#endif +#ifdef VERIFIC_LIBERTY_SUPPORT + synlib_file::Reset(); +#endif + Libset::Reset(); + Message::Reset(); + RuntimeFlags::DeleteAllFlags(); + set_verific_global_flags = true; + LineFile::DeleteAllLineFiles(); + VerificCommand::reset_settings(); + verific_import_pending = false; +} + +std::string verific_import(Design *design, const std::map ¶meters, std::string top) +{ + verific_sva_fsm_limit = 16; + + std::map nl_todo, nl_done; + + Map verific_params(STRING_HASH); + for (const auto &i : parameters) + verific_params.Insert(i.first.c_str(), i.second.c_str()); + + std::set top_mod_names; + if (top.empty()) { + import_all("work", &nl_todo, &verific_params, false, ""); + } else { + std::vector tops; + tops.push_back(top); +#ifdef VERIFIC_SYSTEMVERILOG_SUPPORT + veri_file::RemoveAllLOptions(); + veri_file::AddLOption("work"); +#endif + top_mod_names = import_tops("work", &nl_todo, &verific_params, false, "", tops, &top) ; + } + + if (!verific_error_msg.empty()) + log_error("%s\n", verific_error_msg); + + for (auto nl : nl_todo) + nl.second->ChangePortBusStructures(1 /* hierarchical */); + + verific_extnets(nl_todo); + + while (!nl_todo.empty()) { + auto it = nl_todo.begin(); + Netlist *nl = it->second; + if (nl_done.count(it->first) == 0) { + VerificImporter importer(false, false, false, false, false, false, false, false); + nl_done[it->first] = it->second; + importer.import_netlist(design, nl, nl_todo, top_mod_names.count(nl->CellBaseName())); + } + nl_todo.erase(it); + } + + if (!verific_error_msg.empty()) + log_error("%s\n", verific_error_msg); + return top; +} + +bool check_noverific_env() +{ + const char *e = getenv("YOSYS_NOVERIFIC"); + if (e == nullptr) + return false; + if (atoi(e) == 0) + return false; + return true; +} + +YOSYS_NAMESPACE_END +#endif /* YOSYS_ENABLE_VERIFIC */ diff --git a/chips/yosys/frontends/verific/verific.h b/chips/yosys/frontends/verific/verific.h new file mode 100644 index 0000000000000000000000000000000000000000..62c46cdf3e02bd158446976d5fb7157b8de5c14e --- /dev/null +++ b/chips/yosys/frontends/verific/verific.h @@ -0,0 +1,75 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#ifndef VERIFIC_H +#define VERIFIC_H + +#ifdef YOSYS_ENABLE_VERIFIC + +#include +#include + +#include "DataBase.h" + +#include "frontends/verific/verific_clocking.h" +#include "frontends/verific/verific_importer.h" + +YOSYS_NAMESPACE_BEGIN + +extern int verific_verbose; + +bool check_noverific_env(); +void verific_setup(); + +struct VerificSession { + ~VerificSession(); + static void begin(Design *design); + static std::unique_ptr deferred_end(Design *design); +private: + static inline std::mutex mutex; + static inline std::condition_variable cv; + static inline Design *owner = nullptr; +}; + +extern bool verific_import_pending; +extern std::string verific_import(Design *design, const std::map ¶meters, std::string top = std::string()); + +extern pool verific_sva_prims; + +void verific_import_sva_assert(VerificImporter *importer, Verific::Instance *inst); +void verific_import_sva_assume(VerificImporter *importer, Verific::Instance *inst); +void verific_import_sva_cover(VerificImporter *importer, Verific::Instance *inst); +void verific_import_sva_trigger(VerificImporter *importer, Verific::Instance *inst); +bool verific_is_sva_net(VerificImporter *importer, Verific::Net *net); + +extern int verific_sva_fsm_limit; + +extern std::string verific_error_msg; + +std::string get_full_netlist_name(Verific::Netlist *nl); +void save_blackbox_msg_state(); +void restore_blackbox_msg_state(); +void import_all(const char* work, std::map *nl_todo, Verific::Map *parameters, bool show_message, std::string ppfile); +std::set import_tops(const char* work, std::map *nl_todo, Verific::Map *parameters, bool show_message, std::string ppfile, std::vector &tops, std::string *top = nullptr); +void verific_extnets(const std::map &nl_todo); + +YOSYS_NAMESPACE_END + +#endif +#endif diff --git a/chips/yosys/frontends/verific/verific_clocking.cc b/chips/yosys/frontends/verific/verific_clocking.cc new file mode 100644 index 0000000000000000000000000000000000000000..1c40e765081a6100c6b78f909e4812b93826712b --- /dev/null +++ b/chips/yosys/frontends/verific/verific_clocking.cc @@ -0,0 +1,321 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" + +#include "frontends/verific/verific.h" + +#ifdef VERIFIC_NAMESPACE +using namespace Verific; +#endif + +YOSYS_NAMESPACE_BEGIN + +VerificClocking::VerificClocking(VerificImporter *importer, Net *net, bool sva_at_only YS_MAYBE_UNUSED) +{ + module = importer->module; + + log_assert(importer != nullptr); + log_assert(net != nullptr); + + Instance *inst = net->Driver(); + +#ifdef VERIFIC_SYSTEMVERILOG_SUPPORT + // Detect condition expression in sva_at_only mode + if (sva_at_only) + do { + Instance *inst_mux = net->Driver(); + if (inst_mux == nullptr || inst_mux->Type() != PRIM_MUX) + break; + + bool pwr1 = inst_mux->GetInput1()->IsPwr(); + bool pwr2 = inst_mux->GetInput2()->IsPwr(); + + bool gnd1 = inst_mux->GetInput1()->IsGnd(); + bool gnd2 = inst_mux->GetInput2()->IsGnd(); + + if (!pwr1 && !pwr2) { + pwr1 = gnd1; + pwr2 = gnd2; + } + + if (!pwr1 && !pwr2) + break; + + Net *sva_net = pwr1 ? inst_mux->GetInput2() : inst_mux->GetInput1(); + if (!verific_is_sva_net(importer, sva_net)) + break; + + inst = sva_net->Driver(); + cond_net = inst_mux->GetControl(); + cond_pol = pwr1; + } while (0); + + if (inst != nullptr && inst->Type() == PRIM_SVA_AT) + { + net = inst->GetInput1(); + body_net = inst->GetInput2(); + + inst = net->Driver(); + + Instance *body_inst = body_net->Driver(); + if (body_inst != nullptr && body_inst->Type() == PRIM_SVA_DISABLE_IFF) { + disable_net = body_inst->GetInput1(); + disable_sig = importer->net_map_at(disable_net); + body_net = body_inst->GetInput2(); + } + } + else + { + if (sva_at_only) + return; + } + + // Use while() instead of if() to work around VIPER #13453 + while (inst != nullptr && inst->Type() == PRIM_SVA_POSEDGE) + { + net = inst->GetInput(); + inst = net->Driver();; + } +#endif + if (inst != nullptr && inst->Type() == PRIM_INV) + { + net = inst->GetInput(); + inst = net->Driver();; + posedge = false; + } + + // Detect clock-enable circuit + do { + if (inst == nullptr || inst->Type() != PRIM_AND) + break; + + Net *net_dlatch = inst->GetInput1(); + Instance *inst_dlatch = net_dlatch->Driver(); + + if (inst_dlatch == nullptr || inst_dlatch->Type() != PRIM_DLATCHRS) + break; + + if (!inst_dlatch->GetSet()->IsGnd() || !inst_dlatch->GetReset()->IsGnd()) + break; + + Net *net_enable = inst_dlatch->GetInput(); + Net *net_not_clock = inst_dlatch->GetControl(); + + if (net_enable == nullptr || net_not_clock == nullptr) + break; + + Instance *inst_not_clock = net_not_clock->Driver(); + + if (inst_not_clock == nullptr || inst_not_clock->Type() != PRIM_INV) + break; + + Net *net_clock1 = inst_not_clock->GetInput(); + Net *net_clock2 = inst->GetInput2(); + + if (net_clock1 == nullptr || net_clock1 != net_clock2) + break; + + enable_net = net_enable; + enable_sig = importer->net_map_at(enable_net); + + net = net_clock1; + inst = net->Driver();; + } while (0); + +#ifdef VERIFIC_SYSTEMVERILOG_SUPPORT + // Detect condition expression + do { + if (body_net == nullptr) + break; + + Instance *inst_mux = body_net->Driver(); + + if (inst_mux == nullptr || inst_mux->Type() != PRIM_MUX) + break; + + bool pwr1 = inst_mux->GetInput1()->IsPwr(); + bool pwr2 = inst_mux->GetInput2()->IsPwr(); + + bool gnd1 = inst_mux->GetInput1()->IsGnd(); + bool gnd2 = inst_mux->GetInput2()->IsGnd(); + + if (!pwr1 && !pwr2) { + pwr1 = gnd1; + pwr2 = gnd2; + } + + if (!pwr1 && !pwr2) + break; + + Net *sva_net = pwr1 ? inst_mux->GetInput2() : inst_mux->GetInput1(); + if (!verific_is_sva_net(importer, sva_net)) + break; + + body_net = sva_net; + cond_net = inst_mux->GetControl(); + cond_pol = pwr1; + } while (0); + + // Detect disable condition + do { + if (body_net == nullptr) + break; + + Instance *inst_disable = body_net->Driver(); + if (inst_disable == nullptr || inst_disable->Type() != PRIM_SVA_DISABLE_IFF) + break; + + disable_net = inst_disable->GetInput1(); + disable_sig = importer->net_map_at(disable_net); + body_net = inst_disable->GetInput2(); + } while (0); +#endif + + clock_net = net; + clock_sig = importer->net_map_at(clock_net); + + const char *gclk_attr = clock_net->GetAttValue("gclk"); + if (gclk_attr != nullptr && (!strcmp(gclk_attr, "1") || !strcmp(gclk_attr, "'1'"))) + gclk = true; +} + +Cell *VerificClocking::addDff(IdString name, SigSpec sig_d, SigSpec sig_q, Const init_value) +{ + log_assert(GetSize(sig_d) == GetSize(sig_q)); + + auto set_init_attribute = [&](SigSpec &s) { + if (GetSize(init_value) == 0) + return; + log_assert(GetSize(s) == GetSize(init_value)); + if (s.is_wire()) { + s.as_wire()->attributes[ID::init] = init_value; + } else { + Wire *w = module->addWire(NEW_ID, GetSize(s)); + w->attributes[ID::init] = init_value; + module->connect(s, w); + s = w; + } + }; + + if (enable_sig != State::S1) + sig_d = module->Mux(NEW_ID, sig_q, sig_d, enable_sig); + + if (disable_sig != State::S0) { + log_assert(GetSize(sig_q) == GetSize(init_value)); + + if (gclk) { + Wire *pre_d = module->addWire(NEW_ID, GetSize(sig_d)); + Wire *post_q_w = module->addWire(NEW_ID, GetSize(sig_q)); + + Const initval(State::Sx, GetSize(sig_q)); + int offset = 0; + for (auto c : sig_q.chunks()) { + if (c.wire && c.wire->attributes.count(ID::init)) { + Const val = c.wire->attributes.at(ID::init); + for (int i = 0; i < GetSize(c); i++) + initval.set(offset+i, val[c.offset+i]); + } + offset += GetSize(c); + } + + if (!initval.is_fully_undef()) + post_q_w->attributes[ID::init] = initval; + + module->addMux(NEW_ID, sig_d, init_value, disable_sig, pre_d); + module->addMux(NEW_ID, post_q_w, init_value, disable_sig, sig_q); + + SigSpec post_q(post_q_w); + set_init_attribute(post_q); + return module->addFf(name, pre_d, post_q); + } + + set_init_attribute(sig_q); + return module->addAdff(name, clock_sig, disable_sig, sig_d, sig_q, init_value, posedge); + } + + if (gclk) { + set_init_attribute(sig_q); + return module->addFf(name, sig_d, sig_q); + } + + set_init_attribute(sig_q); + return module->addDff(name, clock_sig, sig_d, sig_q, posedge); +} + +Cell *VerificClocking::addAdff(IdString name, RTLIL::SigSpec sig_arst, SigSpec sig_d, SigSpec sig_q, Const arst_value) +{ + log_assert(gclk == false); + log_assert(disable_sig == State::S0); + + // FIXME: Adffe + if (enable_sig != State::S1) + sig_d = module->Mux(NEW_ID, sig_q, sig_d, enable_sig); + + return module->addAdff(name, clock_sig, sig_arst, sig_d, sig_q, arst_value, posedge); +} + +Cell *VerificClocking::addDffsr(IdString name, RTLIL::SigSpec sig_set, RTLIL::SigSpec sig_clr, SigSpec sig_d, SigSpec sig_q) +{ + log_assert(gclk == false); + log_assert(disable_sig == State::S0); + + // FIXME: Dffsre + if (enable_sig != State::S1) + sig_d = module->Mux(NEW_ID, sig_q, sig_d, enable_sig); + + return module->addDffsr(name, clock_sig, sig_set, sig_clr, sig_d, sig_q, posedge); +} + +Cell *VerificClocking::addAldff(IdString name, RTLIL::SigSpec sig_aload, RTLIL::SigSpec sig_adata, SigSpec sig_d, SigSpec sig_q) +{ + log_assert(disable_sig == State::S0); + + // FIXME: Aldffe + if (enable_sig != State::S1) + sig_d = module->Mux(NEW_ID, sig_q, sig_d, enable_sig); + + if (gclk) { + Wire *pre_d = module->addWire(NEW_ID, GetSize(sig_d)); + Wire *post_q = module->addWire(NEW_ID, GetSize(sig_q)); + + Const initval(State::Sx, GetSize(sig_q)); + int offset = 0; + for (auto c : sig_q.chunks()) { + if (c.wire && c.wire->attributes.count(ID::init)) { + Const val = c.wire->attributes.at(ID::init); + for (int i = 0; i < GetSize(c); i++) + initval.set(offset+i, val[c.offset+i]); + } + offset += GetSize(c); + } + + if (!initval.is_fully_undef()) + post_q->attributes[ID::init] = initval; + + module->addMux(NEW_ID, sig_d, sig_adata, sig_aload, pre_d); + module->addMux(NEW_ID, post_q, sig_adata, sig_aload, sig_q); + + return module->addFf(name, pre_d, post_q); + } + + return module->addAldff(name, clock_sig, sig_aload, sig_d, sig_q, sig_adata, posedge); +} + +YOSYS_NAMESPACE_END diff --git a/chips/yosys/frontends/verific/verific_clocking.h b/chips/yosys/frontends/verific/verific_clocking.h new file mode 100644 index 0000000000000000000000000000000000000000..cceb183faad11036d25419c97a85ad8bf2f4337a --- /dev/null +++ b/chips/yosys/frontends/verific/verific_clocking.h @@ -0,0 +1,70 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#ifndef VERIFIC_CLOCKING_H +#define VERIFIC_CLOCKING_H + +#ifdef YOSYS_ENABLE_VERIFIC + +#include "kernel/yosys.h" + +#include "DataBase.h" + +YOSYS_NAMESPACE_BEGIN + +struct VerificImporter; + +struct VerificClocking { + RTLIL::Module *module = nullptr; + Verific::Net *clock_net = nullptr; + Verific::Net *enable_net = nullptr; + Verific::Net *disable_net = nullptr; + Verific::Net *body_net = nullptr; + Verific::Net *cond_net = nullptr; + SigBit clock_sig = State::Sx; + SigBit enable_sig = State::S1; + SigBit disable_sig = State::S0; + bool posedge = true; + bool gclk = false; + bool cond_pol = true; + + VerificClocking() { } + VerificClocking(VerificImporter *importer, Verific::Net *net, bool sva_at_only = false); + RTLIL::Cell *addDff(IdString name, SigSpec sig_d, SigSpec sig_q, Const init_value = Const()); + RTLIL::Cell *addAdff(IdString name, RTLIL::SigSpec sig_arst, SigSpec sig_d, SigSpec sig_q, Const arst_value); + RTLIL::Cell *addDffsr(IdString name, RTLIL::SigSpec sig_set, RTLIL::SigSpec sig_clr, SigSpec sig_d, SigSpec sig_q); + RTLIL::Cell *addAldff(IdString name, RTLIL::SigSpec sig_aload, RTLIL::SigSpec sig_adata, SigSpec sig_d, SigSpec sig_q); + YS_NAME_FWD_POOL(addDff, module->twines()) YS_NAME_FWD_POOL(addAdff, module->twines()) + YS_NAME_FWD_POOL(addDffsr, module->twines()) YS_NAME_FWD_POOL(addAldff, module->twines()) + + bool property_matches_sequence(const VerificClocking &seq) const { + if (clock_net != seq.clock_net) + return false; + if (enable_net != seq.enable_net) + return false; + if (posedge != seq.posedge) + return false; + return true; + } +}; + +YOSYS_NAMESPACE_END + +#endif +#endif diff --git a/chips/yosys/frontends/verific/verific_command.cc b/chips/yosys/frontends/verific/verific_command.cc new file mode 100644 index 0000000000000000000000000000000000000000..a53c7f7d909f6d2d5b61ae657f1704760855e313 --- /dev/null +++ b/chips/yosys/frontends/verific/verific_command.cc @@ -0,0 +1,986 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" +#include "kernel/log.h" +#include + +#include "frontends/verific/verific_command.h" + +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Woverloaded-virtual" +#endif + +#include "Array.h" +#include "RuntimeFlags.h" + +#ifdef VERIFIC_SYSTEMVERILOG_SUPPORT +#include "veri_file.h" +#include "VeriModule.h" +#include "VeriWrite.h" +#include "VeriLibrary.h" +#endif + +#ifdef VERIFIC_VHDL_SUPPORT +#include "vhdl_file.h" +#include "VhdlUnits.h" +#endif + +#ifdef VERIFIC_EDIF_SUPPORT +#include "edif_file.h" +#endif + +#ifdef VERIFIC_LIBERTY_SUPPORT +#include "synlib_file.h" +#include "SynlibGroup.h" +#endif + +#ifdef YOSYSHQ_VERIFIC_EXTENSIONS +#include "VerificExtensions.h" +#endif + +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + +#ifdef VERIFIC_NAMESPACE +using namespace Verific; +#endif + +YOSYS_NAMESPACE_BEGIN + +static bool already_imported = false; + +#ifdef VERIFIC_SYSTEMVERILOG_SUPPORT +static std::vector verific_incdirs, verific_libdirs, verific_libexts; +#endif + +void VerificCommand::reset_settings() +{ +#ifdef VERIFIC_SYSTEMVERILOG_SUPPORT + verific_incdirs.clear(); + verific_libdirs.clear(); + verific_libexts.clear(); +#endif +} + +VerificCommand::VerificCommand(Pass &pass, std::vector &args, RTLIL::Design *design) : pass(pass), args(args), design(design) +{ + for (; argidx < GetSize(args); argidx++) + { + if (args[argidx] == "-work" && argidx+1 < GetSize(args)) { + work = args[++argidx]; + is_work_set = true; + continue; + } +#ifdef VERIFIC_SYSTEMVERILOG_SUPPORT + if (args[argidx] == "-L" && argidx+1 < GetSize(args)) { + search_libraries.push_back(args[++argidx]); + continue; + } +#endif + break; + } + + if (argidx < GetSize(args)) + mode = args[argidx]; +} + +VerificCommand::~VerificCommand() +{ + if (tmp_files.empty()) + return; + log("Removing temp files.\n"); + for (auto &fn : tmp_files) + remove(fn.c_str()); +} + +void VerificCommand::apply_library_options() +{ +#ifdef VERIFIC_SYSTEMVERILOG_SUPPORT + veri_file::RemoveAllLOptions(); + if (std::find(search_libraries.begin(), search_libraries.end(), work) == search_libraries.end()) + veri_file::AddLOption(work.c_str()); + for (auto &library : search_libraries) + veri_file::AddLOption(library.c_str()); +#endif +} + +bool VerificCommand::change_setting() +{ + if (mode == "-set-error" || mode == "-set-warning" || mode == "-set-info" || mode == "-set-ignore") + set_msg_type(); +#ifdef VERIFIC_SYSTEMVERILOG_SUPPORT + else if (mode == "-vlog-incdir") + append_remaining_args(verific_incdirs); + else if (mode == "-vlog-libdir") + append_remaining_args(verific_libdirs); + else if (mode == "-vlog-libext") + append_remaining_args(verific_libexts); + else if (mode == "-vlog-define") + define_macros(); + else if (mode == "-vlog-undef") + undefine_macros(); +#endif + else + return false; + return true; +} + +void VerificCommand::run() +{ + if (change_setting()) + return; + + apply_library_options(); + + if (mode == "-import") + import_design(); +#ifdef VERIFIC_SYSTEMVERILOG_SUPPORT + else if (mode == "-target") + read_target(); + else if (mode == "-f" || mode == "-F") + read_f_file(); + else if (const VerilogStandard *verilog = find_verilog_standard(mode)) + read_verilog(*verilog); +#endif +#ifdef VERIFIC_VHDL_SUPPORT + else if (const VhdlStandard *vhdl = find_vhdl_standard(mode)) + read_vhdl(*vhdl); +#endif +#ifdef VERIFIC_EDIF_SUPPORT + else if (mode == "-edif") + read_edif(); +#endif +#ifdef VERIFIC_LIBERTY_SUPPORT + else if (mode == "-liberty") + read_liberty(); +#endif + else if (mode == "-pp") + pretty_print(); + else if (mode == "-cfg") + configure(); + else + run_extension(); +} + +std::string VerificCommand::frontend_rewrite() +{ + std::string filename = args[argidx++]; + //Accommodate heredocs with EOT marker spaced out from "<<", e.g. "<< EOT" vs. "< 0 && (buffer[buffer.size() - 1] == '\n' || buffer[buffer.size() - 1] == '\r')) + break; + } + size_t indent = buffer.find_first_not_of(" \t\r\n"); + if (indent != std::string::npos && buffer.compare(indent, eot_marker.size(), eot_marker) == 0) + break; + last_here_document += buffer; + } + filename = make_temp_file(); + tmp_files.push_back(filename); + std::ofstream file(filename); + file << last_here_document; + } else { + rewrite_filename(filename); + } + return filename; +} + + +#ifdef VERIFIC_VHDL_SUPPORT +static void add_units_to_map(Map &map, std::string work, bool flag_lib) +{ + MapIter mi ; + VhdlPrimaryUnit *unit ; + if (!flag_lib) return; + VhdlLibrary *vhdl_lib = vhdl_file::GetLibrary(work.c_str(), 1); + if (vhdl_lib) { + FOREACH_VHDL_PRIMARY_UNIT(vhdl_lib, mi, unit) { + if (!unit) continue; + map.Insert(unit,unit); + } + } + save_blackbox_msg_state(); +} + +static void set_units_to_blackbox(Map &map, std::string work, bool flag_lib) +{ + MapIter mi ; + VhdlPrimaryUnit *unit ; + if (!flag_lib) return; + VhdlLibrary *vhdl_lib = vhdl_file::GetLibrary(work.c_str(), 1); + FOREACH_VHDL_PRIMARY_UNIT(vhdl_lib, mi, unit) { + if (!unit) continue; + if (!map.GetValue(unit)) { + unit->SetCompileAsBlackbox(); + } + } + restore_blackbox_msg_state(); +} +#endif + +#ifdef VERIFIC_SYSTEMVERILOG_SUPPORT +static void add_modules_to_map(Map &map, std::string work, bool flag_lib) +{ + MapIter mi ; + VeriModule *veri_module ; + if (!flag_lib) return; + VeriLibrary *veri_lib = veri_file::GetLibrary(work.c_str(), 1); + if (veri_lib) { + FOREACH_VERILOG_MODULE_IN_LIBRARY(veri_lib, mi, veri_module) { + if (!veri_module) continue; + map.Insert(veri_module,veri_module); + } + } + save_blackbox_msg_state(); +} + +static void set_modules_to_blackbox(Map &map, std::string work, bool flag_lib) +{ + MapIter mi ; + VeriModule *veri_module ; + if (!flag_lib) return; + VeriLibrary *veri_lib = veri_file::GetLibrary(work.c_str(), 1); + FOREACH_VERILOG_MODULE_IN_LIBRARY(veri_lib, mi, veri_module) { + if (!veri_module) continue; + if (!map.GetValue(veri_module)) { + veri_module->SetCompileAsBlackbox(); + } + } + restore_blackbox_msg_state(); +} +#endif + +#ifdef VERIFIC_SYSTEMVERILOG_SUPPORT +struct VerificCommand::VerilogStandard { + const char *flag; + unsigned mode; +}; + +const VerificCommand::VerilogStandard *VerificCommand::find_verilog_standard(const std::string &flag) +{ + static const VerilogStandard standards[] = { + {"-vlog95", veri_file::VERILOG_95}, + {"-vlog2k", veri_file::VERILOG_2K}, + {"-sv2005", veri_file::SYSTEM_VERILOG_2005}, + {"-sv2009", veri_file::SYSTEM_VERILOG_2009}, + {"-sv2012", veri_file::SYSTEM_VERILOG_2012}, + {"-sv2017", veri_file::SYSTEM_VERILOG_2017}, + {"-sv2023", veri_file::SYSTEM_VERILOG_2023}, + {"-sv", veri_file::SYSTEM_VERILOG}, + {"-formal", veri_file::SYSTEM_VERILOG}, + }; + for (auto &standard : standards) + if (flag == standard.flag) + return &standard; + return nullptr; +} + +static void analyze_verilog_files(Array &file_names, unsigned verilog_mode, const std::string &work, bool flag_lib) +{ + Map map(POINTER_HASH); + add_modules_to_map(map, work, flag_lib); + if (!veri_file::AnalyzeMultipleFiles(&file_names, verilog_mode, work.c_str(), veri_file::MFCU)) { + verific_error_msg.clear(); + log_cmd_error("Reading Verilog/SystemVerilog sources failed.\n"); + } + char* fn; + int i = 0; + + FOREACH_ARRAY_ITEM(&file_names, i, fn) { + free(fn); + } + set_modules_to_blackbox(map, work, flag_lib); + verific_import_pending = true; +} +#endif + +#ifdef VERIFIC_VHDL_SUPPORT +struct VerificCommand::VhdlStandard { + const char *flag; + unsigned mode; + const char *name; + const char *library_dir; + + void set_library_path() const + { + vhdl_file::SetDefaultLibraryPath((proc_share_dirname() + library_dir).c_str()); + } +}; + +const VerificCommand::VhdlStandard *VerificCommand::find_vhdl_standard(const std::string &flag) +{ + static const VhdlStandard standards[] = { + {"-vhdl87", vhdl_file::VHDL_87, "VHDL_87", "verific/vhdl_vdbs_1987"}, + {"-vhdl93", vhdl_file::VHDL_93, "VHDL_93", "verific/vhdl_vdbs_1993"}, + {"-vhdl2k", vhdl_file::VHDL_2K, "VHDL_2K", "verific/vhdl_vdbs_1993"}, + {"-vhdl2008", vhdl_file::VHDL_2008, "VHDL_2008", "verific/vhdl_vdbs_2008"}, + {"-vhdl2019", vhdl_file::VHDL_2019, "VHDL_2019", "verific/vhdl_vdbs_2019"}, + {"-vhdl", vhdl_file::VHDL_2008, "VHDL_2008", "verific/vhdl_vdbs_2008"}, + }; + for (auto &standard : standards) + if (flag == standard.flag) + return &standard; + return nullptr; +} +#endif + +void VerificCommand::set_msg_type() +{ + msg_type_t new_type; + + if (mode == "-set-error") + new_type = VERIFIC_ERROR; + else if (mode == "-set-warning") + new_type = VERIFIC_WARNING; + else if (mode == "-set-info") + new_type = VERIFIC_INFO; + else if (mode == "-set-ignore") + new_type = VERIFIC_IGNORE; + else + log_abort(); + + for (argidx++; argidx < GetSize(args); argidx++) { + if (Strings::compare(args[argidx].c_str(), "errors")) { + Message::SetMessageType("VERI-1063", new_type); + Message::SetAllMessageType(VERIFIC_ERROR, new_type); + } else if (Strings::compare(args[argidx].c_str(), "warnings")) { + Message::SetAllMessageType(VERIFIC_WARNING, new_type); + } else if (Strings::compare(args[argidx].c_str(), "infos")) { + Message::SetMessageType("VERI-1209", new_type); + Message::SetMessageType("VERI-1142", new_type); + Message::SetMessageType("VERI-2418", new_type); + Message::SetAllMessageType(VERIFIC_INFO, new_type); + } else if (Strings::compare(args[argidx].c_str(), "comments")) { + Message::SetAllMessageType(VERIFIC_COMMENT, new_type); + } else { + Message::SetMessageType(args[argidx].c_str(), new_type); + } + } +} + +#ifdef VERIFIC_SYSTEMVERILOG_SUPPORT +void VerificCommand::append_remaining_args(std::vector &list) +{ + for (argidx++; argidx < GetSize(args); argidx++) + list.push_back(args[argidx]); +} + +void VerificCommand::define_macros() +{ + for (argidx++; argidx < GetSize(args); argidx++) { + string name = args[argidx]; + size_t equal = name.find('='); + if (equal != std::string::npos) { + string value = name.substr(equal+1); + name = name.substr(0, equal); + veri_file::DefineCmdLineMacro(name.c_str(), value.c_str()); + } else { + veri_file::DefineCmdLineMacro(name.c_str()); + } + } +} + +void VerificCommand::undefine_macros() +{ + for (argidx++; argidx < GetSize(args); argidx++) { + string name = args[argidx]; + veri_file::UndefineMacro(name.c_str()); + } +} + +void VerificCommand::read_target() +{ + argidx++; + log_experimental("verific -target"); + + if (argidx >= GetSize(args)) + log_cmd_error("Missing target for `-target'.\n"); + + std::string synth_target = args[argidx++]; + std::string synth_family; + + if (argidx < GetSize(args) && args[argidx] == "-family") { + argidx++; + log_experimental("verific -family"); + + if (argidx >= GetSize(args)) + log_cmd_error("Missing family for `-family'.\n"); + + synth_family = args[argidx++]; + } else if (argidx < GetSize(args) && args[argidx][0] == '-') { + log_cmd_error("Unknown option `%s'.\n", args[argidx]); + } + auto target_it = target_register.find(synth_target); + if (target_it == target_register.end()) + log_cmd_error("Unknown target '%s'.\n", synth_target); + + auto family_it = target_it->second.families.find(synth_family); + if (family_it == target_it->second.families.end()) { + if (synth_family.empty()) + log_cmd_error("Family must be specified for target '%s'.\n", synth_target); + else + log_cmd_error("Unknown family '%s' for target '%s'.\n", + synth_family, synth_target); + } + + bool flag_lib = true; + Array file_names; + unsigned verilog_mode = veri_file::SYSTEM_VERILOG; + veri_file::DefineMacro("YOSYS"); + veri_file::DefineMacro("VERIFIC"); + + for (auto &file : family_it->second.files) { + rewrite_filename(file); + file_names.Insert(strdup(file.c_str())); + std::string dir = std::filesystem::path(file).parent_path().string(); + veri_file::AddIncludeDir(dir.c_str()); + } + + analyze_verilog_files(file_names, verilog_mode, work, flag_lib); +} + +void VerificCommand::read_f_file() +{ + unsigned verilog_mode = veri_file::UNDEFINED; +#ifdef VERIFIC_VHDL_SUPPORT + unsigned vhdl_mode = vhdl_file::UNDEFINED; +#endif + bool is_formal = false; + const char* filename = nullptr; + + Verific::veri_file::f_file_flags flags = (args[argidx] == "-f") ? veri_file::F_FILE_NONE : veri_file::F_FILE_CAPITAL; + + for (argidx++; argidx < GetSize(args); argidx++) { + if (const VerilogStandard *verilog = find_verilog_standard(args[argidx])) { + verilog_mode = verilog->mode; + if (args[argidx] == "-formal") is_formal = true; + continue; + } +#ifdef VERIFIC_VHDL_SUPPORT + if (const VhdlStandard *vhdl = find_vhdl_standard(args[argidx])) { + vhdl_mode = vhdl->mode; + vhdl->set_library_path(); + continue; + } +#endif + if (args[argidx].compare(0, 1, "-") == 0) + pass.cmd_error(args, argidx, "unknown option"); + + if (filename) + log_cmd_error("Only one filename can be specified.\n"); + filename = args[argidx].c_str(); + } + if (!filename) + log_cmd_error("Filename must be specified.\n"); + + unsigned analysis_mode = verilog_mode; // keep default as provided by user if not defined in file + Array *file_names = veri_file::ProcessFFile(filename, flags, analysis_mode); + if (analysis_mode != verilog_mode) + log_warning("Provided verilog mode differs from one specified in file.\n"); + + veri_file::DefineMacro("YOSYS"); + veri_file::DefineMacro("VERIFIC"); + veri_file::DefineMacro(is_formal ? "FORMAL" : "SYNTHESIS"); + +#ifdef VERIFIC_VHDL_SUPPORT + if (vhdl_mode == vhdl_file::UNDEFINED) { + vhdl_file::SetDefaultLibraryPath((proc_share_dirname() + "verific/vhdl_vdbs_2008").c_str()); + vhdl_mode = vhdl_file::VHDL_2008; + } + int i; + Array *file_names_sv = new Array(POINTER_HASH); + FOREACH_ARRAY_ITEM(file_names, i, filename) { + std::string filename_str = filename; + if ((filename_str.substr(filename_str.find_last_of(".") + 1) == "vhd") || + (filename_str.substr(filename_str.find_last_of(".") + 1) == "vhdl")) { + if (!vhdl_file::Analyze(filename, work.c_str(), vhdl_mode)) { + verific_error_msg.clear(); + log_cmd_error("Reading VHDL sources failed.\n"); + } + } else { + file_names_sv->Insert(strdup(filename)); + } + } + if (!veri_file::AnalyzeMultipleFiles(file_names_sv, analysis_mode, work.c_str(), veri_file::MFCU)) { + verific_error_msg.clear(); + log_cmd_error("Reading Verilog/SystemVerilog sources failed.\n"); + } + delete file_names_sv; +#else + if (!veri_file::AnalyzeMultipleFiles(file_names, analysis_mode, work.c_str(), veri_file::MFCU)) { + verific_error_msg.clear(); + log_cmd_error("Reading Verilog/SystemVerilog sources failed.\n"); + } +#endif + + delete file_names; + verific_import_pending = true; +} + +void VerificCommand::read_verilog(const VerilogStandard &standard) +{ + Array file_names; + unsigned verilog_mode = standard.mode; + + veri_file::DefineMacro("YOSYS"); + veri_file::DefineMacro("VERIFIC"); + veri_file::DefineMacro(args[argidx] == "-formal" ? "FORMAL" : "SYNTHESIS"); + + for (argidx++; argidx < GetSize(args) && GetSize(args[argidx]) >= 2 && args[argidx].compare(0, 2, "-D") == 0; argidx++) { + std::string name = args[argidx].substr(2); + if (args[argidx] == "-D") { + if (++argidx >= GetSize(args)) + break; + name = args[argidx]; + } + size_t equal = name.find('='); + if (equal != std::string::npos) { + string value = name.substr(equal+1); + name = name.substr(0, equal); + veri_file::DefineMacro(name.c_str(), value.c_str()); + } else { + veri_file::DefineMacro(name.c_str()); + } + } + + for (auto &dir : verific_incdirs) + veri_file::AddIncludeDir(dir.c_str()); + for (auto &dir : verific_libdirs) + veri_file::AddYDir(dir.c_str()); + for (auto &ext : verific_libexts) + veri_file::AddLibExt(ext.c_str()); + + bool flag_lib = false; + while (argidx < GetSize(args)) { + if (args[argidx] == "-lib") { + flag_lib = true; + argidx++; + continue; + } + if (args[argidx].compare(0, 1, "-") == 0) { + pass.cmd_error(args, argidx, "unknown option"); + return; + } + std::string filename = frontend_rewrite(); + file_names.Insert(strdup(filename.c_str())); + } + analyze_verilog_files(file_names, verilog_mode, work, flag_lib); +} +#endif + +#ifdef VERIFIC_VHDL_SUPPORT +void VerificCommand::read_vhdl(const VhdlStandard &standard) +{ + standard.set_library_path(); + argidx++; + bool flag_lib = false; + while (argidx < GetSize(args)) { + if (args[argidx] == "-lib") { + flag_lib = true; + argidx++; + continue; + } + if (args[argidx].compare(0, 1, "-") == 0) + pass.cmd_error(args, argidx, "unknown option"); + Map map(POINTER_HASH); + add_units_to_map(map, work, flag_lib); + std::string filename = frontend_rewrite(); + if (!vhdl_file::Analyze(filename.c_str(), work.c_str(), standard.mode)) + log_cmd_error("Reading `%s' in %s mode failed.\n", filename, standard.name); + set_units_to_blackbox(map, work, flag_lib); + } + verific_import_pending = true; +} +#endif + +#ifdef VERIFIC_EDIF_SUPPORT +void VerificCommand::read_edif() +{ + edif_file edif; + argidx++; + while (argidx < GetSize(args)) { + std::string filename = frontend_rewrite(); + if (!edif.Read(filename.c_str())) + log_cmd_error("Reading `%s' in EDIF mode failed.\n", filename); + } +} +#endif + +#ifdef VERIFIC_LIBERTY_SUPPORT +void VerificCommand::read_liberty() +{ + bool flag_lib = false; + for (argidx++; argidx < GetSize(args); argidx++) { + if (args[argidx] == "-lib") { + flag_lib = true; + continue; + } + if (args[argidx].compare(0, 1, "-") == 0) { + pass.cmd_error(args, argidx, "unknown option"); + return; + } + break; + } + + while (argidx < GetSize(args)) { + std::string filename = frontend_rewrite(); + if (!synlib_file::Read(filename.c_str(), is_work_set ? work.c_str() : nullptr)) + log_cmd_error("Reading `%s' in LIBERTY mode failed.\n", filename); + SynlibLibrary *lib = synlib_file::GetLastLibraryAnalyzed(); + if (lib && flag_lib) { + MapIter mi ; + Verific::Cell *c ; + FOREACH_CELL_OF_LIBRARY(lib->GetLibrary(),mi,c) { + MapIter ni ; + Netlist *nl; + FOREACH_NETLIST_OF_CELL(c, ni, nl) { + if (nl) + nl->MakeBlackBox(); + } + } + } + } +} +#endif + +void VerificCommand::pretty_print() +{ + const char* filename = nullptr; + const char* module = nullptr; + bool mode_vhdl = false; + for (argidx++; argidx < GetSize(args); argidx++) { +#ifdef VERIFIC_VHDL_SUPPORT + if (args[argidx] == "-vhdl") { + mode_vhdl = true; + continue; + } +#endif + if (args[argidx] == "-verilog") { + mode_vhdl = false; + continue; + } + + if (args[argidx].compare(0, 1, "-") == 0) { + pass.cmd_error(args, argidx, "unknown option"); + return; + } + + if (!filename) { + filename = args[argidx].c_str(); + continue; + } + if (module) + log_cmd_error("Only one module can be specified.\n"); + module = args[argidx].c_str(); + } + + if (argidx < GetSize(args)) + pass.cmd_error(args, argidx, "unknown option/parameter"); + + if (!filename) + log_cmd_error("Filename must be specified.\n"); + + if (mode_vhdl) { +#ifdef VERIFIC_VHDL_SUPPORT + vhdl_file::PrettyPrint(filename, module, work.c_str()); +#endif + return; + } +#ifdef VERIFIC_SYSTEMVERILOG_SUPPORT + veri_file::PrettyPrint(filename, module, work.c_str()); +#endif +} + +void VerificCommand::import_design() +{ + std::map nl_todo, nl_done; + bool mode_all = false, mode_gates = false, mode_keep = false; + bool mode_nosva = false, mode_sva_continue = false; + bool mode_names = false, mode_verific = false; + bool mode_autocover = false, mode_fullinit = false; + bool flatten = false, extnets = false, mode_cells = false; + bool split_complex_ports = true; + string dumpfile; + string ppfile; + Map parameters(STRING_HASH); + + for (argidx++; argidx < GetSize(args); argidx++) { + if (args[argidx] == "-all") { + mode_all = true; + continue; + } + if (args[argidx] == "-gates") { + mode_gates = true; + continue; + } + if (args[argidx] == "-flatten") { + flatten = true; + continue; + } + if (args[argidx] == "-no-split-complex-ports") { + split_complex_ports = false; + continue; + } + if (args[argidx] == "-extnets") { + extnets = true; + continue; + } + if (args[argidx] == "-k") { + mode_keep = true; + continue; + } +#ifdef VERIFIC_SYSTEMVERILOG_SUPPORT + if (args[argidx] == "-nosva") { + mode_nosva = true; + continue; + } + if (args[argidx] == "-sva-continue-on-err") { + mode_sva_continue = true; + continue; + } + if (args[argidx] == "-L" && argidx+1 < GetSize(args)) { + verific_sva_fsm_limit = atoi(args[++argidx].c_str()); + continue; + } + if (args[argidx] == "-autocover") { + mode_autocover = true; + continue; + } +#endif + if (args[argidx] == "-n") { + mode_names = true; + continue; + } + if (args[argidx] == "-fullinit") { + mode_fullinit = true; + continue; + } + if (args[argidx] == "-cells") { + mode_cells = true; + continue; + } + if (args[argidx] == "-chparam" && argidx+2 < GetSize(args)) { + const std::string &key = args[++argidx]; + const std::string &value = args[++argidx]; + unsigned new_insertion = parameters.Insert(key.c_str(), value.c_str(), + 1 /* force_overwrite */); + if (!new_insertion) + log_warning_noprefix("-chparam %s already specified: overwriting.\n", key); + continue; + } + if (args[argidx] == "-V") { + mode_verific = true; + continue; + } + if (args[argidx] == "-v") { + verific_verbose = 1; + continue; + } + if (args[argidx] == "-vv") { + verific_verbose = 2; + continue; + } + if (args[argidx] == "-d" && argidx+1 < GetSize(args)) { + dumpfile = args[++argidx]; + continue; + } + if (args[argidx] == "-pp" && argidx+1 < GetSize(args)) { + ppfile = args[++argidx]; + continue; + } + break; + } + + if (argidx > GetSize(args) && args[argidx].compare(0, 1, "-") == 0) + pass.cmd_error(args, argidx, "unknown option"); + + if ((unsigned long)verific_sva_fsm_limit >= sizeof(1ull)*8) + log_cmd_error("-L %d: limit too large; maximum allowed value is %zu.\n", verific_sva_fsm_limit, sizeof(1ull)*8-1); + + if (already_imported) + log_warning("Note that all Verific flags were reset to defaults after last -import.\n"); + + std::set top_mod_names; + + if (mode_all) + { + import_all(work.c_str(), &nl_todo, ¶meters, true, ppfile); + } + else + { + if (argidx == GetSize(args)) + pass.cmd_error(args, argidx, "No top module specified.\n"); + + std::vector tops; + for (int i = argidx; i < GetSize(args); i++) + tops.push_back(args[i].c_str()); + top_mod_names = import_tops(work.c_str(), &nl_todo, ¶meters, true, ppfile, tops) ; + } + if (mode_cells) { + log("Importing all cells.\n"); + Libset *gls = Libset::Global() ; + MapIter it ; + Library *l ; + FOREACH_LIBRARY_OF_LIBSET(gls,it,l) { + MapIter mi ; + Verific::Cell *c ; + FOREACH_CELL_OF_LIBRARY(l,mi,c) { + if (!mode_verific && (l == Library::Primitives() || l == Library::Operators())) continue; + MapIter ni ; + if (c->NumOfNetlists() == 1) { + c->GetFirstNetlist()->SetName(""); + } + Netlist *nl; + FOREACH_NETLIST_OF_CELL(c, ni, nl) { + if (nl) + nl_todo.emplace(nl->CellBaseName(), nl); + } + } + } + } + + if (!verific_error_msg.empty()) + return; + + if (flatten) { + for (auto nl : nl_todo) + nl.second->Flatten(); + } + + if (extnets) + verific_extnets(nl_todo); + + if (split_complex_ports) { + for (auto nl : nl_todo) + nl.second->ChangePortBusStructures(1 /* hierarchical */); + } + +#ifdef VERIFIC_SYSTEMVERILOG_SUPPORT + if (!dumpfile.empty()) { + VeriWrite veri_writer; + veri_writer.WriteFile(dumpfile.c_str(), Netlist::PresentDesign()); + } +#endif + while (!nl_todo.empty()) { + auto it = nl_todo.begin(); + Netlist *nl = it->second; + if (nl_done.count(it->first) == 0) { + VerificImporter importer(mode_gates, mode_keep, mode_nosva, mode_sva_continue, + mode_names, mode_verific, mode_autocover, mode_fullinit); + nl_done[it->first] = it->second; + importer.import_netlist(design, nl, nl_todo, top_mod_names.count(nl->CellBaseName())); + } + nl_todo.erase(it); + } + + already_imported = true; +} + +void VerificCommand::configure() +{ + if (argidx+1 == GetSize(args)) { + MapIter mi; + const char *k, *s; + unsigned long v; + pool lines; + FOREACH_MAP_ITEM(RuntimeFlags::GetVarMap(), mi, &k, &v) { + lines.insert(stringf("%s %lu", k, v)); + } + FOREACH_MAP_ITEM(RuntimeFlags::GetStringVarMap(), mi, &k, &s) { + if (s == nullptr) + lines.insert(stringf("%s NULL", k)); + else + lines.insert(stringf("%s \"%s\"", k, s)); + } + lines.sort(); + for (auto &line : lines) + log("verific -cfg %s\n", line); + return; + } + + if (argidx+2 == GetSize(args)) { + const char *k = args[argidx+1].c_str(); + if (RuntimeFlags::HasUnsignedVar(k)) { + log("verific -cfg %s %lu\n", k, RuntimeFlags::GetVar(k)); + return; + } + if (RuntimeFlags::HasStringVar(k)) { + const char *s = RuntimeFlags::GetStringVar(k); + if (s == nullptr) + log("verific -cfg %s NULL\n", k); + else + log("verific -cfg %s \"%s\"\n", k, s); + return; + } + log_cmd_error("Can't find Verific Runtime flag '%s'.\n", k); + } + + if (argidx+3 == GetSize(args)) { + const auto &k = args[argidx+1], &v = args[argidx+2]; + if (v == "NULL") { + RuntimeFlags::SetStringVar(k.c_str(), nullptr); + return; + } + if (v[0] == '"') { + std::string s = v.substr(1, GetSize(v)-2); + RuntimeFlags::SetStringVar(k.c_str(), s.c_str()); + return; + } + char *endptr; + unsigned long n = strtol(v.c_str(), &endptr, 0); + if (*endptr == 0) { + RuntimeFlags::SetVar(k.c_str(), n); + return; + } + } + + run_extension(); +} + +void VerificCommand::run_extension() +{ +#ifdef YOSYSHQ_VERIFIC_EXTENSIONS + if (VerificExtensions::Execute(args, argidx, work, + [this](const std::vector &args, size_t argidx, std::string msg) + { pass.cmd_error(args, argidx, msg); } )) + return; +#endif + pass.cmd_error(args, argidx, "Missing or unsupported mode parameter.\n"); +} + +YOSYS_NAMESPACE_END diff --git a/chips/yosys/frontends/verific/verific_command.h b/chips/yosys/frontends/verific/verific_command.h new file mode 100644 index 0000000000000000000000000000000000000000..3dc73c71348bea2e5bae2db57aac8be4046caa62 --- /dev/null +++ b/chips/yosys/frontends/verific/verific_command.h @@ -0,0 +1,75 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#ifndef VERIFIC_COMMAND_H +#define VERIFIC_COMMAND_H + +#ifdef YOSYS_ENABLE_VERIFIC + +#include "kernel/register.h" +#include "frontends/verific/verific.h" + +YOSYS_NAMESPACE_BEGIN + +struct VerificCommand { + Pass &pass; + std::vector &args; + RTLIL::Design *design; + int argidx = 1; + std::string mode = {}; + std::string work = "work"; + bool is_work_set = false; + std::vector search_libraries = {}; + std::vector tmp_files = {}; + + VerificCommand(Pass &pass, std::vector &args, RTLIL::Design *design); + ~VerificCommand(); + void run(); + static void reset_settings(); + +private: + struct VerilogStandard; + struct VhdlStandard; + static const VerilogStandard *find_verilog_standard(const std::string &flag); + static const VhdlStandard *find_vhdl_standard(const std::string &flag); + + std::string frontend_rewrite(); + void append_remaining_args(std::vector &list); + void apply_library_options(); + bool change_setting(); + + void set_msg_type(); + void define_macros(); + void undefine_macros(); + void read_target(); + void read_f_file(); + void read_verilog(const VerilogStandard &standard); + void read_vhdl(const VhdlStandard &standard); + void read_edif(); + void read_liberty(); + void pretty_print(); + void import_design(); + void configure(); + void run_extension(); +}; + +YOSYS_NAMESPACE_END + +#endif +#endif diff --git a/chips/yosys/frontends/verific/verific_extnets.cc b/chips/yosys/frontends/verific/verific_extnets.cc new file mode 100644 index 0000000000000000000000000000000000000000..e58b7b622e85444cece1a5f16cc529b31ca3999e --- /dev/null +++ b/chips/yosys/frontends/verific/verific_extnets.cc @@ -0,0 +1,175 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" + +#include "frontends/verific/verific.h" + +#ifdef VERIFIC_NAMESPACE +using namespace Verific; +#endif + +YOSYS_NAMESPACE_BEGIN + +struct VerificExtNets +{ + int portname_cnt = 0; + + // a map from Net to the same Net one level up in the design hierarchy + std::map net_level_up_drive_up; + std::map net_level_up_drive_down; + + Net *route_up(Net *net, bool drive_up, Net *final_net = nullptr) + { + auto &net_level_up = drive_up ? net_level_up_drive_up : net_level_up_drive_down; + + if (net_level_up.count(net) == 0) + { + Netlist *nl = net->Owner(); + + // Simply return if Netlist is not unique + log_assert(nl->NumOfRefs() == 1); + + Instance *up_inst = (Instance*)nl->GetReferences()->GetLast(); + Netlist *up_nl = up_inst->Owner(); + + // create new Port + string name = stringf("___extnets_%d", portname_cnt++); + Port *new_port = new Port(name.c_str(), drive_up ? DIR_OUT : DIR_IN); + nl->Add(new_port); + nl->Buf(net)->Connect(new_port); + + // create new Net in up Netlist + Net *new_net = final_net; + if (new_net == nullptr || new_net->Owner() != up_nl) { + new_net = new Net(name.c_str()); + up_nl->Add(new_net); + } + up_inst->Connect(new_port, new_net); + + net_level_up[net] = new_net; + } + + return net_level_up.at(net); + } + + Net *route_up(Net *net, bool drive_up, Netlist *dest, Net *final_net = nullptr) + { + while (net->Owner() != dest) + net = route_up(net, drive_up, final_net); + if (final_net != nullptr) + log_assert(net == final_net); + return net; + } + + Netlist *find_common_ancestor(Netlist *A, Netlist *B) + { + std::set ancestors_of_A; + + Netlist *cursor = A; + while (1) { + ancestors_of_A.insert(cursor); + if (cursor->NumOfRefs() != 1) + break; + cursor = ((Instance*)cursor->GetReferences()->GetLast())->Owner(); + } + + cursor = B; + while (1) { + if (ancestors_of_A.count(cursor)) + return cursor; + if (cursor->NumOfRefs() != 1) + break; + cursor = ((Instance*)cursor->GetReferences()->GetLast())->Owner(); + } + + log_error("No common ancestor found between %s and %s.\n", get_full_netlist_name(A), get_full_netlist_name(B)); + } + + void run(Netlist *nl) + { + MapIter mi, mi2; + Instance *inst; + PortRef *pr; + + vector> todo_connect; + + FOREACH_INSTANCE_OF_NETLIST(nl, mi, inst) + run(inst->View()); + + FOREACH_INSTANCE_OF_NETLIST(nl, mi, inst) + FOREACH_PORTREF_OF_INST(inst, mi2, pr) + { + Port *port = pr->GetPort(); + Net *net = pr->GetNet(); + + if (!net->IsExternalTo(nl)) + continue; + + if (verific_verbose) + log("Fixing external net reference on port %s.%s.%s:\n", get_full_netlist_name(nl), inst->Name(), port->Name()); + + Netlist *ext_nl = net->Owner(); + + if (verific_verbose) + log(" external net owner: %s\n", get_full_netlist_name(ext_nl)); + + Netlist *ca_nl = find_common_ancestor(nl, ext_nl); + + if (verific_verbose) + log(" common ancestor: %s\n", get_full_netlist_name(ca_nl)); + + Net *ca_net = route_up(net, !port->IsOutput(), ca_nl); + Net *new_net = ca_net; + + if (ca_nl != nl) + { + if (verific_verbose) + log(" net in common ancestor: %s\n", ca_net->Name()); + + string name = stringf("___extnets_%d", portname_cnt++); + new_net = new Net(name.c_str()); + nl->Add(new_net); + + Net *n = route_up(new_net, port->IsOutput(), ca_nl, ca_net); + log_assert(n == ca_net); + } + + if (verific_verbose) + log(" new local net: %s\n", new_net->Name()); + + log_assert(!new_net->IsExternalTo(nl)); + todo_connect.push_back(tuple(inst, port, new_net)); + } + + for (auto it : todo_connect) { + get<0>(it)->Disconnect(get<1>(it)); + get<0>(it)->Connect(get<1>(it), get<2>(it)); + } + } +}; + +void verific_extnets(const std::map &nl_todo) +{ + VerificExtNets worker; + for (auto nl : nl_todo) + worker.run(nl.second); +} + +YOSYS_NAMESPACE_END diff --git a/chips/yosys/frontends/verific/verific_importer.cc b/chips/yosys/frontends/verific/verific_importer.cc new file mode 100644 index 0000000000000000000000000000000000000000..93b35bb64575d1963989e3bfdf58ea6c8f1ccb21 --- /dev/null +++ b/chips/yosys/frontends/verific/verific_importer.cc @@ -0,0 +1,2260 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" +#include "kernel/sigtools.h" +#include "kernel/celltypes.h" +#include "kernel/log.h" +#include "kernel/utils.h" +#include "libs/sha1/sha1.h" + +#include "frontends/verific/verific.h" + +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Woverloaded-virtual" +#endif + +#include "Array.h" + +#ifdef VERIFIC_VHDL_SUPPORT +#include "NameSpace.h" +#endif + +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + +#ifdef VERIFIC_NAMESPACE +using namespace Verific; +#endif + +YOSYS_NAMESPACE_BEGIN + +static std::string format_src_location(DesignObj *obj) +{ + if (obj == nullptr || !obj->Linefile()) + return std::string(); +#ifdef VERIFIC_LINEFILE_INCLUDES_COLUMNS + return stringf("%s:%d.%d-%d.%d", LineFile::GetFileName(obj->Linefile()), obj->Linefile()->GetLeftLine(), obj->Linefile()->GetLeftCol(), obj->Linefile()->GetRightLine(), obj->Linefile()->GetRightCol()); +#else + return stringf("%s:%d", LineFile::GetFileName(obj->Linefile()), LineFile::GetLineNo(obj->Linefile())); +#endif +} + +static std::string announce_src_location(DesignObj *obj) +{ + std::string loc = format_src_location(obj); + if (loc.empty()) + return std::string(); + return loc + ": "; +} + +VerificImporter::VerificImporter(bool mode_gates, bool mode_keep, bool mode_nosva, bool mode_sva_continue, bool mode_names, bool mode_verific, bool mode_autocover, bool mode_fullinit) : + mode_gates(mode_gates), mode_keep(mode_keep), mode_nosva(mode_nosva), mode_sva_continue(mode_sva_continue), + mode_names(mode_names), mode_verific(mode_verific), mode_autocover(mode_autocover), + mode_fullinit(mode_fullinit) +{ +} + +RTLIL::SigBit VerificImporter::net_map_at(Net *net) +{ + if (net->IsExternalTo(netlist)) + log_error("Found external reference to '%s.%s' in netlist '%s', please use -flatten or -extnets.\n", + get_full_netlist_name(net->Owner()), net->Name(), get_full_netlist_name(netlist)); + + return net_map.at(net); +} + +static bool is_blackbox(Netlist *nl) +{ + if (nl->IsBlackBox() || nl->IsEmptyBox()) + return true; + + const char *attr = nl->GetAttValue("blackbox"); + if (attr != nullptr && strcmp(attr, "0")) + return true; + + return false; +} + +RTLIL::IdString VerificImporter::new_verific_id(Verific::DesignObj *obj) +{ + std::string s = stringf("$verific$%s", obj->Name()); + if (obj->Linefile()) + s += stringf("$%s:%d", RTLIL::encode_filename(Verific::LineFile::GetFileName(obj->Linefile())), Verific::LineFile::GetLineNo(obj->Linefile())); + s += stringf("$%d", module->twines().next_autoidx()); + return module->twines().add(std::move(s)); +} + +static const RTLIL::Const extract_vhdl_boolean(std::string &val) +{ + if (val == "false") + return RTLIL::Const::from_string("0"); + if (val == "true") + return RTLIL::Const::from_string("1"); + log_error("Expecting VHDL boolean value.\n"); +} + +static const RTLIL::Const extract_vhdl_bit(std::string &val, std::string &typ) +{ + if (val.size()==3 && val[0]=='\'' && val.back()=='\'') + return RTLIL::Const::from_string(val.substr(1,val.size()-2)); + log_error("Error parsing VHDL %s.\n", typ); +} + +static const RTLIL::Const extract_vhdl_bit_vector(std::string &val, std::string &typ) +{ + if (val.size()>1 && val[0]=='\"' && val.back()=='\"') { + RTLIL::Const c = RTLIL::Const::from_string(val.substr(1,val.size()-2)); + if (typ == "signed") + c.flags |= RTLIL::CONST_FLAG_SIGNED; + return c; + } + log_error("Error parsing VHDL %s.\n", typ); +} + +static const RTLIL::Const extract_vhdl_integer(std::string &val) +{ + char *end; + return RTLIL::Const((int)std::strtol(val.c_str(), &end, 10)); +} + +static const RTLIL::Const extract_vhdl_char(std::string &val) +{ + if (val.size()==3 && val[0]=='\"' && val.back()=='\"') + return RTLIL::Const((int)val[1]); + log_error("Error parsing VHDL character.\n"); +} + +static const RTLIL::Const extract_real_value(std::string &val) +{ + RTLIL::Const c(val); + c.flags |= RTLIL::CONST_FLAG_REAL; + return c; +} + +static const RTLIL::Const extract_vhdl_string(std::string &val) +{ + if (!(val.size()>1 && val[0]=='\"' && val.back()=='\"')) + log_error("Error parsing VHDL string.\n"); + return RTLIL::Const(val.substr(1,val.size()-2)); +} + +static const RTLIL::Const extract_vhdl_const(const char *value, bool output_signed) +{ + RTLIL::Const c; + char *end; + int decimal; + bool is_signed = false; + std::string val = std::string(value); + + if (val.size()>1 && val[0]=='\"' && val.back()=='\"') { + std::string data = val.substr(1,val.size()-2); + bool isBinary = std::all_of(data.begin(), data.end(), [](char c) {return c=='1' || c=='0'; }); + if (isBinary) + c = RTLIL::Const::from_string(data); + else + c = RTLIL::Const(data); + } else if (val.size()==3 && val[0]=='\'' && val.back()=='\'') { + c = RTLIL::Const::from_string(val.substr(1,val.size()-2)); + } else if ((value[0] == '-' || (value[0] >= '0' && value[0] <= '9')) && + ((decimal = std::strtol(value, &end, 10)), !end[0])) { + is_signed = output_signed; + c = RTLIL::Const((int)decimal); + } else if (val == "false") { + c = RTLIL::Const::from_string("0"); + } else if (val == "true") { + c = RTLIL::Const::from_string("1"); + } else { + c = RTLIL::Const(val); + log_warning("encoding value '%s' as string.\n", value); + } + if (is_signed) + c.flags |= RTLIL::CONST_FLAG_SIGNED; + return c; +} + +static const RTLIL::Const extract_verilog_const(const char *value, bool allow_string, bool output_signed) +{ + RTLIL::Const c; + char *end; + int decimal; + bool is_signed = false; + size_t found; + std::string val = std::string(value); + + if (allow_string && val.size()>1 && val[0]=='\"' && val.back()=='\"') { + c = RTLIL::Const(val.substr(1,val.size()-2)); + } else if ((found = val.find("'sb")) != std::string::npos) { + is_signed = output_signed; + c = RTLIL::Const::from_string(val.substr(found + 3)); + } else if ((found = val.find("'b")) != std::string::npos) { + c = RTLIL::Const::from_string(val.substr(found + 2)); + } else if ((value[0] == '-' || (value[0] >= '0' && value[0] <= '9')) && + ((decimal = std::strtol(value, &end, 10)), !end[0])) { + is_signed = output_signed; + c = RTLIL::Const((int)decimal); + } else if (allow_string) { + c = RTLIL::Const(val); + } else { + c = RTLIL::Const(val); + log_warning("encoding value '%s' as string.\n", value); + } + if (is_signed) + c.flags |= RTLIL::CONST_FLAG_SIGNED; + return c; +} + +// When used as attributes or parameter values Verific constants come already processed. +// - Real string values are already under quotes +// - Numeric values with specified width are always converted to binary +// - Rest of user defined values are handled as 32bit integers +// - There could be some internal values that are strings without quotes +// so we check if value is all digits or not +// +// Note: For signed values, verific uses 'sb and decimal values can +// also be negative. +static const RTLIL::Const verific_const(const char* type_name, const char *value, DesignObj *obj, bool allow_string = true, bool output_signed = false) +{ + std::string val = std::string(value); + // VHDL + if (obj->IsFromVhdl()) { + if (type_name) { + std::string typ = std::string(type_name); + transform(typ.begin(), typ.end(), typ.begin(), ::tolower); + if (typ == "integer" || typ == "natural" || typ=="positive") return extract_vhdl_integer(val); + else if (typ =="boolean") return extract_vhdl_boolean(val); + else if (typ == "bit" || typ =="std_logic" || typ == "std_ulogic") return extract_vhdl_bit(val,typ); + else if (typ == "character") return extract_vhdl_char(val); + else if (typ == "bit_vector" || typ == "std_logic_vector" || typ == "std_ulogic_vector" || + typ == "unsigned" || typ == "signed") return extract_vhdl_bit_vector(val,typ); + else if (typ == "real") return extract_real_value(val); + else if (typ == "string") return extract_vhdl_string(val); + else { + if (val.size()>1 && val[0]=='\"' && val.back()=='\"') + return RTLIL::Const(val.substr(1,val.size()-2)); + else if (val.size()==3 && val[0]=='\'' && val.back()=='\'') + return RTLIL::Const(val.substr(1,val.size()-2)); + else + return RTLIL::Const(val); + } + } else + return extract_vhdl_const(value, output_signed); + } + // SystemVerilog + if (type_name && strcmp(type_name, "real")==0) { + return extract_real_value(val); + } else + return extract_verilog_const(value, allow_string, output_signed); +} + +#ifdef YOSYSHQ_VERIFIC_API_VERSION +static const std::string verific_unescape(const char *value) +{ + std::string val = std::string(value); + if (val.size()>1 && val[0]=='\"' && val.back()=='\"') + return val.substr(1,val.size()-2); + return value; +} +#endif + +void VerificImporter::import_attributes(dict &attributes, DesignObj *obj, Netlist *nl, int wire_width_hint) +{ + if (!obj) + return; + + MapIter mi; + Att *attr; + + if (obj->Linefile()) + attributes[ID::src] = format_src_location(obj); + + FOREACH_ATTRIBUTE(obj, mi, attr) { + if (attr->Key()[0] == ' ' || attr->Value() == nullptr) + continue; + attributes[module->twines().add(RTLIL::escape_id(attr->Key()))] = verific_const(nullptr, attr->Value(), obj); + } + + if (nl) { + auto type_range = nl->GetTypeRange(obj->Name()); + if (!type_range) + return; + if (nl->IsFromVhdl() && type_range->IsTypeScalar()) { + const long long bottom_bound = type_range->GetScalarRangeLeftBound(); + const long long top_bound = type_range->GetScalarRangeRightBound(); + int bit_width = type_range->LeftRangeBound()+1; + if (bit_width <= 0) { // VHDL null range + if (wire_width_hint >= 0) + bit_width = wire_width_hint; + else + bit_width = 64; //fallback, currently largest integer width that verific will allow (in vhdl2019 mode) + } else { + if (wire_width_hint >= 0) log_assert(bit_width == wire_width_hint); + } + RTLIL::Const bottom_const(bottom_bound, bit_width); + RTLIL::Const top_const(top_bound, bit_width); + if (bottom_bound < 0 || top_bound < 0) { + bottom_const.flags |= RTLIL::CONST_FLAG_SIGNED; + top_const.flags |= RTLIL::CONST_FLAG_SIGNED; + } + attributes.emplace(ID(bottom_bound), bottom_const); + attributes.emplace(ID(top_bound), top_const); + } + if (!type_range->IsTypeEnum()) + return; +#ifdef VERIFIC_VHDL_SUPPORT + if (nl->IsFromVhdl() && strcmp(type_range->GetTypeName(), "STD_LOGIC") == 0) + return; +#endif + auto type_name = type_range->GetTypeName(); + if (!type_name) + return; + attributes.emplace(ID::wiretype, RTLIL::escape_id(type_name)); + + MapIter mi; + const char *k, *v; + FOREACH_MAP_ITEM(type_range->GetEnumIdMap(), mi, &k, &v) { + if (nl->IsFromVerilog()) { + auto const value = verific_const(type_name, v, nl, false); + + attributes.emplace(module->twines().add(stringf("\\enum_value_%s", value.as_string())), RTLIL::escape_id(k)); + } +#ifdef VERIFIC_VHDL_SUPPORT + else if (nl->IsFromVhdl()) { + // Expect "" or plain + auto p = v; + if (p) { + if (*p != '"') { + auto l = strlen(p); + auto q = (char*)malloc(l+1); + strncpy(q, p, l); + q[l] = '\0'; + for(char *ptr = q; *ptr; ++ptr )*ptr = tolower(*ptr); + attributes.emplace(module->twines().add(stringf("\\enum_value_%s", q)), RTLIL::escape_id(k)); + } else { + auto *q = p+1; + for (; *q != '"'; q++) + if (*q != '0' && *q != '1') { + p = nullptr; + break; + } + if (p && *(q+1) != '\0') + p = nullptr; + + if (p != nullptr) + { + auto l = strlen(p); + auto q = (char*)malloc(l+1-2); + strncpy(q, p+1, l-2); + q[l-2] = '\0'; + attributes.emplace(module->twines().add(stringf("\\enum_value_%s", q)), RTLIL::escape_id(k)); + free(q); + } + } + } + if (p == nullptr) + log_error("%sExpected TypeRange value '%s' to be of form \"\" or .\n", announce_src_location(obj), v); + } +#endif + } + } +} + +RTLIL::SigBit VerificImporter::netToSigBit(Verific::Net *net) { + if (net && net->IsGnd()) + return RTLIL::State::S0; + else if (net && net->IsPwr()) + return RTLIL::State::S1; + else if (net && net->IsX()) + return RTLIL::State::Sx; + else if (net) + return net_map_at(net); + else + return RTLIL::State::Sz; +} + +RTLIL::SigSpec VerificImporter::operatorInput(Instance *inst) +{ + RTLIL::SigSpec sig; + for (int i = int(inst->InputSize())-1; i >= 0; i--) { + Net *net = inst->GetInputBit(i); + sig.append(netToSigBit(net)); + } + return sig; +} + +RTLIL::SigSpec VerificImporter::operatorInput1(Instance *inst) +{ + RTLIL::SigSpec sig; + for (int i = int(inst->Input1Size())-1; i >= 0; i--) { + Net *net = inst->GetInput1Bit(i); + sig.append(netToSigBit(net)); + } + return sig; +} + +RTLIL::SigSpec VerificImporter::operatorInput2(Instance *inst) +{ + RTLIL::SigSpec sig; + for (int i = int(inst->Input2Size())-1; i >= 0; i--) { + Net *net = inst->GetInput2Bit(i); + sig.append(netToSigBit(net)); + } + return sig; +} + +RTLIL::SigSpec VerificImporter::operatorInport(Instance *inst, const char *portname) +{ + PortBus *portbus = inst->View()->GetPortBus(portname); + if (portbus) { + RTLIL::SigSpec sig; + for (unsigned i = 0; i < portbus->Size(); i++) { + Net *net = inst->GetNet(portbus->ElementAtIndex(i)); + if (net) { + if (net->IsConstant()) { + if (net->IsGnd()) + sig.append(RTLIL::State::S0); + else if (net->IsPwr()) + sig.append(RTLIL::State::S1); + else if (net->IsX()) + sig.append(RTLIL::State::Sx); + else + sig.append(RTLIL::State::Sz); + } + else + sig.append(net_map_at(net)); + } else + sig.append(RTLIL::State::Sz); + } + return sig; + } else { + Port *port = inst->View()->GetPort(portname); + log_assert(port != NULL); + Net *net = inst->GetNet(port); + return net_map_at(net); + } +} + +RTLIL::SigSpec VerificImporter::operatorInportCase(Instance *inst, const char *portname) +{ + PortBus *portbus = inst->View()->GetPortBus(portname); + if (portbus) { + RTLIL::SigSpec sig; + for (unsigned i = 0; i < portbus->Size(); i++) { + Net *net = inst->GetNet(portbus->ElementAtIndex(i)); + if (net) { + if (net->IsConstant()) { + if (net->IsGnd()) + sig.append(RTLIL::State::S0); + else if (net->IsPwr()) + sig.append(RTLIL::State::S1); + else + sig.append(RTLIL::State::Sa); + } + else + sig.append(net_map_at(net)); + } else + sig.append(RTLIL::State::Sa); + } + return sig; + } else { + Port *port = inst->View()->GetPort(portname); + log_assert(port != NULL); + Net *net = inst->GetNet(port); + return net_map_at(net); + } +} + +RTLIL::SigSpec VerificImporter::operatorOutput(Instance *inst, const pool *any_all_nets) +{ + RTLIL::SigSpec sig; + RTLIL::Wire *dummy_wire = NULL; + for (int i = int(inst->OutputSize())-1; i >= 0; i--) + if (inst->GetOutputBit(i) && (!any_all_nets || !any_all_nets->count(inst->GetOutputBit(i)))) { + sig.append(net_map_at(inst->GetOutputBit(i))); + dummy_wire = NULL; + } else { + if (dummy_wire == NULL) + dummy_wire = module->addWire(new_verific_id(inst)); + else + dummy_wire->width++; + sig.append(RTLIL::SigSpec(dummy_wire, dummy_wire->width - 1)); + } + return sig; +} + +bool VerificImporter::import_netlist_instance_gates(Instance *inst, RTLIL::IdString inst_name) +{ + if (inst->Type() == PRIM_AND) { + module->addAndGate(inst_name, net_map_at(inst->GetInput1()), net_map_at(inst->GetInput2()), net_map_at(inst->GetOutput())); + return true; + } + + if (inst->Type() == PRIM_NAND) { + RTLIL::SigSpec tmp = module->addWire(new_verific_id(inst)); + module->addAndGate(new_verific_id(inst), net_map_at(inst->GetInput1()), net_map_at(inst->GetInput2()), tmp); + module->addNotGate(inst_name, tmp, net_map_at(inst->GetOutput())); + return true; + } + + if (inst->Type() == PRIM_OR) { + module->addOrGate(inst_name, net_map_at(inst->GetInput1()), net_map_at(inst->GetInput2()), net_map_at(inst->GetOutput())); + return true; + } + + if (inst->Type() == PRIM_NOR) { + RTLIL::SigSpec tmp = module->addWire(new_verific_id(inst)); + module->addOrGate(new_verific_id(inst), net_map_at(inst->GetInput1()), net_map_at(inst->GetInput2()), tmp); + module->addNotGate(inst_name, tmp, net_map_at(inst->GetOutput())); + return true; + } + + if (inst->Type() == PRIM_XOR) { + module->addXorGate(inst_name, net_map_at(inst->GetInput1()), net_map_at(inst->GetInput2()), net_map_at(inst->GetOutput())); + return true; + } + + if (inst->Type() == PRIM_XNOR) { + module->addXnorGate(inst_name, net_map_at(inst->GetInput1()), net_map_at(inst->GetInput2()), net_map_at(inst->GetOutput())); + return true; + } + + if (inst->Type() == PRIM_BUF) { + auto outnet = inst->GetOutput(); + if (!any_all_nets.count(outnet)) + module->addBufGate(inst_name, net_map_at(inst->GetInput()), net_map_at(outnet)); + return true; + } + + if (inst->Type() == PRIM_INV) { + module->addNotGate(inst_name, net_map_at(inst->GetInput()), net_map_at(inst->GetOutput())); + return true; + } + + if (inst->Type() == PRIM_MUX) { + module->addMuxGate(inst_name, net_map_at(inst->GetInput1()), net_map_at(inst->GetInput2()), net_map_at(inst->GetControl()), net_map_at(inst->GetOutput())); + return true; + } + + if ((inst->Type() == PRIM_TRI) || (inst->Type() == PRIM_BUFIF1)) { + module->addMuxGate(inst_name, RTLIL::State::Sz, net_map_at(inst->GetInput()), net_map_at(inst->GetControl()), net_map_at(inst->GetOutput())); + return true; + } + + if (inst->Type() == PRIM_FADD) + { + RTLIL::SigSpec a = net_map_at(inst->GetInput1()), b = net_map_at(inst->GetInput2()), c = net_map_at(inst->GetCin()); + RTLIL::SigSpec x = inst->GetCout() ? net_map_at(inst->GetCout()) : module->addWire(new_verific_id(inst)); + RTLIL::SigSpec y = inst->GetOutput() ? net_map_at(inst->GetOutput()) : module->addWire(new_verific_id(inst)); + RTLIL::SigSpec tmp1 = module->addWire(new_verific_id(inst)); + RTLIL::SigSpec tmp2 = module->addWire(new_verific_id(inst)); + RTLIL::SigSpec tmp3 = module->addWire(new_verific_id(inst)); + module->addXorGate(new_verific_id(inst), a, b, tmp1); + module->addXorGate(inst_name, tmp1, c, y); + module->addAndGate(new_verific_id(inst), tmp1, c, tmp2); + module->addAndGate(new_verific_id(inst), a, b, tmp3); + module->addOrGate(new_verific_id(inst), tmp2, tmp3, x); + return true; + } + + if (inst->Type() == PRIM_DFFRS) + { + VerificClocking clocking(this, inst->GetClock()); + log_assert(clocking.disable_sig == State::S0); + log_assert(clocking.body_net == nullptr); + + if (inst->GetSet()->IsGnd() && inst->GetReset()->IsGnd()) + clocking.addDff(inst_name, net_map_at(inst->GetInput()), net_map_at(inst->GetOutput())); + else if (inst->GetSet()->IsGnd()) + clocking.addAdff(inst_name, net_map_at(inst->GetReset()), net_map_at(inst->GetInput()), net_map_at(inst->GetOutput()), State::S0); + else if (inst->GetReset()->IsGnd()) + clocking.addAdff(inst_name, net_map_at(inst->GetSet()), net_map_at(inst->GetInput()), net_map_at(inst->GetOutput()), State::S1); + else + clocking.addDffsr(inst_name, net_map_at(inst->GetSet()), net_map_at(inst->GetReset()), + net_map_at(inst->GetInput()), net_map_at(inst->GetOutput())); + return true; + } + + if (inst->Type() == PRIM_DLATCHRS) + { + if (inst->GetSet()->IsGnd() && inst->GetReset()->IsGnd()) + module->addDlatch(inst_name, net_map_at(inst->GetControl()), net_map_at(inst->GetInput()), net_map_at(inst->GetOutput())); + else + module->addDlatchsr(inst_name, net_map_at(inst->GetControl()), net_map_at(inst->GetSet()), net_map_at(inst->GetReset()), + net_map_at(inst->GetInput()), net_map_at(inst->GetOutput())); + return true; + } + + if (inst->Type() == PRIM_DFF) + { + VerificClocking clocking(this, inst->GetClock()); + log_assert(clocking.disable_sig == State::S0); + log_assert(clocking.body_net == nullptr); + + if (inst->GetAsyncCond()->IsGnd()) + clocking.addDff(inst_name, net_map_at(inst->GetInput()), net_map_at(inst->GetOutput())); + else + clocking.addAldff(inst_name, net_map_at(inst->GetAsyncCond()), net_map_at(inst->GetAsyncVal()), + net_map_at(inst->GetInput()), net_map_at(inst->GetOutput())); + return true; + } + + if (inst->Type() == PRIM_DLATCH) + { + if (inst->GetAsyncCond()->IsGnd()) { + module->addDlatch(inst_name, net_map_at(inst->GetControl()), net_map_at(inst->GetInput()), net_map_at(inst->GetOutput())); + } else { + RTLIL::SigSpec sig_set = module->And(NEW_ID, net_map_at(inst->GetAsyncCond()), net_map_at(inst->GetAsyncVal())); + RTLIL::SigSpec sig_clr = module->And(NEW_ID, net_map_at(inst->GetAsyncCond()), module->Not(NEW_ID, net_map_at(inst->GetAsyncVal()))); + module->addDlatchsr(inst_name, net_map_at(inst->GetControl()), sig_set, sig_clr, net_map_at(inst->GetInput()), net_map_at(inst->GetOutput())); + } + return true; + } + + return false; +} + +bool VerificImporter::import_netlist_instance_cells(Instance *inst, RTLIL::IdString inst_name) +{ + RTLIL::Cell *cell = nullptr; + + if (inst->Type() == PRIM_AND) { + cell = module->addAnd(inst_name, net_map_at(inst->GetInput1()), net_map_at(inst->GetInput2()), net_map_at(inst->GetOutput())); + import_attributes(cell->attributes, inst); + return true; + } + + if (inst->Type() == PRIM_NAND) { + RTLIL::SigSpec tmp = module->addWire(new_verific_id(inst)); + cell = module->addAnd(new_verific_id(inst), net_map_at(inst->GetInput1()), net_map_at(inst->GetInput2()), tmp); + import_attributes(cell->attributes, inst); + cell = module->addNot(inst_name, tmp, net_map_at(inst->GetOutput())); + import_attributes(cell->attributes, inst); + return true; + } + + if (inst->Type() == PRIM_OR) { + cell = module->addOr(inst_name, net_map_at(inst->GetInput1()), net_map_at(inst->GetInput2()), net_map_at(inst->GetOutput())); + import_attributes(cell->attributes, inst); + return true; + } + + if (inst->Type() == PRIM_NOR) { + RTLIL::SigSpec tmp = module->addWire(new_verific_id(inst)); + cell = module->addOr(new_verific_id(inst), net_map_at(inst->GetInput1()), net_map_at(inst->GetInput2()), tmp); + import_attributes(cell->attributes, inst); + cell = module->addNot(inst_name, tmp, net_map_at(inst->GetOutput())); + import_attributes(cell->attributes, inst); + return true; + } + + if (inst->Type() == PRIM_XOR) { + cell = module->addXor(inst_name, net_map_at(inst->GetInput1()), net_map_at(inst->GetInput2()), net_map_at(inst->GetOutput())); + import_attributes(cell->attributes, inst); + return true; + } + + if (inst->Type() == PRIM_XNOR) { + cell = module->addXnor(inst_name, net_map_at(inst->GetInput1()), net_map_at(inst->GetInput2()), net_map_at(inst->GetOutput())); + import_attributes(cell->attributes, inst); + return true; + } + + if (inst->Type() == PRIM_INV) { + cell = module->addNot(inst_name, net_map_at(inst->GetInput()), net_map_at(inst->GetOutput())); + import_attributes(cell->attributes, inst); + return true; + } + + if (inst->Type() == PRIM_MUX) { + cell = module->addMux(inst_name, net_map_at(inst->GetInput1()), net_map_at(inst->GetInput2()), net_map_at(inst->GetControl()), net_map_at(inst->GetOutput())); + import_attributes(cell->attributes, inst); + return true; + } + + if ((inst->Type() == PRIM_TRI) || (inst->Type() == PRIM_BUFIF1)) { + cell = module->addMux(inst_name, RTLIL::State::Sz, net_map_at(inst->GetInput()), net_map_at(inst->GetControl()), net_map_at(inst->GetOutput())); + import_attributes(cell->attributes, inst); + return true; + } + + if (inst->Type() == PRIM_FADD) + { + RTLIL::SigSpec a_plus_b = module->addWire(new_verific_id(inst), 2); + RTLIL::SigSpec y = inst->GetOutput() ? net_map_at(inst->GetOutput()) : module->addWire(new_verific_id(inst)); + if (inst->GetCout()) + y.append(net_map_at(inst->GetCout())); + cell = module->addAdd(new_verific_id(inst), net_map_at(inst->GetInput1()), net_map_at(inst->GetInput2()), a_plus_b); + import_attributes(cell->attributes, inst); + cell = module->addAdd(inst_name, a_plus_b, net_map_at(inst->GetCin()), y); + import_attributes(cell->attributes, inst); + return true; + } + + if (inst->Type() == PRIM_DFFRS) + { + VerificClocking clocking(this, inst->GetClock()); + log_assert(clocking.disable_sig == State::S0); + log_assert(clocking.body_net == nullptr); + + if (inst->GetSet()->IsGnd() && inst->GetReset()->IsGnd()) + cell = clocking.addDff(inst_name, net_map_at(inst->GetInput()), net_map_at(inst->GetOutput())); + else if (inst->GetSet()->IsGnd()) + cell = clocking.addAdff(inst_name, net_map_at(inst->GetReset()), net_map_at(inst->GetInput()), net_map_at(inst->GetOutput()), RTLIL::State::S0); + else if (inst->GetReset()->IsGnd()) + cell = clocking.addAdff(inst_name, net_map_at(inst->GetSet()), net_map_at(inst->GetInput()), net_map_at(inst->GetOutput()), RTLIL::State::S1); + else + cell = clocking.addDffsr(inst_name, net_map_at(inst->GetSet()), net_map_at(inst->GetReset()), + net_map_at(inst->GetInput()), net_map_at(inst->GetOutput())); + import_attributes(cell->attributes, inst); + return true; + } + + if (inst->Type() == PRIM_DLATCHRS) + { + if (inst->GetSet()->IsGnd() && inst->GetReset()->IsGnd()) + cell = module->addDlatch(inst_name, net_map_at(inst->GetControl()), net_map_at(inst->GetInput()), net_map_at(inst->GetOutput())); + else + cell = module->addDlatchsr(inst_name, net_map_at(inst->GetControl()), net_map_at(inst->GetSet()), net_map_at(inst->GetReset()), + net_map_at(inst->GetInput()), net_map_at(inst->GetOutput())); + import_attributes(cell->attributes, inst); + return true; + } + + if (inst->Type() == PRIM_DFF) + { + VerificClocking clocking(this, inst->GetClock()); + log_assert(clocking.disable_sig == State::S0); + log_assert(clocking.body_net == nullptr); + + if (inst->GetAsyncCond()->IsGnd()) + cell = clocking.addDff(inst_name, net_map_at(inst->GetInput()), net_map_at(inst->GetOutput())); + else + cell = clocking.addAldff(inst_name, net_map_at(inst->GetAsyncCond()), net_map_at(inst->GetAsyncVal()), + net_map_at(inst->GetInput()), net_map_at(inst->GetOutput())); + import_attributes(cell->attributes, inst); + return true; + } + + if (inst->Type() == PRIM_DLATCH) + { + if (inst->GetAsyncCond()->IsGnd()) { + cell = module->addDlatch(inst_name, net_map_at(inst->GetControl()), net_map_at(inst->GetInput()), net_map_at(inst->GetOutput())); + } else { + RTLIL::SigSpec sig_set = module->And(NEW_ID, net_map_at(inst->GetAsyncCond()), net_map_at(inst->GetAsyncVal())); + RTLIL::SigSpec sig_clr = module->And(NEW_ID, net_map_at(inst->GetAsyncCond()), module->Not(NEW_ID, net_map_at(inst->GetAsyncVal()))); + cell = module->addDlatchsr(inst_name, net_map_at(inst->GetControl()), sig_set, sig_clr, net_map_at(inst->GetInput()), net_map_at(inst->GetOutput())); + } + import_attributes(cell->attributes, inst); + return true; + } + + #define IN operatorInput(inst) + #define IN1 operatorInput1(inst) + #define IN2 operatorInput2(inst) + #define OUT operatorOutput(inst) + #define FILTERED_OUT operatorOutput(inst, &any_all_nets) + #define SIGNED inst->View()->IsSigned() + + if (inst->Type() == OPER_ADDER) { + RTLIL::SigSpec out = OUT; + if (inst->GetCout() != NULL) + out.append(net_map_at(inst->GetCout())); + if (inst->GetCin()->IsGnd()) { + cell = module->addAdd(inst_name, IN1, IN2, out, SIGNED); + import_attributes(cell->attributes, inst); + } else { + RTLIL::SigSpec tmp = module->addWire(new_verific_id(inst), GetSize(out)); + cell = module->addAdd(new_verific_id(inst), IN1, IN2, tmp, SIGNED); + import_attributes(cell->attributes, inst); + cell = module->addAdd(inst_name, tmp, net_map_at(inst->GetCin()), out, false); + import_attributes(cell->attributes, inst); + } + return true; + } + + if (inst->Type() == OPER_MULTIPLIER) { + cell = module->addMul(inst_name, IN1, IN2, OUT, SIGNED); + import_attributes(cell->attributes, inst); + return true; + } + + if (inst->Type() == OPER_DIVIDER) { + cell = module->addDiv(inst_name, IN1, IN2, OUT, SIGNED); + import_attributes(cell->attributes, inst); + return true; + } + + if (inst->Type() == OPER_MODULO) { + cell = module->addMod(inst_name, IN1, IN2, OUT, SIGNED); + import_attributes(cell->attributes, inst); + return true; + } + + if (inst->Type() == OPER_REMAINDER) { + cell = module->addMod(inst_name, IN1, IN2, OUT, SIGNED); + import_attributes(cell->attributes, inst); + return true; + } + + if (inst->Type() == OPER_SHIFT_LEFT) { + cell = module->addShl(inst_name, IN1, IN2, OUT, false); + import_attributes(cell->attributes, inst); + return true; + } + + if (inst->Type() == OPER_ENABLED_DECODER) { + RTLIL::SigSpec vec; + vec.append(net_map_at(inst->GetControl())); + for (unsigned i = 1; i < inst->OutputSize(); i++) { + vec.append(RTLIL::State::S0); + } + cell = module->addShl(inst_name, vec, IN, OUT, false); + import_attributes(cell->attributes, inst); + return true; + } + + if (inst->Type() == OPER_DECODER) { + RTLIL::SigSpec vec; + vec.append(RTLIL::State::S1); + for (unsigned i = 1; i < inst->OutputSize(); i++) { + vec.append(RTLIL::State::S0); + } + cell = module->addShl(inst_name, vec, IN, OUT, false); + import_attributes(cell->attributes, inst); + return true; + } + + if (inst->Type() == OPER_SHIFT_RIGHT) { + Net *net_cin = inst->GetCin(); + Net *net_a_msb = inst->GetInput1Bit(0); + if (net_cin->IsGnd()) + cell = module->addShr(inst_name, IN1, IN2, OUT, false); + else if (net_cin == net_a_msb) + cell = module->addSshr(inst_name, IN1, IN2, OUT, true); + else + log_error("%sCan't import Verific OPER_SHIFT_RIGHT instance %s: carry_in is neither 0 nor msb of left input\n", announce_src_location(inst), inst->Name()); + import_attributes(cell->attributes, inst); + return true; + } + + if (inst->Type() == OPER_REDUCE_AND) { + cell = module->addReduceAnd(inst_name, IN, net_map_at(inst->GetOutput()), SIGNED); + import_attributes(cell->attributes, inst); + return true; + } + + if (inst->Type() == OPER_REDUCE_NAND) { + Wire *tmp = module->addWire(NEW_ID); + cell = module->addReduceAnd(inst_name, IN, tmp, SIGNED); + module->addNot(NEW_ID, tmp, net_map_at(inst->GetOutput())); + import_attributes(cell->attributes, inst); + return true; + } + + if (inst->Type() == OPER_REDUCE_OR) { + cell = module->addReduceOr(inst_name, IN, net_map_at(inst->GetOutput()), SIGNED); + import_attributes(cell->attributes, inst); + return true; + } + + if (inst->Type() == OPER_REDUCE_XOR) { + cell = module->addReduceXor(inst_name, IN, net_map_at(inst->GetOutput()), SIGNED); + import_attributes(cell->attributes, inst); + return true; + } + + if (inst->Type() == OPER_REDUCE_XNOR) { + cell = module->addReduceXnor(inst_name, IN, net_map_at(inst->GetOutput()), SIGNED); + import_attributes(cell->attributes, inst); + return true; + } + + if (inst->Type() == OPER_REDUCE_NOR) { + SigSpec t = module->ReduceOr(new_verific_id(inst), IN, SIGNED); + cell = module->addNot(inst_name, t, net_map_at(inst->GetOutput())); + import_attributes(cell->attributes, inst); + return true; + } + + if (inst->Type() == OPER_LESSTHAN) { + Net *net_cin = inst->GetCin(); + if (net_cin->IsGnd()) + cell = module->addLt(inst_name, IN1, IN2, net_map_at(inst->GetOutput()), SIGNED); + else if (net_cin->IsPwr()) + cell = module->addLe(inst_name, IN1, IN2, net_map_at(inst->GetOutput()), SIGNED); + else + log_error("%sCan't import Verific OPER_LESSTHAN instance %s: carry_in is neither 0 nor 1\n", announce_src_location(inst), inst->Name()); + import_attributes(cell->attributes, inst); + return true; + } + + if (inst->Type() == OPER_WIDE_AND) { + cell = module->addAnd(inst_name, IN1, IN2, OUT, SIGNED); + import_attributes(cell->attributes, inst); + return true; + } + + if (inst->Type() == OPER_WIDE_OR) { + cell = module->addOr(inst_name, IN1, IN2, OUT, SIGNED); + import_attributes(cell->attributes, inst); + return true; + } + + if (inst->Type() == OPER_WIDE_XOR) { + cell = module->addXor(inst_name, IN1, IN2, OUT, SIGNED); + import_attributes(cell->attributes, inst); + return true; + } + + if (inst->Type() == OPER_WIDE_XNOR) { + cell = module->addXnor(inst_name, IN1, IN2, OUT, SIGNED); + import_attributes(cell->attributes, inst); + return true; + } + + if (inst->Type() == OPER_WIDE_BUF) { + cell = module->addPos(inst_name, IN, FILTERED_OUT, SIGNED); + import_attributes(cell->attributes, inst); + return true; + } + + if (inst->Type() == OPER_WIDE_INV) { + cell = module->addNot(inst_name, IN, OUT, SIGNED); + import_attributes(cell->attributes, inst); + return true; + } + + if (inst->Type() == OPER_MINUS) { + cell = module->addSub(inst_name, IN1, IN2, OUT, SIGNED); + import_attributes(cell->attributes, inst); + return true; + } + + if (inst->Type() == OPER_UMINUS) { + cell = module->addNeg(inst_name, IN, OUT, SIGNED); + import_attributes(cell->attributes, inst); + return true; + } + + if (inst->Type() == OPER_EQUAL) { + cell = module->addEq(inst_name, IN1, IN2, net_map_at(inst->GetOutput()), SIGNED); + import_attributes(cell->attributes, inst); + return true; + } + + if (inst->Type() == OPER_NEQUAL) { + cell = module->addNe(inst_name, IN1, IN2, net_map_at(inst->GetOutput()), SIGNED); + import_attributes(cell->attributes, inst); + return true; + } + + if (inst->Type() == OPER_WIDE_MUX) { + cell = module->addMux(inst_name, IN1, IN2, net_map_at(inst->GetControl()), OUT); + import_attributes(cell->attributes, inst); + return true; + } + + if (inst->Type() == OPER_NTO1MUX) { + cell = module->addBmux(inst_name, IN2, IN1, net_map_at(inst->GetOutput())); + import_attributes(cell->attributes, inst); + return true; + } + + if (inst->Type() == OPER_WIDE_NTO1MUX) + { + cell = module->addBmux(inst_name, IN2, IN1, OUT); + import_attributes(cell->attributes, inst); + return true; + } + + if (inst->Type() == OPER_SELECTOR) + { + cell = module->addPmux(inst_name, State::S0, IN2, IN1, net_map_at(inst->GetOutput())); + import_attributes(cell->attributes, inst); + return true; + } + + if (inst->Type() == OPER_WIDE_SELECTOR) + { + SigSpec out = OUT; + cell = module->addPmux(inst_name, SigSpec(State::S0, GetSize(out)), IN2, IN1, out); + import_attributes(cell->attributes, inst); + return true; + } + + if (inst->Type() == OPER_WIDE_TRI) { + cell = module->addMux(inst_name, RTLIL::SigSpec(RTLIL::State::Sz, inst->OutputSize()), IN, net_map_at(inst->GetControl()), OUT); + import_attributes(cell->attributes, inst); + return true; + } + + if (inst->Type() == OPER_WIDE_DFFRS) + { + VerificClocking clocking(this, inst->GetClock()); + log_assert(clocking.disable_sig == State::S0); + log_assert(clocking.body_net == nullptr); + + RTLIL::SigSpec sig_set = operatorInport(inst, "set"); + RTLIL::SigSpec sig_reset = operatorInport(inst, "reset"); + + if (sig_set.is_fully_const() && !sig_set.as_bool() && sig_reset.is_fully_const() && !sig_reset.as_bool()) + cell = clocking.addDff(inst_name, IN, OUT); + else + cell = clocking.addDffsr(inst_name, sig_set, sig_reset, IN, OUT); + import_attributes(cell->attributes, inst); + + return true; + } + + if (inst->Type() == OPER_WIDE_DLATCHRS) + { + RTLIL::SigSpec sig_set = operatorInport(inst, "set"); + RTLIL::SigSpec sig_reset = operatorInport(inst, "reset"); + + if (sig_set.is_fully_const() && !sig_set.as_bool() && sig_reset.is_fully_const() && !sig_reset.as_bool()) + cell = module->addDlatch(inst_name, net_map_at(inst->GetControl()), IN, OUT); + else + cell = module->addDlatchsr(inst_name, net_map_at(inst->GetControl()), sig_set, sig_reset, IN, OUT); + import_attributes(cell->attributes, inst); + + return true; + } + + if (inst->Type() == OPER_WIDE_DFF) + { + VerificClocking clocking(this, inst->GetClock()); + log_assert(clocking.disable_sig == State::S0); + log_assert(clocking.body_net == nullptr); + + RTLIL::SigSpec sig_d = IN; + RTLIL::SigSpec sig_q = OUT; + RTLIL::SigSpec sig_adata = IN1; + RTLIL::SigSpec sig_acond = IN2; + + if (sig_acond.is_fully_const() && !sig_acond.as_bool()) { + cell = clocking.addDff(inst_name, sig_d, sig_q); + import_attributes(cell->attributes, inst); + } else { + int offset = 0, width = 0; + for (offset = 0; offset < GetSize(sig_acond); offset += width) { + for (width = 1; offset+width < GetSize(sig_acond); width++) + if (sig_acond[offset] != sig_acond[offset+width]) break; + cell = clocking.addAldff(module->uniquify(inst_name), sig_acond[offset], sig_adata.extract(offset, width), + sig_d.extract(offset, width), sig_q.extract(offset, width)); + import_attributes(cell->attributes, inst); + } + } + + return true; + } + + if (inst->Type() == OPER_WIDE_DLATCH) + { + RTLIL::SigSpec sig_d = IN; + RTLIL::SigSpec sig_q = OUT; + RTLIL::SigSpec sig_adata = IN1; + RTLIL::SigSpec sig_acond = IN2; + + if (sig_acond.is_fully_const() && !sig_acond.as_bool()) { + cell = module->addDlatch(inst_name, net_map_at(inst->GetControl()), sig_d, sig_q); + import_attributes(cell->attributes, inst); + } else { + int offset = 0, width = 0; + for (offset = 0; offset < GetSize(sig_acond); offset += width) { + for (width = 1; offset+width < GetSize(sig_acond); width++) + if (sig_acond[offset] != sig_acond[offset+width]) break; + RTLIL::SigSpec sig_set = module->Mux(NEW_ID, RTLIL::SigSpec(0, width), sig_adata.extract(offset, width), sig_acond[offset]); + RTLIL::SigSpec sig_clr = module->Mux(NEW_ID, RTLIL::SigSpec(0, width), module->Not(NEW_ID, sig_adata.extract(offset, width)), sig_acond[offset]); + cell = module->addDlatchsr(module->uniquify(inst_name), net_map_at(inst->GetControl()), sig_set, sig_clr, + sig_d.extract(offset, width), sig_q.extract(offset, width)); + import_attributes(cell->attributes, inst); + } + } + + return true; + } + + if (inst->Type() == OPER_WIDE_CASE_SELECT_BOX) + { + RTLIL::SigSpec sig_out_val = operatorInport(inst, "out_value"); + RTLIL::SigSpec sig_select = operatorInport(inst, "select"); + RTLIL::SigSpec sig_select_values = operatorInportCase(inst, "select_values"); + RTLIL::SigSpec sig_data_values = operatorInport(inst, "data_values"); + RTLIL::SigSpec sig_data_default = operatorInport(inst, "default_value"); + + RTLIL::Process *proc = module->addProcess(new_verific_id(inst)); + import_attributes(proc->attributes, inst); + + RTLIL::CaseRule *current_case = &proc->root_case; + current_case = &proc->root_case; + + RTLIL::SwitchRule *sw = new RTLIL::SwitchRule; + sw->signal = sig_select; + current_case->switches.push_back(sw); + + unsigned select_width = inst->InputSize(); + unsigned data_width = inst->OutputSize(); + unsigned offset_data = 0; + unsigned offset_select = 0; + + OperWideCaseSelector* selector = (OperWideCaseSelector*) inst->View(); + + for (unsigned i = 0 ; i < selector->GetNumBranches() ; ++i) { + + SigSig action(sig_out_val, sig_data_values.extract(offset_data, data_width)); + offset_data += data_width; + + for (unsigned j = 0 ; j < selector->GetNumConditions(i) ; ++j) { + Array left_bound, right_bound ; + selector->GetCondition(i, j, &left_bound, &right_bound); + + SigSpec sel_left = sig_select_values.extract(offset_select, select_width); + offset_select += select_width; + + if (right_bound.Size()) { + SigSpec sel_right = sig_select_values.extract(offset_select, select_width); + offset_select += select_width; + + log_assert(sel_right.is_fully_const() && sel_right.is_fully_def()); + log_assert(sel_left.is_fully_const() && sel_right.is_fully_def()); + + int32_t left = sel_left.as_int(); + int32_t right = sel_right.as_int(); + int width = sel_left.size(); + + for (int32_t i = right; icompare.push_back(RTLIL::Const(i,width)); + cs->actions.push_back(action); + sw->cases.push_back(cs); + } + } + + RTLIL::CaseRule *cs = new RTLIL::CaseRule; + cs->compare.push_back(sel_left); + cs->actions.push_back(action); + sw->cases.push_back(cs); + } + } + RTLIL::CaseRule *cs_default = new RTLIL::CaseRule; + cs_default->actions.push_back(SigSig(sig_out_val, sig_data_default)); + sw->cases.push_back(cs_default); + + return true; + } + +#ifdef YOSYSHQ_VERIFIC_API_VERSION + if (inst->Type() == OPER_YOSYSHQ_SET_TAG) + { + RTLIL::SigSpec sig_expr = operatorInport(inst, "expr"); + RTLIL::SigSpec sig_set_mask = operatorInport(inst, "set_mask"); + RTLIL::SigSpec sig_clr_mask = operatorInport(inst, "clr_mask"); + RTLIL::SigSpec sig_o = operatorOutput(inst); + std::string tag = inst->GetAtt("tag") ? verific_unescape(inst->GetAttValue("tag")) : ""; + module->connect(sig_o, module->SetTag(new_verific_id(inst), tag, sig_expr, sig_set_mask, sig_clr_mask)); + return true; + } + if (inst->Type() == OPER_YOSYSHQ_GET_TAG) + { + std::string tag = inst->GetAtt("tag") ? verific_unescape(inst->GetAttValue("tag")) : ""; + module->connect(operatorOutput(inst),module->GetTag(new_verific_id(inst), tag, operatorInput(inst))); + return true; + } + if (inst->Type() == OPER_YOSYSHQ_OVERWRITE_TAG) + { + RTLIL::SigSpec sig_signal = operatorInport(inst, "signal"); + RTLIL::SigSpec sig_set_mask = operatorInport(inst, "set_mask"); + RTLIL::SigSpec sig_clr_mask = operatorInport(inst, "clr_mask"); + std::string tag = inst->GetAtt("tag") ? verific_unescape(inst->GetAttValue("tag")) : ""; + module->addOverwriteTag(new_verific_id(inst), tag, sig_signal, sig_set_mask, sig_clr_mask); + return true; + } + if (inst->Type() == OPER_YOSYSHQ_ORIGINAL_TAG) + { + std::string tag = inst->GetAtt("tag") ? verific_unescape(inst->GetAttValue("tag")) : ""; + module->connect(operatorOutput(inst),module->OriginalTag(new_verific_id(inst), tag, operatorInput(inst))); + return true; + } + if (inst->Type() == OPER_YOSYSHQ_FUTURE_FF) + { + module->connect(operatorOutput(inst),module->FutureFF(new_verific_id(inst), operatorInput(inst))); + return true; + } +#endif + + #undef IN + #undef IN1 + #undef IN2 + #undef OUT + #undef SIGNED + + return false; +} + +void VerificImporter::merge_past_ffs_clock(pool &candidates, SigBit clock, bool clock_pol) +{ + bool keep_running = true; + SigMap sigmap; + + while (keep_running) + { + keep_running = false; + + dict> dbits_db; + SigSpec dbits; + + for (auto cell : candidates) { + SigBit bit = sigmap(cell->getPort(ID::D)); + dbits_db[bit].insert(cell); + dbits.append(bit); + } + + dbits.sort_and_unify(); + + for (auto chunk : dbits.chunks()) + { + SigSpec sig_d = chunk; + + if (chunk.wire == nullptr || GetSize(sig_d) == 1) + continue; + + SigSpec sig_q = module->addWire(NEW_ID, GetSize(sig_d)); + RTLIL::Cell *new_ff = module->addDff(NEW_ID, clock, sig_d, sig_q, clock_pol); + + if (verific_verbose) + log(" merging single-bit past_ffs into new %d-bit ff %s.\n", GetSize(sig_d), new_ff); + + for (int i = 0; i < GetSize(sig_d); i++) + for (auto old_ff : dbits_db[sig_d[i]]) + { + if (verific_verbose) + log(" replacing old ff %s on bit %d.\n", old_ff, i); + + SigBit old_q = old_ff->getPort(ID::Q); + SigBit new_q = sig_q[i]; + + sigmap.add(old_q, new_q); + module->connect(old_q, new_q); + candidates.erase(old_ff); + module->remove(old_ff); + keep_running = true; + } + } + } +} + +void VerificImporter::merge_past_ffs(pool &candidates) +{ + dict, pool> database; + + for (auto cell : candidates) + { + if (cell->type != ID($dff)) continue; + SigBit clock = cell->getPort(ID::CLK); + bool clock_pol = cell->getParam(ID::CLK_POLARITY).as_bool(); + database[make_pair(clock, int(clock_pol))].insert(cell); + } + + for (auto it : database) + merge_past_ffs_clock(it.second, it.first.first, it.first.second); +} + +static std::string sha1_if_contain_spaces(std::string str) +{ + if(str.find_first_of(' ') != std::string::npos) { + std::size_t open = str.find_first_of('('); + std::size_t closed = str.find_last_of(')'); + if (open != std::string::npos && closed != std::string::npos) { + std::string content = str.substr(open + 1, closed - open - 1); + return str.substr(0, open + 1) + sha1(content) + str.substr(closed); + } else { + return sha1(str); + } + } + return str; +} + +void VerificImporter::recurse_mem_dimensions(RTLIL::Module *module, RTLIL::Memory *memory, Net *net, const char *&ascii_initdata, int max_bits_in_addr, const RTLIL::SigSpec &prefix, TypeRange *typeRange) { + if (typeRange == nullptr) + typeRange = net->GetOrigTypeRange(); + + auto *nextRange = typeRange->GetNext(); + auto left = typeRange->LeftRangeBound(); + auto right = typeRange->RightRangeBound(); + bool is_up = left < right; + for (auto i = left; is_up ? i <= right : i >= right; is_up ? i++ : i--) { + // TODO verific can do u64 + auto max_bits = max_bits_in_addr - prefix.size(); + auto next_sig = SigSpec(Const(i, typeRange->NumBits())); + auto extra_bits = next_sig.size() - max_bits; + if (extra_bits > 0) { + next_sig = next_sig.extract_end(extra_bits); + auto extra_inc = (1 << extra_bits) - 1; + i = is_up ? i + extra_inc : i - extra_inc; + } + next_sig.append(prefix); + if (nextRange != nullptr && extra_bits < 0) { + recurse_mem_dimensions(module, memory, net, ascii_initdata, max_bits_in_addr, next_sig, nextRange); + } else { + if (next_sig.size() != max_bits_in_addr) { + // TODO verific can do u64 + log_error("Expected %d bits for addr but got %d!\n", max_bits_in_addr, next_sig.size()); + } + Const initval = Const(State::Sx, memory->width); + bool initval_valid = false; + if (ascii_initdata) { + for (int bit_idx = memory->width-1; bit_idx >= 0; bit_idx--) { + if (*ascii_initdata == 0) + break; + if (*ascii_initdata == '0' || *ascii_initdata == '1') { + initval.set(bit_idx, (*ascii_initdata == '0') ? State::S0 : State::S1); + initval_valid = true; + } + ascii_initdata++; + } + } + if (!next_sig.convertible_to_int()) + log_error("Address %s on RAM for identifier '%s' too wide!\n", log_signal(next_sig), net->Name()); + auto next_idx = next_sig.as_int(); + if (initval_valid) { + RTLIL::Cell *cell = module->addCell(new_verific_id(net), ID($meminit)); + cell->parameters[ID::WORDS] = 1; + cell->setPort(ID::ADDR, next_idx); + cell->setPort(ID::DATA, initval); + cell->parameters[ID::MEMID] = RTLIL::Const(memory->name.str()); + cell->parameters[ID::ABITS] = 32; + cell->parameters[ID::WIDTH] = memory->width; + cell->parameters[ID::PRIORITY] = RTLIL::Const(module->twines().autoidx()-1); + } + memory->start_offset = min(memory->start_offset, next_idx); + memory->size = max(memory->size, next_idx); + } + } +} + +void VerificImporter::import_netlist(RTLIL::Design *design, Netlist *nl, std::map &nl_todo, bool norename) +{ + std::string netlist_name = nl->GetAtt(" \\top") || is_blackbox(nl) ? nl->CellBaseName() : nl->Owner()->Name(); + std::string module_name = netlist_name; + + if (nl->IsOperator() || nl->IsPrimitive()) { + module_name = "$verific$" + module_name; + } else { + if (!norename && *nl->Name() && !is_blackbox(nl)) { + module_name += "("; + module_name += nl->Name(); + module_name += ")"; + } + module_name = "\\" + sha1_if_contain_spaces(module_name); + } + + { + Array ram_nets ; + MapIter mem_mi; + Net *mem_net; + FOREACH_NET_OF_NETLIST(nl, mem_mi, mem_net) + { + if (!mem_net->IsRamNet()) continue ; + + if (mem_net->GetAtt("mem2reg")) + ram_nets.Insert(mem_net) ; + } + unsigned i ; + FOREACH_ARRAY_ITEM(&ram_nets, i, mem_net) { + log("Bit blasting RAM for identifier '%s'\n", mem_net->Name()); + mem_net->BlastNet(); + } + nl->RemoveDanglingLogic(0); + } + + netlist = nl; + + IdString module_id = design->twines().add(module_name); + if (design->has(module_id)) { + if (!nl->IsOperator() && !is_blackbox(nl)) + log_cmd_error("Re-definition of module `%s'.\n", netlist_name); + return; + } + + module = new RTLIL::Module(design); + module->name = module_id; + design->add(module); + + if (is_blackbox(nl)) { + log("Importing blackbox module %s.\n", module); + module->set_bool_attribute(ID::blackbox); + } else { + log("Importing module %s.\n", module); + } + import_attributes(module->attributes, nl, nl); + if (module->name.isPublic()) + module->set_string_attribute(ID::hdlname, nl->CellBaseName()); + module->set_string_attribute(ID(library), nl->Owner()->Owner()->Name()); +#ifdef VERIFIC_VHDL_SUPPORT + if (nl->IsFromVhdl()) { + NameSpace name_space(0); + char *architecture_name = name_space.ReName(nl->Name()) ; + module->set_string_attribute(ID(architecture), (architecture_name) ? architecture_name : nl->Name()); + } +#endif + const char *param_name ; + const char *param_value ; + MapIter mi; + FOREACH_PARAMETER_OF_NETLIST(nl, mi, param_name, param_value) { + IdString param_id = design->twines().add(RTLIL::escape_id(param_name)); + module->avail_parameters(param_id); + const TypeRange *tr = nl->GetTypeRange(param_name) ; + const char* type_name = (tr) ? tr->GetTypeName() : nullptr; + module->parameter_default_values[param_id] = verific_const(type_name, param_value, nl); + } + + SetIter si; + MapIter mi2; + Port *port; + PortBus *portbus; + Net *net; + NetBus *netbus; + Instance *inst; + PortRef *pr; + Att *attr; + + FOREACH_ATTRIBUTE(nl, mi, attr) { + if (!strcmp(attr->Key(), "noblackbox")) + module->set_bool_attribute(ID::blackbox, false); + } + + FOREACH_PORT_OF_NETLIST(nl, mi, port) + { + if (port->Bus()) + continue; + + if (verific_verbose) + log(" importing port %s.\n", port->Name()); + + RTLIL::Wire *wire = module->addWire(RTLIL::escape_id(port->Name())); + import_attributes(wire->attributes, port, nl, 1); + + wire->port_id = nl->IndexOf(port) + 1; + + if (port->GetDir() == DIR_INOUT || port->GetDir() == DIR_IN) + wire->port_input = true; + if (port->GetDir() == DIR_INOUT || port->GetDir() == DIR_OUT) + wire->port_output = true; + + if (port->GetNet()) { + net = port->GetNet(); + if (net_map.count(net) == 0) + net_map[net] = wire; + else if (wire->port_input) + module->connect(net_map_at(net), wire); + else + module->connect(wire, net_map_at(net)); + } + } + + FOREACH_PORTBUS_OF_NETLIST(nl, mi, portbus) + { + if (verific_verbose) + log(" importing portbus %s.\n", portbus->Name()); + + RTLIL::Wire *wire = module->addWire(RTLIL::escape_id(portbus->Name()), portbus->Size()); + wire->start_offset = min(portbus->LeftIndex(), portbus->RightIndex()); + wire->upto = portbus->IsUp(); + import_attributes(wire->attributes, portbus, nl, portbus->Size()); + if (portbus->Size() == 1) + wire->set_bool_attribute(ID::single_bit_vector); + SetIter si ; + Port *port ; + FOREACH_PORT_OF_PORTBUS(portbus, si, port) { + wire->port_id = nl->IndexOf(port) + 1; + import_attributes(wire->attributes, port->GetNet(), nl, portbus->Size()); + break; + } + bool portbus_input = portbus->GetDir() == DIR_INOUT || portbus->GetDir() == DIR_IN; + if (portbus_input) + wire->port_input = true; + if (portbus->GetDir() == DIR_INOUT || portbus->GetDir() == DIR_OUT) + wire->port_output = true; + + for (int i = portbus->LeftIndex();; i += portbus->IsUp() ? +1 : -1) { + if (portbus->ElementAtIndex(i) && portbus->ElementAtIndex(i)->GetNet()) { + bool bit_input = portbus_input; + if (portbus->GetDir() == DIR_NONE) { + Port *p = portbus->ElementAtIndex(i); + bit_input = p->GetDir() == DIR_INOUT || p->GetDir() == DIR_IN; + if (bit_input) + wire->port_input = true; + if (p->GetDir() == DIR_INOUT || p->GetDir() == DIR_OUT) + wire->port_output = true; + } + net = portbus->ElementAtIndex(i)->GetNet(); + int bitidx = wire->upto ? (wire->width - 1 - (i - wire->start_offset)) : (i - wire->start_offset); + RTLIL::SigBit bit(wire, bitidx); + if (net_map.count(net) == 0) + net_map[net] = bit; + else if (bit_input) + module->connect(net_map_at(net), bit); + else + module->connect(bit, net_map_at(net)); + } + if (i == portbus->RightIndex()) + break; + } + } + + module->fixup_ports(); + + dict init_nets; + pool anyconst_nets, anyseq_nets; + pool allconst_nets, allseq_nets; + any_all_nets.clear(); + + FOREACH_NET_OF_NETLIST(nl, mi, net) + { + if (net->IsRamNet()) + { + IdString memory_name = design->twines().add(RTLIL::escape_id(net->Name())); + log_assert(module->count_id(memory_name) == 0); + RTLIL::Memory *memory = module->addMemory(memory_name); + import_attributes(memory->attributes, net, nl); + + int number_of_bits = net->Size(); + int min_bits_in_word = number_of_bits; + int max_bits_in_addr = 0; + + // get the size of each memory access + FOREACH_PORTREF_OF_NET(net, si, pr) { + auto *inst = pr->GetInst(); + int bits_in_word; + if (inst->Type() == OPER_READ_PORT) + bits_in_word = inst->OutputSize(); + else if (inst->Type() == OPER_WRITE_PORT || inst->Type() == OPER_CLOCKED_WRITE_PORT) + bits_in_word = inst->Input2Size(); + else + log_error("%sVerific RamNet %s is connected to unsupported instance type %s (%s).\n", announce_src_location(inst), + net->Name(), inst->View()->Owner()->Name(), inst->Name()); + + if (bits_in_word < min_bits_in_word) { + min_bits_in_word = bits_in_word; + max_bits_in_addr = inst->Input1Size(); + } + } + + int number_of_words = number_of_bits / min_bits_in_word; + + memory->width = min_bits_in_word; + memory->size = 0; + memory->start_offset = INT_MAX; + + const char *ascii_initdata = net->GetWideInitialValue(); + if (ascii_initdata) { + while (*ascii_initdata != 0 && *ascii_initdata != '\'') + ascii_initdata++; + if (*ascii_initdata == '\'') + ascii_initdata++; + if (*ascii_initdata != 0) { + log_assert(*ascii_initdata == 'b'); + ascii_initdata++; + } + } + + // process initdata and fixup min/max address + auto prefix = SigSpec(); + recurse_mem_dimensions(module, memory, net, ascii_initdata, max_bits_in_addr, prefix); + + auto min_idx = memory->start_offset; + auto max_idx = memory->size; + memory->size = max_idx - min_idx + 1; + + // sanity check we haven't shrunk the memory + if (memory->size < number_of_words) + log_error("Expected memory of size %d words, but got %d for address range %d to %d (inclusive)\n", number_of_words, memory->size, min_idx, max_idx); + + // warn on oversize memories + // TODO consider using a minimum ratio? + if (memory->size > number_of_words) { + float ratio = memory->size / (float)number_of_words; + log_warning("RAM for identifier '%s' may be up to %.0f%% oversize due to addressing\n", net->Name(), (ratio-1)*100); + log_debug("Expected memory of size %d words, but got %d for address range %d to %d (inclusive)\n", number_of_words, memory->size, min_idx, max_idx); + } + continue; + } + + if (net->GetInitialValue()) + init_nets[net] = net->GetInitialValue(); + + const char *rand_const_attr = net->GetAttValue(" rand_const"); + const char *rand_attr = net->GetAttValue(" rand"); + + const char *anyconst_attr = net->GetAttValue("anyconst"); + const char *anyseq_attr = net->GetAttValue("anyseq"); + + const char *allconst_attr = net->GetAttValue("allconst"); + const char *allseq_attr = net->GetAttValue("allseq"); + + if (rand_const_attr != nullptr && (!strcmp(rand_const_attr, "1") || !strcmp(rand_const_attr, "'1'"))) { + anyconst_nets.insert(net); + any_all_nets.insert(net); + } + else if (rand_attr != nullptr && (!strcmp(rand_attr, "1") || !strcmp(rand_attr, "'1'"))) { + anyseq_nets.insert(net); + any_all_nets.insert(net); + } + else if (anyconst_attr != nullptr && (!strcmp(anyconst_attr, "1") || !strcmp(anyconst_attr, "'1'"))) { + anyconst_nets.insert(net); + any_all_nets.insert(net); + } + else if (anyseq_attr != nullptr && (!strcmp(anyseq_attr, "1") || !strcmp(anyseq_attr, "'1'"))) { + anyseq_nets.insert(net); + any_all_nets.insert(net); + } + else if (allconst_attr != nullptr && (!strcmp(allconst_attr, "1") || !strcmp(allconst_attr, "'1'"))) { + allconst_nets.insert(net); + any_all_nets.insert(net); + } + else if (allseq_attr != nullptr && (!strcmp(allseq_attr, "1") || !strcmp(allseq_attr, "'1'"))) { + allseq_nets.insert(net); + any_all_nets.insert(net); + } + + if (net_map.count(net)) { + if (verific_verbose) + log(" skipping net %s.\n", net->Name()); + continue; + } + + if (net->Bus()) + continue; + + RTLIL::IdString wire_name = module->uniquify(mode_names || net->IsUserDeclared() ? design->twines().add(RTLIL::escape_id(net->Name())) : new_verific_id(net)); + + RTLIL::Wire *wire = module->addWire(wire_name); + + if (verific_verbose) + log(" importing net %s as %s.\n", net->Name(), wire); + import_attributes(wire->attributes, net, nl, 1); + + net_map[net] = wire; + } + + FOREACH_NETBUS_OF_NETLIST(nl, mi, netbus) + { + bool found_new_net = false; + for (int i = netbus->LeftIndex();; i += netbus->IsUp() ? +1 : -1) { + net = netbus->ElementAtIndex(i); + if (net_map.count(net) == 0) + found_new_net = true; + if (i == netbus->RightIndex()) + break; + } + + if (found_new_net) + { + RTLIL::IdString wire_name = module->uniquify(mode_names || netbus->IsUserDeclared() ? design->twines().add(RTLIL::escape_id(netbus->Name())) : new_verific_id(netbus)); + + RTLIL::Wire *wire = module->addWire(wire_name, netbus->Size()); + + if (verific_verbose) + log(" importing netbus %s as %s.\n", netbus->Name(), wire); + wire->start_offset = min(netbus->LeftIndex(), netbus->RightIndex()); + wire->upto = netbus->IsUp(); + MapIter mibus; + FOREACH_NET_OF_NETBUS(netbus, mibus, net) { + if (net) + import_attributes(wire->attributes, net, nl, netbus->Size()); + break; + } + import_attributes(wire->attributes, netbus, nl, netbus->Size()); + if (netbus->Size() == 1) + wire->set_bool_attribute(ID::single_bit_vector); + + RTLIL::Const initval = Const(State::Sx, GetSize(wire)); + bool initval_valid = false; + + for (int i = netbus->LeftIndex();; i += netbus->IsUp() ? +1 : -1) + { + if (netbus->ElementAtIndex(i)) + { + int bitidx = wire->upto ? (wire->width - 1 - (i - wire->start_offset)) : (i - wire->start_offset); + net = netbus->ElementAtIndex(i); + RTLIL::SigBit bit(wire, bitidx); + + if (init_nets.count(net)) { + if (init_nets.at(net) == '0') + initval.set(bitidx, State::S0); + if (init_nets.at(net) == '1') + initval.set(bitidx, State::S1); + initval_valid = true; + init_nets.erase(net); + } + + if (net_map.count(net) == 0) + net_map[net] = bit; + else + module->connect(bit, net_map_at(net)); + } + + if (i == netbus->RightIndex()) + break; + } + + if (initval_valid) + wire->attributes[ID::init] = initval; + } + else + { + if (verific_verbose) + log(" skipping netbus %s.\n", netbus->Name()); + } + + SigSpec anyconst_sig; + SigSpec anyseq_sig; + SigSpec allconst_sig; + SigSpec allseq_sig; + + for (int i = netbus->RightIndex();; i += netbus->IsUp() ? -1 : +1) { + net = netbus->ElementAtIndex(i); + if (net != nullptr && anyconst_nets.count(net)) { + anyconst_sig.append(net_map_at(net)); + anyconst_nets.erase(net); + } + if (net != nullptr && anyseq_nets.count(net)) { + anyseq_sig.append(net_map_at(net)); + anyseq_nets.erase(net); + } + if (net != nullptr && allconst_nets.count(net)) { + allconst_sig.append(net_map_at(net)); + allconst_nets.erase(net); + } + if (net != nullptr && allseq_nets.count(net)) { + allseq_sig.append(net_map_at(net)); + allseq_nets.erase(net); + } + if (i == netbus->LeftIndex()) + break; + } + + if (GetSize(anyconst_sig)) + module->connect(anyconst_sig, module->Anyconst(new_verific_id(netbus), GetSize(anyconst_sig))); + + if (GetSize(anyseq_sig)) + module->connect(anyseq_sig, module->Anyseq(new_verific_id(netbus), GetSize(anyseq_sig))); + + if (GetSize(allconst_sig)) + module->connect(allconst_sig, module->Allconst(new_verific_id(netbus), GetSize(allconst_sig))); + + if (GetSize(allseq_sig)) + module->connect(allseq_sig, module->Allseq(new_verific_id(netbus), GetSize(allseq_sig))); + } + + for (auto it : init_nets) + { + Const initval; + SigBit bit = net_map_at(it.first); + log_assert(bit.wire); + + if (bit.wire->attributes.count(ID::init)) + initval = bit.wire->attributes.at(ID::init); + + if (GetSize(initval) < GetSize(bit.wire)) + initval.resize(GetSize(bit.wire), State::Sx); + + if (it.second == '0') + initval.set(bit.offset, State::S0); + if (it.second == '1') + initval.set(bit.offset, State::S1); + + bit.wire->attributes[ID::init] = initval; + } + + for (auto net : anyconst_nets) + module->connect(net_map_at(net), module->Anyconst(new_verific_id(net))); + + for (auto net : anyseq_nets) + module->connect(net_map_at(net), module->Anyseq(new_verific_id(net))); + +#ifdef VERIFIC_SYSTEMVERILOG_SUPPORT + pool sva_asserts; + pool sva_assumes; + pool sva_covers; + pool sva_triggers; + pool past_ffs; +#endif + + FOREACH_INSTANCE_OF_NETLIST(nl, mi, inst) + { + RTLIL::IdString inst_name = module->uniquify(mode_names || inst->IsUserDeclared() ? design->twines().add(RTLIL::escape_id(inst->Name())) : new_verific_id(inst)); + + if (verific_verbose) + log(" importing cell %s (%s) as %s.\n", inst->Name(), inst->View()->Owner()->Name(), PooledName(design, inst_name).unescape()); + + if (mode_verific) + goto import_verific_cells; + + if (inst->Type() == PRIM_PWR) { + module->connect(net_map_at(inst->GetOutput()), RTLIL::State::S1); + continue; + } + + if (inst->Type() == PRIM_GND) { + module->connect(net_map_at(inst->GetOutput()), RTLIL::State::S0); + continue; + } + + if (inst->Type() == PRIM_BUF) { + auto outnet = inst->GetOutput(); + if (!any_all_nets.count(outnet)) + module->addBufGate(inst_name, net_map_at(inst->GetInput()), net_map_at(outnet)); + continue; + } + + if (inst->Type() == PRIM_X) { + module->connect(net_map_at(inst->GetOutput()), RTLIL::State::Sx); + continue; + } + + if (inst->Type() == PRIM_Z) { + module->connect(net_map_at(inst->GetOutput()), RTLIL::State::Sz); + continue; + } + + if (inst->Type() == OPER_READ_PORT) + { + RTLIL::Memory *memory = module->memories.at(module->twines().find(RTLIL::escape_id(inst->GetInput()->Name())), nullptr); + if (!memory) + log_error("%sMemory net '%s' missing, possibly no driver, use verific -flatten.\n", announce_src_location(inst), inst->GetInput()->Name()); + + int numchunks = int(inst->OutputSize()) / memory->width; + int chunksbits = ceil_log2(numchunks); + + for (int i = 0; i < numchunks; i++) + { + RTLIL::SigSpec addr = {operatorInput1(inst), RTLIL::Const(i, chunksbits)}; + RTLIL::SigSpec data = operatorOutput(inst).extract(i * memory->width, memory->width); + + RTLIL::Cell *cell = module->addCell(numchunks == 1 ? inst_name : + module->twines().add(inst_name, stringf("_%d", i)), ID($memrd)); + cell->parameters[ID::MEMID] = memory->name.str(); + cell->parameters[ID::CLK_ENABLE] = false; + cell->parameters[ID::CLK_POLARITY] = true; + cell->parameters[ID::TRANSPARENT] = false; + cell->parameters[ID::ABITS] = GetSize(addr); + cell->parameters[ID::WIDTH] = GetSize(data); + import_attributes(cell->attributes, inst); + cell->setPort(ID::CLK, RTLIL::State::Sx); + cell->setPort(ID::EN, RTLIL::State::Sx); + cell->setPort(ID::ADDR, addr); + cell->setPort(ID::DATA, data); + } + continue; + } + + if (inst->Type() == OPER_WRITE_PORT || inst->Type() == OPER_CLOCKED_WRITE_PORT) + { + RTLIL::Memory *memory = module->memories.at(module->twines().find(RTLIL::escape_id(inst->GetOutput()->Name())), nullptr); + if (!memory) + log_error("%sMemory net '%s' missing, possibly no driver, use verific -flatten.\n", announce_src_location(inst), inst->GetInput()->Name()); + int numchunks = int(inst->Input2Size()) / memory->width; + int chunksbits = ceil_log2(numchunks); + + for (int i = 0; i < numchunks; i++) + { + RTLIL::SigSpec addr = {operatorInput1(inst), RTLIL::Const(i, chunksbits)}; + RTLIL::SigSpec data = operatorInput2(inst).extract(i * memory->width, memory->width); + + RTLIL::Cell *cell = module->addCell(numchunks == 1 ? inst_name : + module->twines().add(inst_name, stringf("_%d", i)), ID($memwr)); + cell->parameters[ID::MEMID] = memory->name.str(); + cell->parameters[ID::CLK_ENABLE] = false; + cell->parameters[ID::CLK_POLARITY] = true; + cell->parameters[ID::PRIORITY] = 0; + cell->parameters[ID::ABITS] = GetSize(addr); + cell->parameters[ID::WIDTH] = GetSize(data); + import_attributes(cell->attributes, inst); + cell->setPort(ID::EN, RTLIL::SigSpec(net_map_at(inst->GetControl())).repeat(GetSize(data))); + cell->setPort(ID::CLK, RTLIL::State::S0); + cell->setPort(ID::ADDR, addr); + cell->setPort(ID::DATA, data); + + if (inst->Type() == OPER_CLOCKED_WRITE_PORT) { + cell->parameters[ID::CLK_ENABLE] = true; + cell->setPort(ID::CLK, net_map_at(inst->GetClock())); + } + } + continue; + } + + if (!mode_gates) { + if (import_netlist_instance_cells(inst, inst_name)) + continue; + if (inst->IsOperator() && !verific_sva_prims.count(inst->Type())) + log_warning("%sUnsupported Verific operator: %s (fallback to gate level implementation provided by verific)\n", announce_src_location(inst), inst->View()->Owner()->Name()); + } else { + if (import_netlist_instance_gates(inst, inst_name)) + continue; + } + +#ifdef VERIFIC_SYSTEMVERILOG_SUPPORT + if (inst->Type() == PRIM_SVA_ASSERT || inst->Type() == PRIM_SVA_IMMEDIATE_ASSERT) + sva_asserts.insert(inst); + + if (inst->Type() == PRIM_SVA_ASSUME || inst->Type() == PRIM_SVA_IMMEDIATE_ASSUME || inst->Type() == PRIM_SVA_RESTRICT) + sva_assumes.insert(inst); + + if (inst->Type() == PRIM_SVA_COVER || inst->Type() == PRIM_SVA_IMMEDIATE_COVER) + sva_covers.insert(inst); + + if (inst->Type() == PRIM_SVA_TRIGGERED) + sva_triggers.insert(inst); + + if (inst->Type() == OPER_SVA_STABLE) + { + VerificClocking clocking(this, inst->GetInput2Bit(0)); + log_assert(clocking.disable_sig == State::S0); + log_assert(clocking.body_net == nullptr); + + log_assert(inst->Input1Size() == inst->OutputSize()); + + unsigned width = inst->Input1Size(); + + SigSpec sig_d, sig_dx, sig_qx, sig_o, sig_ox; + sig_dx = module->addWire(new_verific_id(inst), width * 2); + sig_qx = module->addWire(new_verific_id(inst), width * 2); + sig_ox = module->addWire(new_verific_id(inst), width * 2); + + for (int i = int(width)-1; i >= 0; i--){ + sig_d.append(net_map_at(inst->GetInput1Bit(i))); + sig_o.append(net_map_at(inst->GetOutputBit(i))); + } + + if (verific_verbose) { + for (unsigned i = 0; i < width; i++) { + log(" NEX with A=%s, B=0, Y=%s.\n", + log_signal(sig_d[i]), log_signal(sig_dx[i])); + log(" EQX with A=%s, B=1, Y=%s.\n", + log_signal(sig_d[i]), log_signal(sig_dx[i + width])); + } + log(" %sedge FF with D=%s, Q=%s, C=%s.\n", clocking.posedge ? "pos" : "neg", + log_signal(sig_dx), log_signal(sig_qx), log_signal(clocking.clock_sig)); + log(" XNOR with A=%s, B=%s, Y=%s.\n", + log_signal(sig_dx), log_signal(sig_qx), log_signal(sig_ox)); + log(" AND with A=%s, B=%s, Y=%s.\n", + log_signal(sig_ox.extract(0, width)), log_signal(sig_ox.extract(width, width)), log_signal(sig_o)); + } + + for (unsigned i = 0; i < width; i++) { + module->addNex(new_verific_id(inst), sig_d[i], State::S0, sig_dx[i]); + module->addEqx(new_verific_id(inst), sig_d[i], State::S1, sig_dx[i + width]); + } + + Const qx_init = Const(State::S1, width); + qx_init.resize(2 * width, State::S0); + + clocking.addDff(new_verific_id(inst), sig_dx, sig_qx, qx_init); + module->addXnor(new_verific_id(inst), sig_dx, sig_qx, sig_ox); + + module->addAnd(new_verific_id(inst), sig_ox.extract(0, width), sig_ox.extract(width, width), sig_o); + + if (!mode_keep) + continue; + } + + if (inst->Type() == PRIM_SVA_STABLE) + { + VerificClocking clocking(this, inst->GetInput2()); + log_assert(clocking.disable_sig == State::S0); + log_assert(clocking.body_net == nullptr); + + SigSpec sig_d = net_map_at(inst->GetInput1()); + SigSpec sig_o = net_map_at(inst->GetOutput()); + SigSpec sig_dx = module->addWire(new_verific_id(inst), 2); + SigSpec sig_qx = module->addWire(new_verific_id(inst), 2); + + if (verific_verbose) { + log(" NEX with A=%s, B=0, Y=%s.\n", + log_signal(sig_d), log_signal(sig_dx[0])); + log(" EQX with A=%s, B=1, Y=%s.\n", + log_signal(sig_d), log_signal(sig_dx[1])); + log(" %sedge FF with D=%s, Q=%s, C=%s.\n", clocking.posedge ? "pos" : "neg", + log_signal(sig_dx), log_signal(sig_qx), log_signal(clocking.clock_sig)); + log(" EQ with A=%s, B=%s, Y=%s.\n", + log_signal(sig_dx), log_signal(sig_qx), log_signal(sig_o)); + } + + module->addNex(new_verific_id(inst), sig_d, State::S0, sig_dx[0]); + module->addEqx(new_verific_id(inst), sig_d, State::S1, sig_dx[1]); + + clocking.addDff(new_verific_id(inst), sig_dx, sig_qx, Const(1, 2)); + module->addEq(new_verific_id(inst), sig_dx, sig_qx, sig_o); + + if (!mode_keep) + continue; + } + + if (inst->Type() == PRIM_SVA_PAST) + { + VerificClocking clocking(this, inst->GetInput2()); + log_assert(clocking.disable_sig == State::S0); + log_assert(clocking.body_net == nullptr); + + SigBit sig_d = net_map_at(inst->GetInput1()); + SigBit sig_q = net_map_at(inst->GetOutput()); + + if (verific_verbose) + log(" %sedge FF with D=%s, Q=%s, C=%s.\n", clocking.posedge ? "pos" : "neg", + log_signal(sig_d), log_signal(sig_q), log_signal(clocking.clock_sig)); + + past_ffs.insert(clocking.addDff(new_verific_id(inst), sig_d, sig_q)); + + if (!mode_keep) + continue; + } + + if ((inst->Type() == PRIM_SVA_ROSE || inst->Type() == PRIM_SVA_FELL)) + { + VerificClocking clocking(this, inst->GetInput2()); + log_assert(clocking.disable_sig == State::S0); + log_assert(clocking.body_net == nullptr); + + SigBit sig_d = net_map_at(inst->GetInput1()); + SigBit sig_o = net_map_at(inst->GetOutput()); + SigBit sig_q = module->addWire(new_verific_id(inst)); + SigBit sig_d_no_x = module->addWire(new_verific_id(inst)); + + if (verific_verbose) { + log(" EQX with A=%s, B=%d, Y=%s.\n", + log_signal(sig_d), inst->Type() == PRIM_SVA_ROSE, log_signal(sig_d_no_x)); + log(" %sedge FF with D=%s, Q=%s, C=%s.\n", clocking.posedge ? "pos" : "neg", + log_signal(sig_d_no_x), log_signal(sig_q), log_signal(clocking.clock_sig)); + log(" EQ with A={%s, %s}, B={0, 1}, Y=%s.\n", + log_signal(sig_q), log_signal(sig_d_no_x), log_signal(sig_o)); + } + + module->addEqx(new_verific_id(inst), sig_d, inst->Type() == PRIM_SVA_ROSE ? State::S1 : State::S0, sig_d_no_x); + clocking.addDff(new_verific_id(inst), sig_d_no_x, sig_q, State::S0); + module->addEq(new_verific_id(inst), {sig_q, sig_d_no_x}, Const(1, 2), sig_o); + + if (!mode_keep) + continue; + } +#endif + +#ifdef YOSYSHQ_VERIFIC_API_VERSION + if (inst->Type() == PRIM_YOSYSHQ_INITSTATE) + { + if (verific_verbose) + log(" adding YosysHQ init state\n"); + SigBit initstate = module->Initstate(new_verific_id(inst)); + SigBit sig_o = net_map_at(inst->GetOutput()); + module->connect(sig_o, initstate); + + if (!mode_keep) + continue; + } +#endif + + if (inst->Type() == PRIM_HDL_ASSERTION) + { + SigBit cond = net_map_at(inst->GetInput()); + + if (verific_verbose) + log(" assert condition %s.\n", log_signal(cond)); + + Cell *cell = module->addAssert(new_verific_id(inst), cond, State::S1); + import_attributes(cell->attributes, inst); + continue; + } + + if (verific_sva_prims.count(inst->Type()) && inst->Type() != PRIM_SVA_EXPECT) + { + if (!mode_keep) + { + if (verific_verbose) + log(" skipping SVA cell in non k-mode\n"); + continue; + } + } + else if (inst->IsPrimitive()) + { + auto msg = stringf("%sUnsupported Verific primitive %s of type %s", announce_src_location(inst), inst->Name(), inst->View()->Owner()->Name()); + if (!mode_keep) + log_error("%s\n", msg); + else + log_warning("%s\n", msg); + } + + import_verific_cells: + std::string inst_type = is_blackbox(inst->View()) ? inst->View()->CellBaseName() : inst->View()->Owner()->Name(); + + nl_todo[inst_type] = inst->View(); + + if (inst->View()->IsOperator() || inst->View()->IsPrimitive()) { + inst_type = "$verific$" + inst_type; + } else { + if (*inst->View()->Name() && !is_blackbox(inst->View())) { + inst_type += "("; + inst_type += inst->View()->Name(); + inst_type += ")"; + } + inst_type = "\\" + sha1_if_contain_spaces(inst_type); + } + + RTLIL::Cell *cell = module->addCell(inst_name, inst_type); + import_attributes(cell->attributes, inst); + + if (inst->IsPrimitive() && mode_keep) + cell->attributes[ID::keep] = 1; + + dict> cell_port_conns; + + if (verific_verbose) + log(" ports in verific db:\n"); + + const char *param_name ; + const char *param_value ; + if (is_blackbox(inst->View())) { + FOREACH_PARAMETER_OF_INST(inst, mi2, param_name, param_value) { + const TypeRange *tr = inst->View()->GetTypeRange(param_name) ; + const char* type_name = (tr) ? tr->GetTypeName() : nullptr; + cell->setParam(RTLIL::escape_id(param_name), verific_const(type_name, param_value, inst->View())); + } + } + + FOREACH_PORTREF_OF_INST(inst, mi2, pr) { + if (verific_verbose) + log(" .%s(%s)\n", pr->GetPort()->Name(), pr->GetNet()->Name()); + const char *port_name = pr->GetPort()->Name(); + int port_offset = 0; + if (pr->GetPort()->Bus()) { + port_name = pr->GetPort()->Bus()->Name(); + int msb_index = pr->GetPort()->Bus()->LeftIndex(); + int lsb_index = pr->GetPort()->Bus()->RightIndex(); + int index_of_port = pr->GetPort()->Bus()->IndexOf(pr->GetPort()); + port_offset = index_of_port - min(msb_index, lsb_index); + // In cases where the msb order is flipped we need to make sure + // that the indices match LSB = 0 order to match the std::vector + // to SigSpec LSB = 0 precondition. + if (lsb_index > msb_index) { + port_offset = abs(port_offset - (lsb_index - min(msb_index, lsb_index))); + } + } + IdString port_name_id = module->twines().add(RTLIL::escape_id(port_name)); + auto &sigvec = cell_port_conns[port_name_id]; + if (GetSize(sigvec) <= port_offset) { + SigSpec zwires = module->addWire(new_verific_id(inst), port_offset+1-GetSize(sigvec)); + for (auto bit : zwires) + sigvec.push_back(bit); + } + // fixing issue where undriven interface nets get driver conflicts - issue 6409 + Net *port_net = pr->GetPort()->GetNet(); + bool unused_output = !is_blackbox(inst->View()) && pr->IsOutput() && port_net && !port_net->Driver(); + if (!unused_output) { + sigvec[port_offset] = net_map_at(pr->GetNet()); + } + } + + if (verific_verbose) + log(" ports in yosys db:\n"); + + for (auto &it : cell_port_conns) { + if (verific_verbose) + log(" .%s(%s)\n", PooledName(module, it.first).unescape(), log_signal(it.second)); + cell->setPort(it.first, it.second); + } + } + +#ifdef VERIFIC_SYSTEMVERILOG_SUPPORT + if (!mode_nosva) + { + for (auto inst : sva_asserts) { + if (mode_autocover) + verific_import_sva_cover(this, inst); + verific_import_sva_assert(this, inst); + } + + for (auto inst : sva_assumes) + verific_import_sva_assume(this, inst); + + for (auto inst : sva_covers) + verific_import_sva_cover(this, inst); + + for (auto inst : sva_triggers) + verific_import_sva_trigger(this, inst); + + merge_past_ffs(past_ffs); + } +#endif + + if (!mode_fullinit) + { + pool non_ff_bits; + CellTypes ff_types; + + ff_types.setup_internals_ff(); + ff_types.setup_stdcells_mem(); + + for (auto cell : module->cells()) + { + if (ff_types.cell_known(cell->type)) + continue; + + for (auto conn : cell->connections()) + { + if (!cell->output(conn.first)) + continue; + + for (auto bit : conn.second) + if (bit.wire != nullptr) + non_ff_bits.insert(bit); + } + } + + for (auto wire : module->wires()) + { + if (!wire->attributes.count(ID::init)) + continue; + + Const &initval = wire->attributes.at(ID::init); + for (int i = 0; i < GetSize(initval); i++) + { + if (initval[i] != State::S0 && initval[i] != State::S1) + continue; + + if (non_ff_bits.count(SigBit(wire, i))) + initval.set(i, State::Sx); + } + + if (wire->port_input) { + wire->attributes[ID::defaultvalue] = Const(initval); + wire->attributes.erase(ID::init); + } else if (initval.is_fully_undef()) + wire->attributes.erase(ID::init); + } + } + + if (num_sva_continue) { + log_warning("Encountered %d items containing unsupported SVA!\n", num_sva_continue); + log_warning("Unsupported SVA imported as 'x and marked using the `unsupported_sva' attribute due to -sva-continue-on-err.\n"); + } + num_sva_continue = 0; +} + +YOSYS_NAMESPACE_END diff --git a/chips/yosys/frontends/verific/verific_importer.h b/chips/yosys/frontends/verific/verific_importer.h new file mode 100644 index 0000000000000000000000000000000000000000..3edc8ed97e5f140cff355d7f528c23cdc14012d3 --- /dev/null +++ b/chips/yosys/frontends/verific/verific_importer.h @@ -0,0 +1,75 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#ifndef VERIFIC_IMPORTER_H +#define VERIFIC_IMPORTER_H + +#ifdef YOSYS_ENABLE_VERIFIC + +#include "kernel/yosys.h" + +#include "DataBase.h" + +YOSYS_NAMESPACE_BEGIN + +struct VerificImporter +{ +private: + void recurse_mem_dimensions(RTLIL::Module *module, RTLIL::Memory *memory, Verific::Net *net, const char *&ascii_initdata, int max_bits_in_addr, const RTLIL::SigSpec &prefix, Verific::TypeRange *typeRange = nullptr); +public: + RTLIL::Module *module; + Verific::Netlist *netlist; + + std::map net_map; + std::map sva_posedge_map; + pool any_all_nets; + + bool mode_gates, mode_keep, mode_nosva, mode_sva_continue, mode_names, mode_verific; + bool mode_autocover, mode_fullinit; + + int num_sva_continue = 0; + + VerificImporter(bool mode_gates, bool mode_keep, bool mode_nosva, bool mode_sva_continue, bool mode_names, bool mode_verific, bool mode_autocover, bool mode_fullinit); + + RTLIL::SigBit net_map_at(Verific::Net *net); + + RTLIL::IdString new_verific_id(Verific::DesignObj *obj); + void import_attributes(dict &attributes, Verific::DesignObj *obj, Verific::Netlist *nl = nullptr, int wire_width_hint = -1); + + RTLIL::SigBit netToSigBit(Verific::Net *net); + RTLIL::SigSpec operatorInput(Verific::Instance *inst); + RTLIL::SigSpec operatorInput1(Verific::Instance *inst); + RTLIL::SigSpec operatorInput2(Verific::Instance *inst); + RTLIL::SigSpec operatorInport(Verific::Instance *inst, const char *portname); + RTLIL::SigSpec operatorInportCase(Verific::Instance *inst, const char *portname); + RTLIL::SigSpec operatorOutput(Verific::Instance *inst, const pool *any_all_nets = nullptr); + + bool import_netlist_instance_gates(Verific::Instance *inst, RTLIL::IdString inst_name); + bool import_netlist_instance_cells(Verific::Instance *inst, RTLIL::IdString inst_name); + + void merge_past_ffs_clock(pool &candidates, SigBit clock, bool clock_pol); + void merge_past_ffs(pool &candidates); + + void import_netlist(RTLIL::Design *design, Verific::Netlist *nl, std::map &nl_todo, bool norename = false); +}; + +YOSYS_NAMESPACE_END + +#endif +#endif diff --git a/chips/yosys/frontends/verific/verific_pass.cc b/chips/yosys/frontends/verific/verific_pass.cc new file mode 100644 index 0000000000000000000000000000000000000000..2620ca6139376028fcbe9c02b6fe22c050335ca4 --- /dev/null +++ b/chips/yosys/frontends/verific/verific_pass.cc @@ -0,0 +1,391 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" + +#include "frontends/verific/verific.h" +#include "frontends/verific/verific_command.h" + +#ifdef YOSYS_ENABLE_VERIFIC + +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Woverloaded-virtual" +#endif + +#include "Message.h" + +#ifdef YOSYSHQ_VERIFIC_EXTENSIONS +#include "VerificExtensions.h" +#endif + +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + +#ifdef VERIFIC_NAMESPACE +using namespace Verific; +#endif + +#endif + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct VerificPass : public Pass { + VerificPass() : Pass("verific", "load Verilog and VHDL designs using Verific") { } + +#ifdef YOSYSHQ_VERIFIC_EXTENSIONS + void on_register() override { VerificExtensions::Reset(); } +#endif + + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); +#ifdef VERIFIC_SYSTEMVERILOG_SUPPORT + log(" verific {-vlog95|-vlog2k|-sv2005|-sv2009|-sv2012|\n"); + log(" -sv2017|-sv2023|-sv} ..\n"); + log("\n"); + log("Load the specified Verilog/SystemVerilog files into Verific.\n"); + log("Note that -sv option will use latest supported SystemVerilog standard.\n"); + log("\n"); + log("All files specified in one call to this command are one compilation unit.\n"); + log("Files passed to different calls to this command are treated as belonging to\n"); + log("different compilation units.\n"); + log("\n"); + log("Additional -D[=] options may be added after the option indicating\n"); + log("the language version (and before file names) to set additional verilog defines.\n"); + log("The macros YOSYS, SYNTHESIS, and VERIFIC are defined implicitly.\n"); + log("\n"); + log("\n"); + log(" verific -formal ..\n"); + log("\n"); + log("Like -sv, but define FORMAL instead of SYNTHESIS.\n"); + log("\n"); + log("\n"); +#endif +#ifdef VERIFIC_VHDL_SUPPORT + log(" verific {-vhdl87|-vhdl93|-vhdl2k|-vhdl2008|-vhdl2019|-vhdl} ..\n"); + log("\n"); + log("Load the specified VHDL files into Verific.\n"); + log("\n"); + log("\n"); +#endif +#ifdef VERIFIC_EDIF_SUPPORT + log(" verific {-edif} ..\n"); + log("\n"); + log("Load the specified EDIF files into Verific.\n"); + log("\n"); + log("\n"); +#endif +#ifdef VERIFIC_LIBERTY_SUPPORT + log(" verific {-liberty} ..\n"); + log("\n"); + log("Load the specified Liberty files into Verific.\n"); + log("Default library when -work is not present is one specified in liberty file.\n"); + log("To use from SystemVerilog or VHDL use -L to specify liberty library.\n"); + log("\n"); + log(" -lib\n"); + log(" only create empty blackbox modules\n"); + log("\n"); + log("\n"); +#endif +#ifdef VERIFIC_SYSTEMVERILOG_SUPPORT + log(" verific {-f|-F} [-vlog95|-vlog2k|-sv2005|-sv2009|\n"); +#ifdef VERIFIC_VHDL_SUPPORT + log(" -vhdl87|-vhdl93|-vhdl2k|-vhdl2008|-vhdl2019|-vhdl|\n"); +#endif + log(" -sv2012|-sv2017|-sv2023|-sv|-formal] \n"); + log("\n"); + log("Load and execute the specified command file.\n"); + log("Override verilog parsing mode can be set.\n"); + log("The macros YOSYS, SYNTHESIS/FORMAL, and VERIFIC are defined implicitly.\n"); + log("\n"); + log("Command file parser supports following commands in file:\n"); + log(" +define+= - defines macro\n"); + log(" -u - upper case all identifier (makes Verilog parser\n"); + log(" case insensitive)\n"); + log(" -v - register library name (file)\n"); + log(" -y - register library name (directory)\n"); + log(" +incdir+ - specify include dir\n"); + log(" +libext+ - specify library extension\n"); + log(" +liborder+ - add library in ordered list\n"); + log(" +librescan - unresolved modules will be always searched\n"); + log(" starting with the first library specified\n"); + log(" by -y/-v options.\n"); + log(" -f/-file - nested -f option\n"); + log(" -F - nested -F option (relative path)\n"); + log(" parse files:\n"); + log(" \n"); + log(" +systemverilogext+\n"); + log(" +verilog1995ext+\n"); + log(" +verilog2001ext+\n"); + log("\n"); + log(" analysis mode:\n"); + log(" -ams\n"); + log(" +v2k\n"); + log(" -sverilog\n"); + log("\n"); + log("\n"); +#endif + log(" verific [-work ] {-sv|-vhdl|...} \n"); + log("\n"); + log("Load the specified Verilog/SystemVerilog/VHDL file into the specified library.\n"); + log("(default library when -work is not present: \"work\")\n"); + log("\n"); + log("\n"); + log(" verific [-L ] {-sv|-vhdl|...} \n"); + log("\n"); + log("Look up external definitions in the specified library.\n"); + log("(-L may be used more than once)\n"); + log("\n"); + log("\n"); +#ifdef VERIFIC_SYSTEMVERILOG_SUPPORT + log(" verific -vlog-incdir ..\n"); + log("\n"); + log("Add Verilog include directories.\n"); + log("\n"); + log("\n"); + log(" verific -vlog-libdir ..\n"); + log("\n"); + log("Add Verilog library directories. Verific will search in this directories to\n"); + log("find undefined modules.\n"); + log("\n"); + log("\n"); + log(" verific -vlog-libext ..\n"); + log("\n"); + log("Add Verilog library extensions, used when searching in library directories.\n"); + log("\n"); + log("\n"); + log(" verific -vlog-define [=]..\n"); + log("\n"); + log("Add Verilog defines.\n"); + log("\n"); + log("\n"); + log(" verific -vlog-undef ..\n"); + log("\n"); + log("Remove Verilog defines previously set with -vlog-define.\n"); + log("\n"); + log("\n"); +#endif + log(" verific -set-error ..\n"); + log(" verific -set-warning ..\n"); + log(" verific -set-info ..\n"); + log(" verific -set-ignore ..\n"); + log("\n"); + log("Set message severity. is the string in square brackets when a message\n"); + log("is printed, such as VERI-1209.\n"); + log("Also errors, warnings, infos and comments could be used to set new severity for\n"); + log("all messages of certain type.\n"); + log("\n"); + log("\n"); + log(" verific -cleanup\n"); + log("\n"); + log("Discard all files read so far without importing them and reset the internal\n"); + log("state of Verific.\n"); + log("\n"); + log("\n"); + log(" verific -import [options] ..\n"); + log("\n"); + log("Elaborate the design for the specified top modules or configurations, import to\n"); + log("Yosys and reset the internal state of Verific.\n"); + log("\n"); + log("Import options:\n"); + log("\n"); + log(" -all\n"); + log(" Elaborate all modules, not just the hierarchy below the given top\n"); + log(" modules. With this option the list of modules to import is optional.\n"); + log("\n"); + log(" -gates\n"); + log(" Create a gate-level netlist.\n"); + log("\n"); + log(" -flatten\n"); + log(" Flatten the design in Verific before importing.\n"); + log("\n"); + log(" -extnets\n"); + log(" Resolve references to external nets by adding module ports as needed.\n"); + log("\n"); + log(" -no-split-complex-ports\n"); + log(" Complex ports (structs or arrays) are not split and remain packed as a single port.\n"); + log("\n"); +#ifdef VERIFIC_SYSTEMVERILOG_SUPPORT + log(" -autocover\n"); + log(" Generate automatic cover statements for all asserts\n"); + log("\n"); +#endif + log(" -fullinit\n"); + log(" Keep all register initializations, even those for non-FF registers.\n"); + log("\n"); + log(" -cells\n"); + log(" Import all cell definitions from Verific loaded libraries even if they are\n"); + log(" unused in design. Useful with \"-edif\" and \"-liberty\" option.\n"); + log("\n"); + log(" -chparam name value \n"); + log(" Elaborate the specified top modules (all modules when -all given) using\n"); + log(" this parameter value. Modules on which this parameter does not exist will\n"); + log(" cause Verific to produce a VERI-1928 or VHDL-1676 message. This option\n"); + log(" can be specified multiple times to override multiple parameters.\n"); + log(" String values must be passed in double quotes (\").\n"); + log("\n"); + log(" -v, -vv\n"); + log(" Verbose log messages. (-vv is even more verbose than -v.)\n"); + log("\n"); + log(" -pp \n"); + log(" Pretty print design after elaboration to specified file.\n"); + log("\n"); + log("The following additional import options are useful for debugging the Verific\n"); + log("bindings (for Yosys and/or Verific developers):\n"); + log("\n"); + log(" -k\n"); + log(" Keep going after an unsupported verific primitive is found. The\n"); + log(" unsupported primitive is added as blackbox module to the design.\n"); + log(" This will also add all SVA related cells to the design parallel to\n"); + log(" the checker logic inferred by it.\n"); + log("\n"); + log(" -V\n"); + log(" Import Verific netlist as-is without translating to Yosys cell types. \n"); + log("\n"); +#ifdef VERIFIC_SYSTEMVERILOG_SUPPORT + log(" -nosva\n"); + log(" Ignore SVA properties, do not infer checker logic.\n"); + log("\n"); + log(" -sva-continue-on-err\n"); + log(" Turns unsupported SVA from an error into a warning. Properties are imported\n"); + log(" with their trigger condition replaced with 'x and with an `unsupported_sva'\n"); + log(" attribute to produce a later error in SBY if they remain in the design.\n"); + log("\n"); + log(" -L \n"); + log(" Maximum number of ctrl bits for SVA checker FSMs (default=16).\n"); + log("\n"); +#endif + log(" -n\n"); + log(" Keep all Verific names on instances and nets. By default only\n"); + log(" user-declared names are preserved.\n"); + log("\n"); + log(" -d \n"); + log(" Dump the Verific netlist as a verilog file.\n"); + log("\n"); + log("\n"); + log(" verific [-work ] -pp [options] []..\n"); + log("\n"); + log("Pretty print design (or just module) to the specified file from the\n"); + log("specified library. (default library when -work is not present: \"work\")\n"); + log("\n"); + log("Pretty print options:\n"); + log("\n"); + log(" -verilog\n"); + log(" Save output for Verilog/SystemVerilog design modules (default).\n"); + log("\n"); + log(" -vhdl\n"); + log(" Save output for VHDL design units.\n"); + log("\n"); + log("\n"); + log(" verific -cfg [ []]\n"); + log("\n"); + log("Get/set Verific runtime flags.\n"); + log("\n"); + log("\n"); +#ifdef VERIFIC_SYSTEMVERILOG_SUPPORT + log(" verific -target [-family ]]\n"); + log("\n"); + log("Loads required cell definitions for specified and .\n"); + log("\n"); + log("\n"); +#endif +#if defined(YOSYS_ENABLE_VERIFIC) and defined(YOSYSHQ_VERIFIC_EXTENSIONS) + VerificExtensions::Help(); +#endif + log("Use YosysHQ Tabby CAD Suite if you need Yosys+Verific.\n"); + log("https://www.yosyshq.com/\n"); + log("\n"); + log("Contact office@yosyshq.com for free evaluation\n"); + log("binaries of YosysHQ Tabby CAD Suite.\n"); + log("\n"); + } +#ifdef YOSYS_ENABLE_VERIFIC + void log_release() + { + const char *release_str = Message::ReleaseString(); + time_t release_time = Message::ReleaseDate(); + char *release_tmstr = ctime(&release_time); + + if (release_str == nullptr) + release_str = "(no release string)"; + + for (char *p = release_tmstr; *p; p++) + if (*p == '\n') *p = 0; + + log("Built with Verific %s, released at %s.\n", release_str, release_tmstr); + } + + void execute(std::vector args, RTLIL::Design *design) override + { + if (check_noverific_env()) + log_cmd_error("This version of Yosys is built without Verific support.\n" + "\n" + "Use YosysHQ Tabby CAD Suite if you need Yosys+Verific.\n" + "https://www.yosyshq.com/\n" + "\n" + "Contact office@yosyshq.com for free evaluation\n" + "binaries of YosysHQ Tabby CAD Suite.\n"); + + log_header(design, "Executing VERIFIC (loading SystemVerilog and VHDL designs using Verific).\n"); + + std::unique_ptr ending_session = {}; + { + VerificCommand command(*this, args, design); + + if (command.mode == "-cleanup") { + (void)VerificSession::deferred_end(design); + return; + } + + if (command.mode == "-import") { + ending_session = VerificSession::deferred_end(design); + if (!ending_session) + log_cmd_error("Nothing was read into Verific for this design.\n"); + } else { + VerificSession::begin(design); + } + + verific_setup(); + verific_verbose = 0; + verific_sva_fsm_limit = 16; + log_release(); + command.run(); + } + + if (!verific_error_msg.empty()) + log_error("%s\n", verific_error_msg); + } +#else /* YOSYS_ENABLE_VERIFIC */ + void execute(std::vector, RTLIL::Design *) override { + log_cmd_error("This version of Yosys is built without Verific support.\n" + "\n" + "Use YosysHQ Tabby CAD Suite if you need Yosys+Verific.\n" + "https://www.yosyshq.com/\n" + "\n" + "Contact office@yosyshq.com for free evaluation\n" + "binaries of YosysHQ Tabby CAD Suite.\n"); + } +#endif +} VerificPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/frontends/verific/verificsva.cc b/chips/yosys/frontends/verific/verificsva.cc new file mode 100644 index 0000000000000000000000000000000000000000..251997ec3d5555cc8bdff980136b83ff9b2476fe --- /dev/null +++ b/chips/yosys/frontends/verific/verificsva.cc @@ -0,0 +1,1949 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + + +// Currently supported SVA sequence and property syntax: +// https://yosyshq.readthedocs.io/projects/sby/en/latest/verific.html +// +// Next gen property syntax: +// basic_property +// [antecedent_condition] property +// [antecedent_condition] always.. property +// [antecedent_condition] eventually.. basic_property +// [antecedent_condition] property until.. expression +// [antecedent_condition] basic_property until.. basic_property (assert/assume only) +// +// antecedent_condition: +// sequence |-> +// sequence |=> +// +// basic_property: +// sequence +// not basic_property +// nexttime basic_property +// nexttime[N] basic_property +// sequence #-# basic_property +// sequence #=# basic_property +// basic_property or basic_property (cover only) +// basic_property and basic_property (assert/assume only) +// basic_property implies basic_property +// basic_property iff basic_property +// +// sequence: +// expression +// sequence ##N sequence +// sequence ##[*] sequence +// sequence ##[+] sequence +// sequence ##[N:M] sequence +// sequence ##[N:$] sequence +// expression [*] +// expression [+] +// expression [*N] +// expression [*N:M] +// expression [*N:$] +// sequence or sequence +// sequence and sequence +// expression throughout sequence +// sequence intersect sequence +// sequence within sequence +// first_match( sequence ) +// expression [=N] +// expression [=N:M] +// expression [=N:$] +// expression [->N] +// expression [->N:M] +// expression [->N:$] + + +#include "kernel/yosys.h" +#include "frontends/verific/verific.h" + +USING_YOSYS_NAMESPACE + +#ifdef VERIFIC_NAMESPACE +using namespace Verific; +#endif + +#ifdef VERIFIC_SYSTEMVERILOG_SUPPORT +PRIVATE_NAMESPACE_BEGIN + +// Non-deterministic FSM +struct SvaNFsmNode +{ + // Edge: Activate the target node if ctrl signal is true, consumes clock cycle + // Link: Activate the target node if ctrl signal is true, doesn't consume clock cycle + vector> edges, links; + bool is_cond_node; +}; + +// Non-deterministic FSM after resolving links +struct SvaUFsmNode +{ + // Edge: Activate the target node if all bits in ctrl signal are true, consumes clock cycle + // Accept: This node functions as an accept node if all bits in ctrl signal are true + vector> edges; + vector accept, cond; + bool reachable; +}; + +// Deterministic FSM +struct SvaDFsmNode +{ + // A DFSM state corresponds to a set of NFSM states. We represent DFSM states as sorted vectors + // of NFSM state node ids. Edge/accept controls are constants matched against the ctrl sigspec. + SigSpec ctrl; + vector, Const>> edges; + vector accept, reject; + + // additional temp data for getReject() + Wire *ffoutwire; + SigBit statesig; + SigSpec nextstate; + + // additional temp data for getDFsm() + int outnode; +}; + +struct SvaFsm +{ + Module *module; + VerificClocking clocking; + std::function parser_error; + + SigBit trigger_sig = State::S1, disable_sig; + SigBit throughout_sig = State::S1; + bool in_cond_mode = false; + + vector disable_stack; + vector throughout_stack; + + int startNode, acceptNode, condNode; + vector nodes; + + vector unodes; + dict, SvaDFsmNode> dnodes; + dict, SigBit> cond_eq_cache; + bool materialized = false; + + SigBit final_accept_sig = State::Sx; + SigBit final_reject_sig = State::Sx; + + SvaFsm(const VerificClocking &clking, SigBit trig = State::S1) + { + module = clking.module; + clocking = clking; + trigger_sig = trig; + parser_error = [](std::string msg){ log_error("%s", msg); }; + + startNode = createNode(); + acceptNode = createNode(); + + in_cond_mode = true; + condNode = createNode(); + in_cond_mode = false; + } + + void pushDisable(SigBit sig) + { + log_assert(!materialized); + + disable_stack.push_back(disable_sig); + + if (disable_sig == State::S0) + disable_sig = sig; + else + disable_sig = module->Or(NEW_ID, disable_sig, sig); + } + + void popDisable() + { + log_assert(!materialized); + log_assert(!disable_stack.empty()); + + disable_sig = disable_stack.back(); + disable_stack.pop_back(); + } + + void pushThroughout(SigBit sig) + { + log_assert(!materialized); + + throughout_stack.push_back(throughout_sig); + + if (throughout_sig == State::S1) + throughout_sig = sig; + else + throughout_sig = module->And(NEW_ID, throughout_sig, sig); + } + + void popThroughout() + { + log_assert(!materialized); + log_assert(!throughout_stack.empty()); + + throughout_sig = throughout_stack.back(); + throughout_stack.pop_back(); + } + + int createNode(int link_node = -1) + { + log_assert(!materialized); + + int idx = GetSize(nodes); + nodes.push_back(SvaNFsmNode()); + nodes.back().is_cond_node = in_cond_mode; + if (link_node >= 0) + createLink(link_node, idx); + return idx; + } + + int createStartNode() + { + return createNode(startNode); + } + + void createEdge(int from_node, int to_node, SigBit ctrl = State::S1) + { + log_assert(!materialized); + log_assert(0 <= from_node && from_node < GetSize(nodes)); + log_assert(0 <= to_node && to_node < GetSize(nodes)); + log_assert(from_node != acceptNode); + log_assert(to_node != acceptNode); + log_assert(from_node != condNode); + log_assert(to_node != condNode); + log_assert(to_node != startNode); + + if (from_node != startNode) + log_assert(nodes.at(from_node).is_cond_node == nodes.at(to_node).is_cond_node); + + if (throughout_sig != State::S1) { + if (ctrl != State::S1) + ctrl = module->And(NEW_ID, throughout_sig, ctrl); + else + ctrl = throughout_sig; + } + + nodes[from_node].edges.push_back(make_pair(to_node, ctrl)); + } + + void createLink(int from_node, int to_node, SigBit ctrl = State::S1) + { + log_assert(!materialized); + log_assert(0 <= from_node && from_node < GetSize(nodes)); + log_assert(0 <= to_node && to_node < GetSize(nodes)); + log_assert(from_node != acceptNode); + log_assert(from_node != condNode); + log_assert(to_node != startNode); + + if (from_node != startNode) + log_assert(nodes.at(from_node).is_cond_node == nodes.at(to_node).is_cond_node); + + if (throughout_sig != State::S1) { + if (ctrl != State::S1) + ctrl = module->And(NEW_ID, throughout_sig, ctrl); + else + ctrl = throughout_sig; + } + + nodes[from_node].links.push_back(make_pair(to_node, ctrl)); + } + + void make_link_order(vector &order, int node, int min) + { + order[node] = std::max(order[node], min); + for (auto &it : nodes[node].links) + make_link_order(order, it.first, order[node]+1); + } + + // ---------------------------------------------------- + // Generating NFSM circuit to acquire accept signal + + SigBit getAccept() + { + log_assert(!materialized); + materialized = true; + + vector state_wire(GetSize(nodes)); + vector state_sig(GetSize(nodes)); + vector next_state_sig(GetSize(nodes)); + + // Create state signals + + { + SigBit not_disable = State::S1; + + if (disable_sig != State::S0) + not_disable = module->Not(NEW_ID, disable_sig); + + for (int i = 0; i < GetSize(nodes); i++) + { + Wire *w = module->addWire(NEW_ID); + state_wire[i] = w; + state_sig[i] = w; + + if (i == startNode) + state_sig[i] = module->Or(NEW_ID, state_sig[i], trigger_sig); + + if (disable_sig != State::S0) + state_sig[i] = module->And(NEW_ID, state_sig[i], not_disable); + } + } + + // Follow Links + + { + vector node_order(GetSize(nodes)); + vector> order_to_nodes; + + for (int i = 0; i < GetSize(nodes); i++) + make_link_order(node_order, i, 0); + + for (int i = 0; i < GetSize(nodes); i++) { + if (node_order[i] >= GetSize(order_to_nodes)) + order_to_nodes.resize(node_order[i]+1); + order_to_nodes[node_order[i]].push_back(i); + } + + for (int order = 0; order < GetSize(order_to_nodes); order++) + for (int node : order_to_nodes[order]) + { + for (auto &it : nodes[node].links) + { + int target = it.first; + SigBit ctrl = state_sig[node]; + + if (it.second != State::S1) + ctrl = module->And(NEW_ID, ctrl, it.second); + + state_sig[target] = module->Or(NEW_ID, state_sig[target], ctrl); + } + } + } + + // Construct activations + + { + vector activate_sig(GetSize(nodes)); + vector activate_bit(GetSize(nodes)); + + for (int i = 0; i < GetSize(nodes); i++) { + for (auto &it : nodes[i].edges) + activate_sig[it.first].append(module->And(NEW_ID, state_sig[i], it.second)); + } + + for (int i = 0; i < GetSize(nodes); i++) { + if (GetSize(activate_sig[i]) == 0) + next_state_sig[i] = State::S0; + else if (GetSize(activate_sig[i]) == 1) + next_state_sig[i] = activate_sig[i]; + else + next_state_sig[i] = module->ReduceOr(NEW_ID, activate_sig[i]); + } + } + + // Create state FFs + + for (int i = 0; i < GetSize(nodes); i++) + { + if (next_state_sig[i] != State::S0) { + clocking.addDff(NEW_ID, next_state_sig[i], state_wire[i], State::S0); + } else { + module->connect(state_wire[i], State::S0); + } + } + + final_accept_sig = state_sig[acceptNode]; + return final_accept_sig; + } + + // ---------------------------------------------------- + // Generating quantifier-based NFSM circuit to acquire reject signal + + SigBit getAnyAllRejectWorker(bool /* allMode */) + { + // FIXME + log_abort(); + } + + SigBit getAnyReject() + { + return getAnyAllRejectWorker(false); + } + + SigBit getAllReject() + { + return getAnyAllRejectWorker(true); + } + + // ---------------------------------------------------- + // Generating DFSM circuit to acquire reject signal + + void node_to_unode(int node, int unode, SigSpec ctrl) + { + if (node == acceptNode) + unodes[unode].accept.push_back(ctrl); + + if (node == condNode) + unodes[unode].cond.push_back(ctrl); + + for (auto &it : nodes[node].edges) { + if (it.second != State::S1) { + SigSpec s = {ctrl, it.second}; + s.sort_and_unify(); + unodes[unode].edges.push_back(make_pair(it.first, s)); + } else { + unodes[unode].edges.push_back(make_pair(it.first, ctrl)); + } + } + + for (auto &it : nodes[node].links) { + if (it.second != State::S1) { + SigSpec s = {ctrl, it.second}; + s.sort_and_unify(); + node_to_unode(it.first, unode, s); + } else { + node_to_unode(it.first, unode, ctrl); + } + } + } + + void mark_reachable_unode(int unode) + { + if (unodes[unode].reachable) + return; + + unodes[unode].reachable = true; + for (auto &it : unodes[unode].edges) + mark_reachable_unode(it.first); + } + + void usortint(vector &vec) + { + vector newvec; + std::sort(vec.begin(), vec.end()); + for (int i = 0; i < GetSize(vec); i++) + if (i == GetSize(vec)-1 || vec[i] != vec[i+1]) + newvec.push_back(vec[i]); + vec.swap(newvec); + } + + bool cmp_ctrl(const pool &ctrl_bits, const SigSpec &ctrl) + { + for (int i = 0; i < GetSize(ctrl); i++) + if (ctrl_bits.count(ctrl[i]) == 0) + return false; + return true; + } + + void create_dnode(const vector &state, bool firstmatch, bool condaccept) + { + if (dnodes.count(state) != 0) + return; + + SvaDFsmNode dnode; + dnodes[state] = SvaDFsmNode(); + + for (int unode : state) { + log_assert(unodes[unode].reachable); + for (auto &it : unodes[unode].edges) + dnode.ctrl.append(it.second); + for (auto &it : unodes[unode].accept) + dnode.ctrl.append(it); + for (auto &it : unodes[unode].cond) + dnode.ctrl.append(it); + } + + dnode.ctrl.sort_and_unify(); + + if (GetSize(dnode.ctrl) > verific_sva_fsm_limit) { + if (verific_verbose >= 2) { + log(" detected state explosion in DFSM generation:\n"); + dump(); + log(" ctrl signal: %s\n", log_signal(dnode.ctrl)); + } + parser_error(stringf("SVA DFSM state ctrl signal has %d (>%d) bits. Stopping to prevent exponential design size explosion.\n", + GetSize(dnode.ctrl), verific_sva_fsm_limit)); + } + + for (unsigned long long i = 0; i < (1ull << GetSize(dnode.ctrl)); i++) + { + Const ctrl_val(i, GetSize(dnode.ctrl)); + pool ctrl_bits; + + for (int j = 0; j < GetSize(dnode.ctrl); j++) + if (ctrl_val[j] == State::S1) + ctrl_bits.insert(dnode.ctrl[j]); + + vector new_state; + bool accept = false, cond = false; + + for (int unode : state) { + for (auto &it : unodes[unode].accept) + if (cmp_ctrl(ctrl_bits, it)) + accept = true; + for (auto &it : unodes[unode].cond) + if (cmp_ctrl(ctrl_bits, it)) + cond = true; + } + + bool new_state_cond = false; + bool new_state_noncond = false; + + if (accept && condaccept) + accept = cond; + + if (!accept || !firstmatch) { + for (int unode : state) + for (auto &it : unodes[unode].edges) + if (cmp_ctrl(ctrl_bits, it.second)) { + if (nodes.at(it.first).is_cond_node) + new_state_cond = true; + else + new_state_noncond = true; + new_state.push_back(it.first); + } + } + + if (accept) + dnode.accept.push_back(ctrl_val); + + if (condaccept && (!new_state_cond || !new_state_noncond)) + new_state.clear(); + + if (new_state.empty()) { + if (!accept) + dnode.reject.push_back(ctrl_val); + } else { + usortint(new_state); + dnode.edges.push_back(make_pair(new_state, ctrl_val)); + create_dnode(new_state, firstmatch, condaccept); + } + } + + dnodes[state] = dnode; + } + + void optimize_cond(vector &values) + { + bool did_something = true; + + while (did_something) + { + did_something = false; + + for (int i = 0; i < GetSize(values); i++) + for (int j = 0; j < GetSize(values); j++) + { + if (i == j) + continue; + + log_assert(GetSize(values[i]) == GetSize(values[j])); + + int delta_pos = -1; + bool i_within_j = true; + bool j_within_i = true; + + for (int k = 0; k < GetSize(values[i]); k++) { + if (values[i][k] == State::Sa && values[j][k] != State::Sa) { + i_within_j = false; + continue; + } + if (values[i][k] != State::Sa && values[j][k] == State::Sa) { + j_within_i = false; + continue; + } + if (values[i][k] == values[j][k]) + continue; + if (delta_pos >= 0) + goto next_pair; + delta_pos = k; + } + + if (delta_pos >= 0 && i_within_j && j_within_i) { + did_something = true; + values[i].set(delta_pos, State::Sa); + values[j] = values.back(); + values.pop_back(); + goto next_pair; + } + + if (delta_pos < 0 && i_within_j) { + did_something = true; + values[i] = values.back(); + values.pop_back(); + goto next_pair; + } + + if (delta_pos < 0 && j_within_i) { + did_something = true; + values[j] = values.back(); + values.pop_back(); + goto next_pair; + } + next_pair:; + } + } + } + + SigBit make_cond_eq(const SigSpec &ctrl, const Const &value, SigBit enable = State::S1) + { + SigSpec sig_a, sig_b; + + log_assert(GetSize(ctrl) == GetSize(value)); + + for (int i = 0; i < GetSize(ctrl); i++) + if (value[i] != State::Sa) { + sig_a.append(ctrl[i]); + sig_b.append(value[i]); + } + + if (GetSize(sig_a) == 0) + return enable; + + if (enable != State::S1) { + sig_a.append(enable); + sig_b.append(State::S1); + } + + auto key = make_pair(sig_a, sig_b); + + if (cond_eq_cache.count(key) == 0) + { + if (sig_b == State::S1) + cond_eq_cache[key] = sig_a; + else if (sig_b == State::S0) + cond_eq_cache[key] = module->Not(NEW_ID, sig_a); + else + cond_eq_cache[key] = module->Eq(NEW_ID, sig_a, sig_b); + + if (verific_verbose >= 2) { + log(" Cond: %s := %s == %s\n", log_signal(cond_eq_cache[key]), + log_signal(sig_a), log_signal(sig_b)); + } + } + + return cond_eq_cache.at(key); + } + + void getFirstAcceptReject(SigBit *accept_p, SigBit *reject_p) + { + log_assert(!materialized); + materialized = true; + + // Create unlinked NFSM + + unodes.resize(GetSize(nodes)); + + for (int node = 0; node < GetSize(nodes); node++) + node_to_unode(node, node, SigSpec()); + + mark_reachable_unode(startNode); + + // Create DFSM + + create_dnode(vector{startNode}, true, false); + dnodes.sort(); + + // Create DFSM Circuit + + SigSpec accept_sig, reject_sig; + + for (auto &it : dnodes) + { + SvaDFsmNode &dnode = it.second; + dnode.ffoutwire = module->addWire(NEW_ID); + dnode.statesig = dnode.ffoutwire; + + if (it.first == vector{startNode}) + dnode.statesig = module->Or(NEW_ID, dnode.statesig, trigger_sig); + } + + for (auto &it : dnodes) + { + SvaDFsmNode &dnode = it.second; + dict, vector> edge_cond; + + for (auto &edge : dnode.edges) + edge_cond[edge.first].push_back(edge.second); + + for (auto &it : edge_cond) { + optimize_cond(it.second); + for (auto &value : it.second) + dnodes.at(it.first).nextstate.append(make_cond_eq(dnode.ctrl, value, dnode.statesig)); + } + + if (accept_p) { + vector accept_cond = dnode.accept; + optimize_cond(accept_cond); + for (auto &value : accept_cond) + accept_sig.append(make_cond_eq(dnode.ctrl, value, dnode.statesig)); + } + + if (reject_p) { + vector reject_cond = dnode.reject; + optimize_cond(reject_cond); + for (auto &value : reject_cond) + reject_sig.append(make_cond_eq(dnode.ctrl, value, dnode.statesig)); + } + } + + for (auto &it : dnodes) + { + SvaDFsmNode &dnode = it.second; + if (GetSize(dnode.nextstate) == 0) { + module->connect(dnode.ffoutwire, State::S0); + } else + if (GetSize(dnode.nextstate) == 1) { + clocking.addDff(NEW_ID, dnode.nextstate, dnode.ffoutwire, State::S0); + } else { + SigSpec nextstate = module->ReduceOr(NEW_ID, dnode.nextstate); + clocking.addDff(NEW_ID, nextstate, dnode.ffoutwire, State::S0); + } + } + + if (accept_p) + { + if (GetSize(accept_sig) == 0) + final_accept_sig = State::S0; + else if (GetSize(accept_sig) == 1) + final_accept_sig = accept_sig; + else + final_accept_sig = module->ReduceOr(NEW_ID, accept_sig); + *accept_p = final_accept_sig; + } + + if (reject_p) + { + if (GetSize(reject_sig) == 0) + final_reject_sig = State::S0; + else if (GetSize(reject_sig) == 1) + final_reject_sig = reject_sig; + else + final_reject_sig = module->ReduceOr(NEW_ID, reject_sig); + *reject_p = final_reject_sig; + } + } + + SigBit getFirstAccept() + { + SigBit accept; + getFirstAcceptReject(&accept, nullptr); + return accept; + } + + SigBit getReject() + { + SigBit reject; + getFirstAcceptReject(nullptr, &reject); + return reject; + } + + void getDFsm(SvaFsm &output_fsm, int output_start_node, int output_accept_node, int output_reject_node = -1, bool firstmatch = true, bool condaccept = false) + { + log_assert(!materialized); + materialized = true; + + // Create unlinked NFSM + + unodes.resize(GetSize(nodes)); + + for (int node = 0; node < GetSize(nodes); node++) + node_to_unode(node, node, SigSpec()); + + mark_reachable_unode(startNode); + + // Create DFSM + + create_dnode(vector{startNode}, firstmatch, condaccept); + dnodes.sort(); + + // Create DFSM Graph + + for (auto &it : dnodes) + { + SvaDFsmNode &dnode = it.second; + dnode.outnode = output_fsm.createNode(); + + if (it.first == vector{startNode}) + output_fsm.createLink(output_start_node, dnode.outnode); + + if (output_accept_node >= 0) { + vector accept_cond = dnode.accept; + optimize_cond(accept_cond); + for (auto &value : accept_cond) + output_fsm.createLink(it.second.outnode, output_accept_node, make_cond_eq(dnode.ctrl, value)); + } + + if (output_reject_node >= 0) { + vector reject_cond = dnode.reject; + optimize_cond(reject_cond); + for (auto &value : reject_cond) + output_fsm.createLink(it.second.outnode, output_reject_node, make_cond_eq(dnode.ctrl, value)); + } + } + + for (auto &it : dnodes) + { + SvaDFsmNode &dnode = it.second; + dict, vector> edge_cond; + + for (auto &edge : dnode.edges) + edge_cond[edge.first].push_back(edge.second); + + for (auto &it : edge_cond) { + optimize_cond(it.second); + for (auto &value : it.second) + output_fsm.createEdge(dnode.outnode, dnodes.at(it.first).outnode, make_cond_eq(dnode.ctrl, value)); + } + } + } + + // ---------------------------------------------------- + // State dump for verbose log messages + + void dump_nodes() + { + if (nodes.empty()) + return; + + log(" non-deterministic encoding:\n"); + for (int i = 0; i < GetSize(nodes); i++) + { + log(" node %d:%s\n", i, + i == startNode ? " [start]" : + i == acceptNode ? " [accept]" : + i == condNode ? " [cond]" : ""); + + for (auto &it : nodes[i].edges) { + if (it.second != State::S1) + log(" edge %s -> %d\n", log_signal(it.second), it.first); + else + log(" edge -> %d\n", it.first); + } + + for (auto &it : nodes[i].links) { + if (it.second != State::S1) + log(" link %s -> %d\n", log_signal(it.second), it.first); + else + log(" link -> %d\n", it.first); + } + } + } + + void dump_unodes() + { + if (unodes.empty()) + return; + + log(" unlinked non-deterministic encoding:\n"); + for (int i = 0; i < GetSize(unodes); i++) + { + if (!unodes[i].reachable) + continue; + + log(" unode %d:%s\n", i, i == startNode ? " [start]" : ""); + + for (auto &it : unodes[i].edges) { + if (!it.second.empty()) + log(" edge %s -> %d\n", log_signal(it.second), it.first); + else + log(" edge -> %d\n", it.first); + } + + for (auto &ctrl : unodes[i].accept) { + if (!ctrl.empty()) + log(" accept %s\n", log_signal(ctrl)); + else + log(" accept\n"); + } + + for (auto &ctrl : unodes[i].cond) { + if (!ctrl.empty()) + log(" cond %s\n", log_signal(ctrl)); + else + log(" cond\n"); + } + } + } + + void dump_dnodes() + { + if (dnodes.empty()) + return; + + log(" deterministic encoding:\n"); + for (auto &it : dnodes) + { + std::string message; + for (int i = 0; i < GetSize(it.first); i++) + message += stringf("%s%d", i ? "," : "", it.first[i]); + log(" dnode {%s}:%s\n", message, GetSize(it.first) == 1 && it.first[0] == startNode ? " [start]" : ""); + + log(" ctrl %s\n", log_signal(it.second.ctrl)); + + for (auto &edge : it.second.edges) { + std::string message; + for (int i = 0; i < GetSize(edge.first); i++) + message += stringf("%s%d", i ? "," : "", edge.first[i]); + log(" edge %s -> {%s}\n", log_signal(edge.second), message); + } + + for (auto &value : it.second.accept) + log(" accept %s\n", log_signal(value)); + + for (auto &value : it.second.reject) + log(" reject %s\n", log_signal(value)); + } + } + + void dump() + { + if (!nodes.empty()) + log(" number of NFSM states: %d\n", GetSize(nodes)); + + if (!unodes.empty()) { + int count = 0; + for (auto &unode : unodes) + if (unode.reachable) + count++; + log(" number of reachable UFSM states: %d\n", count); + } + + if (!dnodes.empty()) + log(" number of DFSM states: %d\n", GetSize(dnodes)); + + if (verific_verbose >= 2) { + dump_nodes(); + dump_unodes(); + dump_dnodes(); + } + + if (trigger_sig != State::S1) + log(" trigger signal: %s\n", log_signal(trigger_sig)); + + if (final_accept_sig != State::Sx) + log(" accept signal: %s\n", log_signal(final_accept_sig)); + + if (final_reject_sig != State::Sx) + log(" reject signal: %s\n", log_signal(final_reject_sig)); + } +}; + +PRIVATE_NAMESPACE_END + +YOSYS_NAMESPACE_BEGIN + +pool verific_sva_prims = { + // Copy&paste from Verific 3.16_484_32_170630 Netlist.h + PRIM_SVA_IMMEDIATE_ASSERT, PRIM_SVA_ASSERT, PRIM_SVA_COVER, PRIM_SVA_ASSUME, + PRIM_SVA_EXPECT, PRIM_SVA_POSEDGE, PRIM_SVA_NOT, PRIM_SVA_FIRST_MATCH, + PRIM_SVA_ENDED, PRIM_SVA_MATCHED, PRIM_SVA_CONSECUTIVE_REPEAT, + PRIM_SVA_NON_CONSECUTIVE_REPEAT, PRIM_SVA_GOTO_REPEAT, + PRIM_SVA_MATCH_ITEM_TRIGGER, PRIM_SVA_AND, PRIM_SVA_OR, PRIM_SVA_SEQ_AND, + PRIM_SVA_SEQ_OR, PRIM_SVA_EVENT_OR, PRIM_SVA_OVERLAPPED_IMPLICATION, + PRIM_SVA_NON_OVERLAPPED_IMPLICATION, PRIM_SVA_OVERLAPPED_FOLLOWED_BY, + PRIM_SVA_NON_OVERLAPPED_FOLLOWED_BY, PRIM_SVA_INTERSECT, PRIM_SVA_THROUGHOUT, + PRIM_SVA_WITHIN, PRIM_SVA_AT, PRIM_SVA_DISABLE_IFF, PRIM_SVA_SAMPLED, + PRIM_SVA_ROSE, PRIM_SVA_FELL, PRIM_SVA_STABLE, PRIM_SVA_PAST, + PRIM_SVA_MATCH_ITEM_ASSIGN, PRIM_SVA_SEQ_CONCAT, PRIM_SVA_IF, + PRIM_SVA_RESTRICT, PRIM_SVA_TRIGGERED, PRIM_SVA_STRONG, PRIM_SVA_WEAK, + PRIM_SVA_NEXTTIME, PRIM_SVA_S_NEXTTIME, PRIM_SVA_ALWAYS, PRIM_SVA_S_ALWAYS, + PRIM_SVA_S_EVENTUALLY, PRIM_SVA_EVENTUALLY, PRIM_SVA_UNTIL, PRIM_SVA_S_UNTIL, + PRIM_SVA_UNTIL_WITH, PRIM_SVA_S_UNTIL_WITH, PRIM_SVA_IMPLIES, PRIM_SVA_IFF, + PRIM_SVA_ACCEPT_ON, PRIM_SVA_REJECT_ON, PRIM_SVA_SYNC_ACCEPT_ON, + PRIM_SVA_SYNC_REJECT_ON, PRIM_SVA_GLOBAL_CLOCKING_DEF, + PRIM_SVA_GLOBAL_CLOCKING_REF, PRIM_SVA_IMMEDIATE_ASSUME, + PRIM_SVA_IMMEDIATE_COVER, OPER_SVA_SAMPLED, OPER_SVA_STABLE +}; + +struct VerificSvaImporter +{ + VerificImporter *importer = nullptr; + Module *module = nullptr; + + Netlist *netlist = nullptr; + Instance *root = nullptr; + + VerificClocking clocking; + + bool mode_assert = false; + bool mode_assume = false; + bool mode_cover = false; + bool mode_trigger = false; + + Instance *net_to_ast_driver(Net *n) + { + if (n == nullptr) + return nullptr; + + if (n->IsMultipleDriven()) + return nullptr; + + Instance *inst = n->Driver(); + + if (inst == nullptr) + return nullptr; + + if (!verific_sva_prims.count(inst->Type())) + return nullptr; + + if (inst->Type() == PRIM_SVA_ROSE || inst->Type() == PRIM_SVA_FELL || + inst->Type() == PRIM_SVA_STABLE || inst->Type() == OPER_SVA_STABLE || + inst->Type() == PRIM_SVA_PAST || inst->Type() == PRIM_SVA_TRIGGERED) + return nullptr; + + return inst; + } + + Instance *get_ast_input(Instance *inst) { return net_to_ast_driver(inst->GetInput()); } + Instance *get_ast_input1(Instance *inst) { return net_to_ast_driver(inst->GetInput1()); } + Instance *get_ast_input2(Instance *inst) { return net_to_ast_driver(inst->GetInput2()); } + Instance *get_ast_input3(Instance *inst) { return net_to_ast_driver(inst->GetInput3()); } + Instance *get_ast_control(Instance *inst) { return net_to_ast_driver(inst->GetControl()); } + + // ---------------------------------------------------------- + // SVA Importer + + struct ParserErrorException { + }; + + [[noreturn]] void parser_error(std::string errmsg) + { + if (!importer->mode_keep && !importer->mode_sva_continue) + log_error("%s", errmsg); + log_warning("%s", errmsg); + throw ParserErrorException(); + } + + [[noreturn]] void parser_error(std::string errmsg, linefile_type loc) + { + parser_error(stringf("%s at %s:%d.\n", errmsg, LineFile::GetFileName(loc), LineFile::GetLineNo(loc))); + } + + [[noreturn]] void parser_error(std::string errmsg, Instance *inst) + { + parser_error(stringf("%s at %s (%s)", errmsg, inst->View()->Owner()->Name(), inst->Name()), inst->Linefile()); + } + + [[noreturn]] void parser_error(Instance *inst) + { + std::string msg; + if (inst->Type() == PRIM_SVA_MATCH_ITEM_TRIGGER || inst->Type() == PRIM_SVA_MATCH_ITEM_ASSIGN) + { + msg = "SVA sequences with local variable assignments are currently not supported.\n"; + } + + parser_error(stringf("%sVerific SVA primitive %s (%s) is currently unsupported in this context", + msg, inst->View()->Owner()->Name(), inst->Name()), inst->Linefile()); + } + + dict check_expression_cache; + + bool check_expression(Net *net, bool raise_error = false) + { + while (!check_expression_cache.count(net)) + { + Instance *inst = net_to_ast_driver(net); + + if (inst == nullptr) { + check_expression_cache[net] = true; + break; + } + + if (inst->Type() == PRIM_SVA_AT) + { + VerificClocking new_clocking(importer, net); + log_assert(new_clocking.cond_net == nullptr); + if (!clocking.property_matches_sequence(new_clocking)) + parser_error("Mixed clocking is currently not supported", inst); + check_expression_cache[net] = check_expression(new_clocking.body_net, raise_error); + break; + } + + if (inst->Type() == PRIM_SVA_FIRST_MATCH || inst->Type() == PRIM_SVA_NOT) + { + check_expression_cache[net] = check_expression(inst->GetInput(), raise_error); + break; + } + + if (inst->Type() == PRIM_SVA_SEQ_OR || inst->Type() == PRIM_SVA_SEQ_AND || inst->Type() == PRIM_SVA_INTERSECT || + inst->Type() == PRIM_SVA_WITHIN || inst->Type() == PRIM_SVA_THROUGHOUT || + inst->Type() == PRIM_SVA_OR || inst->Type() == PRIM_SVA_AND) + { + check_expression_cache[net] = check_expression(inst->GetInput1(), raise_error) && check_expression(inst->GetInput2(), raise_error); + break; + } + + if (inst->Type() == PRIM_SVA_SEQ_CONCAT) + { + const char *sva_low_s = inst->GetAttValue("sva:low"); + const char *sva_high_s = inst->GetAttValue("sva:high"); + + int sva_low = atoi(sva_low_s); + int sva_high = atoi(sva_high_s); + bool sva_inf = !strcmp(sva_high_s, "$"); + + if (sva_low == 0 && sva_high == 0 && !sva_inf) + check_expression_cache[net] = check_expression(inst->GetInput1(), raise_error) && check_expression(inst->GetInput2(), raise_error); + else + check_expression_cache[net] = false; + break; + } + + check_expression_cache[net] = false; + } + + if (raise_error && !check_expression_cache.at(net)) + parser_error(net_to_ast_driver(net)); + return check_expression_cache.at(net); + } + + SigBit parse_expression(Net *net) + { + check_expression(net, true); + + Instance *inst = net_to_ast_driver(net); + + if (inst == nullptr) { + return importer->net_map_at(net); + } + + if (inst->Type() == PRIM_SVA_AT) + { + VerificClocking new_clocking(importer, net); + log_assert(new_clocking.cond_net == nullptr); + if (!clocking.property_matches_sequence(new_clocking)) + parser_error("Mixed clocking is currently not supported", inst); + return parse_expression(new_clocking.body_net); + } + + if (inst->Type() == PRIM_SVA_FIRST_MATCH) + return parse_expression(inst->GetInput()); + + if (inst->Type() == PRIM_SVA_NOT) + return module->Not(NEW_ID, parse_expression(inst->GetInput())); + + if (inst->Type() == PRIM_SVA_SEQ_OR || inst->Type() == PRIM_SVA_OR) + return module->Or(NEW_ID, parse_expression(inst->GetInput1()), parse_expression(inst->GetInput2())); + + if (inst->Type() == PRIM_SVA_SEQ_AND || inst->Type() == PRIM_SVA_AND || inst->Type() == PRIM_SVA_INTERSECT || + inst->Type() == PRIM_SVA_WITHIN || inst->Type() == PRIM_SVA_THROUGHOUT || inst->Type() == PRIM_SVA_SEQ_CONCAT) + return module->And(NEW_ID, parse_expression(inst->GetInput1()), parse_expression(inst->GetInput2())); + + log_abort(); + } + + bool check_zero_consecutive_repeat(Net *net) + { + Instance *inst = net_to_ast_driver(net); + + if (inst == nullptr) + return false; + + if (inst->Type() != PRIM_SVA_CONSECUTIVE_REPEAT) + return false; + + const char *sva_low_s = inst->GetAttValue("sva:low"); + int sva_low = atoi(sva_low_s); + + return sva_low == 0; + } + + int parse_consecutive_repeat(SvaFsm &fsm, int start_node, Net *net, bool add_pre_delay, bool add_post_delay) + { + Instance *inst = net_to_ast_driver(net); + + log_assert(inst->Type() == PRIM_SVA_CONSECUTIVE_REPEAT); + + const char *sva_low_s = inst->GetAttValue("sva:low"); + const char *sva_high_s = inst->GetAttValue("sva:high"); + + int sva_low = atoi(sva_low_s); + int sva_high = atoi(sva_high_s); + bool sva_inf = !strcmp(sva_high_s, "$"); + + Net *body_net = inst->GetInput(); + + if (add_pre_delay || add_post_delay) + log_assert(sva_low == 0); + + if (sva_low == 0) { + if (!add_pre_delay && !add_post_delay) + parser_error("Possibly zero-length consecutive repeat must follow or precede a delay of at least one cycle", inst); + sva_low++; + } + + int node = fsm.createNode(start_node); + start_node = node; + + if (add_pre_delay) { + node = fsm.createNode(start_node); + fsm.createEdge(start_node, node); + } + + int prev_node = node; + node = parse_sequence(fsm, node, body_net); + + for (int i = 1; i < sva_low; i++) + { + int next_node = fsm.createNode(); + fsm.createEdge(node, next_node); + + prev_node = node; + node = parse_sequence(fsm, next_node, body_net); + } + + if (sva_inf) + { + log_assert(prev_node >= 0); + fsm.createEdge(node, prev_node); + } + else + { + for (int i = sva_low; i < sva_high; i++) + { + int next_node = fsm.createNode(); + fsm.createEdge(node, next_node); + + prev_node = node; + node = parse_sequence(fsm, next_node, body_net); + + fsm.createLink(prev_node, node); + } + } + + if (add_post_delay) { + int next_node = fsm.createNode(); + fsm.createEdge(node, next_node); + node = next_node; + } + + if (add_pre_delay || add_post_delay) + fsm.createLink(start_node, node); + + return node; + } + + int parse_sequence(SvaFsm &fsm, int start_node, Net *net) + { + if (check_expression(net)) { + int node = fsm.createNode(); + fsm.createLink(start_node, node, parse_expression(net)); + return node; + } + + Instance *inst = net_to_ast_driver(net); + + if (inst->Type() == PRIM_SVA_AT) + { + VerificClocking new_clocking(importer, net); + log_assert(new_clocking.cond_net == nullptr); + if (!clocking.property_matches_sequence(new_clocking)) + parser_error("Mixed clocking is currently not supported", inst); + return parse_sequence(fsm, start_node, new_clocking.body_net); + } + + if (inst->Type() == PRIM_SVA_FIRST_MATCH) + { + SvaFsm match_fsm(clocking); + match_fsm.parser_error = [&](std::string msg) { this->parser_error(msg); }; + match_fsm.createLink(parse_sequence(match_fsm, match_fsm.createStartNode(), inst->GetInput()), match_fsm.acceptNode); + + int node = fsm.createNode(); + match_fsm.getDFsm(fsm, start_node, node); + + if (verific_verbose) { + log(" First Match FSM:\n"); + match_fsm.dump(); + } + + return node; + } + + if (inst->Type() == PRIM_SVA_NEXTTIME || inst->Type() == PRIM_SVA_S_NEXTTIME) + { + const char *sva_low_s = inst->GetAttValue("sva:low"); + const char *sva_high_s = inst->GetAttValue("sva:high"); + + int sva_low = atoi(sva_low_s); + int sva_high = atoi(sva_high_s); + log_assert(sva_low == sva_high); + + int node = start_node; + + for (int i = 0; i < sva_low; i++) { + int next_node = fsm.createNode(); + fsm.createEdge(node, next_node); + node = next_node; + } + + return parse_sequence(fsm, node, inst->GetInput()); + } + + if (inst->Type() == PRIM_SVA_SEQ_CONCAT) + { + const char *sva_low_s = inst->GetAttValue("sva:low"); + const char *sva_high_s = inst->GetAttValue("sva:high"); + + int sva_low = atoi(sva_low_s); + int sva_high = atoi(sva_high_s); + bool sva_inf = !strcmp(sva_high_s, "$"); + + int node = -1; + bool past_add_delay = false; + + if (check_zero_consecutive_repeat(inst->GetInput1()) && sva_low > 0) { + node = parse_consecutive_repeat(fsm, start_node, inst->GetInput1(), false, true); + sva_low--, sva_high--; + } else { + node = parse_sequence(fsm, start_node, inst->GetInput1()); + } + + if (check_zero_consecutive_repeat(inst->GetInput2()) && sva_low > 0) { + past_add_delay = true; + sva_low--, sva_high--; + } + + for (int i = 0; i < sva_low; i++) { + int next_node = fsm.createNode(); + fsm.createEdge(node, next_node); + node = next_node; + } + + if (sva_inf) + { + fsm.createEdge(node, node); + } + else + { + for (int i = sva_low; i < sva_high; i++) + { + int next_node = fsm.createNode(); + fsm.createEdge(node, next_node); + fsm.createLink(node, next_node); + node = next_node; + } + } + + if (past_add_delay) + node = parse_consecutive_repeat(fsm, node, inst->GetInput2(), true, false); + else + node = parse_sequence(fsm, node, inst->GetInput2()); + + return node; + } + + if (inst->Type() == PRIM_SVA_CONSECUTIVE_REPEAT) + { + return parse_consecutive_repeat(fsm, start_node, net, false, false); + } + + if (inst->Type() == PRIM_SVA_NON_CONSECUTIVE_REPEAT || inst->Type() == PRIM_SVA_GOTO_REPEAT) + { + const char *sva_low_s = inst->GetAttValue("sva:low"); + const char *sva_high_s = inst->GetAttValue("sva:high"); + + int sva_low = atoi(sva_low_s); + int sva_high = atoi(sva_high_s); + bool sva_inf = !strcmp(sva_high_s, "$"); + + Net *body_net = inst->GetInput(); + int node = fsm.createNode(start_node); + + SigBit cond = parse_expression(body_net); + SigBit not_cond = module->Not(NEW_ID, cond); + + for (int i = 0; i < sva_low; i++) + { + int wait_node = fsm.createNode(); + fsm.createEdge(wait_node, wait_node, not_cond); + + if (i == 0) + fsm.createLink(node, wait_node); + else + fsm.createEdge(node, wait_node); + + int next_node = fsm.createNode(); + fsm.createLink(wait_node, next_node, cond); + + node = next_node; + } + + if (sva_inf) + { + int wait_node = fsm.createNode(); + fsm.createEdge(wait_node, wait_node, not_cond); + fsm.createEdge(node, wait_node); + fsm.createLink(wait_node, node, cond); + } + else + { + for (int i = sva_low; i < sva_high; i++) + { + int wait_node = fsm.createNode(); + fsm.createEdge(wait_node, wait_node, not_cond); + + if (i == 0) + fsm.createLink(node, wait_node); + else + fsm.createEdge(node, wait_node); + + int next_node = fsm.createNode(); + fsm.createLink(wait_node, next_node, cond); + + fsm.createLink(node, next_node); + node = next_node; + } + } + + if (inst->Type() == PRIM_SVA_NON_CONSECUTIVE_REPEAT) + fsm.createEdge(node, node); + + return node; + } + + if (inst->Type() == PRIM_SVA_SEQ_OR || inst->Type() == PRIM_SVA_OR) + { + int node = parse_sequence(fsm, start_node, inst->GetInput1()); + int node2 = parse_sequence(fsm, start_node, inst->GetInput2()); + fsm.createLink(node2, node); + return node; + } + + if (inst->Type() == PRIM_SVA_SEQ_AND || inst->Type() == PRIM_SVA_AND) + { + SvaFsm fsm1(clocking); + fsm1.parser_error = [&](std::string msg) { this->parser_error(msg); }; + fsm1.createLink(parse_sequence(fsm1, fsm1.createStartNode(), inst->GetInput1()), fsm1.acceptNode); + + SvaFsm fsm2(clocking); + fsm2.parser_error = [&](std::string msg) { this->parser_error(msg); }; + fsm2.createLink(parse_sequence(fsm2, fsm2.createStartNode(), inst->GetInput2()), fsm2.acceptNode); + + SvaFsm combined_fsm(clocking); + combined_fsm.parser_error = [&](std::string msg) { this->parser_error(msg); }; + fsm1.getDFsm(combined_fsm, combined_fsm.createStartNode(), -1, combined_fsm.acceptNode); + fsm2.getDFsm(combined_fsm, combined_fsm.createStartNode(), -1, combined_fsm.acceptNode); + + int node = fsm.createNode(); + combined_fsm.getDFsm(fsm, start_node, -1, node); + + if (verific_verbose) + { + log(" Left And FSM:\n"); + fsm1.dump(); + + log(" Right And FSM:\n"); + fsm1.dump(); + + log(" Combined And FSM:\n"); + combined_fsm.dump(); + } + + return node; + } + + if (inst->Type() == PRIM_SVA_INTERSECT || inst->Type() == PRIM_SVA_WITHIN) + { + SvaFsm intersect_fsm(clocking); + intersect_fsm.parser_error = [&](std::string msg) { this->parser_error(msg); }; + + if (inst->Type() == PRIM_SVA_INTERSECT) + { + intersect_fsm.createLink(parse_sequence(intersect_fsm, intersect_fsm.createStartNode(), inst->GetInput1()), intersect_fsm.acceptNode); + } + else + { + int n = intersect_fsm.createNode(); + intersect_fsm.createLink(intersect_fsm.createStartNode(), n); + intersect_fsm.createEdge(n, n); + + n = parse_sequence(intersect_fsm, n, inst->GetInput1()); + + intersect_fsm.createLink(n, intersect_fsm.acceptNode); + intersect_fsm.createEdge(n, n); + } + + intersect_fsm.in_cond_mode = true; + intersect_fsm.createLink(parse_sequence(intersect_fsm, intersect_fsm.createStartNode(), inst->GetInput2()), intersect_fsm.condNode); + intersect_fsm.in_cond_mode = false; + + int node = fsm.createNode(); + intersect_fsm.getDFsm(fsm, start_node, node, -1, false, true); + + if (verific_verbose) { + log(" Intersect FSM:\n"); + intersect_fsm.dump(); + } + + return node; + } + + if (inst->Type() == PRIM_SVA_THROUGHOUT) + { + SigBit expr = parse_expression(inst->GetInput1()); + + fsm.pushThroughout(expr); + int node = parse_sequence(fsm, start_node, inst->GetInput2()); + fsm.popThroughout(); + + return node; + } + + parser_error(inst); + } + + void get_fsm_accept_reject(SvaFsm &fsm, SigBit *accept_p, SigBit *reject_p, bool swap_accept_reject = false) + { + log_assert(accept_p != nullptr || reject_p != nullptr); + + if (swap_accept_reject) + get_fsm_accept_reject(fsm, reject_p, accept_p); + else if (reject_p == nullptr) + *accept_p = fsm.getAccept(); + else if (accept_p == nullptr) + *reject_p = fsm.getReject(); + else + fsm.getFirstAcceptReject(accept_p, reject_p); + } + + void check_eventually(Instance *inst) + { + if (mode_cover || mode_trigger) + parser_error("Unsupported eventually cover", inst); + + const char *sva_low_s = inst->GetAttValue("sva:low"); + const char *sva_high_s = inst->GetAttValue("sva:high"); + int sva_low = atoi(sva_low_s); + bool sva_inf = !strcmp(sva_high_s, "$"); + + if (sva_low != 0 || !sva_inf) + parser_error("Unsupported bounded eventually", inst); + } + + bool eventually_property(Net *&net, SigBit &trig) + { + Instance *inst = net_to_ast_driver(net); + + if (inst == nullptr) + return false; + + if (clocking.cond_net != nullptr) { + trig = importer->net_map_at(clocking.cond_net); + if (!clocking.cond_pol) + trig = module->Not(NEW_ID, trig); + } else { + trig = State::S1; + } + + if (inst->Type() == PRIM_SVA_S_EVENTUALLY || inst->Type() == PRIM_SVA_EVENTUALLY) + { + check_eventually(inst); + + net = inst->GetInput(); + clocking.cond_net = nullptr; + + return true; + } + + if (inst->Type() == PRIM_SVA_OVERLAPPED_IMPLICATION || + inst->Type() == PRIM_SVA_NON_OVERLAPPED_IMPLICATION) + { + Net *antecedent_net = inst->GetInput1(); + Net *consequent_net = inst->GetInput2(); + + Instance *consequent_inst = net_to_ast_driver(consequent_net); + + if (consequent_inst == nullptr) + return false; + + if (consequent_inst->Type() != PRIM_SVA_S_EVENTUALLY && consequent_inst->Type() != PRIM_SVA_EVENTUALLY) + return false; + + check_eventually(consequent_inst); + + int node; + + SvaFsm antecedent_fsm(clocking, trig); + antecedent_fsm.parser_error = [&](std::string msg) { this->parser_error(msg); }; + node = parse_sequence(antecedent_fsm, antecedent_fsm.createStartNode(), antecedent_net); + if (inst->Type() == PRIM_SVA_NON_OVERLAPPED_IMPLICATION) { + int next_node = antecedent_fsm.createNode(); + antecedent_fsm.createEdge(node, next_node); + node = next_node; + } + antecedent_fsm.createLink(node, antecedent_fsm.acceptNode); + + trig = antecedent_fsm.getAccept(); + net = consequent_inst->GetInput(); + clocking.cond_net = nullptr; + + if (verific_verbose) { + log(" Eventually Antecedent FSM:\n"); + antecedent_fsm.dump(); + } + + return true; + } + + return false; + } + + void parse_property(Net *net, SigBit *accept_p, SigBit *reject_p) + { + Instance *inst = net_to_ast_driver(net); + + SigBit trig = State::S1; + + if (clocking.cond_net != nullptr) { + trig = importer->net_map_at(clocking.cond_net); + if (!clocking.cond_pol) + trig = module->Not(NEW_ID, trig); + } + + if (inst == nullptr) + { + if (trig != State::S1) { + if (accept_p != nullptr) + *accept_p = module->And(NEW_ID, trig, importer->net_map_at(net)); + if (reject_p != nullptr) + *reject_p = module->And(NEW_ID, trig, module->Not(NEW_ID, importer->net_map_at(net))); + } else { + if (accept_p != nullptr) + *accept_p = importer->net_map_at(net); + if (reject_p != nullptr) + *reject_p = module->Not(NEW_ID, importer->net_map_at(net)); + } + } + else + if (inst->Type() == PRIM_SVA_OVERLAPPED_IMPLICATION || + inst->Type() == PRIM_SVA_NON_OVERLAPPED_IMPLICATION || + (mode_cover && ( + inst->Type() == PRIM_SVA_OVERLAPPED_FOLLOWED_BY || + inst->Type() == PRIM_SVA_NON_OVERLAPPED_FOLLOWED_BY))) + { + Net *antecedent_net = inst->GetInput1(); + Net *consequent_net = inst->GetInput2(); + int node; + + SvaFsm antecedent_fsm(clocking, trig); + antecedent_fsm.parser_error = [&](std::string msg) { this->parser_error(msg); }; + node = parse_sequence(antecedent_fsm, antecedent_fsm.createStartNode(), antecedent_net); + if (inst->Type() == PRIM_SVA_NON_OVERLAPPED_IMPLICATION || inst->Type() == PRIM_SVA_NON_OVERLAPPED_FOLLOWED_BY) { + int next_node = antecedent_fsm.createNode(); + antecedent_fsm.createEdge(node, next_node); + node = next_node; + } + + Instance *consequent_inst = net_to_ast_driver(consequent_net); + + if (consequent_inst && (consequent_inst->Type() == PRIM_SVA_UNTIL || consequent_inst->Type() == PRIM_SVA_S_UNTIL || + consequent_inst->Type() == PRIM_SVA_UNTIL_WITH || consequent_inst->Type() == PRIM_SVA_S_UNTIL_WITH || + consequent_inst->Type() == PRIM_SVA_ALWAYS || consequent_inst->Type() == PRIM_SVA_S_ALWAYS)) + { + bool until_with = consequent_inst->Type() == PRIM_SVA_UNTIL_WITH || consequent_inst->Type() == PRIM_SVA_S_UNTIL_WITH; + + Net *until_net = nullptr; + if (consequent_inst->Type() == PRIM_SVA_ALWAYS || consequent_inst->Type() == PRIM_SVA_S_ALWAYS) + { + consequent_net = consequent_inst->GetInput(); + consequent_inst = net_to_ast_driver(consequent_net); + } + else + { + until_net = consequent_inst->GetInput2(); + consequent_net = consequent_inst->GetInput1(); + consequent_inst = net_to_ast_driver(consequent_net); + } + + SigBit until_sig = until_net ? parse_expression(until_net) : RTLIL::S0; + SigBit not_until_sig = module->Not(NEW_ID, until_sig); + antecedent_fsm.createEdge(node, node, not_until_sig); + + antecedent_fsm.createLink(node, antecedent_fsm.acceptNode, until_with ? State::S1 : not_until_sig); + } + else + { + antecedent_fsm.createLink(node, antecedent_fsm.acceptNode); + } + + SigBit antecedent_match = antecedent_fsm.getAccept(); + + if (verific_verbose) { + log(" Antecedent FSM:\n"); + antecedent_fsm.dump(); + } + + bool consequent_not = false; + if (consequent_inst && consequent_inst->Type() == PRIM_SVA_NOT) { + consequent_not = true; + consequent_net = consequent_inst->GetInput(); + consequent_inst = net_to_ast_driver(consequent_net); + } + + SvaFsm consequent_fsm(clocking, antecedent_match); + consequent_fsm.parser_error = [&](std::string msg) { this->parser_error(msg); }; + node = parse_sequence(consequent_fsm, consequent_fsm.createStartNode(), consequent_net); + consequent_fsm.createLink(node, consequent_fsm.acceptNode); + + get_fsm_accept_reject(consequent_fsm, accept_p, reject_p, consequent_not); + + if (verific_verbose) { + log(" Consequent FSM:\n"); + consequent_fsm.dump(); + } + } + else + { + bool prop_not = inst->Type() == PRIM_SVA_NOT; + if (prop_not) { + net = inst->GetInput(); + inst = net_to_ast_driver(net); + } + + SvaFsm fsm(clocking, trig); + fsm.parser_error = [&](std::string msg) { this->parser_error(msg); }; + int node = parse_sequence(fsm, fsm.createStartNode(), net); + fsm.createLink(node, fsm.acceptNode); + + get_fsm_accept_reject(fsm, accept_p, reject_p, prop_not); + + if (verific_verbose) { + log(" Sequence FSM:\n"); + fsm.dump(); + } + } + } + + void import() + { + module = importer->module; + netlist = root->Owner(); + + int initial_cell_count = GetSize(module->cells_); + int initial_wire_count = GetSize(module->wires_); + int initial_connection_count = GetSize(module->connections_); + + if (verific_verbose) + log(" importing SVA property at root cell %s (%s) at %s:%d.\n", root->Name(), root->View()->Owner()->Name(), + LineFile::GetFileName(root->Linefile()), LineFile::GetLineNo(root->Linefile())); + + bool is_user_declared = root->IsUserDeclared(); + + // FIXME + if (!is_user_declared) { + const char *name = root->Name(); + for (int i = 0; name[i]; i++) { + if (i ? (name[i] < '0' || name[i] > '9') : (name[i] != 'i')) { + is_user_declared = true; + break; + } + } + } + + RTLIL::IdString root_name = module->uniquify(importer->mode_names || is_user_declared ? module->twines().add(RTLIL::escape_id(root->Name())) : module->twines().add(NEW_ID)); + + try + { + // parse SVA sequence into trigger signal + + clocking = VerificClocking(importer, root->GetInput(), true); + SigBit accept_bit = State::S0, reject_bit = State::S0; + + if (clocking.body_net == nullptr) + { + if (clocking.clock_net != nullptr || clocking.enable_net != nullptr || clocking.disable_net != nullptr || clocking.cond_net != nullptr) + parser_error(stringf("Failed to parse SVA clocking"), root); + + if (mode_assert || mode_assume) { + reject_bit = module->Not(NEW_ID, parse_expression(root->GetInput())); + } else { + accept_bit = parse_expression(root->GetInput()); + } + } + else + { + Net *net = clocking.body_net; + SigBit trig; + + if (eventually_property(net, trig)) + { + SigBit sig_a, sig_en = trig; + parse_property(net, &sig_a, nullptr); + + // add final FF stage + + SigBit sig_a_q, sig_en_q; + + if (clocking.body_net == nullptr) { + sig_a_q = sig_a; + sig_en_q = sig_en; + } else { + sig_a_q = module->addWire(NEW_ID); + sig_en_q = module->addWire(NEW_ID); + clocking.addDff(NEW_ID, sig_a, sig_a_q, State::S0); + clocking.addDff(NEW_ID, sig_en, sig_en_q, State::S0); + } + + // accept in disable case + + if (clocking.disable_sig != State::S0) + sig_a_q = module->Or(NEW_ID, sig_a_q, clocking.disable_sig); + + // generate fair/live cell + + RTLIL::Cell *c = nullptr; + + if (mode_assert) c = module->addLive(root_name, sig_a_q, sig_en_q); + if (mode_assume) c = module->addFair(root_name, sig_a_q, sig_en_q); + + if (c) importer->import_attributes(c->attributes, root); + + return; + } + else + { + if (mode_assert || mode_assume) { + parse_property(net, nullptr, &reject_bit); + } else { + parse_property(net, &accept_bit, nullptr); + } + } + } + + if (mode_trigger) + { + module->connect(importer->net_map_at(root->GetOutput()), accept_bit); + } + else + { + SigBit sig_a = module->Not(NEW_ID, reject_bit); + SigBit sig_en = module->Or(NEW_ID, accept_bit, reject_bit); + + // add final FF stage + + SigBit sig_a_q, sig_en_q; + + if (clocking.body_net == nullptr) { + sig_a_q = sig_a; + sig_en_q = sig_en; + } else { + sig_a_q = module->addWire(NEW_ID); + sig_en_q = module->addWire(NEW_ID); + clocking.addDff(NEW_ID, sig_a, sig_a_q, State::S0); + clocking.addDff(NEW_ID, sig_en, sig_en_q, State::S0); + } + + // generate assert/assume/cover cell + + RTLIL::Cell *c = nullptr; + + if (mode_assert) c = module->addAssert(root_name, sig_a_q, sig_en_q); + if (mode_assume) c = module->addAssume(root_name, sig_a_q, sig_en_q); + if (mode_cover) c = module->addCover(root_name, sig_a_q, sig_en_q); + + if (c) { + c->set_bool_attribute(ID(keep)); + importer->import_attributes(c->attributes, root); + } + } + } + catch (ParserErrorException) + { + if (importer->mode_sva_continue) { + + std::vector remove_cells; + pool remove_wires; + + for (int i = 0, end = GetSize(module->cells_) - initial_cell_count; i != end; ++i) + remove_cells.push_back(module->cells_.element(i)->second); + + for (int i = 0, end = GetSize(module->wires_) - initial_wire_count; i != end; ++i) + remove_wires.emplace(module->wires_.element(i)->second); + + for (auto cell : remove_cells) + module->remove(cell); + module->remove(remove_wires); + + module->connections_.resize(initial_connection_count); + + RTLIL::Cell *c = nullptr; + + if (mode_assert) c = module->addAssert(root_name, State::Sx, State::Sx); + if (mode_assume) c = module->addAssume(root_name, State::Sx, State::Sx); + if (mode_cover) c = module->addCover(root_name, State::Sx, State::Sx); + + if (c) { + importer->import_attributes(c->attributes, root); + c->set_bool_attribute(ID(unsupported_sva)); + } + + importer->num_sva_continue++; + } + } + } +}; + +void verific_import_sva_assert(VerificImporter *importer, Instance *inst) +{ + VerificSvaImporter worker; + worker.importer = importer; + worker.root = inst; + worker.mode_assert = true; + worker.import(); +} + +void verific_import_sva_assume(VerificImporter *importer, Instance *inst) +{ + VerificSvaImporter worker; + worker.importer = importer; + worker.root = inst; + worker.mode_assume = true; + worker.import(); +} + +void verific_import_sva_cover(VerificImporter *importer, Instance *inst) +{ + VerificSvaImporter worker; + worker.importer = importer; + worker.root = inst; + worker.mode_cover = true; + worker.import(); +} + +void verific_import_sva_trigger(VerificImporter *importer, Instance *inst) +{ + VerificSvaImporter worker; + worker.importer = importer; + worker.root = inst; + worker.mode_trigger = true; + worker.import(); +} + +bool verific_is_sva_net(VerificImporter *importer, Verific::Net *net) +{ + VerificSvaImporter worker; + worker.importer = importer; + return worker.net_to_ast_driver(net) != nullptr; +} +#else +YOSYS_NAMESPACE_BEGIN +pool verific_sva_prims = {}; +#endif +YOSYS_NAMESPACE_END diff --git a/chips/yosys/frontends/verilog/.gitignore b/chips/yosys/frontends/verilog/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..aadbcdcdd51512e5917e74772f92ba667c81ac0f --- /dev/null +++ b/chips/yosys/frontends/verilog/.gitignore @@ -0,0 +1,4 @@ +verilog_lexer.cc +verilog_parser.output +verilog_parser.tab.cc +verilog_parser.tab.hh diff --git a/chips/yosys/frontends/verilog/CMakeLists.txt b/chips/yosys/frontends/verilog/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..e002abd3da9b8c3dc6b4def4061fa62cf6b40951 --- /dev/null +++ b/chips/yosys/frontends/verilog/CMakeLists.txt @@ -0,0 +1,43 @@ +if (NOT FLEX_INCLUDE_DIRS) + set(FLEX_INCLUDE_DIRS ${YOSYS_CMAKE_SOURCE_DIR}/libs/flex) +endif() + +flex_target(verilog_lexer + verilog_lexer.l + verilog_lexer.cc +) +bison_target(verilog_parser + verilog_parser.y + verilog_parser.tab.cc + # (requires CMake 4.0) + # OPTIONS + # -Wall -Werror +) +yosys_frontend(verilog + const2ast.cc + preproc.cc + preproc.h + verilog_error.cc + verilog_error.h + verilog_frontend.cc + verilog_frontend.h + verilog_lexer.h + verilog_location.h + ${FLEX_verilog_lexer_OUTPUTS} + ${BISON_verilog_parser_OUTPUTS} + INCLUDE_DIRS + ${FLEX_INCLUDE_DIRS} + REQUIRES + sha1 + ast + PROVIDES + verilog_defaults + verilog_defines + read_verilog_file_list + ESSENTIAL +) +set_source_files_properties( + ${BISON_verilog_parser_OUTPUT_SOURCE} + PROPERTIES + COMPILE_DEFINITIONS -DYYMAXDEPTH=10000000 +) diff --git a/chips/yosys/frontends/verilog/const2ast.cc b/chips/yosys/frontends/verilog/const2ast.cc new file mode 100644 index 0000000000000000000000000000000000000000..e61b0e72cc5b8a860cabec87f33db12cac938496 --- /dev/null +++ b/chips/yosys/frontends/verilog/const2ast.cc @@ -0,0 +1,271 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * --- + * + * The Verilog frontend. + * + * This frontend is using the AST frontend library (see frontends/ast/). + * Thus this frontend does not generate RTLIL code directly but creates an + * AST directly from the Verilog parse tree and then passes this AST to + * the AST frontend library. + * + * --- + * + * This file contains an ad-hoc parser for Verilog constants. The Verilog + * lexer does only recognize a constant but does not actually split it to its + * components. I.e. it just passes the Verilog code for the constant to the + * bison parser. The parser then uses the function const2ast() from this file + * to create an AST node for the constant. + * + */ + +#include "verilog_frontend.h" +#include "kernel/log.h" +#include "kernel/register.h" +#include +#include + +YOSYS_NAMESPACE_BEGIN + +using namespace AST; +using namespace VERILOG_FRONTEND; + +void ConstParser::log_maybe_loc_error(std::string msg) { + if (loc.begin.filename) + log_file_error(loc.to_loc(), "%s\n", msg); + else if (!Frontend::current_script_filename.empty()) + log_file_error(LogSourceLocation(Frontend::current_script_filename, Frontend::current_script_lineno), + "Failed to parse constant `%s': %s\n", code_str, msg); + else + log_error("Failed to parse constant `%s': %s\n", code_str, msg); +} + +void ConstParser::log_maybe_loc_warn(std::string msg) { + if (loc.begin.filename) + log_file_warning(loc.to_loc(), "%s\n", msg); + else if (!Frontend::current_script_filename.empty()) + log_file_warning(LogSourceLocation(Frontend::current_script_filename, Frontend::current_script_lineno), + "While parsing constant `%s': %s\n", code_str, msg); + else + log_warning("While parsing constant `%s': %s\n", code_str, msg); +} + +// divide an arbitrary length decimal number by two and return the rest +int ConstParser::my_decimal_div_by_two(std::vector &digits) +{ + int carry = 0; + for (size_t i = 0; i < digits.size(); i++) { + if (digits[i] >= 10) + log_maybe_loc_error("Invalid use of [a-fxz?] in decimal constant."); + digits[i] += carry * 10; + carry = digits[i] % 2; + digits[i] /= 2; + } + while (!digits.empty() && !digits.front()) + digits.erase(digits.begin()); + return carry; +} + +// find the number of significant bits in a binary number (not including the sign bit) +int ConstParser::my_ilog2(int x) +{ + int ret = 0; + while (x != 0 && x != -1) { + x = x >> 1; + ret++; + } + return ret; +} + +// parse a binary, decimal, hexadecimal or octal number with support for special bits ('x', 'z' and '?') +void ConstParser::my_strtobin(std::vector &data, const char *str, int len_in_bits, int base, char case_type, bool is_unsized) +{ + // all digits in string (MSB at index 0) + std::vector digits; + + while (*str) { + if ('0' <= *str && *str <= '9') + digits.push_back(*str - '0'); + else if ('a' <= *str && *str <= 'f') + digits.push_back(10 + *str - 'a'); + else if ('A' <= *str && *str <= 'F') + digits.push_back(10 + *str - 'A'); + else if (*str == 'x' || *str == 'X') + digits.push_back(0xf0); + else if (*str == 'z' || *str == 'Z' || *str == '?') + digits.push_back(0xf1); + str++; + } + + if (base == 10 && GetSize(digits) == 1 && digits.front() >= 0xf0) + base = 2; + + data.clear(); + + if (base == 10) { + while (!digits.empty()) + data.push_back(my_decimal_div_by_two(digits) ? State::S1 : State::S0); + } else { + int bits_per_digit = my_ilog2(base-1); + for (auto it = digits.rbegin(), e = digits.rend(); it != e; it++) { + if (*it > (base-1) && *it < 0xf0) + log_maybe_loc_error(stringf("Digit larger than %d used in in base-%d constant.", + base-1, base)); + for (int i = 0; i < bits_per_digit; i++) { + int bitmask = 1 << i; + if (*it == 0xf0) + data.push_back(case_type == 'x' ? RTLIL::Sa : RTLIL::Sx); + else if (*it == 0xf1) + data.push_back(case_type == 'x' || case_type == 'z' ? RTLIL::Sa : RTLIL::Sz); + else + data.push_back((*it & bitmask) ? State::S1 : State::S0); + } + } + } + + int len = GetSize(data); + RTLIL::State msb = data.empty() ? State::S0 : data.back(); + + if (len_in_bits < 0) { + if (len < 32) + data.resize(32, msb == State::S0 || msb == State::S1 ? RTLIL::S0 : msb); + return; + } + + if (is_unsized && (len > len_in_bits)) + log_maybe_loc_error(stringf("Unsized constant must have width of 1 bit, but have %d bits!", len)); + + for (len = len - 1; len >= 0; len--) + if (data[len] == State::S1) + break; + if (msb == State::S0 || msb == State::S1) { + len += 1; + data.resize(len_in_bits, State::S0); + } else { + len += 2; + data.resize(len_in_bits, msb); + } + + if (len_in_bits == 0) + log_maybe_loc_error("Illegal integer constant size of zero (IEEE 1800-2012, 5.7)."); + + if (len > len_in_bits) + log_maybe_loc_warn(stringf("Literal has a width of %d bit, but value requires %d bit.", + len_in_bits, len)); +} +// convert the Verilog code for a constant to an AST node +std::unique_ptr ConstParser::const2ast(std::string code, char case_type, bool warn_z) +{ + code_str = code; + + if (warn_z) { + auto ret = const2ast(code, case_type); + if (ret != nullptr && std::find(ret->bits.begin(), ret->bits.end(), RTLIL::State::Sz) != ret->bits.end()) + log_maybe_loc_warn("Yosys has only limited support for tri-state logic at the moment."); + return ret; + } + + const char *str = code.c_str(); + + // Strings + if (*str == '"') { + int len = strlen(str) - 2; + std::vector data; + data.reserve(len * 8); + for (int i = 0; i < len; i++) { + unsigned char ch = str[len - i]; + for (int j = 0; j < 8; j++) { + data.push_back((ch & 1) ? State::S1 : State::S0); + ch = ch >> 1; + } + } + auto ast = AstNode::mkconst_bits(loc, data, false); + ast->str = code; + return ast; + } + + for (size_t i = 0; i < code.size(); i++) + if (code[i] == '_' || code[i] == ' ' || code[i] == '\t' || code[i] == '\r' || code[i] == '\n') + code.erase(code.begin()+(i--)); + str = code.c_str(); + + char *endptr; + long len_in_bits = strtol(str, &endptr, 10); + + // Simple base-10 integer + if (*endptr == 0) { + std::vector data; + my_strtobin(data, str, -1, 10, case_type, false); + if (data.back() == State::S1) + data.push_back(State::S0); + return AstNode::mkconst_bits(loc, data, true); + } + + // unsized constant + if (str == endptr) + len_in_bits = -1; + + // The "'[sS]?[bodhBODH]" syntax + if (*endptr == '\'') + { + std::vector data; + bool is_signed = false; + bool is_unsized = len_in_bits < 0; + if (*(endptr+1) == 's' || *(endptr+1) == 'S') { + is_signed = true; + endptr++; + } + switch (*(endptr+1)) + { + case 'b': + case 'B': + my_strtobin(data, endptr+2, len_in_bits, 2, case_type, is_unsized); + break; + case 'o': + case 'O': + my_strtobin(data, endptr+2, len_in_bits, 8, case_type, is_unsized); + break; + case 'd': + case 'D': + my_strtobin(data, endptr+2, len_in_bits, 10, case_type, is_unsized); + break; + case 'h': + case 'H': + my_strtobin(data, endptr+2, len_in_bits, 16, case_type, is_unsized); + break; + default: + char next_char = char(tolower(*(endptr+1))); + if (next_char == '0' || next_char == '1' || next_char == 'x' || next_char == 'z') { + is_unsized = true; + my_strtobin(data, endptr+1, 1, 2, case_type, is_unsized); + } else { + return NULL; + } + } + if (len_in_bits < 0) { + if (is_signed && data.back() == State::S1) + data.push_back(State::S0); + } + return AstNode::mkconst_bits(loc, data, is_signed, is_unsized); + } + + return NULL; +} + + +YOSYS_NAMESPACE_END diff --git a/chips/yosys/frontends/verilog/preproc.cc b/chips/yosys/frontends/verilog/preproc.cc new file mode 100644 index 0000000000000000000000000000000000000000..816c30706465c813e47ef925af4b6f47e0ff091e --- /dev/null +++ b/chips/yosys/frontends/verilog/preproc.cc @@ -0,0 +1,1006 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * --- + * + * The Verilog frontend. + * + * This frontend is using the AST frontend library (see frontends/ast/). + * Thus this frontend does not generate RTLIL code directly but creates an + * AST directly from the Verilog parse tree and then passes this AST to + * the AST frontend library. + * + * --- + * + * Ad-hoc implementation of a Verilog preprocessor. The directives `define, + * `include, `ifdef, `ifndef, `else and `endif are handled here. All other + * directives are handled by the lexer (see verilog_lexer.l). + * + */ + +#include "preproc.h" +#include "verilog_frontend.h" +#include "frontends/verilog/verilog_parser.tab.hh" +#include "kernel/log.h" +#include +#include +#include +#include +#include + +YOSYS_NAMESPACE_BEGIN +using namespace VERILOG_FRONTEND; + +static std::list output_code; +static std::list input_buffer; +static size_t input_buffer_charp; + +static void return_char(char ch) +{ + if (input_buffer_charp == 0) + input_buffer.push_front(std::string() + ch); + else + input_buffer.front()[--input_buffer_charp] = ch; +} + +static void insert_input(std::string str) +{ + if (input_buffer_charp != 0) { + input_buffer.front() = input_buffer.front().substr(input_buffer_charp); + input_buffer_charp = 0; + } + input_buffer.push_front(str); +} + +static char next_char() +{ + if (input_buffer.empty()) + return 0; + + log_assert(input_buffer_charp <= input_buffer.front().size()); + if (input_buffer_charp == input_buffer.front().size()) { + input_buffer_charp = 0; + input_buffer.pop_front(); + return next_char(); + } + + char ch = input_buffer.front()[input_buffer_charp++]; + return ch == '\r' ? next_char() : ch; +} + +static std::string skip_spaces() +{ + std::string spaces; + while (1) { + char ch = next_char(); + if (ch == 0) + break; + if (ch != ' ' && ch != '\t') { + return_char(ch); + break; + } + spaces += ch; + } + return spaces; +} + +static std::string next_token(bool pass_newline = false) +{ + std::string token; + + char ch = next_char(); + if (ch == 0) + return token; + + token += ch; + if (ch == '\n') { + if (pass_newline) { + output_code.push_back(token); + return ""; + } + return token; + } + + if (ch == ' ' || ch == '\t') + { + while ((ch = next_char()) != 0) { + if (ch != ' ' && ch != '\t') { + return_char(ch); + break; + } + token += ch; + } + } + else if (ch == '"') + { + while ((ch = next_char()) != 0) { + token += ch; + if (ch == '"') + break; + if (ch == '\\') { + if ((ch = next_char()) != 0) + token += ch; + } + } + if (token == "\"\"" && (ch = next_char()) != 0) { + if (ch == '"') + token += ch; + else + return_char(ch); + } + } + else if (ch == '\\') + { + while ((ch = next_char()) != 0) { + if (ch < 33 || ch > 126) { + return_char(ch); + break; + } + token += ch; + } + } + else if (ch == '/') + { + if ((ch = next_char()) != 0) { + if (ch == '/') { + token += '*'; + char last_ch = 0; + while ((ch = next_char()) != 0) { + if (ch == '\n') { + return_char(ch); + break; + } + if (last_ch != '*' || ch != '/') { + token += ch; + last_ch = ch; + } + } + token += " */"; + } + else if (ch == '*') { + token += '*'; + int newline_count = 0; + char last_ch = 0; + while ((ch = next_char()) != 0) { + if (ch == '\n') { + newline_count++; + token += ' '; + } else + token += ch; + if (last_ch == '*' && ch == '/') + break; + last_ch = ch; + } + while (newline_count-- > 0) + return_char('\n'); + } + else + return_char(ch); + } + } + else + { + const char *ok = "abcdefghijklmnopqrstuvwxyz_ABCDEFGHIJKLMNOPQRSTUVWXYZ$0123456789"; + if (ch == '`' || strchr(ok, ch) != NULL) + { + char first = ch; + ch = next_char(); + if (first == '`' && (ch == '"' || ch == '`')) { + token += ch; + } else do { + if (strchr(ok, ch) == NULL) { + return_char(ch); + break; + } + token += ch; + } while ((ch = next_char()) != 0); + } + } + return token; +} + +struct macro_arg_t +{ + macro_arg_t(const std::string &name_, const char *default_value_) + : name(name_), + has_default(default_value_ != nullptr), + default_value(default_value_ ? default_value_ : "") + {} + + std::string name; + bool has_default; + std::string default_value; +}; + +static bool all_white(const std::string &str) +{ + for (char c : str) + if (!isspace(c)) + return false; + return true; +} + +struct arg_map_t +{ + arg_map_t() + {} + + void add_arg(const std::string &name, const char *default_value) + { + if (find(name)) { + log_error("Duplicate macro arguments with name `%s'.\n", name); + } + + name_to_pos[name] = args.size(); + args.push_back(macro_arg_t(name, default_value)); + } + + // Find an argument by name; return nullptr if it doesn't exist. If pos is not null, write + // the argument's position to it on success. + const macro_arg_t *find(const std::string &name, int *pos = nullptr) const + { + auto it = name_to_pos.find(name); + if (it == name_to_pos.end()) + return nullptr; + + if (pos) *pos = it->second; + return &args[it->second]; + } + + // Construct the name for the local macro definition we use for the given argument + // (something like macro_foobar_arg2). This doesn't include the leading backtick. + static std::string str_token(const std::string ¯o_name, int pos) + { + return stringf("macro_%s_arg%d", macro_name, pos); + } + + // Return definitions for the macro arguments (so that substituting in the macro body and + // then performing macro expansion will do argument substitution properly). + std::vector> + get_vals(const std::string ¯o_name, const std::vector &arg_vals) const + { + std::vector> ret; + for (int i = 0; i < GetSize(args); ++ i) { + // The SystemVerilog rules are: + // + // - If the call site specifies an argument and it's not whitespace, use + // it. + // + // - Otherwise, if the argument has a default value, use it. + // + // - Otherwise, if the call site specified whitespace, use that. + // + // - Otherwise, error. + const std::string *dflt = nullptr; + if (args[i].has_default) + dflt = &args[i].default_value; + + const std::string *given = nullptr; + if (i < GetSize(arg_vals)) + given = &arg_vals[i]; + + const std::string *val = nullptr; + if (given && (! (dflt && all_white(*given)))) + val = given; + else if (dflt) + val = dflt; + else if (given) + val = given; + else + log_error("Cannot expand macro `%s by giving only %d argument%s " + "(argument %d has no default).\n", + macro_name, GetSize(arg_vals), + (GetSize(arg_vals) == 1 ? "" : "s"), i + 1); + + assert(val); + ret.push_back(std::make_pair(str_token(macro_name, i), * val)); + } + return ret; + } + + + std::vector args; + std::map name_to_pos; +}; + +struct define_body_t +{ + define_body_t(const std::string &body, const arg_map_t *args = nullptr) + : body(body), + has_args(args != nullptr), + args(args ? *args : arg_map_t()) + {} + + std::string body; + bool has_args; + arg_map_t args; +}; + +define_map_t::define_map_t() +{ + add("YOSYS", "1"); +} + +// We must define this destructor here (rather than relying on the default), because we need to +// define it somewhere we've got a complete definition of define_body_t. +define_map_t::~define_map_t() +{} + +void +define_map_t::add(const std::string &name, const std::string &txt, const arg_map_t *args) +{ + defines[name] = std::unique_ptr(new define_body_t(txt, args)); +} + +void define_map_t::add(const std::string &name, const define_body_t &body) +{ + defines[name] = std::unique_ptr(new define_body_t(body)); +} + +void define_map_t::merge(const define_map_t &map) +{ + for (const auto &pr : map.defines) { + // These contortions are so that we take a copy of each definition body in + // map.defines. + defines[pr.first] = std::unique_ptr(new define_body_t(*pr.second)); + } +} + +const define_body_t *define_map_t::find(const std::string &name) const +{ + auto it = defines.find(name); + return (it == defines.end()) ? nullptr : it->second.get(); +} + +void define_map_t::erase(const std::string &name) +{ + defines.erase(name); +} + +void define_map_t::clear() +{ + defines.clear(); +} + +void define_map_t::log() const +{ + for (auto &it : defines) { + const std::string &name = it.first; + const define_body_t &body = *it.second; + Yosys::log("`define %s%s %s\n", + name, body.has_args ? "()" : "", body.body); + } +} + +static void input_file(std::istream &f, std::string filename) +{ + char buffer[513]; + int rc; + + insert_input(""); + auto it = input_buffer.begin(); + + input_buffer.insert(it, "`file_push \"" + filename + "\"\n"); + while ((rc = readsome(f, buffer, sizeof(buffer)-1)) > 0) { + buffer[rc] = 0; + input_buffer.insert(it, buffer); + } + input_buffer.insert(it, "\n`file_pop\n"); +} + +static bool is_blank_token(const std::string &tok) +{ + return tok.empty() || tok[0] == ' ' || tok[0] == '\t' || tok.compare(0, 2, "/*") == 0; +} + +// Read tokens to get one argument (either a macro argument at a callsite or a default argument in a +// macro definition). Writes the argument to dest. Returns true if we finished with ')' (the end of +// the argument list); false if we finished with ','. +static bool read_argument(std::string &dest) +{ + std::vector openers; + bool pending_space = false; + for (;;) { + std::string tok = next_token(true); + if (is_blank_token(tok)) { + pending_space = !dest.empty(); + continue; + } + if (openers.empty() && (tok == ")" || tok == ",")) + return tok == ")"; + if (pending_space) + dest += ' '; + pending_space = false; + + if (tok == ")") { + if (openers.back() != '(') + log_error("Mismatched brackets in macro argument: %c and %c.\n", + openers.back(), tok[0]); + + openers.pop_back(); + dest += tok; + continue; + } + if (tok == "]") { + char opener = openers.empty() ? '(' : openers.back(); + if (opener != '[') + log_error("Mismatched brackets in macro argument: %c and %c.\n", + opener, tok[0]); + + openers.pop_back(); + dest += tok; + continue; + } + if (tok == "}") { + char opener = openers.empty() ? '(' : openers.back(); + if (opener != '{') + log_error("Mismatched brackets in macro argument: %c and %c.\n", + opener, tok[0]); + + openers.pop_back(); + dest += tok; + continue; + } + + if (tok == "(" || tok == "[" || tok == "{") + openers.push_back(tok[0]); + + dest += tok; + } +} + +using macro_arg_stack_t = std::stack>; + +static void restore_macro_arg(define_map_t &defines, macro_arg_stack_t ¯o_arg_stack) +{ + log_assert(!macro_arg_stack.empty()); + auto &overwritten_arg = macro_arg_stack.top(); + defines.add(overwritten_arg.first, overwritten_arg.second); + macro_arg_stack.pop(); +} + +static bool try_expand_macro(define_map_t &defines, macro_arg_stack_t ¯o_arg_stack, std::string &tok) +{ + if (tok == "`\"") { + std::string literal("\""); + // Expand string literal + while (!input_buffer.empty()) { + std::string ntok = next_token(); + if (ntok == "`\"") { + insert_input(literal+"\""); + return true; + } else if (!try_expand_macro(defines, macro_arg_stack, ntok)) { + literal += ntok; + } + } + return false; // error - unmatched `" + } + + if (tok == "``") { + // Swallow `` in macro expansion + return true; + } + + if (tok.size() <= 1 || tok[0] != '`') + return false; + + // This token looks like a macro name (`foo). + std::string macro_name = tok.substr(1); + const define_body_t *body = defines.find(tok.substr(1)); + + if (! body) { + // Apparently not a name we know. + return false; + } + + std::string name = tok.substr(1); + std::string skipped_spaces = skip_spaces(); + tok = next_token(false); + if (body->has_args) { + if (tok != "(") { + if (tok.size() == 1 && iscntrl(tok[0])) { + char buf[5]; + snprintf(buf, sizeof(buf), "\\x%02x", tok[0]); + tok = buf; + } + log_error("Expected to find '(' to begin macro arguments for '%s', but instead found '%s'\n", + name, tok); + } + std::vector args; + bool done = false; + while (!done) { + std::string arg; + done = read_argument(arg); + args.push_back(arg); + } + for (const auto &pr : body->args.get_vals(name, args)) { + if (const define_body_t *existing = defines.find(pr.first)) { + macro_arg_stack.push({pr.first, *existing}); + insert_input("`__restore_macro_arg "); + } + defines.add(pr.first, pr.second); + } + } else { + insert_input(tok); + insert_input(skipped_spaces); + } + insert_input(body->body); + return true; +} + +// Read the arguments for a `define preprocessor directive with formal arguments. This is called +// just after reading the token containing "(". Returns the number of newlines to emit afterwards to +// keep line numbers in sync, together with the map from argument name to data (pos and default +// value). +static std::pair +read_define_args() +{ + // Each argument looks like one of the following: + // + // identifier + // identifier = default_text + // identifier = + // + // The first example is an argument with no default value. The second is an argument whose + // default value is default_text. The third is an argument with default value the empty + // string. + + int newline_count = 0; + arg_map_t args; + + // FSM state. + // + // 0: At start of identifier + // 1: After identifier (stored in arg_name) + // 2: After closing paren + int state = 0; + + std::string arg_name, default_val; + + skip_spaces(); + for (;;) { + if (state == 2) + // We've read the closing paren. + break; + + std::string tok = next_token(); + + // Cope with escaped EOLs + if (tok == "\\") { + char ch = next_char(); + if (ch == '\n') { + // Eat the \, the \n and any trailing space and keep going. + skip_spaces(); + continue; + } else { + // There aren't any other situations where a backslash makes sense. + log_error("Backslash in macro arguments (not at end of line).\n"); + } + } + + switch (state) { + case 0: + // At start of argument. If the token is ')', we've presumably just seen + // something like "`define foo() ...". Set state to 2 to finish. Otherwise, + // the token should be a valid simple identifier, but we'll allow anything + // here. + if (tok == ")") { + state = 2; + } else { + arg_name = tok; + state = 1; + } + skip_spaces(); + break; + + case 1: + // After argument. The token should either be an equals sign or a comma or + // closing paren. + if (tok == "=") { + std::string default_val; + //Read an argument into default_val and set state to 2 if we're at + // the end; 0 if we hit a comma. + state = read_argument(default_val) ? 2 : 0; + args.add_arg(arg_name, default_val.c_str()); + skip_spaces(); + break; + } + if (tok == ",") { + // Take the identifier as an argument with no default value. + args.add_arg(arg_name, nullptr); + state = 0; + skip_spaces(); + break; + } + if (tok == ")") { + // As with comma, but set state to 2 (end of args) + args.add_arg(arg_name, nullptr); + state = 2; + skip_spaces(); + break; + } + log_error("Trailing contents after identifier in macro argument `%s': " + "expected '=', ',' or ')'.\n", + arg_name); + + default: + // The only FSM states are 0-2 and we dealt with 2 at the start of the loop. + log_assert(false); + } + } + + return std::make_pair(newline_count, args); +} + +// Read a `define preprocessor directive. This is called just after reading the token containing +// "`define". +static void +read_define(const std::string &filename, + define_map_t &defines_map, + define_map_t &global_defines_cache) +{ + std::string name, value; + arg_map_t args; + + skip_spaces(); + name = next_token(true); + + bool here_doc_mode = false; + int newline_count = 0; + + // The FSM state starts at 0. If it sees space (or enters here_doc_mode), it assumes this is + // a macro without formal arguments and jumps to state 1. + // + // In state 0, if it sees an opening parenthesis, it assumes this is a macro with formal + // arguments. It reads the arguments with read_define_args() and then jumps to state 2. + // + // In states 1 or 2, the FSM reads tokens to the end of line (or end of here_doc): this is + // the body of the macro definition. + int state = 0; + + if (skip_spaces() != "") + state = 1; + + for (;;) { + std::string tok = next_token(); + if (tok.empty()) + break; + + // printf("define-tok: >>%s<<\n", tok != "\n" ? tok.c_str() : "NEWLINE"); + + if (tok == "\"\"\"") { + here_doc_mode = !here_doc_mode; + continue; + } + + if (state == 0 && tok == "(") { + auto pr = read_define_args(); + newline_count += pr.first; + args = pr.second; + + state = 2; + continue; + } + + // This token isn't an opening parenthesis immediately following the macro name, so + // it's presumably at or after the start of the macro body. If state isn't already 2 + // (which would mean we'd parsed an argument list), set it to 1. + if (state == 0) { + state = 1; + } + + if (tok == "\n") { + if (here_doc_mode) { + value += " "; + newline_count++; + } else { + return_char('\n'); + break; + } + continue; + } + + if (tok == "\\") { + char ch = next_char(); + if (ch == '\n') { + value += " "; + newline_count++; + } else { + value += std::string("\\"); + return_char(ch); + } + continue; + } + + // Is this token the name of a macro argument? If so, replace it with a magic symbol + // that we'll replace with the argument value. + int arg_pos; + if (args.find(tok, &arg_pos)) { + value += '`' + args.str_token(name, arg_pos); + continue; + } + + // This token is nothing special. Insert it verbatim into the macro body. + value += tok; + } + + // Append some newlines so that we don't mess up line counts in error messages. + while (newline_count-- > 0) + return_char('\n'); + + if (strchr("abcdefghijklmnopqrstuvwxyz_ABCDEFGHIJKLMNOPQRSTUVWXYZ$0123456789", name[0])) { + // printf("define: >>%s<< -> >>%s<<\n", name.c_str(), value.c_str()); + defines_map.add(name, value, (state == 2) ? &args : nullptr); + global_defines_cache.add(name, value, (state == 2) ? &args : nullptr); + } else { + log_file_error(LogSourceLocation(filename), "Invalid name for macro definition: >>%s<<.\n", name); + } +} + +std::string +frontend_verilog_preproc(std::istream &f, + std::string filename, + const define_map_t &pre_defines, + define_map_t &global_defines_cache, + const std::list &include_dirs, + ParseMode &parse_mode) +{ + define_map_t defines; + defines.merge(pre_defines); + defines.merge(global_defines_cache); + + macro_arg_stack_t macro_arg_stack; + std::vector filename_stack; + // We are inside pass_level levels of satisfied ifdefs, and then within + // fail_level levels of unsatisfied ifdefs. The unsatisfied ones are + // always within satisfied ones — even if some condition within is true, + // the parent condition failing renders it moot. + int ifdef_fail_level = 0; + int ifdef_pass_level = 0; + // For the outermost unsatisfied ifdef, true iff that ifdef already + // had a satisfied branch, and further elsif/else branches should be + // considered unsatisfied even if the condition is true. + // Meaningless if ifdef_fail_level == 0. + bool ifdef_already_satisfied = false; + + output_code.clear(); + input_buffer.clear(); + input_buffer_charp = 0; + + input_file(f, filename); + + while (!input_buffer.empty()) + { + std::string tok = next_token(); + // printf("token: >>%s<<\n", tok != "\n" ? tok.c_str() : "NEWLINE"); + + if (tok == "`endif") { + if (ifdef_fail_level > 0) + ifdef_fail_level--; + else if (ifdef_pass_level > 0) + ifdef_pass_level--; + else + log_error("Found %s outside of macro conditional branch!\n", tok); + continue; + } + + if (tok == "`else") { + if (ifdef_fail_level == 0) { + if (ifdef_pass_level == 0) + log_error("Found %s outside of macro conditional branch!\n", tok); + ifdef_pass_level--; + ifdef_fail_level = 1; + ifdef_already_satisfied = true; + } else if (ifdef_fail_level == 1 && !ifdef_already_satisfied) { + ifdef_fail_level = 0; + ifdef_pass_level++; + ifdef_already_satisfied = true; + } + continue; + } + + if (tok == "`elsif") { + skip_spaces(); + std::string name = next_token(true); + if (ifdef_fail_level == 0) { + if (ifdef_pass_level == 0) + log_error("Found %s outside of macro conditional branch!\n", tok); + ifdef_pass_level--; + ifdef_fail_level = 1; + ifdef_already_satisfied = true; + } else if (ifdef_fail_level == 1 && !ifdef_already_satisfied && defines.find(name)) { + ifdef_fail_level = 0; + ifdef_pass_level++; + ifdef_already_satisfied = true; + } + continue; + } + + if (tok == "`ifdef") { + skip_spaces(); + std::string name = next_token(true); + if (ifdef_fail_level > 0 || !defines.find(name)) { + ifdef_fail_level++; + } else { + ifdef_pass_level++; + ifdef_already_satisfied = true; + } + if (ifdef_fail_level == 1) + ifdef_already_satisfied = false; + continue; + } + + if (tok == "`ifndef") { + skip_spaces(); + std::string name = next_token(true); + if (ifdef_fail_level > 0 || defines.find(name)) { + ifdef_fail_level++; + } else { + ifdef_pass_level++; + ifdef_already_satisfied = true; + } + if (ifdef_fail_level == 1) + ifdef_already_satisfied = false; + continue; + } + + if (ifdef_fail_level > 0) { + if (tok == "\n") + output_code.push_back(tok); + continue; + } + + if (tok == "`include") { + skip_spaces(); + std::string fn = next_token(true); + while (try_expand_macro(defines, macro_arg_stack, fn)) { + fn = next_token(); + } + while (1) { + size_t pos = fn.find('"'); + if (pos == std::string::npos) + break; + if (pos == 0) + fn = fn.substr(1); + else + fn = fn.substr(0, pos) + fn.substr(pos+1); + } + std::ifstream ff; + ff.clear(); + std::string fixed_fn = fn; + ff.open(fixed_fn.c_str()); + + bool filename_path_sep_found; + bool fn_relative; +#ifdef _WIN32 + // Both forward and backslash are acceptable separators on Windows. + filename_path_sep_found = (filename.find_first_of("/\\") != std::string::npos); + // Easier just to invert the check for an absolute path (e.g. C:\ or C:/) + fn_relative = !(fn[1] == ':' && (fn[2] == '/' || fn[2] == '\\')); +#else + filename_path_sep_found = (filename.find('/') != std::string::npos); + fn_relative = (fn[0] != '/'); +#endif + + if (ff.fail() && fn.size() > 0 && fn_relative && filename_path_sep_found) { + // if the include file was not found, it is not given with an absolute path, and the + // currently read file is given with a path, then try again relative to its directory + ff.clear(); + fixed_fn = parent_from_file_path(filename) + fn; + ff.open(fixed_fn); + } + if (ff.fail() && fn.size() > 0 && fn_relative) { + // if the include file was not found and it is not given with an absolute path, then + // search it in the include path + for (auto incdir : include_dirs) { + ff.clear(); + fixed_fn = incdir + '/' + fn; + ff.open(fixed_fn); + if (!ff.fail()) break; + } + } + if (ff.fail()) { + output_code.push_back("`file_notfound " + fn); + } else { + input_file(ff, fixed_fn); + yosys_input_files.insert(fixed_fn); + } + continue; + } + + if (tok == "`file_push") { + skip_spaces(); + std::string fn = next_token(true); + if (!fn.empty() && fn.front() == '"' && fn.back() == '"') + fn = fn.substr(1, fn.size()-2); + output_code.push_back(tok + " \"" + fn + "\""); + filename_stack.push_back(filename); + filename = fn; + continue; + } + + if (tok == "`file_pop") { + output_code.push_back(tok); + filename = filename_stack.back(); + filename_stack.pop_back(); + continue; + } + + if (tok == "`define") { + read_define(filename, defines, global_defines_cache); + continue; + } + + if (tok == "`undef") { + std::string name; + skip_spaces(); + name = next_token(true); + // printf("undef: >>%s<<\n", name.c_str()); + defines.erase(name); + global_defines_cache.erase(name); + continue; + } + + if (tok == "`timescale") { + skip_spaces(); + while (!tok.empty() && tok != "\n") + tok = next_token(true); + if (tok == "\n") + return_char('\n'); + continue; + } + + if (tok == "`resetall") { + // `resetall is consumed here and never reaches the lexer, which owns + // `default_nettype during parsing. + output_code.push_back("\n`default_nettype wire\n"); + continue; + } + + if (tok == "`undefineall" && parse_mode.sv) { + defines.clear(); + global_defines_cache.clear(); + continue; + } + + if (tok == "`__restore_macro_arg") { + restore_macro_arg(defines, macro_arg_stack); + continue; + } + + if (try_expand_macro(defines, macro_arg_stack, tok)) + continue; + + output_code.push_back(tok); + } + + if (ifdef_fail_level > 0 || ifdef_pass_level > 0) { + log_error("Unterminated preprocessor conditional!\n"); + } + + std::string output; + for (auto &str : output_code) + output += str; + + output_code.clear(); + input_buffer.clear(); + input_buffer_charp = 0; + + return output; +} + +YOSYS_NAMESPACE_END diff --git a/chips/yosys/frontends/verilog/preproc.h b/chips/yosys/frontends/verilog/preproc.h new file mode 100644 index 0000000000000000000000000000000000000000..1efe1cad3207009f8d8d359dfc706fe83ecc1e6a --- /dev/null +++ b/chips/yosys/frontends/verilog/preproc.h @@ -0,0 +1,84 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * --- + * + * The Verilog preprocessor. + * + */ +#ifndef VERILOG_PREPROC_H +#define VERILOG_PREPROC_H + +#include "kernel/yosys.h" + +#include +#include +#include +#include + +YOSYS_NAMESPACE_BEGIN + +struct define_body_t; +struct arg_map_t; + +namespace VERILOG_FRONTEND { + struct ParseState; + struct ParseMode; +}; + +struct define_map_t +{ + define_map_t(); + ~ define_map_t(); + + // Add a definition, overwriting any existing definition for name. + void add(const std::string &name, const std::string &txt, const arg_map_t *args = nullptr); + void add(const std::string &name, const define_body_t &body); + + // Merge in another map of definitions (which take precedence + // over anything currently defined). + void merge(const define_map_t &map); + + // Find a definition by name. If no match, returns null. + const define_body_t *find(const std::string &name) const; + + // Erase a definition by name (no effect if not defined). + void erase(const std::string &name); + + // Clear any existing definitions + void clear(); + + // Print a list of definitions, using the log function + void log() const; + + std::map> defines; +}; + + +struct define_map_t; + +std::string +frontend_verilog_preproc(std::istream &f, + std::string filename, + const define_map_t &pre_defines, + define_map_t &global_defines_cache, + const std::list &include_dirs, + VERILOG_FRONTEND::ParseMode &parse_mode); + +YOSYS_NAMESPACE_END + +#endif diff --git a/chips/yosys/frontends/verilog/verilog_error.cc b/chips/yosys/frontends/verilog/verilog_error.cc new file mode 100644 index 0000000000000000000000000000000000000000..5c9b5fb50ade3804afd3fe0f89859fe796bb498f --- /dev/null +++ b/chips/yosys/frontends/verilog/verilog_error.cc @@ -0,0 +1,43 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * --- + * + */ + +#include "kernel/yosys_common.h" +#include "frontends/verilog/verilog_error.h" +#include "frontends/verilog/verilog_location.h" + +USING_YOSYS_NAMESPACE + +/** + * Legacy behavior is to only track lines. Now we have columns too, but we don't + * report them in errors. + * TODO: report columns, too + */ + +[[noreturn]] +void VERILOG_FRONTEND::formatted_err_at_loc(Location loc, std::string str) +{ + YOSYS_NAMESPACE_PREFIX log_file_error(loc.to_loc(), "%s\n", std::move(str)); +} + +void VERILOG_FRONTEND::formatted_warn_at_loc(Location loc, std::string str) +{ + YOSYS_NAMESPACE_PREFIX log_file_warning(loc.to_loc(), "%s\n", std::move(str)); +} diff --git a/chips/yosys/frontends/verilog/verilog_error.h b/chips/yosys/frontends/verilog/verilog_error.h new file mode 100644 index 0000000000000000000000000000000000000000..ede489b26c98d7097fc739fb76a4b9790c9a6450 --- /dev/null +++ b/chips/yosys/frontends/verilog/verilog_error.h @@ -0,0 +1,31 @@ +#ifndef VERILOG_ERROR_H +#define VERILOG_ERROR_H + +#include "kernel/yosys_common.h" +#include "frontends/ast/ast.h" +#include "frontends/verilog/verilog_location.h" + +YOSYS_NAMESPACE_BEGIN + +namespace VERILOG_FRONTEND +{ + [[noreturn]] + void formatted_err_at_loc(Location loc, std::string str); + template + [[noreturn]] + void err_at_loc(Location loc, FmtString...> fmt, const Args &... args) + { + formatted_err_at_loc(std::move(loc), fmt.format(args...)); + } + + void formatted_warn_at_loc(Location loc, std::string str); + template + void warn_at_loc(Location loc, FmtString...> fmt, const Args &... args) + { + formatted_warn_at_loc(std::move(loc), fmt.format(args...)); + } +}; + +YOSYS_NAMESPACE_END + +#endif diff --git a/chips/yosys/frontends/verilog/verilog_frontend.cc b/chips/yosys/frontends/verilog/verilog_frontend.cc new file mode 100644 index 0000000000000000000000000000000000000000..4801291ab60327ac162126d41736141cfe3c9b46 --- /dev/null +++ b/chips/yosys/frontends/verilog/verilog_frontend.cc @@ -0,0 +1,805 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * --- + * + * The Verilog frontend. + * + * This frontend is using the AST frontend library (see frontends/ast/). + * Thus this frontend does not generate RTLIL code directly but creates an + * AST directly from the Verilog parse tree and then passes this AST to + * the AST frontend library. + * + */ + +#include + +#include "verilog_frontend.h" +#include "verilog_lexer.h" +#include "verilog_error.h" +#include "verilog_location.h" +#include "preproc.h" +#include "kernel/yosys.h" +#include "libs/sha1/sha1.h" +#include +#include + +YOSYS_NAMESPACE_BEGIN +using namespace VERILOG_FRONTEND; + +// use the Verilog bison/flex parser to generate an AST and use AST::process() to convert it to RTLIL + +static std::vector verilog_defaults; +static std::list> verilog_defaults_stack; + +static void error_on_dpi_function(AST::AstNode *node) +{ + if (node->type == AST::AST_DPI_FUNCTION) + err_at_loc(node->location, "Found DPI function %s.\n", node->str); + for (auto& child : node->children) + error_on_dpi_function(child.get()); +} + +static void add_package_types(dict &user_types, std::vector> &package_list) +{ + // prime the parser's user type lookup table with the package qualified names + // of typedefed names in the packages seen so far. + for (const auto &pkg : package_list) { + log_assert(pkg->type==AST::AST_PACKAGE); + for (const auto &node: pkg->children) { + if (node->type == AST::AST_TYPEDEF) { + std::string s = pkg->str + "::" + node->str.substr(1); + user_types[s] = node.get(); + } + } + } +} + +struct VerilogFrontend : public Frontend { + VerilogFrontend() : Frontend("verilog", "read modules from Verilog file") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" read_verilog [options] [filename]\n"); + log("\n"); + log("Load modules from a Verilog file to the current design. A large subset of\n"); + log("Verilog-2005 is supported.\n"); + log("\n"); + log(" -sv\n"); + log(" enable support for SystemVerilog features. (only a small subset\n"); + log(" of SystemVerilog is supported)\n"); + log("\n"); + log(" -formal\n"); + log(" enable support for SystemVerilog assertions and some Yosys extensions\n"); + log(" replace the implicit -D SYNTHESIS with -D FORMAL\n"); + log("\n"); + log(" -nosynthesis\n"); + log(" don't add implicit -D SYNTHESIS\n"); + log("\n"); + log(" -noassert\n"); + log(" ignore assert() statements\n"); + log("\n"); + log(" -noassume\n"); + log(" ignore assume() statements\n"); + log("\n"); + log(" -norestrict\n"); + log(" ignore restrict() statements\n"); + log("\n"); + log(" -assume-asserts\n"); + log(" treat all assert() statements like assume() statements\n"); + log("\n"); + log(" -assert-assumes\n"); + log(" treat all assume() statements like assert() statements\n"); + log("\n"); + log(" -nodisplay\n"); + log(" suppress output from display system tasks ($display et. al).\n"); + log(" This does not affect the output from a later 'sim' command.\n"); + log("\n"); + log(" -debug\n"); + log(" alias for -dump_ast1 -dump_ast2 -dump_vlog1 -dump_vlog2 -yydebug\n"); + log("\n"); + log(" -dump_ast1\n"); + log(" dump abstract syntax tree (before simplification)\n"); + log("\n"); + log(" -dump_ast2\n"); + log(" dump abstract syntax tree (after simplification)\n"); + log("\n"); + log(" -no_dump_ptr\n"); + log(" do not include hex memory addresses in dump (easier to diff dumps)\n"); + log("\n"); + log(" -dump_vlog1\n"); + log(" dump ast as Verilog code (before simplification)\n"); + log("\n"); + log(" -dump_vlog2\n"); + log(" dump ast as Verilog code (after simplification)\n"); + log("\n"); + log(" -dump_rtlil\n"); + log(" dump generated RTLIL netlist\n"); + log("\n"); + log(" -yydebug\n"); + log(" enable parser debug output\n"); + log("\n"); + log(" -nolatches\n"); + log(" usually latches are synthesized into logic loops\n"); + log(" this option prohibits this and sets the output to 'x'\n"); + log(" in what would be the latches hold condition\n"); + log("\n"); + log(" this behavior can also be achieved by setting the\n"); + log(" 'nolatches' attribute on the respective module or\n"); + log(" always block.\n"); + log("\n"); + log(" -nomem2reg\n"); + log(" under certain conditions memories are converted to registers\n"); + log(" early during simplification to ensure correct handling of\n"); + log(" complex corner cases. this option disables this behavior.\n"); + log("\n"); + log(" this can also be achieved by setting the 'nomem2reg'\n"); + log(" attribute on the respective module or register.\n"); + log("\n"); + log(" This is potentially dangerous. Usually the front-end has good\n"); + log(" reasons for converting an array to a list of registers.\n"); + log(" Prohibiting this step will likely result in incorrect synthesis\n"); + log(" results.\n"); + log("\n"); + log(" -mem2reg\n"); + log(" always convert memories to registers. this can also be\n"); + log(" achieved by setting the 'mem2reg' attribute on the respective\n"); + log(" module or register.\n"); + log("\n"); + log(" -nomeminit\n"); + log(" do not infer $meminit cells and instead convert initialized\n"); + log(" memories to registers directly in the front-end.\n"); + log("\n"); + log(" -ppdump\n"); + log(" dump Verilog code after pre-processor\n"); + log("\n"); + log(" -nopp\n"); + log(" do not run the pre-processor\n"); + log("\n"); + log(" -nodpi\n"); + log(" disable DPI-C support\n"); + log("\n"); + log(" -noblackbox\n"); + log(" do not automatically add a (* blackbox *) attribute to an\n"); + log(" empty module.\n"); + log("\n"); + log(" -lib\n"); + log(" only create empty blackbox modules. This implies -DBLACKBOX.\n"); + log(" modules with the (* whitebox *) attribute will be preserved.\n"); + log(" (* lib_whitebox *) will be treated like (* whitebox *).\n"); + log("\n"); + log(" -nowb\n"); + log(" delete (* whitebox *) and (* lib_whitebox *) attributes from\n"); + log(" all modules.\n"); + log("\n"); + log(" -specify\n"); + log(" parse and import specify blocks\n"); + log("\n"); + log(" -noopt\n"); + log(" don't perform basic optimizations (such as const folding) in the\n"); + log(" high-level front-end.\n"); + log("\n"); + log(" -icells\n"); + log(" interpret cell types starting with '$' as internal cell types\n"); + log("\n"); + log(" -pwires\n"); + log(" add a wire for each module parameter\n"); + log("\n"); + log(" -nooverwrite\n"); + log(" ignore re-definitions of modules. (the default behavior is to\n"); + log(" create an error message if the existing module is not a black box\n"); + log(" module, and overwrite the existing module otherwise.)\n"); + log("\n"); + log(" -overwrite\n"); + log(" overwrite existing modules with the same name\n"); + log("\n"); + log(" -defer\n"); + log(" only read the abstract syntax tree and defer actual compilation\n"); + log(" to a later 'hierarchy' command. Useful in cases where the default\n"); + log(" parameters of modules yield invalid or not synthesizable code.\n"); + log("\n"); + log(" -noautowire\n"); + log(" make the default of `default_nettype be \"none\" instead of \"wire\".\n"); + log("\n"); + log(" -unroll-limit \n"); + log(" set the limit for how many loop unrolls occur by default\n"); + log("\n"); + log(" -setattr \n"); + log(" set the specified attribute (to the value 1) on all loaded modules\n"); + log("\n"); + log(" -Dname[=definition]\n"); + log(" define the preprocessor symbol 'name' and set its optional value\n"); + log(" 'definition'\n"); + log("\n"); + log(" -Idir\n"); + log(" add 'dir' to the directories which are used when searching include\n"); + log(" files\n"); + log("\n"); + log(" -relativeshare\n"); + log(" use paths relative to share directory for source locations\n"); + log(" where possible (experimental).\n"); + log("\n"); + log("The command 'verilog_defaults' can be used to register default options for\n"); + log("subsequent calls to 'read_verilog'.\n"); + log("\n"); + log("Note that the Verilog frontend does a pretty good job of processing valid\n"); + log("verilog input, but has not very good error reporting. It generally is\n"); + log("recommended to use a simulator (for example Icarus Verilog) for checking\n"); + log("the syntax of the code, rather than to rely on read_verilog for that.\n"); + log("\n"); + log("Depending on if read_verilog is run in -formal mode, either the macro\n"); + log("SYNTHESIS or FORMAL is defined automatically, unless -nosynthesis is used.\n"); + log("In addition, read_verilog always defines the macro YOSYS.\n"); + log("\n"); + log("See the Yosys README file for a list of non-standard Verilog features\n"); + log("supported by the Yosys Verilog front-end.\n"); + log("\n"); + } + void execute(std::istream *&f, std::string filename, std::vector args, RTLIL::Design *design) override + { + bool flag_nodisplay = false; + bool flag_dump_ast1 = false; + bool flag_dump_ast2 = false; + bool flag_no_dump_ptr = false; + bool flag_dump_vlog1 = false; + bool flag_dump_vlog2 = false; + bool flag_dump_rtlil = false; + bool flag_debug_lexer = false; + bool flag_debug_parser = false; + bool flag_nolatches = false; + bool flag_nomeminit = false; + bool flag_nomem2reg = false; + bool flag_mem2reg = false; + bool flag_ppdump = false; + bool flag_nopp = false; + bool flag_nodpi = false; + bool flag_noopt = false; + bool flag_icells = false; + bool flag_pwires = false; + bool flag_nooverwrite = false; + bool flag_overwrite = false; + bool flag_defer = false; + bool flag_noblackbox = false; + bool flag_nowb = false; + bool flag_nosynthesis = false; + bool flag_yydebug = false; + bool flag_relative_share = false; + int flag_unroll_limit = 4000; + define_map_t defines_map; + + std::list include_dirs; + std::list attributes; + + ParseMode parse_mode = {}; + ParseState parse_state = {}; + parse_mode.sv = false; + parse_mode.formal = false; + parse_mode.noassert = false; + parse_mode.noassume = false; + parse_mode.norestrict = false; + parse_mode.assume_asserts = false; + parse_mode.assert_assumes = false; + parse_mode.lib = false; + parse_mode.specify = false; + parse_state.default_nettype_wire = true; + + args.insert(args.begin()+1, verilog_defaults.begin(), verilog_defaults.end()); + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) { + std::string arg = args[argidx]; + if (arg == "-sv") { + parse_mode.sv = true; + continue; + } + if (arg == "-formal") { + parse_mode.formal = true; + continue; + } + if (arg == "-nosynthesis") { + flag_nosynthesis = true; + continue; + } + if (arg == "-noassert") { + parse_mode.noassert = true; + continue; + } + if (arg == "-noassume") { + parse_mode.noassume = true; + continue; + } + if (arg == "-norestrict") { + parse_mode.norestrict = true; + continue; + } + if (arg == "-assume-asserts") { + parse_mode.assume_asserts = true; + continue; + } + if (arg == "-assert-assumes") { + parse_mode.assert_assumes = true; + continue; + } + if (arg == "-nodisplay") { + flag_nodisplay = true; + continue; + } + if (arg == "-debug") { + flag_dump_ast1 = true; + flag_dump_ast2 = true; + flag_dump_vlog1 = true; + flag_dump_vlog2 = true; + flag_debug_lexer = true; + flag_debug_parser = true; + continue; + } + if (arg == "-dump_ast1") { + flag_dump_ast1 = true; + continue; + } + if (arg == "-dump_ast2") { + flag_dump_ast2 = true; + continue; + } + if (arg == "-no_dump_ptr") { + flag_no_dump_ptr = true; + continue; + } + if (arg == "-dump_vlog1") { + flag_dump_vlog1 = true; + continue; + } + if (arg == "-dump_vlog2") { + flag_dump_vlog2 = true; + continue; + } + if (arg == "-dump_rtlil") { + flag_dump_rtlil = true; + continue; + } + if (arg == "-yydebug") { + flag_yydebug = true; + flag_debug_lexer = true; + flag_debug_parser = true; + continue; + } + if (arg == "-nolatches") { + flag_nolatches = true; + continue; + } + if (arg == "-nomeminit") { + flag_nomeminit = true; + continue; + } + if (arg == "-nomem2reg") { + flag_nomem2reg = true; + continue; + } + if (arg == "-mem2reg") { + flag_mem2reg = true; + continue; + } + if (arg == "-ppdump") { + flag_ppdump = true; + continue; + } + if (arg == "-nopp") { + flag_nopp = true; + continue; + } + if (arg == "-nodpi") { + flag_nodpi = true; + continue; + } + if (arg == "-noblackbox") { + flag_noblackbox = true; + continue; + } + if (arg == "-lib") { + parse_mode.lib = true; + defines_map.add("BLACKBOX", ""); + continue; + } + if (arg == "-nowb") { + flag_nowb = true; + continue; + } + if (arg == "-specify") { + parse_mode.specify = true; + continue; + } + if (arg == "-noopt") { + flag_noopt = true; + continue; + } + if (arg == "-icells") { + flag_icells = true; + continue; + } + if (arg == "-pwires") { + flag_pwires = true; + continue; + } + if (arg == "-ignore_redef" || arg == "-nooverwrite") { + flag_nooverwrite = true; + flag_overwrite = false; + continue; + } + if (arg == "-overwrite") { + flag_nooverwrite = false; + flag_overwrite = true; + continue; + } + if (arg == "-defer") { + flag_defer = true; + continue; + } + if (arg == "-noautowire") { + parse_state.default_nettype_wire = false; + continue; + } + if (arg == "-unroll-limit" && argidx+1 < args.size()) { + flag_unroll_limit = stoi(args[++argidx]); + if (flag_unroll_limit < 0) log_error("Cannot choose negative value for -unroll-limit"); + continue; + } + if (arg == "-setattr" && argidx+1 < args.size()) { + attributes.push_back(RTLIL::escape_id(args[++argidx])); + continue; + } + if (arg == "-relativeshare") { + flag_relative_share = true; + log_experimental("read_verilog -relativeshare"); + continue; + } + if (arg == "-D" && argidx+1 < args.size()) { + std::string name = args[++argidx], value; + size_t equal = name.find('='); + if (equal != std::string::npos) { + value = name.substr(equal+1); + name = name.substr(0, equal); + } + defines_map.add(name, value); + continue; + } + if (arg.compare(0, 2, "-D") == 0) { + size_t equal = arg.find('=', 2); + std::string name = arg.substr(2, equal-2); + std::string value; + if (equal != std::string::npos) + value = arg.substr(equal+1); + defines_map.add(name, value); + continue; + } + if (arg == "-I" && argidx+1 < args.size()) { + include_dirs.push_back(args[++argidx]); + continue; + } + if (arg.compare(0, 2, "-I") == 0) { + include_dirs.push_back(arg.substr(2)); + continue; + } + break; + } + + if (parse_mode.formal || !flag_nosynthesis) + defines_map.add(parse_mode.formal ? "FORMAL" : "SYNTHESIS", "1"); + + extra_args(f, filename, args, argidx); + + log_header(design, "Executing Verilog-2005 frontend: %s\n", filename); + + AST::DesignScope design_scope(design); + + log("Parsing %s%s input from `%s' to AST representation.\n", + parse_mode.formal ? "formal " : "", parse_mode.sv ? "SystemVerilog" : "Verilog", filename); + + if (flag_relative_share) { + auto share_path = proc_share_dirname(); + if (filename.substr(0, share_path.length()) == share_path) + filename = std::string("+/") + filename.substr(share_path.length()); + log("new filename %s\n", filename); + } + AST::sv_mode_but_global_and_used_for_literally_one_condition = parse_mode.sv; + std::string code_after_preproc; + + parse_state.lexin = f; + if (!flag_nopp) { + code_after_preproc = frontend_verilog_preproc(*f, filename, defines_map, *design->verilog_defines, include_dirs, parse_mode); + if (flag_ppdump) { + log("-- Verilog code after preprocessor --\n"); + log_lines(code_after_preproc); + log("-- END OF DUMP --\n"); + } + parse_state.lexin = new std::istringstream(code_after_preproc); + } + + auto filename_shared = std::make_shared(filename); + auto top_loc = Location(); + top_loc.begin.filename = filename_shared; + parse_state.current_ast = new AST::AstNode(top_loc, AST::AST_DESIGN); + VerilogLexer lexer(&parse_state, &parse_mode, filename_shared); + frontend_verilog_yy::parser parser(&lexer, &parse_state, &parse_mode); + lexer.set_debug(flag_debug_lexer); + parser.set_debug_level(flag_debug_parser ? 1 : 0); + + // make package typedefs available to parser + add_package_types(parse_state.pkg_user_types, design->verilog_packages); + + UserTypeMap global_types_map; + for (auto& def : design->verilog_globals) { + if (def->type == AST::AST_TYPEDEF) { + global_types_map[def->str] = def.get(); + } + } + + log_assert(parse_state.user_type_stack.empty()); + // use previous global typedefs as bottom level of user type stack + parse_state.user_type_stack.push_back(std::move(global_types_map)); + // add a new empty type map to allow overriding existing global definitions + parse_state.user_type_stack.push_back(UserTypeMap()); + + if (flag_yydebug) { + lexer.set_debug(true); + parser.set_debug_level(1); + } + parser.parse(); + // frontend_verilog_yyset_lineno(1); + + for (auto &child : parse_state.current_ast->children) { + if (child->type == AST::AST_MODULE) + for (auto &attr : attributes) { + IdString attr_id = AST::intern_attr_name(attr); + if (child->attributes.count(attr_id) == 0) + child->attributes[attr_id] = AST::AstNode::mkconst_int(top_loc, 1, false); + } + } + + if (flag_nodpi) + error_on_dpi_function(parse_state.current_ast); + + AST::process(design, parse_state.current_ast, flag_nodisplay, flag_dump_ast1, flag_dump_ast2, flag_no_dump_ptr, flag_dump_vlog1, flag_dump_vlog2, flag_dump_rtlil, flag_nolatches, + flag_nomeminit, flag_nomem2reg, flag_mem2reg, flag_noblackbox, parse_mode.lib, flag_nowb, flag_noopt, flag_icells, flag_pwires, flag_nooverwrite, flag_overwrite, flag_defer, parse_state.default_nettype_wire, flag_unroll_limit); + + + if (!flag_nopp) + delete parse_state.lexin; + + // only the previous and new global type maps remain + log_assert(parse_state.user_type_stack.size() == 2); + parse_state.user_type_stack.clear(); + + delete parse_state.current_ast; + parse_state.current_ast = NULL; + + log("Successfully finished Verilog frontend.\n"); + } +} VerilogFrontend; + +struct VerilogDefaults : public Pass { + VerilogDefaults() : Pass("verilog_defaults", "set default options for read_verilog") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" verilog_defaults -add [options]\n"); + log("\n"); + log("Add the specified options to the list of default options to read_verilog.\n"); + log("\n"); + log("\n"); + log(" verilog_defaults -clear\n"); + log("\n"); + log("Clear the list of Verilog default options.\n"); + log("\n"); + log("\n"); + log(" verilog_defaults -push\n"); + log(" verilog_defaults -pop\n"); + log("\n"); + log("Push or pop the list of default options to a stack. Note that -push does\n"); + log("not imply -clear.\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design*) override + { + if (args.size() < 2) + cmd_error(args, 1, "Missing argument."); + + if (args[1] == "-add") { + verilog_defaults.insert(verilog_defaults.end(), args.begin()+2, args.end()); + return; + } + + if (args.size() != 2) + cmd_error(args, 2, "Extra argument."); + + if (args[1] == "-clear") { + verilog_defaults.clear(); + return; + } + + if (args[1] == "-push") { + verilog_defaults_stack.push_back(verilog_defaults); + return; + } + + if (args[1] == "-pop") { + if (verilog_defaults_stack.empty()) { + verilog_defaults.clear(); + } else { + verilog_defaults.swap(verilog_defaults_stack.back()); + verilog_defaults_stack.pop_back(); + } + return; + } + } +} VerilogDefaults; + +struct VerilogDefines : public Pass { + VerilogDefines() : Pass("verilog_defines", "define and undefine verilog defines") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" verilog_defines [options]\n"); + log("\n"); + log("Define and undefine verilog preprocessor macros.\n"); + log("\n"); + log(" -Dname[=definition]\n"); + log(" define the preprocessor symbol 'name' and set its optional value\n"); + log(" 'definition'\n"); + log("\n"); + log(" -Uname[=definition]\n"); + log(" undefine the preprocessor symbol 'name'\n"); + log("\n"); + log(" -reset\n"); + log(" clear list of defined preprocessor symbols\n"); + log("\n"); + log(" -list\n"); + log(" list currently defined preprocessor symbols\n"); + log("\n"); + } + void execute(std::vector args, RTLIL::Design *design) override + { + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) { + std::string arg = args[argidx]; + if (arg == "-D" && argidx+1 < args.size()) { + std::string name = args[++argidx], value; + size_t equal = name.find('='); + if (equal != std::string::npos) { + value = name.substr(equal+1); + name = name.substr(0, equal); + } + design->verilog_defines->add(name, value); + continue; + } + if (arg.compare(0, 2, "-D") == 0) { + size_t equal = arg.find('=', 2); + std::string name = arg.substr(2, equal-2); + std::string value; + if (equal != std::string::npos) + value = arg.substr(equal+1); + design->verilog_defines->add(name, value); + continue; + } + if (arg == "-U" && argidx+1 < args.size()) { + std::string name = args[++argidx]; + design->verilog_defines->erase(name); + continue; + } + if (arg.compare(0, 2, "-U") == 0) { + std::string name = arg.substr(2); + design->verilog_defines->erase(name); + continue; + } + if (arg == "-reset") { + design->verilog_defines->clear(); + continue; + } + if (arg == "-list") { + design->verilog_defines->log(); + continue; + } + break; + } + + if (args.size() != argidx) + cmd_error(args, argidx, "Extra argument."); + } +} VerilogDefines; + +static void parse_file_list(const std::string &file_list_path, RTLIL::Design *design, bool relative_to_file_list_path) +{ + std::ifstream flist(file_list_path); + if (!flist.is_open()) { + log_error("Verilog file list file does not exist\n"); + exit(1); + } + + std::filesystem::path file_list_parent_dir = std::filesystem::path(file_list_path).parent_path(); + + std::string v_file_name; + while (std::getline(flist, v_file_name)) { + if (v_file_name.empty()) { + continue; + } + + std::filesystem::path verilog_file_path; + if (relative_to_file_list_path) { + verilog_file_path = file_list_parent_dir / v_file_name; + } else { + verilog_file_path = std::filesystem::current_path() / v_file_name; + } + + bool is_sv = (verilog_file_path.extension() == ".sv"); + + std::vector read_verilog_cmd = {"read_verilog", "-defer"}; + if (is_sv) { + read_verilog_cmd.push_back("-sv"); + } + read_verilog_cmd.push_back(verilog_file_path.string()); + Pass::call(design, read_verilog_cmd); + } + + flist.close(); +} + +struct VerilogFileList : public Pass { + VerilogFileList() : Pass("read_verilog_file_list", "parse a Verilog file list") {} + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" read_verilog_file_list [options]\n"); + log("\n"); + log("Parse a Verilog file list, and pass the list of Verilog files to read_verilog\n"); + log("command\n"); + log("\n"); + log(" -F file_list_path\n"); + log(" File list file contains list of Verilog files to be parsed, any path is\n"); + log(" treated relative to the file list file\n"); + log("\n"); + log(" -f file_list_path\n"); + log(" File list file contains list of Verilog files to be parsed, any path is\n"); + log(" treated relative to current working directroy\n"); + log("\n"); + } + + void execute(std::vector args, RTLIL::Design *design) override + { + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) { + std::string arg = args[argidx]; + if (arg == "-F" && argidx + 1 < args.size()) { + std::string file_list_path = args[++argidx]; + parse_file_list(file_list_path, design, true); + continue; + } + if (arg == "-f" && argidx + 1 < args.size()) { + std::string file_list_path = args[++argidx]; + parse_file_list(file_list_path, design, false); + continue; + } + break; + } + + extra_args(args, argidx, design, false); + } +} VerilogFilelist; + +YOSYS_NAMESPACE_END diff --git a/chips/yosys/frontends/verilog/verilog_frontend.h b/chips/yosys/frontends/verilog/verilog_frontend.h new file mode 100644 index 0000000000000000000000000000000000000000..112f0977a0d3c32d9834b2aec1ab8dbb5f2493c9 --- /dev/null +++ b/chips/yosys/frontends/verilog/verilog_frontend.h @@ -0,0 +1,65 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * --- + * + * The Verilog frontend. + * + * This frontend is using the AST frontend library (see frontends/ast/). + * Thus this frontend does not generate RTLIL code directly but creates an + * AST directly from the Verilog parse tree and then passes this AST to + * the AST frontend library. + * + */ + +#ifndef VERILOG_FRONTEND_H +#define VERILOG_FRONTEND_H + +#include "kernel/yosys.h" +#include "frontends/ast/ast.h" + +#include +#include + +YOSYS_NAMESPACE_BEGIN + +namespace VERILOG_FRONTEND +{ + /* Ephemeral context class */ + struct ConstParser { + AST::AstSrcLocType loc; + // original constant text, used in diagnostics when loc has no source file + std::string code_str = {}; + private: + void log_maybe_loc_error(std::string msg); + void log_maybe_loc_warn(std::string msg); + // divide an arbitrary length decimal number by two and return the rest + int my_decimal_div_by_two(std::vector &digits); + // find the number of significant bits in a binary number (not including the sign bit) + int my_ilog2(int x); + // parse a binary, decimal, hexadecimal or octal number with support for special bits ('x', 'z' and '?') + void my_strtobin(std::vector &data, const char *str, int len_in_bits, int base, char case_type, bool is_unsized); + public: + // convert the Verilog code for a constant to an AST node + std::unique_ptr const2ast(std::string code, char case_type = 0, bool warn_z = false); + + }; +}; + +YOSYS_NAMESPACE_END + +#endif diff --git a/chips/yosys/frontends/verilog/verilog_lexer.h b/chips/yosys/frontends/verilog/verilog_lexer.h new file mode 100644 index 0000000000000000000000000000000000000000..363c17b76caea3783e2e010a23d5edacf8991c7a --- /dev/null +++ b/chips/yosys/frontends/verilog/verilog_lexer.h @@ -0,0 +1,48 @@ +#ifndef VERILOG_LEXER_H +#define VERILOG_LEXER_H + +#include "kernel/yosys.h" +#include "frontends/ast/ast.h" +#include "frontends/verilog/verilog_parser.tab.hh" +#include +#include + +#if ! defined(yyFlexLexerOnce) +#define yyFlexLexer frontend_verilog_yyFlexLexer +#include +#endif + +YOSYS_NAMESPACE_BEGIN + +namespace VERILOG_FRONTEND { + using parser = frontend_verilog_yy::parser; + class VerilogLexer : public frontend_verilog_yyFlexLexer { + ParseState* extra; + ParseMode* mode; + parser::location_type out_loc; + public: + VerilogLexer(ParseState* e, ParseMode* m, std::shared_ptr filename) : frontend_verilog_yyFlexLexer(e->lexin), extra(e), mode(m) { + out_loc.begin.filename = filename; + } + ~VerilogLexer() override {} + // autogenerated body due to YY_DECL + parser::symbol_type nextToken(); + // get rid of override virtual function warning + using FlexLexer::yylex; + parser::symbol_type terminate() { + return parser::make_FRONTEND_VERILOG_YYEOF(out_loc); + } + private: + std::shared_ptr current_filename; + std::vector> fn_stack; + std::vector ln_stack; + int LexerInput(char* buf, int max_size) override { + return readsome(*extra->lexin, buf, max_size); + } + }; + +}; + +YOSYS_NAMESPACE_END + +#endif diff --git a/chips/yosys/frontends/verilog/verilog_lexer.l b/chips/yosys/frontends/verilog/verilog_lexer.l new file mode 100644 index 0000000000000000000000000000000000000000..d15937cc70b0a74c15b429a08163f8bd091179f0 --- /dev/null +++ b/chips/yosys/frontends/verilog/verilog_lexer.l @@ -0,0 +1,714 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * --- + * + * The Verilog frontend. + * + * This frontend is using the AST frontend library (see frontends/ast/). + * Thus this frontend does not generate RTLIL code directly but creates an + * AST directly from the Verilog parse tree and then passes this AST to + * the AST frontend library. + * + * --- + * + * A simple lexer for Verilog code. Non-preprocessor compiler directives are + * handled here. The preprocessor stuff is handled in preproc.cc. Everything + * else is left to the bison parser (see verilog_parser.y). + * + */ + +%option c++ +%option yyclass="VerilogLexer" +%option noyywrap +%option nounput +%option yylineno +%option prefix="frontend_verilog_yy" + +%{ + +#ifdef __clang__ +// bison generates code using the 'register' storage class specifier +#pragma clang diagnostic ignored "-Wdeprecated-register" +// flex generates weirdly-indented code +#pragma clang diagnostic ignored "-Wmisleading-indentation" +#endif + +#include "frontends/verilog/verilog_lexer.h" +#include "frontends/ast/ast.h" +#include "frontends/verilog/verilog_location.h" +#include "kernel/log.h" +#include +#include + +USING_YOSYS_NAMESPACE +using namespace AST; +using namespace VERILOG_FRONTEND; +using parser = frontend_verilog_yy::parser; + +YOSYS_NAMESPACE_BEGIN +#undef YY_DECL +#define YY_DECL parser::symbol_type VerilogLexer::nextToken() + +#undef yyterminate +#define yyterminate() return terminate() + +YOSYS_NAMESPACE_END + +#define SV_KEYWORD(_tok) \ + if (mode->sv) return _tok; \ + log("Lexer warning: The SystemVerilog keyword `%s' (at %s:%d) is not "\ + "recognized unless read_verilog is called with -sv!\n", YYText(), \ + current_filename->c_str(), yylineno); \ + string_t val = std::make_unique(std::string("\\") + YYText()); \ + return parser::make_TOK_ID(std::move(val), out_loc); + +#define NON_KEYWORD() \ + string_t val = std::make_unique(std::string("\\") + YYText()); \ + return parser::make_TOK_ID(std::move(val), out_loc); + + +#define YY_USER_ACTION \ + out_loc.step(); \ + for(int i = 0; YYText()[i] != '\0'; ++i){ \ + if(YYText()[i] == '\n') { \ + out_loc.lines(); \ + } \ + else { \ + out_loc.columns(); \ + } \ + } \ + out_loc.begin.filename = current_filename; \ + out_loc.end.filename = current_filename; + +#define YY_BREAK \ + break; + +#undef YY_BUF_SIZE +#define YY_BUF_SIZE 65536 + +static bool isUserType(ParseState* extra, std::string &s) +{ + // check current scope then outer scopes for a name + for (auto it = extra->user_type_stack.rbegin(); it != extra->user_type_stack.rend(); ++it) { + if (it->count(s) > 0) { + return true; + } + } + return false; +} + +parser::symbol_type char_tok(char c, parser::location_type loc) { + switch (c) { + case '!': return parser::make_TOK_EXCL(loc); + case '#': return parser::make_TOK_HASH(loc); + case '%': return parser::make_TOK_PERC(loc); + case '&': return parser::make_TOK_AMP(loc); + case '(': return parser::make_TOK_LPAREN(loc); + case ')': return parser::make_TOK_RPAREN(loc); + case '*': return parser::make_TOK_ASTER(loc); + case '+': return parser::make_TOK_PLUS(loc); + case ',': return parser::make_TOK_COMMA(loc); + case '-': return parser::make_TOK_MINUS(loc); + case '.': return parser::make_TOK_DOT(loc); + case '/': return parser::make_TOK_SLASH(loc); + case ':': return parser::make_TOK_COL(loc); + case ';': return parser::make_TOK_SEMICOL(loc); + case '<': return parser::make_TOK_LT(loc); + case '=': return parser::make_TOK_EQ(loc); + case '>': return parser::make_TOK_GT(loc); + case '?': return parser::make_TOK_QUE(loc); + case '@': return parser::make_TOK_AT(loc); + case '[': return parser::make_TOK_LBRA(loc); + case ']': return parser::make_TOK_RBRA(loc); + case '^': return parser::make_TOK_CARET(loc); + case '_': return parser::make_TOK_UNDER(loc); + case '{': return parser::make_TOK_LCURL(loc); + case '|': return parser::make_TOK_PIPE(loc); + case '}': return parser::make_TOK_RCURL(loc); + case '~': return parser::make_TOK_TILDE(loc); + case 'n': return parser::make_TOK_n(loc); + case 'p': return parser::make_TOK_p(loc); + case 'x': return parser::make_TOK_x(loc); + case 'z': return parser::make_TOK_z(loc); + case 0: return parser::make_FRONTEND_VERILOG_YYEOF(loc); + default: + return parser::make_ch_t(c, loc); + } +} +static bool is_hex_dig(char c, int *val, parser::location_type loc) +{ + if ('0' <= c && c <= '9') { + *val = c - '0'; + return true; + } else if ('a' <= c && c <= 'f') { + *val = c - 'a' + 0xA; + return true; + } else if ('A' <= c && c <= 'F') { + *val = c - 'A' + 0xA; + return true; + } else if (c == 'x' || c == 'X' || c == 'z' || c == 'Z' || c == '?') { + log_file_warning(loc.to_loc(), "'%c' not a valid digit in hex escape sequence.\n", c); + *val = 0; // not semantically valid in hex escape... + return true; // ...but still processed as part of hex token + } + + return false; +} + +static bool is_oct_dig(char c, int *val, parser::location_type loc) +{ + if ('0' <= c && c <= '7') { + *val = c - '0'; + return true; + } else if (c == 'x' || c == 'X' || c == 'z' || c == 'Z' || c == '?') { + log_file_warning(loc.to_loc(), "'%c' not a valid digit in octal escape sequence.\n", c); + *val = 0; // not semantically valid in octal escape... + return true; // ...but still processed as part of octal token + } + + return false; +} + +static parser::symbol_type process_str(char *str, int len, bool triple, parser::location_type loc) +{ + char *in, *out; // Overwrite input buffer: flex manual states "Actions + // are free to modify 'yytext' except for lengthening it". + + for (in = str, out = str; in < str + len; in++) + switch (*in) { + case '\n': + case '\r': + if (in + 1 < str + len && (in[1] ^ *in) == ('\n' ^ '\r')) + in++; + if (!triple) + log_file_warning(loc.to_loc(), "Multi-line string literals should be triple-quoted or escaped.\n"); + *out++ = '\n'; + break; + case '\\': + in++; + log_assert(in < str + len); + switch (*in) { + case 'a': + *out++ = '\a'; + break; + case 'f': + *out++ = '\f'; + break; + case 'n': + *out++ = '\n'; + break; + case 'r': /* not part of IEEE-1800 2023, but seems + like a good idea to support it anyway */ + *out++ = '\r'; + break; + case 't': + *out++ = '\t'; + break; + case 'v': + *out++ = '\v'; + break; + case 'x': + int val; + if (in + 1 < str + len && is_hex_dig(in[1], &val, loc)) { + *out = val; + in++; + if (in + 1 < str + len && is_hex_dig(in[1], &val, loc)) { + *out = *out * 0x10 + val; + in++; + } + out++; + } else + log_file_warning(loc.to_loc(), "ignoring invalid hex escape.\n"); + break; + case '\\': + *out++ = '\\'; + break; + case '"': + *out++ = '"'; + break; + case '\n': + case '\r': + if (in + 1 < str + len && (in[1] ^ *in) == ('\n' ^ '\r')) + in++; + break; + default: + if ('0' <= *in && *in <= '7') { + int val; + + *out = *in - '0'; + if (in + 1 < str + len && is_oct_dig(in[1], &val, loc)) { + *out = *out * 010 + val; + in++; + if (in + 1 < str + len && is_oct_dig(in[1], &val, loc)) { + if (*out >= 040) + log_file_warning(loc.to_loc(), "octal escape exceeds \\377\n"); + *out = *out * 010 + val; + in++; + } + } + out++; + } else + *out++ = *in; + } + break; + default: + *out++ = *in; + } + + return parser::make_TOK_STRING(std::make_unique(str, out - str), loc); +} + +%} + +%x COMMENT +%x SYNOPSYS_TRANSLATE_OFF +%x SYNOPSYS_FLAGS +%x IMPORT_DPI +%x BASED_CONST + +UNSIGNED_NUMBER [0-9][0-9_]* +FIXED_POINT_NUMBER_DEC [0-9][0-9_]*\.[0-9][0-9_]*([eE][-+]?[0-9_]+)? +FIXED_POINT_NUMBER_NO_DEC [0-9][0-9_]*[eE][-+]?[0-9_]+ +TIME_SCALE_SUFFIX [munpf]?s + +%% + + // Initialise comment_caller to something to avoid a "maybe undefined" + // warning from GCC. + int comment_caller = INITIAL; + +"`file_push "[^\n]* { + fn_stack.push_back(current_filename); + ln_stack.push_back(yylineno); + std::string filename = YYText()+11; + if (!filename.empty() && filename.front() == '"') + filename = filename.substr(1); + if (!filename.empty() && filename.back() == '"') + filename = filename.substr(0, filename.size()-1); + current_filename = std::make_shared(filename); + yylineno = (0); + out_loc.begin.line = out_loc.end.line = 0; +} + +"`file_pop"[^\n]*\n { + current_filename = fn_stack.back(); + fn_stack.pop_back(); + yylineno = (ln_stack.back()); + out_loc.begin.line = out_loc.end.line = ln_stack.back(); + ln_stack.pop_back(); +} + +"`line"[ \t]+[^ \t\r\n]+[ \t]+\"[^ \r\n]+\"[^\r\n]*\n { + const char *p = YYText() + 5; + while (*p == ' ' || *p == '\t') p++; + yylineno = (atoi(p)); + out_loc.begin.line = out_loc.end.line = atoi(p); + while (*p && *p != ' ' && *p != '\t') p++; + while (*p == ' ' || *p == '\t') p++; + const char *q = *p ? p + 1 : p; + while (*q && *q != '"') q++; + current_filename = std::make_shared(std::string(p).substr(1, q-p-1)); +} + +"`file_notfound "[^\n]* { + log_error("Can't open include file `%s'!\n", YYText() + 15); +} + +"`timescale"[ \t]+[^ \t\r\n/]+[ \t]*"/"[ \t]*[^ \t\r\n]* /* ignore timescale directive */ + +"`celldefine"[^\n]* /* ignore `celldefine */ +"`endcelldefine"[^\n]* /* ignore `endcelldefine */ + +"`default_nettype"[ \t]+[^ \t\r\n/]+ { + const char *p = YYText(); + while (*p != 0 && *p != ' ' && *p != '\t') p++; + while (*p == ' ' || *p == '\t') p++; + if (!strcmp(p, "none")) + extra->default_nettype_wire = false; + else if (!strcmp(p, "wire")) + extra->default_nettype_wire = true; + else + err_at_loc(out_loc, "Unsupported default nettype: %s", p); +} + +"`protect"[^\n]* /* ignore `protect*/ +"`endprotect"[^\n]* /* ignore `endprotect*/ + +"`"[a-zA-Z_$][a-zA-Z0-9_$]* { + err_at_loc(out_loc, "Unimplemented compiler directive or undefined macro %s.", YYText()); +} + +"module" { return parser::make_TOK_MODULE(out_loc); } +"endmodule" { return parser::make_TOK_ENDMODULE(out_loc); } +"function" { return parser::make_TOK_FUNCTION(out_loc); } +"endfunction" { return parser::make_TOK_ENDFUNCTION(out_loc); } +"task" { return parser::make_TOK_TASK(out_loc); } +"endtask" { return parser::make_TOK_ENDTASK(out_loc); } +"specify" { return mode->specify ? parser::make_TOK_SPECIFY(out_loc) : parser::make_TOK_IGNORED_SPECIFY(out_loc); } +"endspecify" { return parser::make_TOK_ENDSPECIFY(out_loc); } +"specparam" { return parser::make_TOK_SPECPARAM(out_loc); } +"package" { SV_KEYWORD(parser::make_TOK_PACKAGE(out_loc)); } +"endpackage" { SV_KEYWORD(parser::make_TOK_ENDPACKAGE(out_loc)); } +"import" { SV_KEYWORD(parser::make_TOK_IMPORT(out_loc)); } +"interface" { SV_KEYWORD(parser::make_TOK_INTERFACE(out_loc)); } +"endinterface" { SV_KEYWORD(parser::make_TOK_ENDINTERFACE(out_loc)); } +"modport" { SV_KEYWORD(parser::make_TOK_MODPORT(out_loc)); } +"parameter" { return parser::make_TOK_PARAMETER(out_loc); } +"localparam" { return parser::make_TOK_LOCALPARAM(out_loc); } +"defparam" { return parser::make_TOK_DEFPARAM(out_loc); } +"assign" { return parser::make_TOK_ASSIGN(out_loc); } +"always" { return parser::make_TOK_ALWAYS(out_loc); } +"initial" { return parser::make_TOK_INITIAL(out_loc); } +"begin" { return parser::make_TOK_BEGIN(out_loc); } +"end" { return parser::make_TOK_END(out_loc); } +"if" { return parser::make_TOK_IF(out_loc); } +"ifnone" { return parser::make_TOK_IFNONE(out_loc); } +"else" { return parser::make_TOK_ELSE(out_loc); } +"for" { return parser::make_TOK_FOR(out_loc); } +"posedge" { return parser::make_TOK_POSEDGE(out_loc); } +"negedge" { return parser::make_TOK_NEGEDGE(out_loc); } +"or" { return parser::make_TOK_OR(out_loc); } +"case" { return parser::make_TOK_CASE(out_loc); } +"casex" { return parser::make_TOK_CASEX(out_loc); } +"casez" { return parser::make_TOK_CASEZ(out_loc); } +"endcase" { return parser::make_TOK_ENDCASE(out_loc); } +"default" { return parser::make_TOK_DEFAULT(out_loc); } +"generate" { return parser::make_TOK_GENERATE(out_loc); } +"endgenerate" { return parser::make_TOK_ENDGENERATE(out_loc); } +"while" { return parser::make_TOK_WHILE(out_loc); } +"repeat" { return parser::make_TOK_REPEAT(out_loc); } +"automatic" { return parser::make_TOK_AUTOMATIC(out_loc); } + +"unique" { SV_KEYWORD(parser::make_TOK_UNIQUE(out_loc)); } +"unique0" { SV_KEYWORD(parser::make_TOK_UNIQUE0(out_loc)); } +"priority" { SV_KEYWORD(parser::make_TOK_PRIORITY(out_loc)); } + +"always_comb" { SV_KEYWORD(parser::make_TOK_ALWAYS_COMB(out_loc)); } +"always_ff" { SV_KEYWORD(parser::make_TOK_ALWAYS_FF(out_loc)); } +"always_latch" { SV_KEYWORD(parser::make_TOK_ALWAYS_LATCH(out_loc)); } + + /* use special token for labels on assert, assume, cover, and restrict because it's insanley complex + to fix parsing of cells otherwise. (the current cell parser forces a reduce very early to update some + global state.. its a mess) */ +[a-zA-Z_$][a-zA-Z0-9_$]*/[ \t\r\n]*:[ \t\r\n]*(assert|assume|cover|restrict)[^a-zA-Z0-9_$\.] { + if (!strcmp(YYText(), "default")) + return parser::make_TOK_DEFAULT(out_loc); + string_t val = std::make_unique(std::string("\\") + YYText()); + return parser::make_TOK_SVA_LABEL(std::move(val), out_loc); +} + +"assert" { if (mode->formal) return parser::make_TOK_ASSERT(out_loc); SV_KEYWORD(parser::make_TOK_ASSERT(out_loc)); } +"assume" { if (mode->formal) return parser::make_TOK_ASSUME(out_loc); SV_KEYWORD(parser::make_TOK_ASSUME(out_loc)); } +"cover" { if (mode->formal) return parser::make_TOK_COVER(out_loc); SV_KEYWORD(parser::make_TOK_COVER(out_loc)); } +"restrict" { if (mode->formal) return parser::make_TOK_RESTRICT(out_loc); SV_KEYWORD(parser::make_TOK_RESTRICT(out_loc)); } +"property" { if (mode->formal) return parser::make_TOK_PROPERTY(out_loc); SV_KEYWORD(parser::make_TOK_PROPERTY(out_loc)); } +"rand" { if (mode->formal) return parser::make_TOK_RAND(out_loc); SV_KEYWORD(parser::make_TOK_RAND(out_loc)); } +"const" { if (mode->formal) return parser::make_TOK_CONST(out_loc); SV_KEYWORD(parser::make_TOK_CONST(out_loc)); } +"checker" { if (mode->formal) return parser::make_TOK_CHECKER(out_loc); SV_KEYWORD(parser::make_TOK_CHECKER(out_loc)); } +"endchecker" { if (mode->formal) return parser::make_TOK_ENDCHECKER(out_loc); SV_KEYWORD(parser::make_TOK_ENDCHECKER(out_loc)); } +"final" { SV_KEYWORD(parser::make_TOK_FINAL(out_loc)); } +"logic" { SV_KEYWORD(parser::make_TOK_LOGIC(out_loc)); } +"var" { SV_KEYWORD(parser::make_TOK_VAR(out_loc)); } +"bit" { SV_KEYWORD(parser::make_TOK_LOGIC(out_loc)); } +"int" { SV_KEYWORD(parser::make_TOK_INT(out_loc)); } +"byte" { SV_KEYWORD(parser::make_TOK_BYTE(out_loc)); } +"shortint" { SV_KEYWORD(parser::make_TOK_SHORTINT(out_loc)); } +"longint" { SV_KEYWORD(parser::make_TOK_LONGINT(out_loc)); } +"void" { SV_KEYWORD(parser::make_TOK_VOID(out_loc)); } + +"eventually" { if (mode->formal) return parser::make_TOK_EVENTUALLY(out_loc); SV_KEYWORD(parser::make_TOK_EVENTUALLY(out_loc)); } +"s_eventually" { if (mode->formal) return parser::make_TOK_EVENTUALLY(out_loc); SV_KEYWORD(parser::make_TOK_EVENTUALLY(out_loc)); } + +"input" { return parser::make_TOK_INPUT(out_loc); } +"output" { return parser::make_TOK_OUTPUT(out_loc); } +"inout" { return parser::make_TOK_INOUT(out_loc); } +"wire" { return parser::make_TOK_WIRE(out_loc); } +"tri" { return parser::make_TOK_WIRE(out_loc); } +"wor" { return parser::make_TOK_WOR(out_loc); } +"trior" { return parser::make_TOK_WOR(out_loc); } +"wand" { return parser::make_TOK_WAND(out_loc); } +"triand" { return parser::make_TOK_WAND(out_loc); } +"reg" { return parser::make_TOK_REG(out_loc); } +"integer" { return parser::make_TOK_INTEGER(out_loc); } +"signed" { return parser::make_TOK_SIGNED(out_loc); } +"unsigned" { SV_KEYWORD(parser::make_TOK_UNSIGNED(out_loc)); } +"genvar" { return parser::make_TOK_GENVAR(out_loc); } +"real" { return parser::make_TOK_REAL(out_loc); } + +"enum" { SV_KEYWORD(parser::make_TOK_ENUM(out_loc)); } +"typedef" { SV_KEYWORD(parser::make_TOK_TYPEDEF(out_loc)); } +"struct" { SV_KEYWORD(parser::make_TOK_STRUCT(out_loc)); } +"union" { SV_KEYWORD(parser::make_TOK_UNION(out_loc)); } +"packed" { SV_KEYWORD(parser::make_TOK_PACKED(out_loc)); } + +{UNSIGNED_NUMBER} { + string_t val = std::make_unique(YYText()); + return parser::make_TOK_CONSTVAL(std::move(val), out_loc); +} + +\'[01zxZX] { + string_t val = std::make_unique(YYText()); + return parser::make_TOK_UNBASED_UNSIZED_CONSTVAL(std::move(val), out_loc); +} + +\'[sS]?[bodhBODH] { + BEGIN(BASED_CONST); + string_t val = std::make_unique(YYText()); + return parser::make_TOK_BASE(std::move(val), out_loc); +} + +[0-9a-fA-FzxZX?][0-9a-fA-FzxZX?_]* { + BEGIN(0); + string_t val = std::make_unique(YYText()); + return parser::make_TOK_BASED_CONSTVAL(std::move(val), out_loc); +} + +{FIXED_POINT_NUMBER_DEC} { + string_t val = std::make_unique(YYText()); + return parser::make_TOK_REALVAL(std::move(val), out_loc); +} + +{FIXED_POINT_NUMBER_NO_DEC} { + string_t val = std::make_unique(YYText()); + return parser::make_TOK_REALVAL(std::move(val), out_loc); +} + +\"([^\\"]|\\.|\\\n)*\" { return process_str(yytext + 1, yyleng - 2, false, out_loc); } + +\"{3}(\"{0,2}([^\\"]|\\.|\\\n))*\"{3} { return process_str(yytext + 3, yyleng - 6, true, out_loc); } + +and|nand|or|nor|xor|xnor|not|buf|bufif0|bufif1|notif0|notif1|tran { + auto val = std::make_unique(YYText()); + return parser::make_TOK_PRIMITIVE(std::move(val), out_loc); +} + +supply0 { return parser::make_TOK_SUPPLY0(out_loc); } +supply1 { return parser::make_TOK_SUPPLY1(out_loc); } + +"$"(display[bho]?|write[bho]?|strobe|monitor|time|realtime|stop|finish|dumpfile|dumpvars|dumpon|dumpoff|dumpall) { + auto val = std::make_unique(YYText()); + return parser::make_TOK_ID(std::move(val), out_loc); +} + +"$"(setup|hold|setuphold|removal|recovery|recrem|skew|timeskew|fullskew|nochange) { + if (!mode->specify) REJECT; + auto val = std::make_unique(YYText()); + return parser::make_TOK_ID(std::move(val), out_loc); +} + +"$"(info|warning|error|fatal) { + auto val = std::make_unique(YYText()); + return parser::make_TOK_MSG_TASKS(std::move(val), out_loc); +} + +"$signed" { return parser::make_TOK_TO_SIGNED(out_loc); } +"$unsigned" { return parser::make_TOK_TO_UNSIGNED(out_loc); } + +[a-zA-Z_][a-zA-Z0-9_]*::[a-zA-Z_$][a-zA-Z0-9_$]* { + // package qualifier + auto s = std::string("\\") + YYText(); + if (extra->pkg_user_types.count(s) > 0) { + // package qualified typedefed name + auto val = std::make_unique(s); + return parser::make_TOK_PKG_USER_TYPE(std::move(val), out_loc); + } + else { + // backup before :: just return first part + size_t len = strchr(YYText(), ':') - YYText(); + yyless(len); + auto val = std::make_unique(std::string("\\") + YYText()); + return parser::make_TOK_ID(std::move(val), out_loc); + } +} + +[a-zA-Z_$][a-zA-Z0-9_$]* { + auto s = std::string("\\") + YYText(); + if (isUserType(extra, s)) { + // previously typedefed name + auto val = std::make_unique(s); + return parser::make_TOK_USER_TYPE(std::move(val), out_loc); + } + else { + auto val = std::make_unique(std::string("\\") + YYText()); + return parser::make_TOK_ID(std::move(val), out_loc); + } +} + +[a-zA-Z_$][a-zA-Z0-9_$\.]* { + auto val = std::make_unique(std::string("\\") + YYText()); + return parser::make_TOK_ID(std::move(val), out_loc); +} + +"/*"[ \t]*(synopsys|synthesis)[ \t]*translate_off[ \t]*"*/" { + static bool printed_warning = false; + if (!printed_warning) { + log_warning( + "Encountered `translate_off' comment! Such legacy hot " + "comments are supported by Yosys, but are not part of " + "any formal language specification. Using a portable " + "and standards-compliant construct such as `ifdef is " + "recommended!\n" + ); + printed_warning = true; + } + BEGIN(SYNOPSYS_TRANSLATE_OFF); +} +. /* ignore synopsys translate_off body */ +\n /* ignore synopsys translate_off body */ +"/*"[ \t]*(synopsys|synthesis)[ \t]*"translate_on"[ \t]*"*/" { BEGIN(0); } + +"/*"[ \t]*(synopsys|synthesis)[ \t]+ { + BEGIN(SYNOPSYS_FLAGS); +} +full_case { + static bool printed_warning = false; + if (!printed_warning) { + log_warning( + "Encountered `full_case' comment! Such legacy hot " + "comments are supported by Yosys, but are not part of " + "any formal language specification. Using the Verilog " + "`full_case' attribute or the SystemVerilog `unique' " + "or `unique0' keywords is recommended!\n" + ); + printed_warning = true; + } + return parser::make_TOK_SYNOPSYS_FULL_CASE(out_loc); +} +parallel_case { + static bool printed_warning = false; + if (!printed_warning) { + log_warning( + "Encountered `parallel_case' comment! Such legacy hot " + "comments are supported by Yosys, but are not part of " + "any formal language specification. Using the Verilog " + "`parallel_case' attribute or the SystemVerilog " + "`unique' or `priority' keywords is recommended!\n" + ); + printed_warning = true; + } + return parser::make_TOK_SYNOPSYS_PARALLEL_CASE(out_loc); +} +. /* ignore everything else */ +"*/" { BEGIN(0); } + +import[ \t\r\n]+\"(DPI|DPI-C)\"[ \t\r\n]+function[ \t\r\n]+ { + BEGIN(IMPORT_DPI); + return parser::make_TOK_DPI_FUNCTION(out_loc); +} + +[a-zA-Z_$][a-zA-Z0-9_$]* { + auto val = std::make_unique(std::string("\\") + YYText()); + return parser::make_TOK_ID(std::move(val), out_loc); +} + +[ \t\r\n] /* ignore whitespaces */ + +";" { + BEGIN(0); + return char_tok(*YYText(), out_loc); +} + +. { + return char_tok(*YYText(), out_loc); +} + +"\\"[^ \t\r\n]+ { + auto val = std::make_unique(YYText()); + return parser::make_TOK_ID(std::move(val), out_loc); +} + +"(*" { return parser::make_ATTR_BEGIN(out_loc); } +"*)" { return parser::make_ATTR_END(out_loc); } + +"{*" { return parser::make_DEFATTR_BEGIN(out_loc); } +"*}" { return parser::make_DEFATTR_END(out_loc); } + +"**" { return parser::make_OP_POW(out_loc); } +"||" { return parser::make_OP_LOR(out_loc); } +"&&" { return parser::make_OP_LAND(out_loc); } +"==" { return parser::make_OP_EQ(out_loc); } +"!=" { return parser::make_OP_NE(out_loc); } +"<=" { return parser::make_OP_LE(out_loc); } +">=" { return parser::make_OP_GE(out_loc); } + +"===" { return parser::make_OP_EQX(out_loc); } +"!==" { return parser::make_OP_NEX(out_loc); } + +"~&" { return parser::make_OP_NAND(out_loc); } +"~|" { return parser::make_OP_NOR(out_loc); } +"~^" { return parser::make_OP_XNOR(out_loc); } +"^~" { return parser::make_OP_XNOR(out_loc); } + +"<<" { return parser::make_OP_SHL(out_loc); } +">>" { return parser::make_OP_SHR(out_loc); } +"<<<" { return parser::make_OP_SSHL(out_loc); } +">>>" { return parser::make_OP_SSHR(out_loc); } + +"'" { return parser::make_OP_CAST(out_loc); } + +"::" { return parser::make_TOK_PACKAGESEP(out_loc); } +"++" { return parser::make_TOK_INCREMENT(out_loc); } +"--" { return parser::make_TOK_DECREMENT(out_loc); } + +"+:" { return parser::make_TOK_POS_INDEXED(out_loc); } +"-:" { return parser::make_TOK_NEG_INDEXED(out_loc); } + +".*" { return parser::make_TOK_WILDCARD_CONNECT(out_loc); } + +"|=" { SV_KEYWORD(parser::make_TOK_BIT_OR_ASSIGN(out_loc)); } +"&=" { SV_KEYWORD(parser::make_TOK_BIT_AND_ASSIGN(out_loc)); } +"+=" { SV_KEYWORD(parser::make_TOK_ADD_ASSIGN(out_loc)); } +"-=" { SV_KEYWORD(parser::make_TOK_SUB_ASSIGN(out_loc)); } +"^=" { SV_KEYWORD(parser::make_TOK_BIT_XOR_ASSIGN(out_loc)); } +"/=" { SV_KEYWORD(parser::make_TOK_DIV_ASSIGN(out_loc)); } +"%=" { SV_KEYWORD(parser::make_TOK_MOD_ASSIGN(out_loc)); } +"*=" { SV_KEYWORD(parser::make_TOK_MUL_ASSIGN(out_loc)); } +"<<=" { SV_KEYWORD(parser::make_TOK_SHL_ASSIGN(out_loc)); } +">>=" { SV_KEYWORD(parser::make_TOK_SHR_ASSIGN(out_loc)); } +"<<<=" { SV_KEYWORD(parser::make_TOK_SSHL_ASSIGN(out_loc)); } +">>>=" { SV_KEYWORD(parser::make_TOK_SSHR_ASSIGN(out_loc)); } + +[-+]?[=*]> { + if (!mode->specify) REJECT; + auto val = std::make_unique(YYText()); + return parser::make_TOK_SPECIFY_OPER(std::move(val), out_loc); +} + +"&&&" { + if (!mode->specify) return parser::make_TOK_IGNORED_SPECIFY_AND(out_loc); + return parser::make_TOK_SPECIFY_AND(out_loc); +} + +{UNSIGNED_NUMBER}{TIME_SCALE_SUFFIX} { return parser::make_TOK_TIME_SCALE(out_loc); } +{FIXED_POINT_NUMBER_DEC}{TIME_SCALE_SUFFIX} { return parser::make_TOK_TIME_SCALE(out_loc); } +{FIXED_POINT_NUMBER_NO_DEC}{TIME_SCALE_SUFFIX} { return parser::make_TOK_TIME_SCALE(out_loc); } + +"/*" { comment_caller=YY_START; BEGIN(COMMENT); } +. /* ignore comment body */ +\n /* ignore comment body */ +"*/" { BEGIN(comment_caller); } + + +[ \t\r\n] /* ignore whitespaces */ +\\[\r\n] /* ignore continuation sequence */ +"//"[^\r\n]* /* ignore one-line comments */ + +. { return char_tok(*YYText(), out_loc); } +<*>. { BEGIN(0); return char_tok(*YYText(), out_loc); } + +%% diff --git a/chips/yosys/frontends/verilog/verilog_location.h b/chips/yosys/frontends/verilog/verilog_location.h new file mode 100644 index 0000000000000000000000000000000000000000..1fba2197820dfeb2b91ea7237192a7790c4c3285 --- /dev/null +++ b/chips/yosys/frontends/verilog/verilog_location.h @@ -0,0 +1,101 @@ +#ifndef VERILOG_LOCATION_H +#define VERILOG_LOCATION_H + +#include +#include +#include +#include +#include + +/** + * Provide frontend-wide location tracking like what bison generates + * but using shared_ptr for filename + */ + +struct Position { + std::shared_ptr filename; + int line; + int column; + + Position(std::shared_ptr filename, int line = 1, int column = 1) + : filename(filename), line(line), column(column) {} + Position() = default; + Position(const Position& other) = default; + Position& operator=(const Position& other) = default; + + void advance() { ++column; } + void columns(int count = 1) { + column += count; + } + + void lines(int count = 1) { + line += count; + column = 1; + } + std::string to_string() const { + std::ostringstream oss; + if (filename && !filename->empty()) { + oss << *filename << ":"; + } + oss << line << ":" << column; + return oss.str(); + } +}; + +struct Location { + Position begin; + Position end; + + Location() = default; + Location(const Position& b, const Position& e) + : begin(b), end(e) {} + Location(const Location& other) = default; + Location& operator=(const Location& other) = default; + + void step() { begin = end; } + + void columns(int count = 1) { + end.columns(count); + } + + void lines(int count = 1) { + end.lines(count); + } + std::string to_string() const { + std::ostringstream oss; + bool same_file = (!begin.filename && !end.filename) || + (begin.filename && end.filename && + *begin.filename == *end.filename); + + if (same_file) { + if (begin.filename && !begin.filename->empty()) + oss << *begin.filename << ":"; + + if (begin.line == end.line) { + if (begin.column == end.column) { + oss << begin.line << ":" << begin.column; + } else { + oss << begin.line << ":" << begin.column + << "-" << end.column; + } + } else { + oss << begin.line << ":" << begin.column + << "-" << end.line << ":" << end.column; + } + } else { + oss << begin.to_string() << "-" << end.to_string(); + } + + return oss.str(); + } + + YOSYS_NAMESPACE_PREFIX LogSourceLocation to_loc() const { + return YOSYS_NAMESPACE_PREFIX LogSourceLocation(begin.filename ? *(begin.filename) : "UNKNOWN", begin.line, begin.column, end.line, end.column); + } +}; + +static inline std::ostream& operator<<(std::ostream& os, const Location& loc) { + return os << loc.to_string(); +} + +#endif diff --git a/chips/yosys/frontends/verilog/verilog_parser.y b/chips/yosys/frontends/verilog/verilog_parser.y new file mode 100644 index 0000000000000000000000000000000000000000..384d9d4b910722b2fe6fac2f44ae36af6b5b007f --- /dev/null +++ b/chips/yosys/frontends/verilog/verilog_parser.y @@ -0,0 +1,3585 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * --- + * + * The Verilog frontend. + * + * This frontend is using the AST frontend library (see frontends/ast/). + * Thus this frontend does not generate RTLIL code directly but creates an + * AST directly from the Verilog parse tree and then passes this AST to + * the AST frontend library. + * + * --- + * + * This is the actual bison parser for Verilog code. The AST ist created directly + * from the bison reduce functions here. Note that this code uses a few global + * variables to hold the state of the AST generator and therefore this parser is + * not reentrant. + * + */ + +%require "3.6" +%language "c++" +%define api.value.type variant +%define api.prefix {frontend_verilog_yy} +%define api.token.constructor +%define api.location.type {Location} + +%param { YOSYS_NAMESPACE_PREFIX VERILOG_FRONTEND::VerilogLexer* lexer } +%parse-param { YOSYS_NAMESPACE_PREFIX VERILOG_FRONTEND::ParseState* extra } +%parse-param { YOSYS_NAMESPACE_PREFIX VERILOG_FRONTEND::ParseMode* mode } + + +%code requires { + #include "kernel/yosys_common.h" + #include "frontends/verilog/verilog_error.h" + #include "frontends/verilog/verilog_location.h" + YOSYS_NAMESPACE_BEGIN + namespace VERILOG_FRONTEND { + struct ParseState; + struct ParseMode; + class VerilogLexer; + }; + YOSYS_NAMESPACE_END +} + +%code provides { + USING_YOSYS_NAMESPACE; + using namespace AST; + using namespace VERILOG_FRONTEND; + using parser = frontend_verilog_yy::parser; + YOSYS_NAMESPACE_BEGIN + namespace VERILOG_FRONTEND { + typedef std::map UserTypeMap; + struct ParseState { + int port_counter; + dict port_stubs; + std::unique_ptr>> attr_list; + dict> default_attr_list; + std::stack>>> attr_list_stack; + std::unique_ptr>> albuf; + std::vector user_type_stack; + dict pkg_user_types; + std::vector ast_stack; + std::unique_ptr astbuf1, astbuf2, astbuf3; + AstNode* cell_hack; + AstNode* member_hack; + struct AstNode *current_function_or_task; + struct AstNode *current_ast, *current_ast_mod; + int current_function_or_task_port_id; + std::vector case_type_stack; + bool do_not_require_port_stubs; + bool current_wire_rand, current_wire_const, current_wire_automatic; + bool current_modport_input, current_modport_output; + bool default_nettype_wire = true; + std::istream* lexin; + + AstNode* saveChild(std::unique_ptr child); + AstNode* pushChild(std::unique_ptr child); + void addWiretypeNode(std::string *name, AstNode* node); + void addTypedefNode(std::string *name, std::unique_ptr node); + void enterTypeScope(); + void exitTypeScope(); + bool isInLocalScope(const std::string *name); + void rewriteGenForDeclInit(AstNode *loop); + void ensureAsgnExprAllowed(const parser::location_type loc, bool sv_mode); + const AstNode *addIncOrDecStmt(std::unique_ptr>> stmt_attr, + std::unique_ptr lhs, + std::unique_ptr>> op_attr, AST::AstNodeType op, + parser::location_type loc); + std::unique_ptr addIncOrDecExpr(std::unique_ptr lhs, + std::unique_ptr>> attr, + AST::AstNodeType op, parser::location_type loc, bool undo, bool sv_mode); + // add a binary operator assignment statement, e.g., a += b + std::unique_ptr addAsgnBinopStmt(std::unique_ptr>> attr, + std::unique_ptr eq_lhs, AST::AstNodeType op, std::unique_ptr rhs); + }; + struct ParseMode { + bool noassert = false; + bool noassume = false; + bool norestrict = false; + bool sv = false; + bool formal = false; + bool lib = false; + bool specify = false; + bool assume_asserts = false; + bool assert_assumes = false; + }; + }; + YOSYS_NAMESPACE_END +} + +%code { + #include + #include + #include + #include + #include "kernel/log.h" + #include "frontends/verilog/verilog_lexer.h" + + USING_YOSYS_NAMESPACE + using namespace AST; + using namespace VERILOG_FRONTEND; + + // Silly little C adapter between C++ bison and C++ flex + auto frontend_verilog_yylex(YOSYS_NAMESPACE_PREFIX VERILOG_FRONTEND::VerilogLexer* lexer) { + return lexer->nextToken(); + } + + #define SET_AST_NODE_LOC(WHICH, BEGIN, END) (WHICH)->location = location_range(BEGIN, END) + + #define SET_RULE_LOC(LHS, BEGIN, END) \ + do { (LHS).begin = BEGIN.begin; \ + (LHS).end = (END).end; } while(0) + + YOSYS_NAMESPACE_BEGIN + namespace VERILOG_FRONTEND { + + static Location location_range(Location begin, Location end) { + return Location(begin.begin, end.end); + } + + static void append_attr(AstNode *ast, std::unique_ptr>> al) + { + for (auto &it : *al) { + ast->attributes[AST::intern_attr_name(it.first)] = std::move(it.second); + } + } + + static void append_attr_clone(AstNode *ast, std::unique_ptr>> &al) + { + for (auto &it : *al) { + ast->attributes[AST::intern_attr_name(it.first)] = it.second->clone(); + } + } + + static std::unique_ptr makeRange(parser::location_type loc, int msb = 31, int lsb = 0, bool isSigned = true) + { + auto range = std::make_unique(loc, AST_RANGE); + range->children.push_back(AstNode::mkconst_int(loc, msb, true)); + range->children.push_back(AstNode::mkconst_int(loc, lsb, true)); + range->is_signed = isSigned; + return range; + } + + static void addRange(AstNode *parent, int msb = 31, int lsb = 0, bool isSigned = true) + { + auto range = makeRange(parent->location, msb, lsb, isSigned); + parent->children.push_back(std::move(range)); + } + + static std::unique_ptr checkRange(AstNode *type_node, std::unique_ptr range_node) + { + if (type_node->range_left >= 0 && type_node->range_right >= 0) { + // type already restricts the range + if (range_node) { + err_at_loc(type_node->location, "integer/genvar types cannot have packed dimensions."); + } + else { + range_node = makeRange(type_node->location, type_node->range_left, type_node->range_right, false); + } + } + + if (range_node) { + bool valid = true; + if (range_node->type == AST_RANGE) { + valid = range_node->children.size() == 2; + } else { // AST_MULTIRANGE + for (auto& child : range_node->children) { + valid = valid && child->children.size() == 2; + } + } + if (!valid) + err_at_loc(type_node->location, "wire/reg/logic packed dimension must be of the form [:]"); + } + + return range_node; + } + + static void rewriteRange(AstNode *rangeNode) + { + if (rangeNode->type == AST_RANGE && rangeNode->children.size() == 1) { + // SV array size [n], rewrite as [0:n-1] + rangeNode->children.push_back(std::make_unique(rangeNode->location, AST_SUB, std::move(rangeNode->children[0]), AstNode::mkconst_int(rangeNode->location, 1, true))); + rangeNode->children[0] = AstNode::mkconst_int(rangeNode->location, 0, false); + } + } + + static void rewriteAsMemoryNode(AstNode *node, std::unique_ptr rangeNode) + { + node->type = AST_MEMORY; + if (rangeNode->type == AST_MULTIRANGE) { + for (auto& child : rangeNode->children) + rewriteRange(child.get()); + } else + rewriteRange(rangeNode.get()); + node->children.push_back(std::move(rangeNode)); + } + + static void checkLabelsMatch(const frontend_verilog_yy::parser::location_type& loc, const char *element, const std::string* before, const std::string *after) + { + if (!before && after) + err_at_loc(loc, "%s missing where end label (%s) was given.", + element, after->c_str() + 1); + if (before && after && *before != *after) + err_at_loc(loc, "%s (%s) and end label (%s) don't match.", + element, before->c_str() + 1, after->c_str() + 1); + } + + AstNode* ParseState::saveChild(std::unique_ptr child) { + auto* child_leaky = child.get(); + ast_stack.back()->children.push_back(std::move(child)); + return child_leaky; + } + AstNode* ParseState::pushChild(std::unique_ptr child) { + auto* child_leaky = saveChild(std::move(child)); + ast_stack.push_back(child_leaky); + return child_leaky; + } + + void ParseState::addWiretypeNode(std::string *name, AstNode* node) + { + log_assert(node); + node->is_custom_type = true; + node->children.push_back(std::make_unique(node->location, AST_WIRETYPE)); + node->children.back()->str = *name; + } + + void ParseState::addTypedefNode(std::string *name, std::unique_ptr node) + { + log_assert((bool)node); + AstNode* tnode = saveChild(std::make_unique(node->location, AST_TYPEDEF, std::move(node))); + log_assert((bool)name); + tnode->str = *name; + auto &user_types = user_type_stack.back(); + user_types[*name] = tnode; + if (current_ast_mod && current_ast_mod->type == AST_PACKAGE) { + // typedef inside a package so we need the qualified name + auto qname = current_ast_mod->str + "::" + (*name).substr(1); + pkg_user_types[qname] = tnode; + } + } + + void ParseState::enterTypeScope() + { + user_type_stack.push_back(UserTypeMap()); + } + + void ParseState::exitTypeScope() + { + user_type_stack.pop_back(); + } + + bool ParseState::isInLocalScope(const std::string *name) + { + // tests if a name was declared in the current block scope + auto &user_types = user_type_stack.back(); + return (user_types.count(*name) > 0); + } + + // This transforms a loop like + // for (genvar i = 0; i < 10; i++) begin : blk + // to + // genvar _i; + // for (_i = 0; _i < 10; _i++) begin : blk + // localparam i = _i; + // where `_i` is actually some auto-generated name. + void ParseState::rewriteGenForDeclInit(AstNode *loop) + { + // check if this generate for loop contains an inline declaration + log_assert(loop->type == AST_GENFOR); + auto& decl = loop->children[0]; + if (decl->type == AST_ASSIGN_EQ) + return; + + log_assert(decl->type == AST_GENVAR); + log_assert(loop->children.size() == 5); + + // identify each component of the loop + AstNode *init = loop->children[1].get(); + AstNode *cond = loop->children[2].get(); + AstNode *incr = loop->children[3].get(); + AstNode *body = loop->children[4].get(); + log_assert(init->type == AST_ASSIGN_EQ); + log_assert(incr->type == AST_ASSIGN_EQ); + log_assert(body->type == AST_GENBLOCK); + + // create a unique name for the genvar + std::string old_str = decl->str; + std::string new_str = stringf("$genfordecl$%d$%s", ast_autoidx(), old_str); + + // rename and move the genvar declaration to the containing description + decl->str = new_str; + log_assert(current_ast_mod != nullptr); + current_ast_mod->children.push_back(std::move(decl)); + + // create a new localparam with old name so that the items in the loop + // can simply use the old name and shadow it as necessary + auto indirect = std::make_unique(loop->location, AST_LOCALPARAM); + indirect->str = old_str; + auto ident = std::make_unique(loop->location, AST_IDENTIFIER); + ident->str = new_str; + indirect->children.push_back(std::move(ident)); + + body->children.insert(body->children.begin(), std::move(indirect)); + + // only perform the renaming for the initialization, guard, and + // incrementation to enable proper shadowing of the synthetic localparam + std::function substitute = [&](AstNode *node) { + if (node->type == AST_IDENTIFIER && node->str == old_str) + node->str = new_str; + for (auto& child : node->children) + substitute(child.get()); + }; + substitute(init); + substitute(cond); + substitute(incr); + loop->children.erase(loop->children.begin()); + } + + void ParseState::ensureAsgnExprAllowed(const parser::location_type loc, bool sv_mode) + { + if (!sv_mode) + err_at_loc(loc, "Assignments within expressions are only supported in SystemVerilog mode."); + if (ast_stack.back()->type != AST_BLOCK) + err_at_loc(loc, "Assignments within expressions are only permitted within procedures."); + } + + // add a pre/post-increment/decrement statement + const AstNode *ParseState::addIncOrDecStmt(std::unique_ptr>> stmt_attr, + std::unique_ptr lhs, + std::unique_ptr>> op_attr, AST::AstNodeType op, + Location loc) + { + auto one = AstNode::mkconst_int(loc, 1, true); + auto rhs = std::make_unique(loc, op, lhs->clone(), std::move(one)); + if (op_attr) + append_attr(rhs.get(), std::move(op_attr)); + auto stmt_owned = std::make_unique(loc, AST_ASSIGN_EQ, std::move(lhs), std::move(rhs)); + auto* stmt = stmt_owned.get(); + ast_stack.back()->children.push_back(std::move(stmt_owned)); + if (stmt_attr) + append_attr(stmt, std::move(stmt_attr)); + return stmt; + } + + // create a pre/post-increment/decrement expression, and add the corresponding statement + std::unique_ptr ParseState::addIncOrDecExpr(std::unique_ptr lhs, + std::unique_ptr>> attr, + AST::AstNodeType op, Location loc, bool undo, bool sv_mode) + { + ensureAsgnExprAllowed(loc, sv_mode); + const AstNode *stmt = addIncOrDecStmt(nullptr, std::move(lhs), std::move(attr), op, loc); + log_assert(stmt->type == AST_ASSIGN_EQ); + auto expr = stmt->children[0]->clone(); + if (undo) { + auto one = AstNode::mkconst_int(loc, 1, false, 1); + auto minus_one = std::make_unique(loc, AST_NEG, std::move(one)); + expr = std::make_unique(loc, op, std::move(expr), std::move(minus_one)); + } + return expr; + } + + // add a binary operator assignment statement, e.g., a += b + std::unique_ptr ParseState::addAsgnBinopStmt(std::unique_ptr>> attr, + std::unique_ptr eq_lhs, AST::AstNodeType op, std::unique_ptr rhs) + { + Location loc = location_range(eq_lhs->location, rhs->location); + if (op == AST_SHIFT_LEFT || op == AST_SHIFT_RIGHT || + op == AST_SHIFT_SLEFT || op == AST_SHIFT_SRIGHT) { + rhs = std::make_unique(rhs->location, AST_TO_UNSIGNED, std::move(rhs)); + } + auto binop_lhs = eq_lhs->clone(); + auto eq_rhs_owned = std::make_unique(loc, op, std::move(binop_lhs), std::move(rhs)); + auto ret_lhs = eq_lhs->clone(); + auto stmt_owned = std::make_unique(loc, AST_ASSIGN_EQ, std::move(eq_lhs), std::move(eq_rhs_owned)); + auto* stmt = stmt_owned.get(); + ast_stack.back()->children.push_back(std::move(stmt_owned)); + if (attr) + append_attr(stmt, std::move(attr)); + return ret_lhs; + } + }; + YOSYS_NAMESPACE_END + + void frontend_verilog_yy::parser::error(const frontend_verilog_yy::parser::location_type& loc, const std::string& msg) + { + err_at_loc(loc, "%s", msg); + } +} + +%code requires { + #include + #include + #include + #include "frontends/verilog/verilog_frontend.h" + + struct specify_target { + char polarity_op; + std::unique_ptr dst, dat; + specify_target& operator=(specify_target&& other) noexcept { + if (this != &other) { + dst = std::move(other.dst); + dat = std::move(other.dat); + polarity_op = other.polarity_op; + } + return *this; + } + }; + + struct specify_triple { + std::unique_ptr t_min, t_avg, t_max; + specify_triple& operator=(specify_triple&& other) noexcept { + if (this != &other) { + t_min = std::move(other.t_min); + t_avg = std::move(other.t_avg); + t_max = std::move(other.t_max); + } + return *this; + } + }; + + struct specify_rise_fall { + specify_triple rise; + specify_triple fall; + }; + + using string_t = std::unique_ptr; + using ast_t = std::unique_ptr; + using al_t = std::unique_ptr>>; + using specify_target_ptr_t = std::unique_ptr; + using specify_triple_ptr_t = std::unique_ptr; + using specify_rise_fall_ptr_t = std::unique_ptr; + using boolean_t = bool; + using ch_t = char; + using integer_t = int; + using ast_node_type_t = YOSYS_NAMESPACE_PREFIX AST::AstNodeType; +} + +%token string_t "string" +%token ast_t +%token al_t +%token specify_target_ptr_t "specify target" +%token specify_triple_ptr_t "specify triple" +%token specify_rise_fall_ptr_t "specify rise and fall" +%token boolean_t "boolean" +%token ch_t "invalid token" +%token integer_t "integer" +%token ast_node_type_t + +%token TOK_STRING TOK_ID TOK_CONSTVAL TOK_REALVAL TOK_PRIMITIVE +%token TOK_SVA_LABEL TOK_SPECIFY_OPER TOK_MSG_TASKS +%token TOK_BASE TOK_BASED_CONSTVAL TOK_UNBASED_UNSIZED_CONSTVAL +%token TOK_USER_TYPE TOK_PKG_USER_TYPE +%token TOK_ASSERT TOK_ASSUME TOK_RESTRICT TOK_COVER TOK_FINAL +%token ATTR_BEGIN ATTR_END DEFATTR_BEGIN DEFATTR_END +%token TOK_MODULE TOK_ENDMODULE TOK_PARAMETER TOK_LOCALPARAM TOK_DEFPARAM +%token TOK_PACKAGE TOK_ENDPACKAGE TOK_PACKAGESEP +%token TOK_INTERFACE TOK_ENDINTERFACE TOK_MODPORT TOK_VAR TOK_WILDCARD_CONNECT +%token TOK_INPUT TOK_OUTPUT TOK_INOUT TOK_WIRE TOK_WAND TOK_WOR TOK_REG TOK_LOGIC +%token TOK_INTEGER TOK_SIGNED TOK_ASSIGN TOK_ALWAYS TOK_INITIAL +%token TOK_ALWAYS_FF TOK_ALWAYS_COMB TOK_ALWAYS_LATCH +%token TOK_BEGIN TOK_END TOK_IF TOK_ELSE TOK_IFNONE TOK_FOR TOK_WHILE TOK_REPEAT +%token TOK_DPI_FUNCTION TOK_POSEDGE TOK_NEGEDGE TOK_OR TOK_AUTOMATIC +%token TOK_CASE TOK_CASEX TOK_CASEZ TOK_ENDCASE TOK_DEFAULT +%token TOK_FUNCTION TOK_ENDFUNCTION TOK_TASK TOK_ENDTASK TOK_SPECIFY +%token TOK_IGNORED_SPECIFY TOK_ENDSPECIFY TOK_SPECPARAM TOK_SPECIFY_AND TOK_IGNORED_SPECIFY_AND +%token TOK_GENERATE TOK_ENDGENERATE TOK_GENVAR TOK_REAL +%token TOK_SYNOPSYS_FULL_CASE TOK_SYNOPSYS_PARALLEL_CASE +%token TOK_SUPPLY0 TOK_SUPPLY1 TOK_TO_SIGNED TOK_TO_UNSIGNED +%token TOK_POS_INDEXED TOK_NEG_INDEXED TOK_PROPERTY TOK_ENUM TOK_TYPEDEF +%token TOK_RAND TOK_CONST TOK_CHECKER TOK_ENDCHECKER TOK_EVENTUALLY +%token TOK_INCREMENT TOK_DECREMENT TOK_UNIQUE TOK_UNIQUE0 TOK_PRIORITY +%token TOK_STRUCT TOK_PACKED TOK_UNSIGNED TOK_INT TOK_BYTE TOK_SHORTINT TOK_LONGINT TOK_VOID TOK_UNION +%token TOK_BIT_OR_ASSIGN TOK_BIT_AND_ASSIGN TOK_BIT_XOR_ASSIGN TOK_ADD_ASSIGN +%token TOK_SUB_ASSIGN TOK_DIV_ASSIGN TOK_MOD_ASSIGN TOK_MUL_ASSIGN +%token TOK_SHL_ASSIGN TOK_SHR_ASSIGN TOK_SSHL_ASSIGN TOK_SSHR_ASSIGN +%token TOK_TIME_SCALE +%token TOK_IMPORT + +%token TOK_EXCL "'!'" +%token TOK_HASH "'#'" +%token TOK_PERC "'%'" +%token TOK_AMP "'&'" +%token TOK_LPAREN "'('" +%token TOK_RPAREN "')'" +%token TOK_ASTER "'*'" +%token TOK_PLUS "'+'" +%token TOK_COMMA "','" +%token TOK_MINUS "'-'" +%token TOK_DOT "'.'" +%token TOK_SLASH "'/'" +%token TOK_COL "':'" +%token TOK_SEMICOL "';'" +%token TOK_LT "'<'" +%token TOK_EQ "'='" +%token TOK_GT "'>'" +%token TOK_QUE "'?'" +%token TOK_AT "'@'" +%token TOK_LBRA "'['" +%token TOK_RBRA "']'" +%token TOK_CARET "'^'" +%token TOK_UNDER "'_'" +%token TOK_LCURL "'{'" +%token TOK_PIPE "'|'" +%token TOK_RCURL "'}'" +%token TOK_TILDE "'~'" +%token TOK_n "'n'" +%token TOK_p "'p'" +%token TOK_x "'x'" +%token TOK_z "'z'" + +%type range range_or_multirange non_opt_range non_opt_multirange +%type wire_type expr basic_expr concat_list assignment_pattern_list rvalue lvalue lvalue_concat_list non_io_wire_type io_wire_type +%type opt_label opt_sva_label tok_prim_wrapper hierarchical_id hierarchical_type_id integral_number +%type type_name +%type opt_enum_init enum_type struct_type enum_struct_type func_return_type typedef_base_type +%type opt_property always_comb_or_latch always_or_always_ff +%type opt_signedness_default_signed opt_signedness_default_unsigned +%type integer_atom_type integer_vector_type +%type attr if_attr case_attr +%type struct_union +%type asgn_binop inc_or_dec_op +%type genvar_identifier + +%type specify_target +%type specify_triple specify_opt_triple +%type specify_rise_fall +%type specify_if specify_condition +%type specify_edge + +// operator precedence from low to high +%left OP_LOR +%left OP_LAND +%left TOK_PIPE OP_NOR +%left TOK_CARET OP_XNOR +%left TOK_AMP OP_NAND +%left OP_EQ OP_NE OP_EQX OP_NEX +%left TOK_LT OP_LE OP_GE TOK_GT +%left OP_SHL OP_SHR OP_SSHL OP_SSHR +%left TOK_PLUS TOK_MINUS +%left TOK_ASTER TOK_SLASH TOK_PERC +%right OP_POW +%precedence UNARY_OPS +%precedence OP_CAST + +%define parse.error detailed +%define parse.lac full + +%precedence FAKE_THEN +%precedence TOK_ELSE + +%debug +%locations + +%% + +input: { + (void)yynerrs_; + extra->ast_stack.clear(); + extra->ast_stack.push_back(extra->current_ast); +} design { + extra->ast_stack.pop_back(); + log_assert(GetSize(extra->ast_stack) == 0); + extra->default_attr_list.clear(); +}; + +design: + module design | + defattr design | + task_func_decl design | + param_decl design | + localparam_decl design | + typedef_decl design | + package design | + import_stmt design | + interface design | + %empty; + +attr: + { + if (extra->attr_list) + extra->attr_list_stack.push(std::move(extra->attr_list)); + extra->attr_list = std::make_unique>>(); + for (auto &it : extra->default_attr_list) + (*extra->attr_list)[it.first] = it.second->clone(); + } attr_opt { + $$ = std::move(extra->attr_list); + if (!extra->attr_list_stack.empty()) { + extra->attr_list = std::move(extra->attr_list_stack.top()); + extra->attr_list_stack.pop(); + } else + extra->attr_list = nullptr; + }; + +attr_opt: + attr_opt ATTR_BEGIN opt_attr_list ATTR_END { + SET_RULE_LOC(@$, @2, @$); + }| + %empty; + +defattr: + DEFATTR_BEGIN { + if (extra->attr_list != nullptr) + extra->attr_list_stack.push(std::move(extra->attr_list)); + extra->attr_list = std::make_unique>>(); + extra->default_attr_list.clear(); + } opt_attr_list { + extra->attr_list->swap(extra->default_attr_list); + extra->attr_list.reset(); + if (!extra->attr_list_stack.empty()) { + extra->attr_list = std::move(extra->attr_list_stack.top()); + extra->attr_list_stack.pop(); + } else + extra->attr_list = nullptr; + } DEFATTR_END; + +opt_attr_list: + attr_list | %empty; + +attr_list: + attr_assign | + attr_list TOK_COMMA attr_assign; + +attr_assign: + hierarchical_id { + (*extra->attr_list)[*$1] = AstNode::mkconst_int(@1, 1, false); + } | + hierarchical_id TOK_EQ expr { + (*extra->attr_list)[*$1] = std::move($3); + }; + +hierarchical_id: + TOK_ID { + $$ = std::move($1); + } | + hierarchical_id TOK_PACKAGESEP TOK_ID { + if ($3->compare(0, 1, "\\") == 0) + *$1 += "::" + $3->substr(1); + else + *$1 += "::" + *$3; + $$ = std::move($1); + } | + hierarchical_id TOK_DOT TOK_ID { + if ($3->compare(0, 1, "\\") == 0) + *$1 += "." + $3->substr(1); + else + *$1 += "." + *$3; + $$ = std::move($1); + }; + +hierarchical_type_id: + TOK_USER_TYPE {$$ = std::move($1); } + | TOK_PKG_USER_TYPE {$$ = std::move($1); } // package qualified type name + | TOK_LPAREN TOK_USER_TYPE TOK_RPAREN { $$ = std::move($2); } // non-standard grammar + ; + +module: + attr TOK_MODULE { + extra->enterTypeScope(); + } TOK_ID { + extra->do_not_require_port_stubs = false; + AstNode* mod = extra->pushChild(std::make_unique(@$, AST_MODULE)); + extra->current_ast_mod = mod; + extra->port_stubs.clear(); + extra->port_counter = 0; + mod->str = *$4; + append_attr(mod, std::move($1)); + } module_para_opt module_args_opt TOK_SEMICOL module_body TOK_ENDMODULE opt_label { + if (extra->port_stubs.size() != 0) + err_at_loc(@7, "Missing details for module port `%s'.", + extra->port_stubs.begin()->first.c_str()); + SET_AST_NODE_LOC(extra->ast_stack.back(), @2, @$); + extra->ast_stack.pop_back(); + log_assert(extra->ast_stack.size() == 1); + checkLabelsMatch(@11, "Module name", $4.get(), $11.get()); + extra->current_ast_mod = nullptr; + extra->exitTypeScope(); + }; + +module_para_opt: + TOK_HASH TOK_LPAREN module_para_list TOK_RPAREN | %empty; + +module_para_list: + single_module_para | module_para_list TOK_COMMA single_module_para; + +single_module_para: + %empty | + attr TOK_PARAMETER { + extra->astbuf1 = std::make_unique(@$, AST_PARAMETER); + extra->astbuf1->children.push_back(AstNode::mkconst_int(@2, 0, true)); + append_attr(extra->astbuf1.get(), std::move($1)); + } param_type single_param_decl | + attr TOK_LOCALPARAM { + extra->astbuf1 = std::make_unique(@$, AST_LOCALPARAM); + extra->astbuf1->children.push_back(AstNode::mkconst_int(@2, 0, true)); + append_attr(extra->astbuf1.get(), std::move($1)); + } param_type single_param_decl | + single_param_decl; + +module_args_opt: + TOK_LPAREN TOK_RPAREN | %empty | TOK_LPAREN module_args optional_comma TOK_RPAREN; + +module_args: + module_arg | module_args TOK_COMMA module_arg; + +optional_comma: + TOK_COMMA | %empty; + +module_arg_opt_assignment: + TOK_EQ expr { + if (extra->ast_stack.back()->children.size() > 0 && extra->ast_stack.back()->children.back()->type == AST_WIRE) { + if (extra->ast_stack.back()->children.back()->is_input) { + auto& n = extra->ast_stack.back()->children.back(); + n->attributes[ID::defaultvalue] = std::move($2); + } else { + auto wire = std::make_unique(@$, AST_IDENTIFIER); + wire->str = extra->ast_stack.back()->children.back()->str; + if (extra->ast_stack.back()->children.back()->is_reg || extra->ast_stack.back()->children.back()->is_logic) + extra->ast_stack.back()->children.push_back(std::make_unique(@$, AST_INITIAL, std::make_unique(@$, AST_BLOCK, std::make_unique(@$, AST_ASSIGN_LE, std::move(wire), std::move($2))))); + else + extra->ast_stack.back()->children.push_back(std::make_unique(@$, AST_ASSIGN, std::move(wire), std::move($2))); + } + } else + err_at_loc(@2, "SystemVerilog interface in module port list cannot have a default value."); + } | + %empty; + +module_arg: + TOK_ID { + if (extra->ast_stack.back()->children.size() > 0 && extra->ast_stack.back()->children.back()->type == AST_WIRE) { + auto node = extra->ast_stack.back()->children.back()->clone(); + node->str = *$1; + node->port_id = ++extra->port_counter; + SET_AST_NODE_LOC(node.get(), @1, @1); + extra->ast_stack.back()->children.push_back(std::move(node)); + } else { + if (extra->port_stubs.count(*$1) != 0) + err_at_loc(@1, "Duplicate module port `%s'.", *$1); + extra->port_stubs[*$1] = ++extra->port_counter; + } + } module_arg_opt_assignment | + TOK_ID { + extra->astbuf1 = std::make_unique(@$, AST_INTERFACEPORT); + extra->astbuf1->children.push_back(std::make_unique(@$, AST_INTERFACEPORTTYPE)); + extra->astbuf1->children[0]->str = *$1; + } TOK_ID { /* SV interfaces */ + if (!mode->sv) + err_at_loc(@3, "Interface found in port list (%s). This is not supported unless read_verilog is called with -sv!", *$3); + extra->astbuf2 = extra->astbuf1->clone(); // really only needed if multiple instances of same type. + extra->astbuf2->str = *$3; + extra->astbuf2->port_id = ++extra->port_counter; + extra->ast_stack.back()->children.push_back(std::move(extra->astbuf2)); + } module_arg_opt_assignment | + attr wire_type range_or_multirange TOK_ID { + auto node = std::move($2); + node->str = *$4; + SET_AST_NODE_LOC(node.get(), @4, @4); + node->port_id = ++extra->port_counter; + auto range = checkRange(node.get(), std::move($3)); + if (range != nullptr) + node->children.push_back(std::move(range)); + if (!node->is_input && !node->is_output) + err_at_loc(@4, "Module port `%s' is neither input nor output.", *$4); + if (node->is_reg && node->is_input && !node->is_output && !mode->sv) + err_at_loc(@4, "Input port `%s' is declared as register.", *$4); + append_attr(node.get(), std::move($1)); + extra->ast_stack.back()->children.push_back(std::move(node)); + } module_arg_opt_assignment | + TOK_DOT TOK_DOT TOK_DOT { + extra->do_not_require_port_stubs = true; + }; + +package: + attr TOK_PACKAGE { + extra->enterTypeScope(); + } TOK_ID { + AstNode* mod = extra->pushChild(std::make_unique(@$, AST_PACKAGE)); + extra->current_ast_mod = mod; + mod->str = *$4; + append_attr(mod, std::move($1)); + } TOK_SEMICOL package_body TOK_ENDPACKAGE opt_label { + extra->ast_stack.pop_back(); + checkLabelsMatch(@9, "Package name", $4.get(), $9.get()); + extra->current_ast_mod = nullptr; + extra->exitTypeScope(); + }; + +package_body: + package_body package_body_stmt | %empty; + +package_body_stmt: + typedef_decl | localparam_decl | param_decl | task_func_decl; + +import_stmt: + TOK_IMPORT TOK_ID TOK_PACKAGESEP TOK_ASTER TOK_SEMICOL { + // Create an import node to track wildcard package imports + auto import_node = std::make_unique(@$, AST_IMPORT); + import_node->str = *$2; + extra->ast_stack.back()->children.push_back(std::move(import_node)); + } | + TOK_IMPORT TOK_ID TOK_PACKAGESEP { + // Start a specific import: create and push the AST_IMPORT node + AstNode* import_node = extra->pushChild(std::make_unique(@$, AST_IMPORT)); + import_node->str = *$2; + } import_item_list TOK_SEMICOL { + // Done collecting specific items, pop the AST_IMPORT node + extra->ast_stack.pop_back(); + }; + +import_item_list: + import_item | + import_item_list TOK_COMMA import_item ; + +import_item: + TOK_ID { + // Append this specific import name under the current AST_IMPORT + auto item_node = std::make_unique(@$, AST_NONE); + item_node->str = *$1; + extra->ast_stack.back()->children.push_back(std::move(item_node)); + }; + +interface: + TOK_INTERFACE { + extra->enterTypeScope(); + } TOK_ID { + extra->do_not_require_port_stubs = false; + AstNode* intf = extra->pushChild(std::make_unique(@$, AST_INTERFACE)); + extra->current_ast_mod = intf; + extra->port_stubs.clear(); + extra->port_counter = 0; + intf->str = *$3; + } module_para_opt module_args_opt TOK_SEMICOL interface_body TOK_ENDINTERFACE { + if (extra->port_stubs.size() != 0) + err_at_loc(@6, "Missing details for module port `%s'.", + extra->port_stubs.begin()->first.c_str()); + extra->ast_stack.pop_back(); + log_assert(extra->ast_stack.size() == 1); + extra->current_ast_mod = nullptr; + extra->exitTypeScope(); + }; + +interface_body: + interface_body interface_body_stmt | %empty; + +interface_body_stmt: + param_decl | localparam_decl | typedef_decl | defparam_decl | wire_decl | always_stmt | assign_stmt | + modport_stmt; + +// bind_target matches the target of the bind (everything before +// bind_instantiation in the IEEE 1800 spec). +// +// We can't use the BNF from the spec directly because it's ambiguous: +// something like "bind foo bar_i (.*)" can either be interpreted with "foo" as +// a module or interface identifier (matching bind_target_scope in the spec) or +// by considering foo as a degenerate hierarchical identifier with no TOK_DOT +// characters, followed by no bit select (which matches bind_target_instance in +// the spec). +// +// Instead, we resolve everything as an instance name and then deal with the +// ambiguity when converting to RTLIL / in the hierarchy pass. +bind_target: + bind_target_instance opt_bind_target_instance_list; + +// An optional list of target instances for a bind statement, introduced by a +// colon. +opt_bind_target_instance_list: + TOK_COL bind_target_instance_list | + %empty; + +bind_target_instance_list: + bind_target_instance | + bind_target_instance_list TOK_COMMA bind_target_instance; + +// A single target instance for a bind statement. The top of extra->ast_stack will be +// the bind node where we should add it. +bind_target_instance: + hierarchical_id { + auto node = std::make_unique(@$, AST_IDENTIFIER); + node->str = *$1; + extra->ast_stack.back()->children.push_back(std::move(node)); + }; + +mintypmax_expr: + expr { } | + expr TOK_COL expr TOK_COL expr { }; + +non_opt_delay: + TOK_HASH TOK_ID { } | + TOK_HASH TOK_CONSTVAL { } | + TOK_HASH TOK_REALVAL { } | + // our `expr` doesn't have time_scale, so we need the parenthesized variant + TOK_HASH TOK_TIME_SCALE | + TOK_HASH TOK_LPAREN TOK_TIME_SCALE TOK_RPAREN | + TOK_HASH TOK_LPAREN mintypmax_expr TOK_RPAREN | + TOK_HASH TOK_LPAREN mintypmax_expr TOK_COMMA mintypmax_expr TOK_RPAREN | + TOK_HASH TOK_LPAREN mintypmax_expr TOK_COMMA mintypmax_expr TOK_COMMA mintypmax_expr TOK_RPAREN; + +delay: + non_opt_delay | %empty; + +io_wire_type: + { extra->astbuf3 = std::make_unique(@$, AST_WIRE); extra->current_wire_rand = false; extra->current_wire_const = false; extra->current_wire_automatic = false; } + wire_type_token_io wire_type_const_rand opt_wire_type_token wire_type_signedness + { $$ = std::move(extra->astbuf3); SET_RULE_LOC(@$, @2, @$); }; + +non_io_wire_type: + { extra->astbuf3 = std::make_unique(@$, AST_WIRE); extra->current_wire_rand = false; extra->current_wire_const = false; extra->current_wire_automatic = false; } + opt_lifetime wire_type_const_rand wire_type_token wire_type_signedness + { + if (extra->current_wire_automatic) + extra->astbuf3->set_attribute(ID::nosync, AstNode::mkconst_int(extra->astbuf3->location, 1, false)); + $$ = std::move(extra->astbuf3); SET_RULE_LOC(@$, @2, @$); + }; + +wire_type: + io_wire_type { $$ = std::move($1); } | + non_io_wire_type { $$ = std::move($1); }; + +wire_type_token_io: + TOK_INPUT { + extra->astbuf3->is_input = true; + } | + TOK_OUTPUT { + extra->astbuf3->is_output = true; + } | + TOK_INOUT { + extra->astbuf3->is_input = true; + extra->astbuf3->is_output = true; + }; + +wire_type_signedness: + TOK_SIGNED { extra->astbuf3->is_signed = true; } | + TOK_UNSIGNED { extra->astbuf3->is_signed = false; } | + %empty; + +wire_type_const_rand: + TOK_RAND TOK_CONST { + extra->current_wire_rand = true; + extra->current_wire_const = true; + } | + TOK_CONST { + extra->current_wire_const = true; + } | + TOK_RAND { + extra->current_wire_rand = true; + } | + %empty; + +opt_wire_type_token: + wire_type_token | %empty; + +wire_type_token: + // nets + net_type { + } | + net_type logic_type { + } | + // regs + TOK_REG { + extra->astbuf3->is_reg = true; + } | + TOK_VAR TOK_REG { + extra->astbuf3->is_reg = true; + } | + // logics + TOK_VAR { + extra->astbuf3->is_logic = true; + } | + TOK_VAR logic_type { + extra->astbuf3->is_logic = true; + } | + logic_type { + extra->astbuf3->is_logic = true; + } | + TOK_GENVAR { + extra->astbuf3->type = AST_GENVAR; + extra->astbuf3->is_reg = true; + extra->astbuf3->is_signed = true; + extra->astbuf3->range_left = 31; + extra->astbuf3->range_right = 0; + }; + +net_type: + TOK_WOR { + extra->astbuf3->is_wor = true; + } | + TOK_WAND { + extra->astbuf3->is_wand = true; + } | + TOK_WIRE; + +logic_type: + TOK_LOGIC { + } | + integer_atom_type { + extra->astbuf3->range_left = $1 - 1; + extra->astbuf3->range_right = 0; + extra->astbuf3->is_signed = true; + } | + hierarchical_type_id { + extra->addWiretypeNode($1.get(), extra->astbuf3.get()); + }; + +integer_atom_type: + TOK_INTEGER { $$ = 32; } | + TOK_INT { $$ = 32; } | + TOK_SHORTINT { $$ = 16; } | + TOK_LONGINT { $$ = 64; } | + TOK_BYTE { $$ = 8; } ; + +integer_vector_type: + TOK_LOGIC { $$ = token::TOK_LOGIC; } | + TOK_REG { $$ = token::TOK_REG; } ; + +non_opt_range: + TOK_LBRA expr TOK_COL expr TOK_RBRA { + $$ = std::make_unique(@$, AST_RANGE); + $$->children.push_back(std::move($2)); + $$->children.push_back(std::move($4)); + } | + TOK_LBRA expr TOK_POS_INDEXED expr TOK_RBRA { + $$ = std::make_unique(@$, AST_RANGE); + auto expr = std::make_unique(@$, AST_SELFSZ, std::move($2)); + $$->children.push_back(std::make_unique(@$, AST_SUB, std::make_unique(@$, AST_ADD, expr->clone(), std::move($4)), AstNode::mkconst_int(@$, 1, true))); + $$->children.push_back(std::make_unique(@$, AST_ADD, std::move(expr), AstNode::mkconst_int(@$, 0, true))); + } | + TOK_LBRA expr TOK_NEG_INDEXED expr TOK_RBRA { + $$ = std::make_unique(@$, AST_RANGE); + auto expr = std::make_unique(@$, AST_SELFSZ, std::move($2)); + $$->children.push_back(std::make_unique(@$, AST_ADD, expr->clone(), AstNode::mkconst_int(@$, 0, true))); + $$->children.push_back(std::make_unique(@$, AST_SUB, std::make_unique(@$, AST_ADD, std::move(expr), AstNode::mkconst_int(@$, 1, true)), std::move($4))); + } | + TOK_LBRA expr TOK_RBRA { + $$ = std::make_unique(@$, AST_RANGE); + $$->children.push_back(std::move($2)); + }; + +non_opt_multirange: + non_opt_range non_opt_range { + $$ = std::make_unique(@$, AST_MULTIRANGE, std::move($1), std::move($2)); + } | + non_opt_multirange non_opt_range { + $$ = std::move($1); + $$->children.push_back(std::move($2)); + }; + +range: + non_opt_range { + $$ = std::move($1); + } | + %empty { + $$ = nullptr; + }; + +range_or_multirange: + range { $$ = std::move($1); } | + non_opt_multirange { $$ = std::move($1); }; + +module_body: + module_body module_body_stmt | + /* the following line makes the generate..endgenrate keywords optional */ + module_body gen_stmt | + module_body gen_block | + module_body TOK_SEMICOL | + %empty; + +module_body_stmt: + task_func_decl | specify_block | param_decl | localparam_decl | typedef_decl | defparam_decl | specparam_declaration | wire_decl | assign_stmt | cell_stmt | + enum_decl | struct_decl | + always_stmt | TOK_GENERATE module_gen_body TOK_ENDGENERATE | defattr | assert_property | checker_decl | ignored_specify_block; + +checker_decl: + TOK_CHECKER TOK_ID TOK_SEMICOL { + AstNode* node = extra->pushChild(std::make_unique(@$, AST_GENBLOCK)); + node->str = *$2; + } module_body TOK_ENDCHECKER { + extra->ast_stack.pop_back(); + }; + +task_func_decl: + attr TOK_DPI_FUNCTION TOK_ID TOK_ID { + extra->current_function_or_task = extra->saveChild(std::make_unique(@$, AST_DPI_FUNCTION, AstNode::mkconst_str(@3, *$3), AstNode::mkconst_str(@4, *$4))); + extra->current_function_or_task->str = *$4; + append_attr(extra->current_function_or_task, std::move($1)); + } opt_dpi_function_args TOK_SEMICOL { + extra->current_function_or_task = nullptr; + } | + attr TOK_DPI_FUNCTION TOK_ID TOK_EQ TOK_ID TOK_ID { + extra->current_function_or_task = extra->saveChild(std::make_unique(@$, AST_DPI_FUNCTION, AstNode::mkconst_str(@5, *$5), AstNode::mkconst_str(@3, *$3))); + extra->current_function_or_task->str = *$6; + append_attr(extra->current_function_or_task, std::move($1)); + } opt_dpi_function_args TOK_SEMICOL { + extra->current_function_or_task = nullptr; + } | + attr TOK_DPI_FUNCTION TOK_ID TOK_COL TOK_ID TOK_EQ TOK_ID TOK_ID { + extra->current_function_or_task = extra->saveChild(std::make_unique(@$, AST_DPI_FUNCTION, AstNode::mkconst_str(@7, *$7), AstNode::mkconst_str(location_range(@3, @5), *$3 + ":" + RTLIL::unescape_id(*$5)))); + extra->current_function_or_task->str = *$8; + append_attr(extra->current_function_or_task, std::move($1)); + } opt_dpi_function_args TOK_SEMICOL { + extra->current_function_or_task = nullptr; + } | + attr TOK_TASK opt_automatic TOK_ID { + extra->current_function_or_task = extra->pushChild(std::make_unique(@$, AST_TASK)); + extra->current_function_or_task->str = *$4; + append_attr(extra->current_function_or_task, std::move($1)); + extra->current_function_or_task_port_id = 1; + } task_func_args_opt TOK_SEMICOL task_func_body TOK_ENDTASK { + extra->current_function_or_task = nullptr; + extra->ast_stack.pop_back(); + } | + attr TOK_FUNCTION opt_automatic TOK_VOID TOK_ID { + // The difference between void functions and tasks is that + // always_comb's implicit sensitivity list behaves as if functions were + // inlined, but ignores signals read only in tasks. This only matters + // for event based simulation, and for synthesis we can treat a void + // function like a task. + extra->current_function_or_task = extra->pushChild(std::make_unique(@$, AST_TASK)); + extra->current_function_or_task->str = *$5; + append_attr(extra->current_function_or_task, std::move($1)); + extra->current_function_or_task_port_id = 1; + } task_func_args_opt TOK_SEMICOL task_func_body TOK_ENDFUNCTION { + extra->current_function_or_task = nullptr; + extra->ast_stack.pop_back(); + } | + attr TOK_FUNCTION opt_automatic func_return_type TOK_ID { + extra->current_function_or_task = extra->pushChild(std::make_unique(@$, AST_FUNCTION)); + extra->current_function_or_task->str = *$5; + append_attr(extra->current_function_or_task, std::move($1)); + auto outreg = std::make_unique(@$, AST_WIRE); + outreg->str = *$5; + outreg->is_signed = false; + outreg->is_reg = true; + if ($4 != nullptr) { + outreg->is_signed = $4->is_signed; + $4->is_signed = false; + outreg->is_custom_type = $4->type == AST_WIRETYPE; + outreg->children.push_back(std::move($4)); + } + extra->current_function_or_task->children.push_back(std::move(outreg)); + extra->current_function_or_task_port_id = 1; + } task_func_args_opt TOK_SEMICOL task_func_body TOK_ENDFUNCTION { + extra->current_function_or_task = nullptr; + extra->ast_stack.pop_back(); + }; + +func_return_type: + hierarchical_type_id { + $$ = std::make_unique(@$, AST_WIRETYPE); + $$->str = *$1; + } | + opt_type_vec opt_signedness_default_unsigned { + $$ = makeRange(@$, 0, 0, $2); + } | + opt_type_vec opt_signedness_default_unsigned non_opt_range { + $$ = std::move($3); + $$->is_signed = $2; + } | + integer_atom_type opt_signedness_default_signed { + $$ = makeRange(@$, $1 - 1, 0, $2); + }; + +opt_type_vec: + %empty + | TOK_REG + | TOK_LOGIC + ; + +opt_signedness_default_signed: + %empty { $$ = true; } + | TOK_SIGNED { $$ = true; } + | TOK_UNSIGNED { $$ = false; } + ; +opt_signedness_default_unsigned: + %empty { $$ = false; } + | TOK_SIGNED { $$ = true; } + | TOK_UNSIGNED { $$ = false; } + ; + +dpi_function_arg: + TOK_ID TOK_ID { + extra->current_function_or_task->children.push_back(AstNode::mkconst_str(@1, *$1)); + } | + TOK_ID { + extra->current_function_or_task->children.push_back(AstNode::mkconst_str(@1, *$1)); + }; + +opt_dpi_function_args: + TOK_LPAREN dpi_function_args TOK_RPAREN | + %empty; + +dpi_function_args: + dpi_function_args TOK_COMMA dpi_function_arg | + dpi_function_args TOK_COMMA | + dpi_function_arg | + %empty; + +opt_automatic: + TOK_AUTOMATIC | + %empty; + +opt_lifetime: + TOK_AUTOMATIC { extra->current_wire_automatic = true; } | + %empty; + +task_func_args_opt: + TOK_LPAREN TOK_RPAREN | %empty | TOK_LPAREN { + extra->albuf = nullptr; + extra->astbuf1 = nullptr; + extra->astbuf2 = nullptr; + } task_func_args optional_comma { + (void)extra->astbuf1.reset(); + if (extra->astbuf2 != nullptr) + (void)extra->astbuf2.reset(); + extra->albuf.reset(); + } TOK_RPAREN; + +task_func_args: + task_func_port | task_func_args TOK_COMMA task_func_port; + +task_func_port: + attr wire_type range_or_multirange { + bool prev_was_input = true; + bool prev_was_output = false; + if (extra->albuf) { + prev_was_input = extra->astbuf1->is_input; + prev_was_output = extra->astbuf1->is_output; + (void)extra->astbuf1.reset(); + if (extra->astbuf2 != nullptr) + (void)extra->astbuf2.reset(); + extra->albuf.reset(); + } + extra->albuf = std::move($1); + extra->astbuf1 = std::move($2); + extra->astbuf2 = checkRange(extra->astbuf1.get(), std::move($3)); + if (!extra->astbuf1->is_input && !extra->astbuf1->is_output) { + if (!mode->sv) + err_at_loc(@2, "task/function argument direction missing"); + extra->astbuf1->is_input = prev_was_input; + extra->astbuf1->is_output = prev_was_output; + } + } wire_name | + { + if (!extra->astbuf1) { + if (!mode->sv) + err_at_loc(@$, "task/function argument direction missing"); + extra->albuf = std::make_unique>>(); + extra->astbuf1 = std::make_unique(@$, AST_WIRE); + extra->current_wire_rand = false; + extra->current_wire_const = false; + extra->astbuf1->is_input = true; + extra->astbuf2 = nullptr; + } + } wire_name; + +task_func_body: + task_func_body behavioral_stmt | + %empty; + +/*************************** specify parser ***************************/ + +specify_block: + TOK_SPECIFY specify_item_list TOK_ENDSPECIFY; + +specify_item_list: + specify_item specify_item_list | + %empty; + +specify_item: + specify_if TOK_LPAREN specify_edge expr TOK_SPECIFY_OPER specify_target TOK_RPAREN TOK_EQ specify_rise_fall TOK_SEMICOL { + auto en_expr = std::move($1); + char specify_edge = $3; + auto src_expr = std::move($4); + string *oper = $5.get(); + specify_target_ptr_t target = std::move($6); + specify_rise_fall_ptr_t timing = std::move($9); + + if (specify_edge != 0 && target->dat == nullptr) + err_at_loc(@3, "Found specify edge but no data spec."); + + auto cell_owned = std::make_unique(@$, AST_CELL); + auto cell = cell_owned.get(); + extra->ast_stack.back()->children.push_back(std::move(cell_owned)); + cell->str = stringf("$specify$%d", ast_autoidx()); + cell->children.push_back(std::make_unique(@$, AST_CELLTYPE)); + cell->children.back()->str = target->dat ? "$specify3" : "$specify2"; + SET_AST_NODE_LOC(cell, en_expr.get() ? @1 : @2, @10); + + char oper_polarity = 0; + char oper_type = oper->at(0); + + if (oper->size() == 3) { + oper_polarity = oper->at(0); + oper_type = oper->at(1); + } + + cell->children.push_back(std::make_unique(@5, AST_PARASET, AstNode::mkconst_int(@5, oper_type == '*', false, 1))); + cell->children.back()->str = "\\FULL"; + + cell->children.push_back(std::make_unique(@5, AST_PARASET, AstNode::mkconst_int(@5, oper_polarity != 0, false, 1))); + cell->children.back()->str = "\\SRC_DST_PEN"; + + cell->children.push_back(std::make_unique(@5, AST_PARASET, AstNode::mkconst_int(@5, oper_polarity == '+', false, 1))); + cell->children.back()->str = "\\SRC_DST_POL"; + + cell->children.push_back(std::make_unique(@9, AST_PARASET, std::move(timing->rise.t_min))); + cell->children.back()->str = "\\T_RISE_MIN"; + + cell->children.push_back(std::make_unique(@9, AST_PARASET, std::move(timing->rise.t_avg))); + cell->children.back()->str = "\\T_RISE_TYP"; + + cell->children.push_back(std::make_unique(@9, AST_PARASET, std::move(timing->rise.t_max))); + cell->children.back()->str = "\\T_RISE_MAX"; + + cell->children.push_back(std::make_unique(@9, AST_PARASET, std::move(timing->fall.t_min))); + cell->children.back()->str = "\\T_FALL_MIN"; + + cell->children.push_back(std::make_unique(@9, AST_PARASET, std::move(timing->fall.t_avg))); + cell->children.back()->str = "\\T_FALL_TYP"; + + cell->children.push_back(std::make_unique(@9, AST_PARASET, std::move(timing->fall.t_max))); + cell->children.back()->str = "\\T_FALL_MAX"; + + cell->children.push_back(std::make_unique(@1, AST_ARGUMENT, en_expr ? std::move(en_expr) : AstNode::mkconst_int(@1, 1, false, 1))); + cell->children.back()->str = "\\EN"; + + cell->children.push_back(std::make_unique(@4, AST_ARGUMENT, std::move(src_expr))); + cell->children.back()->str = "\\SRC"; + + cell->children.push_back(std::make_unique(@6, AST_ARGUMENT, std::move(target->dst))); + cell->children.back()->str = "\\DST"; + + if (target->dat) + { + cell->children.push_back(std::make_unique(@3, AST_PARASET, AstNode::mkconst_int(@3, specify_edge != 0, false, 1))); + cell->children.back()->str = "\\EDGE_EN"; + + cell->children.push_back(std::make_unique(@3, AST_PARASET, AstNode::mkconst_int(@3, specify_edge == 'p', false, 1))); + cell->children.back()->str = "\\EDGE_POL"; + + cell->children.push_back(std::make_unique(@6, AST_PARASET, AstNode::mkconst_int(@6, target->polarity_op != 0, false, 1))); + cell->children.back()->str = "\\DAT_DST_PEN"; + + cell->children.push_back(std::make_unique(@6, AST_PARASET, AstNode::mkconst_int(@6, target->polarity_op == '+', false, 1))); + cell->children.back()->str = "\\DAT_DST_POL"; + + cell->children.push_back(std::make_unique(@6, AST_ARGUMENT, std::move(target->dat))); + cell->children.back()->str = "\\DAT"; + } + } | + TOK_ID TOK_LPAREN specify_edge expr specify_condition TOK_COMMA specify_edge expr specify_condition TOK_COMMA specify_triple specify_opt_triple TOK_RPAREN TOK_SEMICOL { + if (*$1 != "$setup" && *$1 != "$hold" && *$1 != "$setuphold" && *$1 != "$removal" && *$1 != "$recovery" && + *$1 != "$recrem" && *$1 != "$skew" && *$1 != "$timeskew" && *$1 != "$fullskew" && *$1 != "$nochange") + err_at_loc(@1, "Unsupported specify rule type: %s", *$1); + + auto src_pen = AstNode::mkconst_int(@3, $3 != 0, false, 1); + auto src_pol = AstNode::mkconst_int(@3, $3 == 'p', false, 1); + auto src_expr = std::move($4), src_en = $5 ? std::move($5) : AstNode::mkconst_int(@5, 1, false, 1); + + auto dst_pen = AstNode::mkconst_int(@7, $7 != 0, false, 1); + auto dst_pol = AstNode::mkconst_int(@7, $7 == 'p', false, 1); + auto dst_expr = std::move($8), dst_en = $9 ? std::move($9) : AstNode::mkconst_int(@5, 1, false, 1); + + specify_triple_ptr_t limit = std::move($11); + specify_triple_ptr_t limit2 = std::move($12); + + auto cell_owned = std::make_unique(@$, AST_CELL); + auto cell = cell_owned.get(); + extra->ast_stack.back()->children.push_back(std::move(cell_owned)); + cell->str = stringf("$specify$%d", ast_autoidx()); + cell->children.push_back(std::make_unique(@$, AST_CELLTYPE)); + cell->children.back()->str = "$specrule"; + SET_AST_NODE_LOC(cell, @1, @14); + + cell->children.push_back(std::make_unique(@1, AST_PARASET, AstNode::mkconst_str(@1, *$1))); + cell->children.back()->str = "\\TYPE"; + + cell->children.push_back(std::make_unique(@11, AST_PARASET, std::move(limit->t_min))); + cell->children.back()->str = "\\T_LIMIT_MIN"; + + cell->children.push_back(std::make_unique(@11, AST_PARASET, std::move(limit->t_avg))); + cell->children.back()->str = "\\T_LIMIT_TYP"; + + cell->children.push_back(std::make_unique(@11, AST_PARASET, std::move(limit->t_max))); + cell->children.back()->str = "\\T_LIMIT_MAX"; + + cell->children.push_back(std::make_unique(@12, AST_PARASET, limit2 ? std::move(limit2->t_min) : AstNode::mkconst_int(@12, 0, true))); + cell->children.back()->str = "\\T_LIMIT2_MIN"; + + cell->children.push_back(std::make_unique(@12, AST_PARASET, limit2 ? std::move(limit2->t_avg) : AstNode::mkconst_int(@12, 0, true))); + cell->children.back()->str = "\\T_LIMIT2_TYP"; + + cell->children.push_back(std::make_unique(@12, AST_PARASET, limit2 ? std::move(limit2->t_max) : AstNode::mkconst_int(@12, 0, true))); + cell->children.back()->str = "\\T_LIMIT2_MAX"; + + cell->children.push_back(std::make_unique(@3, AST_PARASET, std::move(src_pen))); + cell->children.back()->str = "\\SRC_PEN"; + + cell->children.push_back(std::make_unique(@3, AST_PARASET, std::move(src_pol))); + cell->children.back()->str = "\\SRC_POL"; + + cell->children.push_back(std::make_unique(@3, AST_PARASET, std::move(dst_pen))); + cell->children.back()->str = "\\DST_PEN"; + + cell->children.push_back(std::make_unique(@7, AST_PARASET, std::move(dst_pol))); + cell->children.back()->str = "\\DST_POL"; + + cell->children.push_back(std::make_unique(@5, AST_ARGUMENT, std::move(src_en))); + cell->children.back()->str = "\\SRC_EN"; + + cell->children.push_back(std::make_unique(@4, AST_ARGUMENT, std::move(src_expr))); + cell->children.back()->str = "\\SRC"; + + cell->children.push_back(std::make_unique(@9, AST_ARGUMENT, std::move(dst_en))); + cell->children.back()->str = "\\DST_EN"; + + cell->children.push_back(std::make_unique(@8, AST_ARGUMENT, std::move(dst_expr))); + cell->children.back()->str = "\\DST"; + }; + +specify_opt_triple: + TOK_COMMA specify_triple { + $$ = std::move($2); + } | + %empty { + $$ = nullptr; + }; + +specify_if: + TOK_IF TOK_LPAREN expr TOK_RPAREN { + $$ = std::move($3); + } | + %empty { + $$ = nullptr; + }; + +specify_condition: + TOK_SPECIFY_AND expr { + $$ = std::move($2); + } | + %empty { + $$ = nullptr; + }; + +specify_target: + expr { + $$ = std::make_unique(); + $$->polarity_op = 0; + $$->dst = std::move($1); + $$->dat = nullptr; + } | + TOK_LPAREN expr TOK_COL expr TOK_RPAREN{ + $$ = std::make_unique(); + $$->polarity_op = 0; + $$->dst = std::move($2); + $$->dat = std::move($4); + } | + TOK_LPAREN expr TOK_NEG_INDEXED expr TOK_RPAREN{ + $$ = std::make_unique(); + $$->polarity_op = '-'; + $$->dst = std::move($2); + $$->dat = std::move($4); + } | + TOK_LPAREN expr TOK_POS_INDEXED expr TOK_RPAREN{ + $$ = std::make_unique(); + $$->polarity_op = '+'; + $$->dst = std::move($2); + $$->dat = std::move($4); + }; + +specify_edge: + TOK_POSEDGE { $$ = 'p'; } | + TOK_NEGEDGE { $$ = 'n'; } | + %empty { $$ = 0; }; + +specify_rise_fall: + specify_triple { + $$ = std::make_unique(); + $$->fall.t_min = $1->t_min->clone(); + $$->fall.t_avg = $1->t_avg->clone(); + $$->fall.t_max = $1->t_max->clone(); + $$->rise = std::move(*$1); + } | + TOK_LPAREN specify_triple TOK_COMMA specify_triple TOK_RPAREN { + $$ = std::make_unique(); + $$->rise = std::move(*$2); + $$->fall = std::move(*$4); + } | + TOK_LPAREN specify_triple TOK_COMMA specify_triple TOK_COMMA specify_triple TOK_RPAREN { + $$ = std::make_unique(); + $$->rise = std::move(*$2); + $$->fall = std::move(*$4); + warn_at_loc(@$, "Path delay expressions beyond rise/fall not currently supported. Ignoring."); + } | + TOK_LPAREN specify_triple TOK_COMMA specify_triple TOK_COMMA specify_triple TOK_COMMA specify_triple TOK_COMMA specify_triple TOK_COMMA specify_triple TOK_RPAREN { + $$ = std::make_unique(); + $$->rise = std::move(*$2); + $$->fall = std::move(*$4); + warn_at_loc(@$, "Path delay expressions beyond rise/fall not currently supported. Ignoring."); + } | + TOK_LPAREN specify_triple TOK_COMMA specify_triple TOK_COMMA specify_triple TOK_COMMA specify_triple TOK_COMMA specify_triple TOK_COMMA specify_triple TOK_COMMA specify_triple TOK_COMMA specify_triple TOK_COMMA specify_triple TOK_COMMA specify_triple TOK_COMMA specify_triple TOK_COMMA specify_triple TOK_RPAREN { + $$ = std::make_unique(); + $$->rise = std::move(*$2); + $$->fall = std::move(*$4); + warn_at_loc(@$, "Path delay expressions beyond rise/fall not currently supported. Ignoring."); + } + +specify_triple: + expr { + $$ = std::make_unique(); + $$->t_avg = $1->clone(); + $$->t_max = $1->clone(); + $$->t_min = std::move($1); + } | + expr TOK_COL expr TOK_COL expr { + $$ = std::make_unique(); + $$->t_min = std::move($1); + $$->t_avg = std::move($3); + $$->t_max = std::move($5); + }; + +/******************** ignored specify parser **************************/ + +ignored_specify_block: + TOK_IGNORED_SPECIFY ignored_specify_item_opt TOK_ENDSPECIFY | + TOK_IGNORED_SPECIFY TOK_ENDSPECIFY ; + +ignored_specify_item_opt: + ignored_specify_item_opt ignored_specify_item | + ignored_specify_item ; + +ignored_specify_item: + specparam_declaration + // | pulsestyle_declaration + // | showcancelled_declaration + | path_declaration + | system_timing_declaration + ; + +specparam_declaration: + TOK_SPECPARAM list_of_specparam_assignments TOK_SEMICOL | + TOK_SPECPARAM specparam_range list_of_specparam_assignments TOK_SEMICOL ; + +// IEEE 1364-2005 calls this sinmply 'range' but the current 'range' rule allows empty match +// and the 'non_opt_range' rule allows index ranges not allowed by 1364-2005 +// exxxxtending this for SV specparam would change this anyhow +specparam_range: + TOK_LBRA ignspec_constant_expression TOK_COL ignspec_constant_expression TOK_RBRA ; + +list_of_specparam_assignments: + specparam_assignment | list_of_specparam_assignments TOK_COMMA specparam_assignment; + +specparam_assignment: + ignspec_id TOK_EQ ignspec_expr ; + +path_declaration : + simple_path_declaration TOK_SEMICOL + // | edge_sensitive_path_declaration + | state_dependent_path_declaration TOK_SEMICOL + ; + +simple_path_declaration : + parallel_path_description TOK_EQ path_delay_value | + full_path_description TOK_EQ path_delay_value + ; + +state_dependent_path_declaration: + TOK_IF TOK_LPAREN module_path_expression TOK_RPAREN simple_path_declaration + // | TOK_IF TOK_LPAREN module_path_expression TOK_RPAREN edge_sensitive_path_declaration + | TOK_IFNONE simple_path_declaration + ; + +module_path_expression: + module_path_primary + // Flatten out unary_operator to avoid shift/reduce conflict + | TOK_EXCL attr module_path_primary + | TOK_TILDE attr module_path_primary + | TOK_AMP attr module_path_primary + | OP_NAND attr module_path_primary + | TOK_PIPE attr module_path_primary + | OP_NOR attr module_path_primary + | TOK_CARET attr module_path_primary + | OP_XNOR attr module_path_primary + // Flatten out binary_operator to avoid shift/reduce conflict + | module_path_expression OP_EQ attr module_path_expression + | module_path_expression OP_NE attr module_path_expression + | module_path_expression OP_LAND attr module_path_expression + | module_path_expression OP_LOR attr module_path_expression + | module_path_expression TOK_AMP attr module_path_expression + | module_path_expression TOK_PIPE attr module_path_expression + | module_path_expression TOK_CARET attr module_path_expression + | module_path_expression OP_XNOR attr module_path_expression + // | module_path_conditional_expression + ; + +module_path_primary: + number + | TOK_ID + // Deviate from specification: Normally string would not be allowed, however they are necessary for the ecp5 tests + | TOK_STRING + // | module_path_concatenation + // | module_path_multiple_concatenation + // | function_subroutine_call + // | TOK_LPAREN module_path_minmax_expression TOK_RPAREN + ; + +number: + integral_number + | TOK_REALVAL + ; + +path_delay_value : + TOK_LPAREN ignspec_expr list_of_path_delay_extra_expressions TOK_RPAREN + | ignspec_expr + | ignspec_expr list_of_path_delay_extra_expressions + ; + +list_of_path_delay_extra_expressions : + TOK_COMMA ignspec_expr + | TOK_COMMA ignspec_expr list_of_path_delay_extra_expressions + ; + +specify_edge_identifier : + TOK_POSEDGE | TOK_NEGEDGE ; + +parallel_path_description : + TOK_LPAREN specify_input_terminal_descriptor opt_polarity_operator TOK_EQ TOK_GT specify_output_terminal_descriptor TOK_RPAREN | + TOK_LPAREN specify_edge_identifier specify_input_terminal_descriptor TOK_EQ TOK_GT TOK_LPAREN specify_output_terminal_descriptor opt_polarity_operator TOK_COL ignspec_expr TOK_RPAREN TOK_RPAREN | + TOK_LPAREN specify_edge_identifier specify_input_terminal_descriptor TOK_EQ TOK_GT TOK_LPAREN specify_output_terminal_descriptor TOK_POS_INDEXED ignspec_expr TOK_RPAREN TOK_RPAREN ; + +full_path_description : + TOK_LPAREN list_of_path_inputs TOK_ASTER TOK_GT list_of_path_outputs TOK_RPAREN | + TOK_LPAREN specify_edge_identifier list_of_path_inputs TOK_ASTER TOK_GT TOK_LPAREN list_of_path_outputs opt_polarity_operator TOK_COL ignspec_expr TOK_RPAREN TOK_RPAREN | + TOK_LPAREN specify_edge_identifier list_of_path_inputs TOK_ASTER TOK_GT TOK_LPAREN list_of_path_outputs TOK_POS_INDEXED ignspec_expr TOK_RPAREN TOK_RPAREN ; + +// This was broken into 2 rules to solve shift/reduce conflicts +list_of_path_inputs : + specify_input_terminal_descriptor opt_polarity_operator | + specify_input_terminal_descriptor more_path_inputs opt_polarity_operator ; + +more_path_inputs : + TOK_COMMA specify_input_terminal_descriptor | + more_path_inputs TOK_COMMA specify_input_terminal_descriptor ; + +list_of_path_outputs : + specify_output_terminal_descriptor | + list_of_path_outputs TOK_COMMA specify_output_terminal_descriptor ; + +opt_polarity_operator : + TOK_PLUS | TOK_MINUS | %empty; + +// Good enough for the time being +specify_input_terminal_descriptor : + ignspec_id ; + +// Good enough for the time being +specify_output_terminal_descriptor : + ignspec_id ; + +system_timing_declaration : + ignspec_id TOK_LPAREN system_timing_args TOK_RPAREN TOK_SEMICOL ; + +system_timing_arg : + TOK_POSEDGE ignspec_id | + TOK_NEGEDGE ignspec_id | + ignspec_expr ; + +system_timing_args : + system_timing_arg | + system_timing_args TOK_IGNORED_SPECIFY_AND system_timing_arg | + system_timing_args TOK_COMMA system_timing_arg ; + +// for the time being this is OK, but we may write our own expr here. +// as I'm not sure it is legal to use a full expr here (probably not) +// On the other hand, other rules requiring constant expressions also use 'expr' +// (such as param assignment), so we may leave this as-is, perhaps adding runtime checks for constant-ness +ignspec_constant_expression: + expr { }; + +ignspec_expr: + expr { } | + expr TOK_COL expr TOK_COL expr { + }; + +ignspec_id: + TOK_ID { } + range_or_multirange { }; + +/**********************************************************************/ + +param_signed: + TOK_SIGNED { + extra->astbuf1->is_signed = true; + } | TOK_UNSIGNED { + extra->astbuf1->is_signed = false; + } | %empty; + +param_integer: + type_atom { + extra->astbuf1->is_reg = false; + }; + +param_real: + TOK_REAL { + extra->astbuf1->children.push_back(std::make_unique(@$, AST_REALVALUE)); + }; + +param_range: + range { + if ($1 != nullptr) { + extra->astbuf1->children.push_back(std::move($1)); + } + }; + +param_integer_type: param_integer param_signed; +param_range_type: + type_vec param_signed { + addRange(extra->astbuf1.get(), 0, 0); + } | + type_vec param_signed non_opt_range { + extra->astbuf1->children.push_back(std::move($3)); + }; +param_implicit_type: param_signed param_range; + +param_type: + param_integer_type | param_real | param_range_type | param_implicit_type | + hierarchical_type_id { + extra->addWiretypeNode($1.get(), extra->astbuf1.get()); + }; + +param_decl: + attr TOK_PARAMETER { + extra->astbuf1 = std::make_unique(@$, AST_PARAMETER); + extra->astbuf1->children.push_back(AstNode::mkconst_int(@$, 0, true)); + append_attr(extra->astbuf1.get(), std::move($1)); + } param_type param_decl_list TOK_SEMICOL { + (void)extra->astbuf1.reset(); + }; + +localparam_decl: + attr TOK_LOCALPARAM { + extra->astbuf1 = std::make_unique(@$, AST_LOCALPARAM); + extra->astbuf1->children.push_back(AstNode::mkconst_int(@$, 0, true)); + append_attr(extra->astbuf1.get(), std::move($1)); + } param_type param_decl_list TOK_SEMICOL { + (void)extra->astbuf1.reset(); + }; + +param_decl_list: + single_param_decl | param_decl_list TOK_COMMA single_param_decl; + +single_param_decl: + single_param_decl_ident TOK_EQ expr { + AstNode *decl = extra->ast_stack.back()->children.back().get(); + log_assert(decl->type == AST_PARAMETER || decl->type == AST_LOCALPARAM); + decl->children[0] = std::move($3); + } | + single_param_decl_ident { + AstNode *decl = extra->ast_stack.back()->children.back().get(); + if (decl->type != AST_PARAMETER) { + log_assert(decl->type == AST_LOCALPARAM); + err_at_loc(@1, "localparam initialization is missing!"); + } + if (!mode->sv) + err_at_loc(@1, "Parameter defaults can only be omitted in SystemVerilog mode!"); + decl->children.erase(decl->children.begin()); + }; + +single_param_decl_ident: + TOK_ID { + std::unique_ptr node_owned; + if (extra->astbuf1 == nullptr) { + if (!mode->sv) + err_at_loc(@1, "In pure Verilog (not SystemVerilog), parameter/localparam with an initializer must use the parameter/localparam keyword"); + node_owned = std::make_unique(@$, AST_PARAMETER); + node_owned->children.push_back(AstNode::mkconst_int(@$, 0, true)); + } else { + node_owned = extra->astbuf1->clone(); + } + node_owned->str = *$1; + auto node = node_owned.get(); + extra->ast_stack.back()->children.push_back(std::move(node_owned)); + SET_AST_NODE_LOC(node, @1, @1); + }; + +defparam_decl: + TOK_DEFPARAM defparam_decl_list TOK_SEMICOL; + +defparam_decl_list: + single_defparam_decl | defparam_decl_list TOK_COMMA single_defparam_decl; + +single_defparam_decl: + range rvalue TOK_EQ expr { + auto node = std::make_unique(@$, AST_DEFPARAM); + node->children.push_back(std::move($2)); + node->children.push_back(std::move($4)); + if ($1 != nullptr) + node->children.push_back(std::move($1)); + extra->ast_stack.back()->children.push_back(std::move(node)); + }; + +///////// +// enum +///////// + +enum_type: TOK_ENUM { + static int enum_count; + // create parent node for the enum + extra->astbuf2 = std::make_unique(@$, AST_ENUM); + extra->astbuf2->str = std::string("$enum"); + extra->astbuf2->str += std::to_string(enum_count++); + log_assert(!extra->cell_hack); + extra->cell_hack = extra->astbuf2.get(); + extra->ast_stack.back()->children.push_back(std::move(extra->astbuf2)); + // create the template for the names + extra->astbuf1 = std::make_unique(@$, AST_ENUM_ITEM); + extra->astbuf1->children.push_back(AstNode::mkconst_int(@$, 0, true)); + } enum_base_type TOK_LCURL enum_name_list optional_comma TOK_RCURL { + // create template for the enum vars + log_assert(extra->cell_hack); + auto tnode_owned = extra->astbuf1->clone(); + auto* tnode = tnode_owned.get(); + extra->astbuf1 = std::move(tnode_owned); + tnode->type = AST_WIRE; + tnode->attributes[ID::enum_type] = AstNode::mkconst_str(@$, extra->cell_hack->str); + extra->cell_hack = nullptr; + // drop constant but keep any range + tnode->children.erase(tnode->children.begin()); + $$ = extra->astbuf1->clone(); + }; + +enum_base_type: type_atom type_signing + | type_vec type_signing range { if ($3) extra->astbuf1->children.push_back(std::move($3)); } + | %empty { extra->astbuf1->is_reg = true; addRange(extra->astbuf1.get()); } + ; + +type_atom: + integer_atom_type { + extra->astbuf1->is_reg = true; + extra->astbuf1->is_signed = true; + addRange(extra->astbuf1.get(), $1 - 1, 0); + }; + +type_vec: TOK_REG { extra->astbuf1->is_reg = true; } // unsigned + | TOK_LOGIC { extra->astbuf1->is_logic = true; } // unsigned + ; + +type_signing: + TOK_SIGNED { extra->astbuf1->is_signed = true; } + | TOK_UNSIGNED { extra->astbuf1->is_signed = false; } + | %empty + ; + +enum_name_list: enum_name_decl + | enum_name_list TOK_COMMA enum_name_decl + ; + +enum_name_decl: + TOK_ID opt_enum_init { + // put in fn + log_assert((bool)extra->astbuf1); + log_assert((bool)extra->cell_hack); + auto node = extra->astbuf1->clone(); + node->str = *$1; + SET_AST_NODE_LOC(node.get(), @1, @1); + node->children[0] = $2 ? std::move($2) : std::make_unique(@$, AST_NONE); + extra->cell_hack->children.push_back(std::move(node)); + } + ; + +opt_enum_init: + TOK_EQ basic_expr { $$ = std::move($2); } // TODO: restrict this + | %empty { $$ = nullptr; } + ; + +enum_var_list: + enum_var + | enum_var_list TOK_COMMA enum_var + ; + +enum_var: TOK_ID { + log_assert((bool)extra->astbuf1); + auto node = extra->astbuf1->clone(); + node->str = *$1; + SET_AST_NODE_LOC(node.get(), @1, @1); + node->is_enum = true; + extra->ast_stack.back()->children.push_back(std::move(node)); + } + ; + +enum_decl: enum_type enum_var_list TOK_SEMICOL { } + ; + +////////////////// +// struct or union +////////////////// + +struct_decl: + attr struct_type { + append_attr(extra->astbuf2.get(), std::move($1)); + } struct_var_list TOK_SEMICOL { + (void)extra->astbuf2.reset(); + } + ; + +struct_type: + struct_union { + extra->astbuf2 = std::move($1); + extra->astbuf2->is_custom_type = true; + } struct_body { + $$ = extra->astbuf2->clone(); + } + ; + +struct_union: + TOK_STRUCT { $$ = std::make_unique(@$, AST_STRUCT); } + | TOK_UNION { $$ = std::make_unique(@$, AST_UNION); } + ; + +struct_body: opt_packed TOK_LCURL struct_member_list TOK_RCURL + ; + +opt_packed: + TOK_PACKED opt_signed_struct | + %empty { err_at_loc(@$, "Only PACKED supported at this time"); }; + +opt_signed_struct: + TOK_SIGNED { extra->astbuf2->is_signed = true; } + | TOK_UNSIGNED { extra->astbuf2->is_signed = false; } + | %empty // default is unsigned + ; + +struct_member_list: struct_member + | struct_member_list struct_member + ; + +struct_member: struct_member_type member_name_list TOK_SEMICOL { (void)extra->astbuf1.reset(); } + ; + +member_name_list: + member_name + | member_name_list TOK_COMMA member_name + ; + +member_name: TOK_ID { + extra->astbuf1->str = $1->substr(1); + extra->astbuf3 = extra->astbuf1->clone(); + log_assert(!extra->member_hack); + extra->member_hack = extra->astbuf3.get(); + SET_AST_NODE_LOC(extra->member_hack, @1, @1); + extra->astbuf2->children.push_back(std::move(extra->astbuf3)); + } range { + log_assert((bool)extra->member_hack); + if ($3) extra->member_hack->children.push_back(std::move($3)); + extra->member_hack = nullptr; + } + ; + +struct_member_type: { extra->astbuf1 = std::make_unique(@$, AST_STRUCT_ITEM); } member_type_token + ; + +member_type_token: + member_type range_or_multirange { + auto range = checkRange(extra->astbuf1.get(), std::move($2)); + if (range) + extra->astbuf1->children.push_back(std::move(range)); + } + | { + (void)extra->astbuf1.reset(); + } struct_union { + // stash state on extra->ast_stack + // sketchy! + extra->ast_stack.push_back(extra->astbuf2.release()); + extra->astbuf2 = std::move($2); + } struct_body { + extra->astbuf1 = std::move(extra->astbuf2); + // recover state + extra->astbuf2.reset(extra->ast_stack.back()); + extra->ast_stack.pop_back(); + } + ; + +member_type: type_atom type_signing + | type_vec type_signing + | hierarchical_type_id { extra->addWiretypeNode($1.get(), extra->astbuf1.get()); } + ; + +struct_var_list: struct_var + | struct_var_list TOK_COMMA struct_var + ; + +struct_var: + TOK_ID { + auto var_node = extra->astbuf2->clone(); + var_node->str = *$1; + SET_AST_NODE_LOC(var_node.get(), @1, @1); + extra->ast_stack.back()->children.push_back(std::move(var_node)); + }; + +///////// +// wire +///////// + +wire_decl: + attr wire_type range_or_multirange { + extra->albuf = std::move($1); + extra->astbuf1 = std::move($2); + extra->astbuf2 = checkRange(extra->astbuf1.get(), std::move($3)); + } delay wire_name_list { + (void)extra->astbuf1.reset(); + if (extra->astbuf2 != nullptr) + (void)extra->astbuf2.reset(); + extra->albuf.reset(); + } TOK_SEMICOL | + attr TOK_SUPPLY0 TOK_ID { + extra->ast_stack.back()->children.push_back(std::make_unique(@$, AST_WIRE)); + extra->ast_stack.back()->children.back()->str = *$3; + append_attr(extra->ast_stack.back()->children.back().get(), std::move($1)); + extra->ast_stack.back()->children.push_back(std::make_unique(@$, AST_ASSIGN, std::make_unique(@$, AST_IDENTIFIER), AstNode::mkconst_int(@$, 0, false, 1))); + extra->ast_stack.back()->children.back()->children[0]->str = *$3; + } opt_supply_wires TOK_SEMICOL | + attr TOK_SUPPLY1 TOK_ID { + extra->ast_stack.back()->children.push_back(std::make_unique(@$, AST_WIRE)); + extra->ast_stack.back()->children.back()->str = *$3; + append_attr(extra->ast_stack.back()->children.back().get(), std::move($1)); + extra->ast_stack.back()->children.push_back(std::make_unique(@$, AST_ASSIGN, std::make_unique(@$, AST_IDENTIFIER), AstNode::mkconst_int(@$, 1, false, 1))); + extra->ast_stack.back()->children.back()->children[0]->str = *$3; + } opt_supply_wires TOK_SEMICOL; + +opt_supply_wires: + %empty | + opt_supply_wires TOK_COMMA TOK_ID { + auto wire_node = extra->ast_stack.back()->children.at(GetSize(extra->ast_stack.back()->children)-2)->clone(); + auto assign_node = extra->ast_stack.back()->children.at(GetSize(extra->ast_stack.back()->children)-1)->clone(); + wire_node->str = *$3; + assign_node->children[0]->str = *$3; + extra->ast_stack.back()->children.push_back(std::move(wire_node)); + extra->ast_stack.back()->children.push_back(std::move(assign_node)); + }; + +wire_name_list: + wire_name_and_opt_assign | wire_name_list TOK_COMMA wire_name_and_opt_assign; + +wire_name_and_opt_assign: + wire_name { + bool attr_anyconst = false; + bool attr_anyseq = false; + bool attr_allconst = false; + bool attr_allseq = false; + if (extra->ast_stack.back()->children.back()->get_bool_attribute(ID::anyconst)) { + extra->ast_stack.back()->children.back()->attributes.erase(ID::anyconst); + attr_anyconst = true; + } + if (extra->ast_stack.back()->children.back()->get_bool_attribute(ID::anyseq)) { + extra->ast_stack.back()->children.back()->attributes.erase(ID::anyseq); + attr_anyseq = true; + } + if (extra->ast_stack.back()->children.back()->get_bool_attribute(ID::allconst)) { + extra->ast_stack.back()->children.back()->attributes.erase(ID::allconst); + attr_allconst = true; + } + if (extra->ast_stack.back()->children.back()->get_bool_attribute(ID::allseq)) { + extra->ast_stack.back()->children.back()->attributes.erase(ID::allseq); + attr_allseq = true; + } + if (extra->current_wire_rand || attr_anyconst || attr_anyseq || attr_allconst || attr_allseq) { + auto wire = std::make_unique(@$, AST_IDENTIFIER); + auto fcall = std::make_unique(@$, AST_FCALL); + wire->str = extra->ast_stack.back()->children.back()->str; + fcall->str = extra->current_wire_const ? "\\$anyconst" : "\\$anyseq"; + if (attr_anyconst) + fcall->str = "\\$anyconst"; + if (attr_anyseq) + fcall->str = "\\$anyseq"; + if (attr_allconst) + fcall->str = "\\$allconst"; + if (attr_allseq) + fcall->str = "\\$allseq"; + fcall->attributes[ID::reg] = AstNode::mkconst_str(@$, RTLIL::unescape_id(wire->str)); + extra->ast_stack.back()->children.push_back(std::make_unique(@$, AST_ASSIGN, std::move(wire), std::move(fcall))); + } + } | + wire_name TOK_EQ expr { + auto wire = std::make_unique(@$, AST_IDENTIFIER); + wire->str = extra->ast_stack.back()->children.back()->str; + if (extra->astbuf1->is_input) { + extra->astbuf1->attributes[ID::defaultvalue] = std::move($3); + } + else if (extra->astbuf1->is_reg || extra->astbuf1->is_logic){ + auto assign = std::make_unique(@$, AST_ASSIGN_LE, std::move(wire), std::move($3)); + SET_AST_NODE_LOC(assign.get(), @1, @3); + auto block = std::make_unique(@$, AST_BLOCK, std::move(assign)); + SET_AST_NODE_LOC(block.get(), @1, @3); + auto init = std::make_unique(@$, AST_INITIAL, std::move(block)); + SET_AST_NODE_LOC(init.get(), @1, @3); + + extra->ast_stack.back()->children.push_back(std::move(init)); + } + else { + auto assign = std::make_unique(@$, AST_ASSIGN, std::move(wire), std::move($3)); + SET_AST_NODE_LOC(assign.get(), @1, @3); + extra->ast_stack.back()->children.push_back(std::move(assign)); + } + + }; + +wire_name: + TOK_ID range_or_multirange { + if (extra->astbuf1 == nullptr) + err_at_loc(@1, "Internal error - should not happen - no AST_WIRE node."); + auto node = extra->astbuf1->clone(); + node->str = *$1; + append_attr_clone(node.get(), extra->albuf); + if (extra->astbuf2 != nullptr) + node->children.push_back(extra->astbuf2->clone()); + if ($2 != nullptr) { + if (node->is_input || node->is_output) + err_at_loc(@2, "input/output/inout ports cannot have unpacked dimensions."); + if (!extra->astbuf2 && !node->is_custom_type) { + addRange(node.get(), 0, 0, false); + } + rewriteAsMemoryNode(node.get(), std::move($2)); + } + if (extra->current_function_or_task) { + if (node->is_input || node->is_output) + node->port_id = extra->current_function_or_task_port_id++; + } else if (extra->ast_stack.back()->type == AST_GENBLOCK) { + if (node->is_input || node->is_output) + err_at_loc(@1, "Cannot declare module port `%s' within a generate block.", *$1); + } else { + if (extra->do_not_require_port_stubs && (node->is_input || node->is_output) && extra->port_stubs.count(*$1) == 0) { + extra->port_stubs[*$1] = ++extra->port_counter; + } + if (extra->port_stubs.count(*$1) != 0) { + if (!node->is_input && !node->is_output) + err_at_loc(@1, "Module port `%s' is neither input nor output.", *$1); + if (node->is_reg && node->is_input && !node->is_output && !mode->sv) + err_at_loc(@1, "Input port `%s' is declared as register.", *$1); + node->port_id = extra->port_stubs[*$1]; + extra->port_stubs.erase(*$1); + } else { + if (node->is_input || node->is_output) + err_at_loc(@1, "Module port `%s' is not declared in module header.", *$1); + } + } + //FIXME: for some reason, TOK_ID has a location which always points to one column *after* the real last column... + SET_AST_NODE_LOC(node.get(), @1, @1); + extra->ast_stack.back()->children.push_back(std::move(node)); + + }; + +assign_stmt: + TOK_ASSIGN delay assign_expr_list TOK_SEMICOL; + +assign_expr_list: + assign_expr | assign_expr_list TOK_COMMA assign_expr; + +assign_expr: + lvalue TOK_EQ expr { + AstNode* node = extra->saveChild(std::make_unique(@$, AST_ASSIGN, std::move($1), std::move($3))); + SET_AST_NODE_LOC(node, @$, @$); + }; + +type_name: TOK_ID { $$ = std::move($1); } // first time seen + | TOK_USER_TYPE { if (extra->isInLocalScope($1.get())) err_at_loc(@1, "Duplicate declaration of TYPEDEF '%s'", $1->c_str()+1); $$ = std::move($1); } + ; + +typedef_decl: + TOK_TYPEDEF typedef_base_type range_or_multirange type_name range_or_multirange TOK_SEMICOL { + extra->astbuf1 = std::move($2); + extra->astbuf2 = checkRange(extra->astbuf1.get(), std::move($3)); + bool has_a_range = (bool)extra->astbuf2; + if (extra->astbuf2) { + extra->astbuf1->children.push_back(std::move(extra->astbuf2)); + } + + if ($5 != nullptr) { + if (!has_a_range && !extra->astbuf1->is_custom_type) { + addRange(extra->astbuf1.get(), 0, 0, false); + } + rewriteAsMemoryNode(extra->astbuf1.get(), std::move($5)); + } + extra->addTypedefNode($4.get(), std::move(extra->astbuf1)); } + | TOK_TYPEDEF enum_struct_type type_name TOK_SEMICOL { extra->addTypedefNode($3.get(), std::move($2)); } + ; + +typedef_base_type: + hierarchical_type_id { + $$ = std::make_unique(@$, AST_WIRE); + $$->is_logic = true; + extra->addWiretypeNode($1.get(), $$.get()); + } | + integer_vector_type opt_signedness_default_unsigned { + $$ = std::make_unique(@$, AST_WIRE); + if ($1 == token::TOK_REG) { + $$->is_reg = true; + } else { + $$->is_logic = true; + } + $$->is_signed = $2; + } | + integer_atom_type opt_signedness_default_signed { + $$ = std::make_unique(@$, AST_WIRE); + $$->is_logic = true; + $$->is_signed = $2; + $$->range_left = $1 - 1; + $$->range_right = 0; + }; + +enum_struct_type: + enum_type { $$ = std::move($1); } + | struct_type { $$ = std::move($1); } + ; + +cell_stmt: + attr TOK_ID { + extra->astbuf1 = std::make_unique(@$, AST_CELL); + append_attr(extra->astbuf1.get(), std::move($1)); + extra->astbuf1->children.push_back(std::make_unique(@$, AST_CELLTYPE)); + extra->astbuf1->children[0]->str = *$2; + } cell_parameter_list_opt cell_list TOK_SEMICOL { + (void)extra->astbuf1.reset(); + } | + attr tok_prim_wrapper delay { + extra->astbuf1 = std::make_unique(@$, AST_PRIMITIVE); + extra->astbuf1->str = *$2; + append_attr(extra->astbuf1.get(), std::move($1)); + } prim_list TOK_SEMICOL { + (void)extra->astbuf1.reset(); + }; + +tok_prim_wrapper: + TOK_PRIMITIVE { + $$ = std::move($1); + } | + TOK_OR { + $$ = std::make_unique("or"); + }; + +cell_list: + single_cell | + cell_list TOK_COMMA single_cell; + +single_cell: + single_cell_no_array | single_cell_arraylist; + +single_cell_no_array: + TOK_ID { + extra->astbuf2 = extra->astbuf1->clone(); + if (extra->astbuf2->type != AST_PRIMITIVE) + extra->astbuf2->str = *$1; + // TODO optimize again + extra->cell_hack = extra->astbuf2.get(); + extra->ast_stack.back()->children.push_back(std::move(extra->astbuf2)); + } TOK_LPAREN cell_port_list TOK_RPAREN { + log_assert(extra->cell_hack); + SET_AST_NODE_LOC(extra->cell_hack, @1, @$); + extra->cell_hack = nullptr; + } + +single_cell_arraylist: + TOK_ID non_opt_range { + extra->astbuf2 = extra->astbuf1->clone(); + if (extra->astbuf2->type != AST_PRIMITIVE) + extra->astbuf2->str = *$1; + // TODO optimize again + extra->cell_hack = extra->astbuf2.get(); + extra->ast_stack.back()->children.push_back(std::make_unique(@$, AST_CELLARRAY, std::move($2), std::move(extra->astbuf2))); + } TOK_LPAREN cell_port_list TOK_RPAREN{ + log_assert(extra->cell_hack); + SET_AST_NODE_LOC(extra->cell_hack, @1, @$); + extra->cell_hack = nullptr; + }; + +cell_list_no_array: + single_cell_no_array | + cell_list_no_array TOK_COMMA single_cell_no_array; + +prim_list: + single_prim | + prim_list TOK_COMMA single_prim; + +single_prim: + single_cell | + /* no name */ { + extra->astbuf2 = extra->astbuf1->clone(); + log_assert(!extra->cell_hack); + extra->cell_hack = extra->astbuf2.get(); + // TODO optimize again + extra->ast_stack.back()->children.push_back(std::move(extra->astbuf2)); + } TOK_LPAREN cell_port_list TOK_RPAREN { + log_assert(extra->cell_hack); + SET_AST_NODE_LOC(extra->cell_hack, @1, @$); + extra->cell_hack = nullptr; + } + +cell_parameter_list_opt: + TOK_HASH TOK_LPAREN cell_parameter_list TOK_RPAREN | %empty; + +cell_parameter_list: + cell_parameter | cell_parameter_list TOK_COMMA cell_parameter; + +cell_parameter: + %empty | + expr { + auto node = std::make_unique(@$, AST_PARASET); + node->children.push_back(std::move($1)); + extra->astbuf1->children.push_back(std::move(node)); + } | + TOK_DOT TOK_ID TOK_LPAREN TOK_RPAREN { + // just ignore empty parameters + } | + TOK_DOT TOK_ID TOK_LPAREN expr TOK_RPAREN { + auto node = std::make_unique(@$, AST_PARASET); + node->str = *$2; + node->children.push_back(std::move($4)); + extra->astbuf1->children.push_back(std::move(node)); + }; + +cell_port_list: + cell_port_list_rules { + // remove empty args from end of list + while (!extra->cell_hack->children.empty()) { + auto& node = extra->cell_hack->children.back(); + if (node->type != AST_ARGUMENT) break; + if (!node->children.empty()) break; + if (!node->str.empty()) break; + extra->cell_hack->children.pop_back(); + } + + // check port types + bool has_positional_args = false; + bool has_named_args = false; + for (auto& node : extra->cell_hack->children) { + if (node->type != AST_ARGUMENT) continue; + if (node->str.empty()) + has_positional_args = true; + else + has_named_args = true; + } + + if (has_positional_args && has_named_args) + err_at_loc(@1, "Mix of positional and named cell ports."); + }; + +cell_port_list_rules: + cell_port | cell_port_list_rules TOK_COMMA cell_port; + +cell_port: + attr { + auto node = std::make_unique(@$, AST_ARGUMENT); + extra->cell_hack->children.push_back(std::move(node)); + } | + attr expr { + auto node = std::make_unique(@$, AST_ARGUMENT); + node->children.push_back(std::move($2)); + extra->cell_hack->children.push_back(std::move(node)); + } | + attr TOK_DOT TOK_ID TOK_LPAREN expr TOK_RPAREN { + auto node = std::make_unique(@$, AST_ARGUMENT); + node->str = *$3; + node->children.push_back(std::move($5)); + extra->cell_hack->children.push_back(std::move(node)); + } | + attr TOK_DOT TOK_ID TOK_LPAREN TOK_RPAREN { + auto node = std::make_unique(@$, AST_ARGUMENT); + node->str = *$3; + extra->cell_hack->children.push_back(std::move(node)); + } | + attr TOK_DOT TOK_ID { + auto node = std::make_unique(@$, AST_ARGUMENT); + node->str = *$3; + node->children.push_back(std::make_unique(@$, AST_IDENTIFIER)); + node->children.back()->str = *$3; + extra->cell_hack->children.push_back(std::move(node)); + } | + attr TOK_WILDCARD_CONNECT { + if (!mode->sv) + err_at_loc(@2, "Wildcard port connections are only supported in SystemVerilog mode."); + extra->cell_hack->attributes[ID::wildcard_port_conns] = AstNode::mkconst_int(@2, 1, false); + }; + +always_comb_or_latch: + TOK_ALWAYS_COMB { + $$ = false; + } | + TOK_ALWAYS_LATCH { + $$ = true; + }; + +always_or_always_ff: + TOK_ALWAYS { + $$ = false; + } | + TOK_ALWAYS_FF { + $$ = true; + }; + +always_stmt: + attr always_or_always_ff { + AstNode* node = extra->pushChild(std::make_unique(@$, AST_ALWAYS)); + append_attr(node, std::move($1)); + if ($2) + node->attributes[ID::always_ff] = AstNode::mkconst_int(@2, 1, false); + } always_cond { + (void)extra->pushChild(std::make_unique(@$, AST_BLOCK)); + } behavioral_stmt { + SET_AST_NODE_LOC(extra->ast_stack.back(), @6, @6); + extra->ast_stack.pop_back(); + + SET_AST_NODE_LOC(extra->ast_stack.back(), @2, @$); + extra->ast_stack.pop_back(); + + SET_RULE_LOC(@$, @2, @$); + } | + attr always_comb_or_latch { + AstNode* node = extra->pushChild(std::make_unique(@$, AST_ALWAYS)); + append_attr(node, std::move($1)); + if ($2) + node->attributes[ID::always_latch] = AstNode::mkconst_int(@2, 1, false); + else + node->attributes[ID::always_comb] = AstNode::mkconst_int(@2, 1, false); + (void)extra->pushChild(std::make_unique(@$, AST_BLOCK)); + } behavioral_stmt { + extra->ast_stack.pop_back(); + extra->ast_stack.pop_back(); + } | + attr TOK_INITIAL { + AstNode* node = extra->pushChild(std::make_unique(@$, AST_INITIAL)); + append_attr(node, std::move($1)); + (void)extra->pushChild(std::make_unique(@$, AST_BLOCK)); + } behavioral_stmt { + extra->ast_stack.pop_back(); + extra->ast_stack.pop_back(); + }; + +always_cond: + TOK_AT TOK_LPAREN always_events TOK_RPAREN | + TOK_AT TOK_LPAREN TOK_ASTER TOK_RPAREN | + TOK_AT ATTR_BEGIN TOK_RPAREN | + TOK_AT TOK_LPAREN ATTR_END | + TOK_AT TOK_ASTER | + %empty; + +always_events: + always_event | + always_events TOK_OR always_event | + always_events TOK_COMMA always_event; + +always_event: + TOK_POSEDGE expr { + auto node = std::make_unique(@$, AST_POSEDGE); + SET_AST_NODE_LOC(node.get(), @1, @1); + node->children.push_back(std::move($2)); + extra->ast_stack.back()->children.push_back(std::move(node)); + } | + TOK_NEGEDGE expr { + auto node = std::make_unique(@$, AST_NEGEDGE); + SET_AST_NODE_LOC(node.get(), @1, @1); + node->children.push_back(std::move($2)); + extra->ast_stack.back()->children.push_back(std::move(node)); + } | + expr { + auto node = std::make_unique(@$, AST_EDGE); + node->children.push_back(std::move($1)); + extra->ast_stack.back()->children.push_back(std::move(node)); + }; + +opt_label: + TOK_COL TOK_ID { + $$ = std::move($2); + } | + %empty { + $$ = nullptr; + }; + +opt_sva_label: + TOK_SVA_LABEL TOK_COL { + $$ = std::move($1); + } | + %empty { + $$ = nullptr; + }; + +opt_property: + TOK_PROPERTY { + $$ = true; + } | + TOK_FINAL { + $$ = false; + } | + %empty { + $$ = false; + }; + +modport_stmt: + TOK_MODPORT TOK_ID { + AstNode* modport = extra->pushChild(std::make_unique(@$, AST_MODPORT)); + modport->str = *$2; + + } modport_args_opt { + extra->ast_stack.pop_back(); + log_assert(extra->ast_stack.size() == 2); + } TOK_SEMICOL + +modport_args_opt: + TOK_LPAREN TOK_RPAREN | TOK_LPAREN modport_args optional_comma TOK_RPAREN; + +modport_args: + modport_arg | modport_args TOK_COMMA modport_arg; + +modport_arg: + modport_type_token modport_member | + modport_member + +modport_member: + TOK_ID { + AstNode* modport_member = extra->saveChild(std::make_unique(@$, AST_MODPORTMEMBER)); + modport_member->str = *$1; + modport_member->is_input = extra->current_modport_input; + modport_member->is_output = extra->current_modport_output; + + } + +modport_type_token: + TOK_INPUT {extra->current_modport_input = 1; extra->current_modport_output = 0;} | TOK_OUTPUT {extra->current_modport_input = 0; extra->current_modport_output = 1;} + +assert: + opt_sva_label TOK_ASSERT opt_property TOK_LPAREN expr TOK_RPAREN TOK_SEMICOL { + if (mode->noassert) { + + } else { + AstNode* node = extra->saveChild(std::make_unique(@$, mode->assume_asserts ? AST_ASSUME : AST_ASSERT, std::move($5))); + SET_AST_NODE_LOC(node, ($1 != nullptr ? @1 : @2), @6); + if ($1 != nullptr) + node->str = *$1; + } + } | + opt_sva_label TOK_ASSUME opt_property TOK_LPAREN expr TOK_RPAREN TOK_SEMICOL { + if (mode->noassume) { + } else { + AstNode* node = extra->saveChild(std::make_unique(@$, mode->assert_assumes ? AST_ASSERT : AST_ASSUME, std::move($5))); + SET_AST_NODE_LOC(node, ($1 != nullptr ? @1 : @2), @6); + if ($1 != nullptr) + node->str = *$1; + } + } | + opt_sva_label TOK_ASSERT opt_property TOK_LPAREN TOK_EVENTUALLY expr TOK_RPAREN TOK_SEMICOL { + if (mode->noassert) { + } else { + AstNode* node = extra->saveChild(std::make_unique(@$, mode->assume_asserts ? AST_FAIR : AST_LIVE, std::move($6))); + SET_AST_NODE_LOC(node, ($1 != nullptr ? @1 : @2), @7); + if ($1 != nullptr) + node->str = *$1; + } + } | + opt_sva_label TOK_ASSUME opt_property TOK_LPAREN TOK_EVENTUALLY expr TOK_RPAREN TOK_SEMICOL { + if (mode->noassume) { + } else { + AstNode* node = extra->saveChild(std::make_unique(@$, mode->assert_assumes ? AST_LIVE : AST_FAIR, std::move($6))); + SET_AST_NODE_LOC(node, ($1 != nullptr ? @1 : @2), @7); + if ($1 != nullptr) + node->str = *$1; + } + } | + opt_sva_label TOK_COVER opt_property TOK_LPAREN expr TOK_RPAREN TOK_SEMICOL { + AstNode* node = extra->saveChild(std::make_unique(@$, AST_COVER, std::move($5))); + SET_AST_NODE_LOC(node, ($1 != nullptr ? @1 : @2), @6); + if ($1 != nullptr) { + node->str = *$1; + } + } | + opt_sva_label TOK_COVER opt_property TOK_LPAREN TOK_RPAREN TOK_SEMICOL { + AstNode* node = extra->saveChild(std::make_unique(@$, AST_COVER, AstNode::mkconst_int(@$, 1, false))); + SET_AST_NODE_LOC(node, ($1 != nullptr ? @1 : @2), @5); + if ($1 != nullptr) { + node->str = *$1; + } + } | + opt_sva_label TOK_COVER TOK_SEMICOL { + AstNode* node = extra->saveChild(std::make_unique(@$, AST_COVER, AstNode::mkconst_int(@$, 1, false))); + SET_AST_NODE_LOC(node, ($1 != nullptr ? @1 : @2), @2); + if ($1 != nullptr) { + node->str = *$1; + } + } | + opt_sva_label TOK_RESTRICT opt_property TOK_LPAREN expr TOK_RPAREN TOK_SEMICOL { + if (mode->norestrict) { + } else { + AstNode* node = extra->saveChild(std::make_unique(@$, AST_ASSUME, std::move($5))); + SET_AST_NODE_LOC(node, ($1 != nullptr ? @1 : @2), @6); + if ($1 != nullptr) + node->str = *$1; + } + if (!$3) + warn_at_loc(@3, "SystemVerilog does not allow \"restrict\" without \"property\"."); + } | + opt_sva_label TOK_RESTRICT opt_property TOK_LPAREN TOK_EVENTUALLY expr TOK_RPAREN TOK_SEMICOL { + if (mode->norestrict) { + } else { + AstNode* node = extra->saveChild(std::make_unique(@$, AST_FAIR, std::move($6))); + SET_AST_NODE_LOC(node, ($1 != nullptr ? @1 : @2), @7); + if ($1 != nullptr) + node->str = *$1; + } + if (!$3) + warn_at_loc(@3, "SystemVerilog does not allow \"restrict\" without \"property\"."); + }; + +assert_property: + opt_sva_label TOK_ASSERT TOK_PROPERTY TOK_LPAREN expr TOK_RPAREN TOK_SEMICOL { + AstNode* node = extra->saveChild(std::make_unique(@$, mode->assume_asserts ? AST_ASSUME : AST_ASSERT, std::move($5))); + SET_AST_NODE_LOC(node, @1, @6); + if ($1 != nullptr) { + extra->ast_stack.back()->children.back()->str = *$1; + } + } | + opt_sva_label TOK_ASSUME TOK_PROPERTY TOK_LPAREN expr TOK_RPAREN TOK_SEMICOL { + AstNode* node = extra->saveChild(std::make_unique(@$, AST_ASSUME, std::move($5))); + SET_AST_NODE_LOC(node, @1, @6); + if ($1 != nullptr) { + extra->ast_stack.back()->children.back()->str = *$1; + } + } | + opt_sva_label TOK_ASSERT TOK_PROPERTY TOK_LPAREN TOK_EVENTUALLY expr TOK_RPAREN TOK_SEMICOL { + AstNode* node = extra->saveChild(std::make_unique(@$, mode->assume_asserts ? AST_FAIR : AST_LIVE, std::move($6))); + SET_AST_NODE_LOC(node, @1, @7); + if ($1 != nullptr) { + extra->ast_stack.back()->children.back()->str = *$1; + } + } | + opt_sva_label TOK_ASSUME TOK_PROPERTY TOK_LPAREN TOK_EVENTUALLY expr TOK_RPAREN TOK_SEMICOL { + AstNode* node = extra->saveChild(std::make_unique(@$, AST_FAIR, std::move($6))); + SET_AST_NODE_LOC(node, @1, @7); + if ($1 != nullptr) { + extra->ast_stack.back()->children.back()->str = *$1; + } + } | + opt_sva_label TOK_COVER TOK_PROPERTY TOK_LPAREN expr TOK_RPAREN TOK_SEMICOL { + AstNode* node = extra->saveChild(std::make_unique(@$, AST_COVER, std::move($5))); + SET_AST_NODE_LOC(node, @1, @6); + if ($1 != nullptr) { + extra->ast_stack.back()->children.back()->str = *$1; + } + } | + opt_sva_label TOK_RESTRICT TOK_PROPERTY TOK_LPAREN expr TOK_RPAREN TOK_SEMICOL { + if (mode->norestrict) { + } else { + AstNode* node = extra->saveChild(std::make_unique(@$, AST_ASSUME, std::move($5))); + SET_AST_NODE_LOC(node, @1, @6); + if ($1 != nullptr) { + extra->ast_stack.back()->children.back()->str = *$1; + } + } + } | + opt_sva_label TOK_RESTRICT TOK_PROPERTY TOK_LPAREN TOK_EVENTUALLY expr TOK_RPAREN TOK_SEMICOL { + if (mode->norestrict) { + } else { + AstNode* node = extra->saveChild(std::make_unique(@$, AST_FAIR, std::move($6))); + SET_AST_NODE_LOC(node, @1, @7); + if ($1 != nullptr) { + extra->ast_stack.back()->children.back()->str = *$1; + } + } + }; + +simple_behavioral_stmt: + attr lvalue TOK_EQ delay expr { + AstNode* node = extra->saveChild(std::make_unique(@$, AST_ASSIGN_EQ, std::move($2), std::move($5))); + SET_AST_NODE_LOC(node, @2, @5); + append_attr(node, std::move($1)); + } | + attr lvalue attr inc_or_dec_op { + extra->addIncOrDecStmt(std::move($1), std::move($2), std::move($3), $4, location_range(@1, @4)); + } | + attr inc_or_dec_op attr lvalue { + extra->addIncOrDecStmt(std::move($1), std::move($4), std::move($3), $2, location_range(@1, @4)); + } | + attr lvalue OP_LE delay expr { + AstNode* node = extra->saveChild(std::make_unique(@$, AST_ASSIGN_LE, std::move($2), std::move($5))); + SET_AST_NODE_LOC(node, @2, @5); + append_attr(node, std::move($1)); + } | + attr lvalue asgn_binop delay expr { + (void)extra->addAsgnBinopStmt(std::move($1), std::move($2), $3, std::move($5)); + }; + +asgn_binop: + TOK_BIT_OR_ASSIGN { $$ = AST_BIT_OR; } | + TOK_BIT_AND_ASSIGN { $$ = AST_BIT_AND; } | + TOK_BIT_XOR_ASSIGN { $$ = AST_BIT_XOR; } | + TOK_ADD_ASSIGN { $$ = AST_ADD; } | + TOK_SUB_ASSIGN { $$ = AST_SUB; } | + TOK_DIV_ASSIGN { $$ = AST_DIV; } | + TOK_MOD_ASSIGN { $$ = AST_MOD; } | + TOK_MUL_ASSIGN { $$ = AST_MUL; } | + TOK_SHL_ASSIGN { $$ = AST_SHIFT_LEFT; } | + TOK_SHR_ASSIGN { $$ = AST_SHIFT_RIGHT; } | + TOK_SSHL_ASSIGN { $$ = AST_SHIFT_SLEFT; } | + TOK_SSHR_ASSIGN { $$ = AST_SHIFT_SRIGHT; } ; + +inc_or_dec_op: + // NOTE: These should only be permitted in SV mode, but Yosys has + // allowed them in all modes since support for them was added in 2017. + TOK_INCREMENT { $$ = AST_ADD; } | + TOK_DECREMENT { $$ = AST_SUB; } ; + +for_initialization: + TOK_ID TOK_EQ expr { + auto ident = std::make_unique(@$, AST_IDENTIFIER); + ident->str = *$1; + auto node = std::make_unique(@$, AST_ASSIGN_EQ, std::move(ident), std::move($3)); + SET_AST_NODE_LOC(node.get(), @1, @3); + extra->ast_stack.back()->children.push_back(std::move(node)); + } | + non_io_wire_type range TOK_ID { + err_at_loc(@3, "For loop variable declaration is missing initialization!"); + } | + non_io_wire_type range TOK_ID TOK_EQ expr { + if (!mode->sv) + err_at_loc(@4, "For loop inline variable declaration is only supported in SystemVerilog mode!"); + + // loop variable declaration + auto wire = std::move($1); + auto range = checkRange(wire.get(), std::move($2)); + SET_AST_NODE_LOC(wire.get(), @1, @3); + SET_AST_NODE_LOC(range.get(), @2, @2); + if (range != nullptr) + wire->children.push_back(std::move(range)); + + auto ident = std::make_unique(@$, AST_IDENTIFIER); + ident->str = *$3; + wire->str = *$3; + + AstNode *parent = extra->ast_stack.at(extra->ast_stack.size() - 2); + auto& loop = parent->children.back(); + log_assert(extra->ast_stack.back() == loop.get()); + + // loop variable initialization + SET_AST_NODE_LOC(ident.get(), @3, @3); + auto asgn = std::make_unique(@$, AST_ASSIGN_EQ, std::move(ident), std::move($5)); + SET_AST_NODE_LOC(asgn.get(), @3, @5); + loop->children.push_back(std::move(asgn)); + + // inject a wrapping block to declare the loop variable and + // contain the current loop + auto wrapper = std::make_unique(@$, AST_BLOCK); + wrapper->str = "$fordecl_block$" + std::to_string(ast_autoidx()); + wrapper->children.push_back(std::move(wire)); + wrapper->children.push_back(std::move(loop)); + parent->children.back() = std::move(wrapper); + }; + +// this production creates the obligatory if-else shift/reduce conflict +behavioral_stmt: + defattr | assert | wire_decl | param_decl | localparam_decl | typedef_decl | + non_opt_delay behavioral_stmt | + simple_behavioral_stmt TOK_SEMICOL | + attr TOK_SEMICOL | + attr hierarchical_id { + AstNode* node = extra->pushChild(std::make_unique(@$, AST_TCALL)); + node->str = *$2; + append_attr(node, std::move($1)); + } opt_arg_list TOK_SEMICOL{ + SET_AST_NODE_LOC(extra->ast_stack.back(), @2, @5); + extra->ast_stack.pop_back(); + } | + attr TOK_MSG_TASKS { + AstNode* node = extra->pushChild(std::make_unique(@$, AST_TCALL)); + node->str = *$2; + append_attr(node, std::move($1)); + } opt_arg_list TOK_SEMICOL{ + SET_AST_NODE_LOC(extra->ast_stack.back(), @2, @5); + extra->ast_stack.pop_back(); + } | + attr TOK_BEGIN { + extra->enterTypeScope(); + } opt_label { + AstNode* node = extra->pushChild(std::make_unique(@$, AST_BLOCK)); + append_attr(node, std::move($1)); + if ($4 != nullptr) + node->str = *$4; + } behavioral_stmt_list TOK_END opt_label { + extra->exitTypeScope(); + checkLabelsMatch(@8, "Begin label", $4.get(), $8.get()); + AstNode *node = extra->ast_stack.back(); + // In SystemVerilog, unnamed blocks with block item declarations + // create an implicit hierarchy scope + if (mode->sv && node->str.empty()) + for (auto& child : node->children) + if (child->type == AST_WIRE || child->type == AST_MEMORY || child->type == AST_PARAMETER + || child->type == AST_LOCALPARAM || child->type == AST_TYPEDEF) { + node->str = "$unnamed_block$" + std::to_string(ast_autoidx()); + break; + } + SET_AST_NODE_LOC(extra->ast_stack.back(), @2, @8); + extra->ast_stack.pop_back(); + } | + attr TOK_FOR TOK_LPAREN { + AstNode* node = extra->pushChild(std::make_unique(@$, AST_FOR)); + append_attr(node, std::move($1)); + } for_initialization TOK_SEMICOL expr { + extra->ast_stack.back()->children.push_back(std::move($7)); + } TOK_SEMICOL simple_behavioral_stmt TOK_RPAREN { + AstNode* block = extra->pushChild(std::make_unique(@$, AST_BLOCK)); + block->str = "$for_loop$" + std::to_string(ast_autoidx()); + } behavioral_stmt { + SET_AST_NODE_LOC(extra->ast_stack.back(), @13, @13); + extra->ast_stack.pop_back(); + SET_AST_NODE_LOC(extra->ast_stack.back(), @2, @13); + extra->ast_stack.pop_back(); + } | + attr TOK_WHILE TOK_LPAREN expr TOK_RPAREN { + AstNode* node = extra->pushChild(std::make_unique(@$, AST_WHILE)); + append_attr(node, std::move($1)); + auto block_owned = std::make_unique(@$, AST_BLOCK); + auto* block = block_owned.get(); + extra->ast_stack.back()->children.push_back(std::move($4)); + extra->ast_stack.back()->children.push_back(std::move(block_owned)); + extra->ast_stack.push_back(block); + } behavioral_stmt { + SET_AST_NODE_LOC(extra->ast_stack.back(), @7, @7); + extra->ast_stack.pop_back(); + extra->ast_stack.pop_back(); + } | + attr TOK_REPEAT TOK_LPAREN expr TOK_RPAREN { + AstNode* node = extra->pushChild(std::make_unique(@$, AST_REPEAT)); + append_attr(node, std::move($1)); + auto block_owned = std::make_unique(@$, AST_BLOCK); + auto* block = block_owned.get(); + extra->ast_stack.back()->children.push_back(std::move($4)); + extra->ast_stack.back()->children.push_back(std::move(block_owned)); + extra->ast_stack.push_back(block); + } behavioral_stmt { + SET_AST_NODE_LOC(extra->ast_stack.back(), @7, @7); + extra->ast_stack.pop_back(); + extra->ast_stack.pop_back(); + } | + if_attr TOK_IF TOK_LPAREN expr TOK_RPAREN { + std::unique_ptr node_owned; + AstNode* node = nullptr; + AstNode *context = extra->ast_stack.back(); + bool patch_block_on_stack = false; + if (context && context->type == AST_BLOCK && context->get_bool_attribute(ID::promoted_if)) { + AstNode *outer = extra->ast_stack[extra->ast_stack.size() - 2]; + log_assert (outer && outer->type == AST_CASE); + if (outer->get_bool_attribute(ID::parallel_case)) { + // parallel "else if": append condition to outer "if" + node = outer; + log_assert (node->children.size()); + node->children.pop_back(); + // `context` has been killed as a grandchild of `outer` + // we have to undangle it from the stack + patch_block_on_stack = true; + } else if (outer->get_bool_attribute(ID::full_case)) + (*$1)[ID::str(ID::full_case)] = AstNode::mkconst_int(@$, 1, false); + } + auto expr = std::make_unique(@$, AST_REDUCE_BOOL, std::move($4)); + if (!node) { + // not parallel "else if": begin new construction + node_owned = std::make_unique(@$, AST_CASE); + node = node_owned.get(); + append_attr(node, std::move($1)); + node->children.push_back(node->get_bool_attribute(ID::parallel_case) ? AstNode::mkconst_int(@$, 1, false, 1) : expr->clone()); + extra->ast_stack.back()->children.push_back(std::move(node_owned)); + } + auto block_owned = std::make_unique(@$, AST_BLOCK); + auto* block = block_owned.get(); + auto cond_owned = std::make_unique(@$, AST_COND, node->get_bool_attribute(ID::parallel_case) ? std::move(expr) : AstNode::mkconst_int(@$, 1, false, 1), std::move(block_owned)); + SET_AST_NODE_LOC(cond_owned.get(), @4, @4); + node->children.push_back(std::move(cond_owned)); + // Double it and give it to the next person + if (patch_block_on_stack) + extra->ast_stack.back() = block; + extra->ast_stack.push_back(node); + extra->ast_stack.push_back(block); + } behavioral_stmt { + SET_AST_NODE_LOC(extra->ast_stack.back(), @7, @7); + } optional_else { + extra->ast_stack.pop_back(); + SET_AST_NODE_LOC(extra->ast_stack.back(), @2, @9); + extra->ast_stack.pop_back(); + } | + case_attr case_type TOK_LPAREN expr TOK_RPAREN { + AstNode* node = extra->pushChild(std::make_unique(@$, AST_CASE, std::move($4))); + append_attr(node, std::move($1)); + SET_AST_NODE_LOC(extra->ast_stack.back(), @4, @4); + } opt_synopsys_attr case_body TOK_ENDCASE { + SET_AST_NODE_LOC(extra->ast_stack.back(), @2, @9); + extra->case_type_stack.pop_back(); + extra->ast_stack.pop_back(); + }; + +if_attr: + attr { + $$ = std::move($1); + } | + attr TOK_UNIQUE0 { + AstNode *context = extra->ast_stack.back(); + if (context && context->type == AST_BLOCK && context->get_bool_attribute(ID::promoted_if)) + err_at_loc(@2, "unique0 keyword cannot be used for 'else if' branch."); + (*$1)[ID::str(ID::parallel_case)] = AstNode::mkconst_int(@$, 1, false); + $$ = std::move($1); + } | + attr TOK_PRIORITY { + AstNode *context = extra->ast_stack.back(); + if (context && context->type == AST_BLOCK && context->get_bool_attribute(ID::promoted_if)) + err_at_loc(@2, "priority keyword cannot be used for 'else if' branch."); + (*$1)[ID::str(ID::full_case)] = AstNode::mkconst_int(@$, 1, false); + $$ = std::move($1); + } | + attr TOK_UNIQUE { + AstNode *context = extra->ast_stack.back(); + if (context && context->type == AST_BLOCK && context->get_bool_attribute(ID::promoted_if)) + err_at_loc(@2, "unique keyword cannot be used for 'else if' branch."); + (*$1)[ID::str(ID::full_case)] = AstNode::mkconst_int(@$, 1, false); + (*$1)[ID::str(ID::parallel_case)] = AstNode::mkconst_int(@$, 1, false); + $$ = std::move($1); + }; + +case_attr: + attr { + $$ = std::move($1); + } | + attr TOK_UNIQUE0 { + (*$1)[ID::str(ID::parallel_case)] = AstNode::mkconst_int(@$, 1, false); + $$ = std::move($1); + } | + attr TOK_PRIORITY { + (*$1)[ID::str(ID::full_case)] = AstNode::mkconst_int(@$, 1, false); + $$ = std::move($1); + } | + attr TOK_UNIQUE { + (*$1)[ID::str(ID::full_case)] = AstNode::mkconst_int(@$, 1, false); + (*$1)[ID::str(ID::parallel_case)] = AstNode::mkconst_int(@$, 1, false); + $$ = std::move($1); + }; + +case_type: + TOK_CASE { + extra->case_type_stack.push_back(0); + } | + TOK_CASEX { + extra->case_type_stack.push_back('x'); + } | + TOK_CASEZ { + extra->case_type_stack.push_back('z'); + }; + +opt_synopsys_attr: + opt_synopsys_attr TOK_SYNOPSYS_FULL_CASE { + if (extra->ast_stack.back()->attributes.count(ID::full_case) == 0) + extra->ast_stack.back()->attributes[ID::full_case] = AstNode::mkconst_int(@$, 1, false); + } | + opt_synopsys_attr TOK_SYNOPSYS_PARALLEL_CASE { + if (extra->ast_stack.back()->attributes.count(ID::parallel_case) == 0) + extra->ast_stack.back()->attributes[ID::parallel_case] = AstNode::mkconst_int(@$, 1, false); + } | + %empty; + +behavioral_stmt_list: + behavioral_stmt_list behavioral_stmt | + %empty; + +optional_else: + TOK_ELSE { + extra->ast_stack.pop_back(); + auto block_owned = std::make_unique(@$, AST_BLOCK); + auto* block = block_owned.get(); + block->attributes[ID::promoted_if] = AstNode::mkconst_int(@$, 1, false); + AstNode* cond = extra->saveChild( + std::make_unique(@$, AST_COND, + std::make_unique(@$, AST_DEFAULT), + std::move(block_owned))); + extra->ast_stack.push_back(block); + SET_AST_NODE_LOC(cond, @1, @1); + } behavioral_stmt { + SET_AST_NODE_LOC(extra->ast_stack.back(), @3, @3); + } | + %empty %prec FAKE_THEN; + +case_body: + case_body case_item | + %empty; + +case_item: + { + (void)extra->pushChild(std::make_unique( + @$, + extra->case_type_stack.size() && extra->case_type_stack.back() == 'x' ? AST_CONDX : + extra->case_type_stack.size() && extra->case_type_stack.back() == 'z' ? AST_CONDZ : AST_COND)); + } case_select { + (void)extra->pushChild(std::make_unique(@$, AST_BLOCK)); + extra->case_type_stack.push_back(0); + } behavioral_stmt { + extra->case_type_stack.pop_back(); + SET_AST_NODE_LOC(extra->ast_stack.back(), @4, @4); + extra->ast_stack.pop_back(); + extra->ast_stack.pop_back(); + }; + +gen_case_body: + gen_case_body gen_case_item | + %empty; + +gen_case_item: + { + (void)extra->pushChild(std::make_unique( + @$, + extra->case_type_stack.size() && extra->case_type_stack.back() == 'x' ? AST_CONDX : + extra->case_type_stack.size() && extra->case_type_stack.back() == 'z' ? AST_CONDZ : AST_COND)); + } case_select { + extra->case_type_stack.push_back(0); + SET_AST_NODE_LOC(extra->ast_stack.back(), @2, @2); + } gen_stmt_block { + extra->case_type_stack.pop_back(); + extra->ast_stack.pop_back(); + }; + +case_select: + case_expr_list TOK_COL | + TOK_DEFAULT; + +case_expr_list: + TOK_DEFAULT { + AstNode* node = extra->saveChild(std::make_unique(@$, AST_DEFAULT)); + SET_AST_NODE_LOC(node, @1, @1); + } | + TOK_SVA_LABEL { + AstNode* node = extra->saveChild(std::make_unique(@$, AST_IDENTIFIER)); + node->str = *$1; + SET_AST_NODE_LOC(node, @1, @1); + } | + expr { + extra->ast_stack.back()->children.push_back(std::move($1)); + } | + case_expr_list TOK_COMMA expr { + extra->ast_stack.back()->children.push_back(std::move($3)); + }; + +rvalue: + hierarchical_id TOK_LBRA expr TOK_RBRA TOK_DOT rvalue { + $$ = std::make_unique(@$, AST_PREFIX, std::move($3), std::move($6)); + $$->str = *$1; + SET_AST_NODE_LOC($$.get(), @1, @6); + } | + hierarchical_id range { + $$ = std::make_unique(@$, AST_IDENTIFIER, std::move($2)); + $$->str = *$1; + SET_AST_NODE_LOC($$.get(), @1, @1); + if ($2 == nullptr && ($$->str == "\\$initstate" || + $$->str == "\\$anyconst" || $$->str == "\\$anyseq" || + $$->str == "\\$allconst" || $$->str == "\\$allseq")) + $$->type = AST_FCALL; + } | + hierarchical_id non_opt_multirange { + $$ = std::make_unique(@$, AST_IDENTIFIER, std::move($2)); + $$->str = *$1; + SET_AST_NODE_LOC($$.get(), @1, @1); + }; + +lvalue: + rvalue { + $$ = std::move($1); + } | + TOK_LCURL lvalue_concat_list TOK_RCURL { + $$ = std::move($2); + }; + +lvalue_concat_list: + expr { + $$ = std::make_unique(@$, AST_CONCAT); + $$->children.push_back(std::move($1)); + } | + expr TOK_COMMA lvalue_concat_list { + $$ = std::move($3); + $$->children.push_back(std::move($1)); + }; + +opt_arg_list: + TOK_LPAREN arg_list optional_comma TOK_RPAREN | + %empty; + +arg_list: + arg_list2 | + %empty; + +arg_list2: + single_arg | + arg_list TOK_COMMA single_arg; + +single_arg: + expr { + extra->ast_stack.back()->children.push_back(std::move($1)); + }; + +module_gen_body: + module_gen_body gen_stmt_or_module_body_stmt | + module_gen_body gen_block | + %empty; + +gen_stmt_or_module_body_stmt: + gen_stmt | module_body_stmt | + attr TOK_SEMICOL; + +genvar_identifier: + TOK_ID { + $$ = std::make_unique(@$, AST_IDENTIFIER); + $$->str = *$1; + }; + +genvar_initialization: + TOK_GENVAR genvar_identifier { + err_at_loc(@2, "Generate for loop variable declaration is missing initialization!"); + } | + TOK_GENVAR genvar_identifier TOK_EQ expr { + if (!mode->sv) + err_at_loc(@3, "Generate for loop inline variable declaration is only supported in SystemVerilog mode!"); + AstNode* node = extra->saveChild(std::make_unique(@$, AST_GENVAR)); + node->is_reg = true; + node->is_signed = true; + node->range_left = 31; + node->range_right = 0; + node->str = $2->str; + node->children.push_back(checkRange(node, nullptr)); + SET_AST_NODE_LOC(node, @1, @4); + node = extra->saveChild(std::make_unique(@$, AST_ASSIGN_EQ, std::move($2), std::move($4))); + SET_AST_NODE_LOC(node, @1, @4); + } | + genvar_identifier TOK_EQ expr { + AstNode* node = extra->saveChild(std::make_unique(@$, AST_ASSIGN_EQ, std::move($1), std::move($3))); + SET_AST_NODE_LOC(node, @1, @3); + }; + +// this production creates the obligatory if-else shift/reduce conflict +gen_stmt: + TOK_FOR TOK_LPAREN { + (void)extra->pushChild(std::make_unique(@$, AST_GENFOR)); + } genvar_initialization TOK_SEMICOL expr { + extra->ast_stack.back()->children.push_back(std::move($6)); + } TOK_SEMICOL simple_behavioral_stmt TOK_RPAREN gen_stmt_block { + SET_AST_NODE_LOC(extra->ast_stack.back(), @1, @11); + extra->rewriteGenForDeclInit(extra->ast_stack.back()); + extra->ast_stack.pop_back(); + } | + TOK_IF TOK_LPAREN expr TOK_RPAREN { + (void)extra->pushChild(std::make_unique(@$, AST_GENIF)); + extra->ast_stack.back()->children.push_back(std::move($3)); + } gen_stmt_block opt_gen_else { + SET_AST_NODE_LOC(extra->ast_stack.back(), @1, @7); + extra->ast_stack.pop_back(); + } | + case_type TOK_LPAREN expr TOK_RPAREN { + (void)extra->pushChild(std::make_unique(@$, AST_GENCASE, std::move($3))); + } gen_case_body TOK_ENDCASE { + extra->case_type_stack.pop_back(); + SET_AST_NODE_LOC(extra->ast_stack.back(), @1, @7); + extra->ast_stack.pop_back(); + } | + TOK_MSG_TASKS { + AstNode* node = extra->pushChild(std::make_unique(@$, AST_TECALL)); + node->str = *$1; + } opt_arg_list TOK_SEMICOL{ + SET_AST_NODE_LOC(extra->ast_stack.back(), @1, @3); + extra->ast_stack.pop_back(); + }; + +gen_block: + TOK_BEGIN { + extra->enterTypeScope(); + } opt_label { + AstNode* node = extra->pushChild(std::make_unique(@$, AST_GENBLOCK)); + node->str = $3 ? *$3 : std::string(); + } module_gen_body TOK_END opt_label { + extra->exitTypeScope(); + checkLabelsMatch(@7, "Begin label", $3.get(), $7.get()); + SET_AST_NODE_LOC(extra->ast_stack.back(), @1, @7); + extra->ast_stack.pop_back(); + }; + +// result is wrapped in a genblock only if necessary +gen_stmt_block: + { + (void)extra->pushChild(std::make_unique(@$, AST_GENBLOCK)); + } gen_stmt_or_module_body_stmt { + SET_AST_NODE_LOC(extra->ast_stack.back(), @2, @2); + extra->ast_stack.pop_back(); + } | gen_block; + +opt_gen_else: + TOK_ELSE gen_stmt_block | %empty %prec FAKE_THEN; + +expr: + basic_expr { + $$ = std::move($1); + } | + basic_expr TOK_QUE attr expr TOK_COL expr { + $$ = std::make_unique(@$, AST_TERNARY); + $$->children.push_back(std::move($1)); + $$->children.push_back(std::move($4)); + $$->children.push_back(std::move($6)); + SET_AST_NODE_LOC($$.get(), @1, @$); + append_attr($$.get(), std::move($3)); + } | + inc_or_dec_op attr rvalue { + $$ = extra->addIncOrDecExpr(std::move($3), std::move($2), $1, location_range(@1, @3), false, mode->sv); + } | + // TODO: Attributes are allowed in the middle here, but they create some + // non-trivial conflicts that don't seem worth solving for now. + rvalue inc_or_dec_op { + $$ = extra->addIncOrDecExpr(std::move($1), nullptr, $2, location_range(@1, @2), true, mode->sv); + }; + +basic_expr: + rvalue { + $$ = std::move($1); + } | + TOK_LPAREN expr TOK_RPAREN integral_number { + if ($4->compare(0, 1, "'") != 0) + err_at_loc(@4, "Cast operation must be applied on sized constants e.g. () , while %s is not a sized constant.", *$4); + ConstParser p{@4}; + auto val = p.const2ast(*$4, extra->case_type_stack.size() == 0 ? 0 : extra->case_type_stack.back(), !mode->lib); + if (val == nullptr) + log_error("Value conversion failed: `%s'\n", *$4); + $$ = std::make_unique(@$, AST_TO_BITS, std::move($2), std::move(val)); + } | + hierarchical_id integral_number { + if ($2->compare(0, 1, "'") != 0) + err_at_loc(@2, "Cast operation must be applied on sized constants, e.g. \'d0, while %s is not a sized constant.", *$2); + auto bits = std::make_unique(@$, AST_IDENTIFIER); + bits->str = *$1; + SET_AST_NODE_LOC(bits.get(), @1, @1); + ConstParser p{@2}; + auto val = p.const2ast(*$2, extra->case_type_stack.size() == 0 ? 0 : extra->case_type_stack.back(), !mode->lib); + SET_AST_NODE_LOC(val.get(), @2, @2); + if (val == nullptr) + log_error("Value conversion failed: `%s'\n", *$2); + $$ = std::make_unique(@$, AST_TO_BITS, std::move(bits), std::move(val)); + } | + integral_number { + ConstParser p{@1}; + $$ = p.const2ast(*$1, extra->case_type_stack.size() == 0 ? 0 : extra->case_type_stack.back(), !mode->lib); + SET_AST_NODE_LOC($$.get(), @1, @1); + if ($$ == nullptr) + log_error("Value conversion failed: `%s'\n", *$1); + } | + TOK_REALVAL { + $$ = std::make_unique(@$, AST_REALVALUE); + char *p = (char*)malloc(GetSize(*$1) + 1), *q; + for (int i = 0, j = 0; j < GetSize(*$1); j++) + if ((*$1)[j] != '_') + p[i++] = (*$1)[j], p[i] = 0; + $$->realvalue = strtod(p, &q); + SET_AST_NODE_LOC($$.get(), @1, @1); + log_assert(*q == 0); + free(p); + } | + TOK_STRING { + $$ = AstNode::mkconst_str(@1, *$1); + SET_AST_NODE_LOC($$.get(), @1, @1); + } | + hierarchical_id attr { + // Here we use "Typed Midrule Actions". + // https://www.gnu.org/software/bison/manual/html_node/Typed-Midrule-Actions.html + auto fcall = std::make_unique(@1, AST_FCALL); + AstNode *fcall_node = fcall.get(); + fcall_node->str = *$1; + extra->ast_stack.push_back(fcall_node); + SET_AST_NODE_LOC(fcall_node, @1, @1); + append_attr(fcall_node, std::move($2)); + $$ = std::move(fcall); + } TOK_LPAREN arg_list optional_comma TOK_RPAREN { + log_assert($3 != nullptr); + $$ = std::move($3); + extra->ast_stack.pop_back(); + } | + TOK_TO_SIGNED attr TOK_LPAREN expr TOK_RPAREN { + $$ = std::make_unique(@$, AST_TO_SIGNED, std::move($4)); + append_attr($$.get(), std::move($2)); + } | + TOK_TO_UNSIGNED attr TOK_LPAREN expr TOK_RPAREN { + $$ = std::make_unique(@$, AST_TO_UNSIGNED, std::move($4)); + append_attr($$.get(), std::move($2)); + } | + TOK_LPAREN expr TOK_RPAREN { + $$ = std::move($2); + } | + TOK_LPAREN expr TOK_COL expr TOK_COL expr TOK_RPAREN { + $$ = std::move($4); + } | + TOK_LCURL concat_list TOK_RCURL { + $$ = std::move($2); + } | + OP_CAST TOK_LCURL assignment_pattern_list optional_comma TOK_RCURL { + if (!mode->sv) + err_at_loc(@1, "Assignment patterns are only supported in SystemVerilog mode."); + $$ = std::move($3); + } | + TOK_LCURL expr TOK_LCURL concat_list TOK_RCURL TOK_RCURL { + $$ = std::make_unique(@$, AST_REPLICATE, std::move($2), std::move($4)); + } | + TOK_TILDE attr basic_expr %prec UNARY_OPS { + $$ = std::make_unique(@$, AST_BIT_NOT, std::move($3)); + SET_AST_NODE_LOC($$.get(), @1, @3); + append_attr($$.get(), std::move($2)); + } | + basic_expr TOK_AMP attr basic_expr { + $$ = std::make_unique(@$, AST_BIT_AND, std::move($1), std::move($4)); + SET_AST_NODE_LOC($$.get(), @1, @4); + append_attr($$.get(), std::move($3)); + } | + basic_expr OP_NAND attr basic_expr { + $$ = std::make_unique(@$, AST_BIT_NOT, std::make_unique(@$, AST_BIT_AND, std::move($1), std::move($4))); + SET_AST_NODE_LOC($$.get(), @1, @4); + append_attr($$.get(), std::move($3)); + } | + basic_expr TOK_PIPE attr basic_expr { + $$ = std::make_unique(@$, AST_BIT_OR, std::move($1), std::move($4)); + SET_AST_NODE_LOC($$.get(), @1, @4); + append_attr($$.get(), std::move($3)); + } | + basic_expr OP_NOR attr basic_expr { + $$ = std::make_unique(@$, AST_BIT_NOT, std::make_unique(@$, AST_BIT_OR, std::move($1), std::move($4))); + SET_AST_NODE_LOC($$.get(), @1, @4); + append_attr($$.get(), std::move($3)); + } | + basic_expr TOK_CARET attr basic_expr { + $$ = std::make_unique(@$, AST_BIT_XOR, std::move($1), std::move($4)); + SET_AST_NODE_LOC($$.get(), @1, @4); + append_attr($$.get(), std::move($3)); + } | + basic_expr OP_XNOR attr basic_expr { + $$ = std::make_unique(@$, AST_BIT_XNOR, std::move($1), std::move($4)); + SET_AST_NODE_LOC($$.get(), @1, @4); + append_attr($$.get(), std::move($3)); + } | + TOK_AMP attr basic_expr %prec UNARY_OPS { + $$ = std::make_unique(@$, AST_REDUCE_AND, std::move($3)); + SET_AST_NODE_LOC($$.get(), @1, @3); + append_attr($$.get(), std::move($2)); + } | + OP_NAND attr basic_expr %prec UNARY_OPS { + $$ = std::make_unique(@$, AST_REDUCE_AND, std::move($3)); + SET_AST_NODE_LOC($$.get(), @1, @3); + append_attr($$.get(), std::move($2)); + $$ = std::make_unique(@$, AST_LOGIC_NOT, std::move($$)); + } | + TOK_PIPE attr basic_expr %prec UNARY_OPS { + $$ = std::make_unique(@$, AST_REDUCE_OR, std::move($3)); + SET_AST_NODE_LOC($$.get(), @1, @3); + append_attr($$.get(), std::move($2)); + } | + OP_NOR attr basic_expr %prec UNARY_OPS { + $$ = std::make_unique(@$, AST_REDUCE_OR, std::move($3)); + SET_AST_NODE_LOC($$.get(), @1, @3); + append_attr($$.get(), std::move($2)); + $$ = std::make_unique(@$, AST_LOGIC_NOT, std::move($$)); + SET_AST_NODE_LOC($$.get(), @1, @3); + } | + TOK_CARET attr basic_expr %prec UNARY_OPS { + $$ = std::make_unique(@$, AST_REDUCE_XOR, std::move($3)); + SET_AST_NODE_LOC($$.get(), @1, @3); + append_attr($$.get(), std::move($2)); + } | + OP_XNOR attr basic_expr %prec UNARY_OPS { + $$ = std::make_unique(@$, AST_REDUCE_XNOR, std::move($3)); + SET_AST_NODE_LOC($$.get(), @1, @3); + append_attr($$.get(), std::move($2)); + } | + basic_expr OP_SHL attr basic_expr { + $$ = std::make_unique(@$, AST_SHIFT_LEFT, std::move($1), std::make_unique(@$, AST_TO_UNSIGNED, std::move($4))); + SET_AST_NODE_LOC($$.get(), @1, @4); + append_attr($$.get(), std::move($3)); + } | + basic_expr OP_SHR attr basic_expr { + $$ = std::make_unique(@$, AST_SHIFT_RIGHT, std::move($1), std::make_unique(@$, AST_TO_UNSIGNED, std::move($4))); + SET_AST_NODE_LOC($$.get(), @1, @4); + append_attr($$.get(), std::move($3)); + } | + basic_expr OP_SSHL attr basic_expr { + $$ = std::make_unique(@$, AST_SHIFT_SLEFT, std::move($1), std::make_unique(@$, AST_TO_UNSIGNED, std::move($4))); + SET_AST_NODE_LOC($$.get(), @1, @4); + append_attr($$.get(), std::move($3)); + } | + basic_expr OP_SSHR attr basic_expr { + $$ = std::make_unique(@$, AST_SHIFT_SRIGHT, std::move($1), std::make_unique(@$, AST_TO_UNSIGNED, std::move($4))); + SET_AST_NODE_LOC($$.get(), @1, @4); + append_attr($$.get(), std::move($3)); + } | + basic_expr TOK_LT attr basic_expr { + $$ = std::make_unique(@$, AST_LT, std::move($1), std::move($4)); + SET_AST_NODE_LOC($$.get(), @1, @4); + append_attr($$.get(), std::move($3)); + } | + basic_expr OP_LE attr basic_expr { + $$ = std::make_unique(@$, AST_LE, std::move($1), std::move($4)); + SET_AST_NODE_LOC($$.get(), @1, @4); + append_attr($$.get(), std::move($3)); + } | + basic_expr OP_EQ attr basic_expr { + $$ = std::make_unique(@$, AST_EQ, std::move($1), std::move($4)); + SET_AST_NODE_LOC($$.get(), @1, @4); + append_attr($$.get(), std::move($3)); + } | + basic_expr OP_NE attr basic_expr { + $$ = std::make_unique(@$, AST_NE, std::move($1), std::move($4)); + SET_AST_NODE_LOC($$.get(), @1, @4); + append_attr($$.get(), std::move($3)); + } | + basic_expr OP_EQX attr basic_expr { + $$ = std::make_unique(@$, AST_EQX, std::move($1), std::move($4)); + SET_AST_NODE_LOC($$.get(), @1, @4); + append_attr($$.get(), std::move($3)); + } | + basic_expr OP_NEX attr basic_expr { + $$ = std::make_unique(@$, AST_NEX, std::move($1), std::move($4)); + SET_AST_NODE_LOC($$.get(), @1, @4); + append_attr($$.get(), std::move($3)); + } | + basic_expr OP_GE attr basic_expr { + $$ = std::make_unique(@$, AST_GE, std::move($1), std::move($4)); + SET_AST_NODE_LOC($$.get(), @1, @4); + append_attr($$.get(), std::move($3)); + } | + basic_expr TOK_GT attr basic_expr { + $$ = std::make_unique(@$, AST_GT, std::move($1), std::move($4)); + SET_AST_NODE_LOC($$.get(), @1, @4); + append_attr($$.get(), std::move($3)); + } | + basic_expr TOK_PLUS attr basic_expr { + $$ = std::make_unique(@$, AST_ADD, std::move($1), std::move($4)); + SET_AST_NODE_LOC($$.get(), @1, @4); + append_attr($$.get(), std::move($3)); + } | + basic_expr TOK_MINUS attr basic_expr { + $$ = std::make_unique(@$, AST_SUB, std::move($1), std::move($4)); + SET_AST_NODE_LOC($$.get(), @1, @4); + append_attr($$.get(), std::move($3)); + } | + basic_expr TOK_ASTER attr basic_expr { + $$ = std::make_unique(@$, AST_MUL, std::move($1), std::move($4)); + SET_AST_NODE_LOC($$.get(), @1, @4); + append_attr($$.get(), std::move($3)); + } | + basic_expr TOK_SLASH attr basic_expr { + $$ = std::make_unique(@$, AST_DIV, std::move($1), std::move($4)); + SET_AST_NODE_LOC($$.get(), @1, @4); + append_attr($$.get(), std::move($3)); + } | + basic_expr TOK_PERC attr basic_expr { + $$ = std::make_unique(@$, AST_MOD, std::move($1), std::move($4)); + SET_AST_NODE_LOC($$.get(), @1, @4); + append_attr($$.get(), std::move($3)); + } | + basic_expr OP_POW attr basic_expr { + $$ = std::make_unique(@$, AST_POW, std::move($1), std::move($4)); + SET_AST_NODE_LOC($$.get(), @1, @4); + append_attr($$.get(), std::move($3)); + } | + TOK_PLUS attr basic_expr %prec UNARY_OPS { + $$ = std::make_unique(@$, AST_POS, std::move($3)); + SET_AST_NODE_LOC($$.get(), @1, @3); + append_attr($$.get(), std::move($2)); + } | + TOK_MINUS attr basic_expr %prec UNARY_OPS { + $$ = std::make_unique(@$, AST_NEG, std::move($3)); + SET_AST_NODE_LOC($$.get(), @1, @3); + append_attr($$.get(), std::move($2)); + } | + basic_expr OP_LAND attr basic_expr { + $$ = std::make_unique(@$, AST_LOGIC_AND, std::move($1), std::move($4)); + SET_AST_NODE_LOC($$.get(), @1, @4); + append_attr($$.get(), std::move($3)); + } | + basic_expr OP_LOR attr basic_expr { + $$ = std::make_unique(@$, AST_LOGIC_OR, std::move($1), std::move($4)); + SET_AST_NODE_LOC($$.get(), @1, @4); + append_attr($$.get(), std::move($3)); + } | + TOK_EXCL attr basic_expr %prec UNARY_OPS { + $$ = std::make_unique(@$, AST_LOGIC_NOT, std::move($3)); + SET_AST_NODE_LOC($$.get(), @1, @3); + append_attr($$.get(), std::move($2)); + } | + TOK_SIGNED OP_CAST TOK_LPAREN expr TOK_RPAREN { + if (!mode->sv) + err_at_loc(@2, "Static cast is only supported in SystemVerilog mode."); + $$ = std::make_unique(@$, AST_TO_SIGNED, std::move($4)); + SET_AST_NODE_LOC($$.get(), @1, @4); + } | + TOK_UNSIGNED OP_CAST TOK_LPAREN expr TOK_RPAREN { + if (!mode->sv) + err_at_loc(@2, "Static cast is only supported in SystemVerilog mode."); + $$ = std::make_unique(@$, AST_TO_UNSIGNED, std::move($4)); + SET_AST_NODE_LOC($$.get(), @1, @4); + } | + basic_expr OP_CAST TOK_LPAREN expr TOK_RPAREN { + if (!mode->sv) + err_at_loc(@2, "Static cast is only supported in SystemVerilog mode."); + $$ = std::make_unique(@$, AST_CAST_SIZE, std::move($1), std::move($4)); + SET_AST_NODE_LOC($$.get(), @1, @4); + } | + typedef_base_type OP_CAST TOK_LPAREN expr TOK_RPAREN { + if (!mode->sv) + err_at_loc(@2, "Static cast is only supported in SystemVerilog mode."); + $$ = std::make_unique(@$, AST_CAST_SIZE, std::move($1), std::move($4)); + SET_AST_NODE_LOC($$.get(), @1, @4); + } | + TOK_LPAREN expr TOK_EQ expr TOK_RPAREN { + extra->ensureAsgnExprAllowed(@3, mode->sv); + $$ = $2->clone(); + auto node = std::make_unique(@$, AST_ASSIGN_EQ, std::move($2), std::move($4)); + SET_AST_NODE_LOC(node.get(), @2, @4); + extra->ast_stack.back()->children.push_back(std::move(node)); + } | + TOK_LPAREN expr asgn_binop expr TOK_RPAREN { + extra->ensureAsgnExprAllowed(@3, mode->sv); + $$ = extra->addAsgnBinopStmt(nullptr, std::move($2), $3, std::move($4))-> clone(); + }; + +concat_list: + expr { + $$ = std::make_unique(@$, AST_CONCAT, std::move($1)); + } | + expr TOK_COMMA concat_list { + $$ = std::move($3); + $$->children.push_back(std::move($1)); + }; + +assignment_pattern_list: + expr { + $$ = std::make_unique(@$, AST_ASSIGN_PATTERN); + $$->children.push_back(std::move($1)); + } | + assignment_pattern_list TOK_COMMA expr { + $$ = std::move($1); + $$->children.push_back(std::move($3)); + }; + +integral_number: + TOK_CONSTVAL { $$ = std::move($1); } | + TOK_UNBASED_UNSIZED_CONSTVAL { $$ = std::move($1); } | + TOK_BASE TOK_BASED_CONSTVAL { + $1->append(*$2); + $$ = std::move($1); + } | + TOK_CONSTVAL TOK_BASE TOK_BASED_CONSTVAL { + $1->append(*$2).append(*$3); + $$ = std::move($1); + }; diff --git a/chips/yosys/guidelines/GettingStarted b/chips/yosys/guidelines/GettingStarted new file mode 100644 index 0000000000000000000000000000000000000000..ea15df93f0c7246b2f3a2f3042afcf719a010d86 --- /dev/null +++ b/chips/yosys/guidelines/GettingStarted @@ -0,0 +1,207 @@ +Getting Started +=============== + + +Outline of a Yosys command +-------------------------- + +Here is the C++ code for a "hello_world" Yosys command (hello.cc): + + #include "kernel/yosys.h" + + USING_YOSYS_NAMESPACE + PRIVATE_NAMESPACE_BEGIN + + struct HelloWorldPass : public Pass { + HelloWorldPass() : Pass("hello_world") { } + void execute(vector, Design*) override { + log("Hello World!\n"); + } + } HelloWorldPass; + + PRIVATE_NAMESPACE_END + +This can be built into a Yosys module using the following command: + + yosys-config --exec --cxx --cxxflags --ldflags -o hello.so -shared hello.cc --ldlibs + +Or short: + + yosys-config --build hello.so hello.cc + +And then executed using the following command: + + yosys -m hello.so -p hello_world + + +Yosys Data Structures +--------------------- + + 1. Container classes based on hashing + +Yosys heavily relies on custom container data structures such as dict or pool +defined in kernel/hashlib.h. +dict is essentially a replacement for std::unordered_map +and pool is a replacement for std::unordered_set. Please refer to +docs/source/yosys_internals/hashing.rst for more information on those. + +Otherwise, Yosys makes use of the following: + + 2. Standard STL data types + +In Yosys we use std::vector and std::string whenever applicable. When +dict and pool are not suitable then std::map and std::set +are used instead. + +The types std::vector and std::string are also available as vector +and string in the Yosys namespace. + + 3. RTLIL objects + +The current design (essentially a collection of modules, each defined by a +netlist) is stored in memory using RTLIL object (declared in kernel/rtlil.h, +automatically included by kernel/yosys.h). You should glance over at least +the declarations for the following types in kernel/rtlil.h: + + RTLIL::IdString + This is a handle for an identifier (e.g. cell or wire name). + It feels a lot like a std::string, but is only a single int + in size. (The actual string is stored in a global lookup + table.) + + RTLIL::SigBit + A single signal bit. I.e. either a constant state (0, 1, + x, z) or a single bit from a wire. + + RTLIL::SigSpec + Essentially a vector of SigBits. + + RTLIL::Wire + RTLIL::Cell + The building blocks of the netlist in a module. + + RTLIL::Module + RTLIL::Design + The module is a container with connected cells and wires + in it. The design is a container with modules in it. + +All these types are also available without the RTLIL:: prefix in the Yosys +namespace. + + 4. SigMap and other Helper Classes + +There are a couple of additional helper classes that are in wide use +in Yosys. Most importantly there is SigMap (declared in kernel/sigtools.h). + +When a design has many wires in it that are connected to each other, then a +single signal bit can have multiple valid names. The SigMap object can be used +to map SigSpecs or SigBits to unique SigSpecs and SigBits that consistently +only use one wire from such a group of connected wires. For example: + + SigBit a = module->addWire(NEW_ID); + SigBit b = module->addWire(NEW_ID); + module->connect(a, b); + + log("%d\n", a == b); // will print 0 + + SigMap sigmap(module); + log("%d\n", sigmap(a) == sigmap(b)); // will print 1 + + +Using the RTLIL Netlist Format +------------------------------ + +In the RTLIL netlist format the cell ports contain SigSpecs that point to the +Wires. There are no references in the other direction. This has two direct +consequences: + +(1) It is very easy to go from cells to wires but hard to go in the other way. + +(2) There is no danger in removing cells from the netlists, but removing wires +can break the netlist format when there are still references to the wire +somewhere in the netlist. + +The solution to (1) is easy: Create custom indexes that allow you to make fast +lookups for the wire-to-cell direction. You can either use existing generic +index structures to do that (such as the ModIndex class) or write your own +index. For many application it is simplest to construct a custom index. For +example: + + SigMap sigmap(module); + dict sigbit_to_driver_index; + + for (auto cell : module->cells()) + for (auto &conn : cell->connections()) + if (cell->output(conn.first)) + for (auto bit : sigmap(conn.second)) + sigbit_to_driver_index[bit] = cell; + +Regarding (2): There is a general theme in Yosys that you don't remove wires +from the design. You can rename them, unconnect them, but you do not actually remove +the Wire object from the module. Instead you let the "clean" command take care +of the dangling wires. On the other hand it is safe to remove cells (as long as +you make sure this does not invalidate a custom index you are using in your code). + + +Example Code +------------ + +The following yosys commands are a good starting point if you are looking for examples +of how to use the Yosys API: + + docs/source/code_examples/stubnets/stubnets.cc + docs/resources/PRESENTATION_Prog/my_cmd.cc + + +Script Passes +------------- + +The ScriptPass base class can be used to implement passes that just call other passes, +like a script. Examples for such passes are: + + techlibs/common/prep.cc + techlibs/common/synth.cc + +In some cases it is easier to implement such a pass as regular pass, for example when +ScriptPass doesn't provide the type of flow control desired. (But many of the +script passes in Yosys that don't use ScriptPass simply predate the ScriptPass base +class.) Examples for such passes are: + + passes/opt/opt.cc + passes/proc/proc.cc + +Whether they use the ScriptPass base-class or not, a pass should always either +call other passes without doing any non-trivial work itself, or should implement +a non-trivial algorithm but not call any other passes. The reason for this is that +this helps containing complexity in individual passes and simplifies debugging the +entire system. + +Exceptions to this rule should be rare and limited to cases where calling other +passes is optional and only happens when requested by the user (such as for +example `techmap -autoproc`), or where it is about commands that are "top-level +commands" in their own right, not components to be used in regular synthesis +flows (such as the `bugpoint` command). + +A pass that would "naturally" call other passes and also do some work itself +should be re-written in one of two ways: + +1) It could be re-written as script pass with the parts that are not calls +to other passes factored out into individual new passes. Usually in those +cases the new sub passes share the same prefix as the top-level script pass. + +2) It could be re-written so that it already expects the design in a certain +state, expecting the calling script to set up this state before calling the +pass in questions. + +Many back-ends are examples for the 2nd approach. For example, `write_aiger` +does not convert the design into AIG representation, but expects the design +to be already in this form, and prints an `Unsupported cell type` error +message otherwise. + + +Notes on the existing codebase +------------------------------ + +For historical reasons not all parts of Yosys adhere to the current coding +style. When adding code to existing parts of the system, adhere to this guide +for the new code instead of trying to mimic the style of the surrounding code. diff --git a/chips/yosys/kernel/CMakeLists.txt b/chips/yosys/kernel/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..485aeafa8332af33aedfdc6d13d6744b83e9dd16 --- /dev/null +++ b/chips/yosys/kernel/CMakeLists.txt @@ -0,0 +1,203 @@ +yosys_version_file(version.cc.in version.cc) +configure_file(yosys_config.h.in yosys_config.h @ONLY) + +set(cellhelp_sources) +foreach (library simlib simcells) + add_custom_command( + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/cellhelp.py ${YOSYS_CMAKE_SOURCE_DIR}/techlibs/common/${library}.v + OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/${library}_help.inc + COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/cellhelp.py + ${YOSYS_CMAKE_SOURCE_DIR}/techlibs/common/${library}.v + > ${CMAKE_CURRENT_BINARY_DIR}/${library}_help.inc + VERBATIM + ) + list(APPEND cellhelp_sources ${CMAKE_CURRENT_BINARY_DIR}/${library}_help.inc) +endforeach() + +yosys_core(kernel + bitpattern.cc + bitpattern.h + calc.cc + cellaigs.cc + cellaigs.h + celledges.cc + celledges.h + celltypes.h + compute_graph.h + compressor_tree.cc + compressor_tree.h + consteval.h + constids.inc + cost.cc + cost.h + drivertools.cc + drivertools.h + ff.cc + ff.h + ffinit.h + ffmerge.cc + ffmerge.h + fmt.cc + fmt.h + functional.cc + functional.h + gzip.cc + gzip.h + hashcons.h + hashcons_impl.h + hashlib.h + io.cc + io.h + json.cc + json.h + log.cc + log.h + $<${YOSYS_ENABLE_VERIFIC}:log_compat.cc> + log_help.cc + log_help.h + macc.h + mem.cc + mem.h + modtools.h + newcelltypes.cc + newcelltypes.h + pattern.h + qcsat.cc + qcsat.h + register.cc + register.h + ${cellhelp_sources} + rtlil_bufnorm.cc + rtlil.cc + rtlil.h + rtlil_twine_compat.h + rtlil_twine_compat_impl.h + satgen.cc + satgen.h + scopeinfo.cc + scopeinfo.h + sexpr.cc + sexpr.h + sigtools.h + tclapi.cc + threading.cc + threading.h + timinginfo.h + topo_scc.h + twine.cc + twine.h + unused_bits.h + utils.h + version.cc + yosys.cc + yosys_common.h + yosys_config.h + yosys.h + yw.cc + yw.h + INCLUDE_DIRS + ${pybind11_INCLUDE_DIR} + LIBRARIES + cxxopts + $<${YOSYS_ENABLE_PLUGINS}:${Dlfcn_LIBRARIES}> + $<${YOSYS_ENABLE_ZLIB}:PkgConfig::zlib> + $<${YOSYS_ENABLE_READLINE}:PkgConfig::readline> + $<${YOSYS_ENABLE_EDITLINE}:PkgConfig::editline> + $<${YOSYS_ENABLE_TCL}:PkgConfig::tcl> + $<${YOSYS_ENABLE_PYTHON}:Python3::Module> + REQUIRES + bigint + ezsat + json11 + sha1 + PROVIDES + help + echo + license + tcl + shell + history + script + DATA_DIR + include/kernel + DATA_FILES + bitpattern.h + cellaigs.h + celledges.h + celltypes.h + newcelltypes.h + consteval.h + constids.inc + cost.h + drivertools.h + ff.h + ffinit.h + ffmerge.h + fmt.h + gzip.h + hashcons.h + hashcons_impl.h + hashlib.h + io.h + json.h + log.h + macc.h + modtools.h + mem.h + qcsat.h + register.h + rtlil.h + rtlil_twine_compat.h + rtlil_twine_compat_impl.h + satgen.h + scopeinfo.h + sexpr.h + sigtools.h + threading.h + timinginfo.h + twine.h + unused_bits.h + utils.h + yosys.h + yosys_common.h + yw.h + DATA_EXPLICIT + yosys_config.h ${CMAKE_CURRENT_BINARY_DIR}/yosys_config.h + ESSENTIAL +) + +set(yosys_cc_definitions + "$<$:ABCEXTERNAL=\"${YOSYS_ABC_EXECUTABLE}\">" + $<$:YOSYS_WIN32_UNIX_DIR> +) +set_source_files_properties(yosys.cc PROPERTIES + COMPILE_DEFINITIONS "${yosys_cc_definitions}" +) + +yosys_core(fstdata + fstdata.cc + fstdata.h + REQUIRES + fst + DATA_DIR + include/kernel + DATA_FILES + fstdata.h +) + +if (NOT YOSYS_BUILD_PYTHON_ONLY) + yosys_core(driver + driver.cc + INCLUDE_DIRS + ${pybind11_INCLUDE_DIR} + LIBRARIES + fmt::fmt + $<${YOSYS_ENABLE_READLINE}:PkgConfig::readline> + $<${YOSYS_ENABLE_EDITLINE}:PkgConfig::editline> + $<${YOSYS_ENABLE_TCL}:PkgConfig::tcl> + $<${YOSYS_ENABLE_PYTHON}:Python3::Python> + REQUIRES + essentials + BOOTSTRAP + ) +endif() diff --git a/chips/yosys/kernel/bitpattern.cc b/chips/yosys/kernel/bitpattern.cc new file mode 100644 index 0000000000000000000000000000000000000000..aff9d718d40f8a7557e48736864711aed7f26105 --- /dev/null +++ b/chips/yosys/kernel/bitpattern.cc @@ -0,0 +1,201 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/bitpattern.h" + +YOSYS_NAMESPACE_BEGIN + +BitPatternPool::BitPatternPool(RTLIL::SigSpec sig) : width(GetSize(sig)) +{ + gave_up = width > MAX_WIDTH; + if (gave_up) + return; + universe.assign(width, RTLIL::State::Sa); + for (int i = 0; i < width; i++) + if (sig[i].wire == nullptr && sig[i].data <= RTLIL::State::S1) + universe[i] = sig[i].data; + rebuild(); +} + +BitPatternPool::BitPatternPool(int width) : BitPatternPool(RTLIL::SigSpec(RTLIL::State::Sa, width)) {} + +bool BitPatternPool::covers_nothing(RTLIL::SigSpec sig) +{ + for (auto bit : sig) + if (bit.wire == nullptr && (bit.data == RTLIL::State::Sx || bit.data == RTLIL::State::Sz)) + return true; + return false; +} + +int BitPatternPool::budget() { return max_nodes >> (3 * ((MAX_ATTEMPTS - 1 - attempt) / 2)); } + +int BitPatternPool::bit_index(int level) { return attempt % 2 ? level : width - 1 - level; } + +int BitPatternPool::make_node(int level, int low, int high) +{ + if (low == high) + return low; + return nodes(std::make_tuple(level, low, high)); +} + +bool BitPatternPool::reaches(int node, const std::vector &bits, int terminal, pool &misses) +{ + if (node == int(Terminal::Empty) || node == int(Terminal::Full)) + return node == terminal; + if (misses.count(node)) + return false; + auto [level, low, high] = nodes[node]; + RTLIL::State bit = bits[bit_index(level)]; + if (bit != RTLIL::State::S1 && reaches(low, bits, terminal, misses)) + return true; + if (bit != RTLIL::State::S0 && reaches(high, bits, terminal, misses)) + return true; + misses.insert(node); + return false; +} + +// node minus cube +int BitPatternPool::remove_cube(int node, int level, const std::vector &bits, dict, int> &cache) +{ + if (node == int(Terminal::Empty)) + return int(Terminal::Empty); + while (level < width && bits[bit_index(level)] > RTLIL::State::S1) + level++; + if (level == width || GetSize(nodes) >= budget()) + return int(Terminal::Empty); + auto it = cache.find({node, level}); + if (it != cache.end()) + return it->second; + + auto [node_level, low, high] = nodes[node]; + int result; + if (node_level < level) { + low = remove_cube(low, level, bits, cache); + high = remove_cube(high, level, bits, cache); + result = make_node(node_level, low, high); + } else { + if (node_level > level) + low = high = node; + if (bits[bit_index(level)] == RTLIL::State::S0) + low = remove_cube(low, level + 1, bits, cache); + else + high = remove_cube(high, level + 1, bits, cache); + result = make_node(level, low, high); + } + cache[{node, level}] = result; + return result; +} + +// false if over budget +bool BitPatternPool::remove(const std::vector &bits) +{ + log_assert(GetSize(bits) == width); + dict, int> cache; + int new_root = remove_cube(root, 0, bits, cache); + if (GetSize(nodes) >= budget()) + return false; + root = new_root; + return true; +} + +bool BitPatternPool::rebuild() +{ + nodes.clear(); + nodes(std::make_tuple(width, int(Terminal::Empty), int(Terminal::Empty))); + nodes(std::make_tuple(width, int(Terminal::Full), int(Terminal::Full))); + root = width > 0 ? int(Terminal::Full) : int(Terminal::Empty); + for (int level = width - 1; level >= 0; level--) { + RTLIL::State bit = universe[bit_index(level)]; + if (bit == RTLIL::State::S1) + root = make_node(level, int(Terminal::Empty), root); + else if (bit == RTLIL::State::S0) + root = make_node(level, root, int(Terminal::Empty)); + } + for (auto &bits : taken) + if (!remove(bits)) + return false; + return true; +} + +bool BitPatternPool::has_any(RTLIL::SigSpec sig) +{ + if (covers_nothing(sig)) + return false; + if (gave_up) + return true; + log_assert(GetSize(sig) == width); + pool misses; + return reaches(root, sig.as_const().to_bits(), int(Terminal::Full), misses); +} + +bool BitPatternPool::has_all(RTLIL::SigSpec sig) +{ + if (covers_nothing(sig)) + return true; + if (gave_up) + return false; + log_assert(GetSize(sig) == width); + pool misses; + return !reaches(root, sig.as_const().to_bits(), int(Terminal::Empty), misses); +} + +bool BitPatternPool::take(RTLIL::SigSpec sig) +{ + if (covers_nothing(sig)) + return false; + if (gave_up) + return true; + if (root == int(Terminal::Empty)) + return false; + std::vector bits = sig.as_const().to_bits(); + int old_root = root; + bool removed = remove(bits); + while (!removed && attempt + 1 < MAX_ATTEMPTS) { + attempt++; + if (rebuild()) { + old_root = root; + removed = remove(bits); + } + } + if (!removed) { + gave_up = true; + nodes = {}; + taken = {}; + return true; + } + // hash-consed, same root means no overlap + if (root == old_root) + return false; + if (attempt + 1 < MAX_ATTEMPTS) + taken.push_back(bits); + return true; +} + +bool BitPatternPool::take_all() +{ + if (empty()) + return false; + root = int(Terminal::Empty); + gave_up = false; + return true; +} + +bool BitPatternPool::empty() { return !gave_up && root == int(Terminal::Empty); } + +YOSYS_NAMESPACE_END diff --git a/chips/yosys/kernel/bitpattern.h b/chips/yosys/kernel/bitpattern.h new file mode 100644 index 0000000000000000000000000000000000000000..19baf3116cf9b47800be87e45bfcfeea5591b00d --- /dev/null +++ b/chips/yosys/kernel/bitpattern.h @@ -0,0 +1,125 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#ifndef BITPATTERN_H +#define BITPATTERN_H + +#include "kernel/log.h" +#include "kernel/rtlil.h" + +YOSYS_NAMESPACE_BEGIN + +/** + * This file implements BitPatternPool for efficiently storing and querying + * sets of fixed-width 2-valued logic constants. + * A pattern (cube) can have don't cares on one or more bit positions (State::Sa). + * + * The pool is a reduced ordered BDD, see https://github.com/YosysHQ/yosys/issues/6359. + * Past max_nodes it gives up and answers conservatively. + * + * BitPatternPool does not permit adding new patterns, only removing. + * Its intended use case is in analysing cases in case/match constructs in HDL. + */ +struct BitPatternPool +{ + enum class Terminal : int { + Empty = 0, + Full = 1 + }; + + // bounds recursion depth + static constexpr int MAX_WIDTH = 4096; + // MSB then LSB first per budget, budgets grow 8x + static constexpr int MAX_ATTEMPTS = 8; + + int width; + int max_nodes = 1 << 17; + bool gave_up = false; + + BitPatternPool(RTLIL::SigSpec sig); + + /** + * Constructs a pool of all possible patterns (all don't-care bits) + */ + BitPatternPool(int width); + + /** + * A literal x/z bit can never match a 2-valued selector, so a pattern containing + * one covers nothing. + */ + static bool covers_nothing(RTLIL::SigSpec sig); + + /** + * Does cube sig overlap the pool? + * For example: + * pool({aaa}).has_any(01a) == true + * pool({01a}).has_any(01a) == true + * pool({011}).has_any(01a) == true + * pool({01a}).has_any(011) == true + * pool({111}).has_any(01a) == false + */ + bool has_any(RTLIL::SigSpec sig); + + /** + * Is cube sig covered by the pool? + * For example: + * pool({aaa}).has_all(01a) == true + * pool({01a}).has_all(01a) == true + * pool({01a}).has_all(011) == true + * pool({011}).has_all(01a) == false + * pool({111}).has_all(01a) == false + */ + bool has_all(RTLIL::SigSpec sig); + + /** + * Remove cube sig from the pool. True if the pool overlapped sig. + * For example: + * Taking 011 out of pool({01a}) -> pool({010}), returns true. + * Taking 011 out of pool({010}) does nothing, returns false. + */ + bool take(RTLIL::SigSpec sig); + + /** + * Remove all patterns. Returns false if already empty. + */ + bool take_all(); + + bool empty(); +private: + int budget(); + int bit_index(int level); + int make_node(int level, int low, int high); + bool reaches(int node, const std::vector &bits, int terminal, pool &misses); + int remove_cube(int node, int level, const std::vector &bits, dict, int> &cache); + bool remove(const std::vector &bits); + bool rebuild(); + + int attempt = 0; + + // (level, low, high) + idict> nodes; + int root = int(Terminal::Empty); + + std::vector universe; + std::vector> taken; +}; + +YOSYS_NAMESPACE_END + +#endif diff --git a/chips/yosys/kernel/calc.cc b/chips/yosys/kernel/calc.cc new file mode 100644 index 0000000000000000000000000000000000000000..685326f82844639be89564d3ed0039fc64260cb4 --- /dev/null +++ b/chips/yosys/kernel/calc.cc @@ -0,0 +1,714 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +// [[CITE]] Power-Modulus Algorithm +// Schneier, Bruce (1996). Applied Cryptography: Protocols, Algorithms, and Source Code in C, +// Second Edition (2nd ed.). Wiley. ISBN 978-0-471-11709-4, page 244 + +#include "kernel/yosys.h" +#include "libs/bigint/BigIntegerLibrary.hh" + +YOSYS_NAMESPACE_BEGIN + +static void extend_u0(RTLIL::Const &arg, int width, bool is_signed) +{ + RTLIL::State padding = RTLIL::State::S0; + + if (arg.size() > 0 && is_signed) + padding = arg.back(); + + arg.resize(width, padding); +} + +static BigInteger const2big(const RTLIL::Const &val, bool as_signed, int &undef_bit_pos) +{ + BigUnsigned mag; + + BigInteger::Sign sign = BigInteger::positive; + State inv_sign_bit = RTLIL::State::S1; + auto num_bits = val.size(); + + if (as_signed && num_bits && val[num_bits-1] == RTLIL::State::S1) { + inv_sign_bit = RTLIL::State::S0; + sign = BigInteger::negative; + num_bits--; + } + + for (auto i = 0; i < num_bits; i++) + if (val[i] == RTLIL::State::S0 || val[i] == RTLIL::State::S1) + mag.setBit(i, val[i] == inv_sign_bit); + else if (undef_bit_pos < 0) + undef_bit_pos = i; + + if (sign == BigInteger::negative) + mag += 1; + + return BigInteger(mag, sign); +} + +static RTLIL::Const big2const(const BigInteger &val, int result_len, int undef_bit_pos) +{ + if (undef_bit_pos >= 0) + return RTLIL::Const(RTLIL::State::Sx, result_len); + + BigUnsigned mag = val.getMagnitude(); + RTLIL::Const result(0, result_len); + + if (!mag.isZero()) + { + if (val.getSign() < 0) + { + mag--; + for (auto i = 0; i < result_len; i++) + result.set(i, mag.getBit(i) ? RTLIL::State::S0 : RTLIL::State::S1); + } + else + { + for (auto i = 0; i < result_len; i++) + result.set(i, mag.getBit(i) ? RTLIL::State::S1 : RTLIL::State::S0); + } + } + +#if 0 + if (undef_bit_pos >= 0) + for (int i = undef_bit_pos; i < result_len; i++) + result[i] = RTLIL::State::Sx; +#endif + + return result; +} + +static RTLIL::State logic_and(RTLIL::State a, RTLIL::State b) +{ + if (a == RTLIL::State::S0) return RTLIL::State::S0; + if (b == RTLIL::State::S0) return RTLIL::State::S0; + if (a != RTLIL::State::S1) return RTLIL::State::Sx; + if (b != RTLIL::State::S1) return RTLIL::State::Sx; + return RTLIL::State::S1; +} + +static RTLIL::State logic_or(RTLIL::State a, RTLIL::State b) +{ + if (a == RTLIL::State::S1) return RTLIL::State::S1; + if (b == RTLIL::State::S1) return RTLIL::State::S1; + if (a != RTLIL::State::S0) return RTLIL::State::Sx; + if (b != RTLIL::State::S0) return RTLIL::State::Sx; + return RTLIL::State::S0; +} + +static RTLIL::State logic_xor(RTLIL::State a, RTLIL::State b) +{ + if (a != RTLIL::State::S0 && a != RTLIL::State::S1) return RTLIL::State::Sx; + if (b != RTLIL::State::S0 && b != RTLIL::State::S1) return RTLIL::State::Sx; + return a != b ? RTLIL::State::S1 : RTLIL::State::S0; +} + +static RTLIL::State logic_xnor(RTLIL::State a, RTLIL::State b) +{ + if (a != RTLIL::State::S0 && a != RTLIL::State::S1) return RTLIL::State::Sx; + if (b != RTLIL::State::S0 && b != RTLIL::State::S1) return RTLIL::State::Sx; + return a == b ? RTLIL::State::S1 : RTLIL::State::S0; +} + +RTLIL::Const RTLIL::const_not(const RTLIL::Const &arg1, const RTLIL::Const&, bool signed1, bool, int result_len) +{ + if (result_len < 0) + result_len = GetSize(arg1); + + RTLIL::Const arg1_ext = arg1; + extend_u0(arg1_ext, result_len, signed1); + + RTLIL::Const result(RTLIL::State::Sx, result_len); + for (auto i = 0; i < result_len; i++) { + if (i >= GetSize(arg1_ext)) + result.set(i, RTLIL::State::S0); + else if (arg1_ext[i] == RTLIL::State::S0) + result.set(i, RTLIL::State::S1); + else if (arg1_ext[i] == RTLIL::State::S1) + result.set(i, RTLIL::State::S0); + } + + return result; +} + +static RTLIL::Const logic_wrapper(RTLIL::State(*logic_func)(RTLIL::State, RTLIL::State), + RTLIL::Const arg1, RTLIL::Const arg2, bool signed1, bool signed2, int result_len = -1) +{ + if (result_len < 0) + result_len = max(GetSize(arg1), GetSize(arg2)); + + extend_u0(arg1, result_len, signed1); + extend_u0(arg2, result_len, signed2); + + RTLIL::Const result(RTLIL::State::Sx, result_len); + for (auto i = 0; i < result_len; i++) { + RTLIL::State a = i < GetSize(arg1) ? arg1[i] : RTLIL::State::S0; + RTLIL::State b = i < GetSize(arg2) ? arg2[i] : RTLIL::State::S0; + result.set(i, logic_func(a, b)); + } + + return result; +} + +RTLIL::Const RTLIL::const_and(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool signed2, int result_len) +{ + return logic_wrapper(logic_and, arg1, arg2, signed1, signed2, result_len); +} + +RTLIL::Const RTLIL::const_or(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool signed2, int result_len) +{ + return logic_wrapper(logic_or, arg1, arg2, signed1, signed2, result_len); +} + +RTLIL::Const RTLIL::const_xor(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool signed2, int result_len) +{ + return logic_wrapper(logic_xor, arg1, arg2, signed1, signed2, result_len); +} + +RTLIL::Const RTLIL::const_xnor(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool signed2, int result_len) +{ + return logic_wrapper(logic_xnor, arg1, arg2, signed1, signed2, result_len); +} + +static RTLIL::Const logic_reduce_wrapper(RTLIL::State initial, RTLIL::State(*logic_func)(RTLIL::State, RTLIL::State), const RTLIL::Const &arg1, int result_len) +{ + RTLIL::State temp = initial; + + for (auto i = 0; i < arg1.size(); i++) + temp = logic_func(temp, arg1[i]); + + RTLIL::Const result(temp); + if (GetSize(result) < result_len) + result.resize(result_len, RTLIL::State::S0); + return result; +} + +RTLIL::Const RTLIL::const_reduce_and(const RTLIL::Const &arg1, const RTLIL::Const&, bool, bool, int result_len) +{ + return logic_reduce_wrapper(RTLIL::State::S1, logic_and, arg1, result_len); +} + +RTLIL::Const RTLIL::const_reduce_or(const RTLIL::Const &arg1, const RTLIL::Const&, bool, bool, int result_len) +{ + return logic_reduce_wrapper(RTLIL::State::S0, logic_or, arg1, result_len); +} + +RTLIL::Const RTLIL::const_reduce_xor(const RTLIL::Const &arg1, const RTLIL::Const&, bool, bool, int result_len) +{ + return logic_reduce_wrapper(RTLIL::State::S0, logic_xor, arg1, result_len); +} + +RTLIL::Const RTLIL::const_reduce_xnor(const RTLIL::Const &arg1, const RTLIL::Const&, bool, bool, int result_len) +{ + RTLIL::Const buffer = logic_reduce_wrapper(RTLIL::State::S0, logic_xor, arg1, result_len); + if (!buffer.empty()) { + if (buffer.front() == RTLIL::State::S0) + buffer.set(0, RTLIL::State::S1); + else if (buffer.front() == RTLIL::State::S1) + buffer.set(0, RTLIL::State::S0); + } + return buffer; +} + +RTLIL::Const RTLIL::const_reduce_bool(const RTLIL::Const &arg1, const RTLIL::Const&, bool, bool, int result_len) +{ + return logic_reduce_wrapper(RTLIL::State::S0, logic_or, arg1, result_len); +} + +RTLIL::Const RTLIL::const_logic_not(const RTLIL::Const &arg1, const RTLIL::Const&, bool signed1, bool, int result_len) +{ + int undef_bit_pos_a = -1; + BigInteger a = const2big(arg1, signed1, undef_bit_pos_a); + RTLIL::Const result(a.isZero() ? undef_bit_pos_a >= 0 ? RTLIL::State::Sx : RTLIL::State::S1 : RTLIL::State::S0); + if (GetSize(result) < result_len) + result.resize(result_len, RTLIL::State::S0); + return result; +} + +RTLIL::Const RTLIL::const_logic_and(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool signed2, int result_len) +{ + int undef_bit_pos_a = -1, undef_bit_pos_b = -1; + BigInteger a = const2big(arg1, signed1, undef_bit_pos_a); + BigInteger b = const2big(arg2, signed2, undef_bit_pos_b); + + RTLIL::State bit_a = a.isZero() ? undef_bit_pos_a >= 0 ? RTLIL::State::Sx : RTLIL::State::S0 : RTLIL::State::S1; + RTLIL::State bit_b = b.isZero() ? undef_bit_pos_b >= 0 ? RTLIL::State::Sx : RTLIL::State::S0 : RTLIL::State::S1; + RTLIL::Const result(logic_and(bit_a, bit_b)); + if (GetSize(result) < result_len) + result.resize(result_len, RTLIL::State::S0); + return result; +} + +RTLIL::Const RTLIL::const_logic_or(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool signed2, int result_len) +{ + int undef_bit_pos_a = -1, undef_bit_pos_b = -1; + BigInteger a = const2big(arg1, signed1, undef_bit_pos_a); + BigInteger b = const2big(arg2, signed2, undef_bit_pos_b); + + RTLIL::State bit_a = a.isZero() ? undef_bit_pos_a >= 0 ? RTLIL::State::Sx : RTLIL::State::S0 : RTLIL::State::S1; + RTLIL::State bit_b = b.isZero() ? undef_bit_pos_b >= 0 ? RTLIL::State::Sx : RTLIL::State::S0 : RTLIL::State::S1; + RTLIL::Const result(logic_or(bit_a, bit_b)); + if (GetSize(result) < result_len) + result.resize(result_len, RTLIL::State::S0); + return result; +} + +// Shift `arg1` by `arg2` bits. +// If `direction` is +1, `arg1` is shifted right by `arg2` bits; if `direction` is -1, `arg1` is shifted left by `arg2` bits. +// If `signed2` is true, `arg2` is interpreted as a signed integer; a negative `arg2` will cause a shift in the opposite direction. +// Any required bits outside the bounds of `arg1` are padded with `vacant_bits` unless `sign_ext` is true, in which case any bits outside the left +// bounds are filled with the leftmost bit of `arg1` (arithmetic shift). +static RTLIL::Const const_shift_worker(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool sign_ext, bool signed2, int direction, int result_len, RTLIL::State vacant_bits = RTLIL::State::S0) +{ + int undef_bit_pos = -1; + BigInteger offset = const2big(arg2, signed2, undef_bit_pos) * direction; + + if (result_len < 0) + result_len = GetSize(arg1); + + RTLIL::Const result(RTLIL::State::Sx, result_len); + if (undef_bit_pos >= 0) + return result; + + for (int i = 0; i < result_len; i++) { + BigInteger pos = BigInteger(i) + offset; + if (pos < 0) + result.set(i, vacant_bits); + else if (pos >= BigInteger(GetSize(arg1))) + result.set(i, sign_ext && !arg1.empty() ? arg1.back() : vacant_bits); + else + result.set(i, arg1[pos.toInt()]); + } + + return result; +} + +RTLIL::Const RTLIL::const_shl(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool, int result_len) +{ + RTLIL::Const arg1_ext = arg1; + extend_u0(arg1_ext, result_len, signed1); + return const_shift_worker(arg1_ext, arg2, false, false, -1, result_len); +} + +RTLIL::Const RTLIL::const_shr(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool, int result_len) +{ + RTLIL::Const arg1_ext = arg1; + extend_u0(arg1_ext, max(result_len, GetSize(arg1)), signed1); + return const_shift_worker(arg1_ext, arg2, false, false, +1, result_len); +} + +RTLIL::Const RTLIL::const_sshl(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool, int result_len) +{ + return const_shift_worker(arg1, arg2, signed1, false, -1, result_len); +} + +RTLIL::Const RTLIL::const_sshr(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool, int result_len) +{ + return const_shift_worker(arg1, arg2, signed1, false, +1, result_len); +} + +RTLIL::Const RTLIL::const_shift(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool signed2, int result_len) +{ + RTLIL::Const arg1_ext = arg1; + extend_u0(arg1_ext, max(result_len, GetSize(arg1)), signed1); + return const_shift_worker(arg1_ext, arg2, false, signed2, +1, result_len); +} + +RTLIL::Const RTLIL::const_shiftx(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool, bool signed2, int result_len) +{ + return const_shift_worker(arg1, arg2, false, signed2, +1, result_len, RTLIL::State::Sx); +} + +RTLIL::Const RTLIL::const_lt(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool signed2, int result_len) +{ + int undef_bit_pos = -1; + bool y = const2big(arg1, signed1, undef_bit_pos) < const2big(arg2, signed2, undef_bit_pos); + RTLIL::Const result(undef_bit_pos >= 0 ? RTLIL::State::Sx : y ? RTLIL::State::S1 : RTLIL::State::S0); + if (GetSize(result) < result_len) + result.resize(result_len, RTLIL::State::S0); + return result; +} + +RTLIL::Const RTLIL::const_le(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool signed2, int result_len) +{ + int undef_bit_pos = -1; + bool y = const2big(arg1, signed1, undef_bit_pos) <= const2big(arg2, signed2, undef_bit_pos); + RTLIL::Const result(undef_bit_pos >= 0 ? RTLIL::State::Sx : y ? RTLIL::State::S1 : RTLIL::State::S0); + if (GetSize(result) < result_len) + result.resize(result_len, RTLIL::State::S0); + return result; +} + +RTLIL::Const RTLIL::const_eq(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool signed2, int result_len) +{ + RTLIL::Const arg1_ext = arg1; + RTLIL::Const arg2_ext = arg2; + RTLIL::Const result(RTLIL::State::S0, result_len); + + int width = max(GetSize(arg1_ext), GetSize(arg2_ext)); + extend_u0(arg1_ext, width, signed1 && signed2); + extend_u0(arg2_ext, width, signed1 && signed2); + + RTLIL::State matched_status = RTLIL::State::S1; + for (auto i = 0; i < arg1_ext.size(); i++) { + if (arg1_ext.at(i) == RTLIL::State::S0 && arg2_ext.at(i) == RTLIL::State::S1) + return result; + if (arg1_ext.at(i) == RTLIL::State::S1 && arg2_ext.at(i) == RTLIL::State::S0) + return result; + if (arg1_ext.at(i) > RTLIL::State::S1 || arg2_ext.at(i) > RTLIL::State::S1) + matched_status = RTLIL::State::Sx; + } + + result.set(0, matched_status); + return result; +} + +RTLIL::Const RTLIL::const_ne(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool signed2, int result_len) +{ + RTLIL::Const result = RTLIL::const_eq(arg1, arg2, signed1, signed2, result_len); + if (result.front() == RTLIL::State::S0) + result.set(0, RTLIL::State::S1); + else if (result.front() == RTLIL::State::S1) + result.set(0, RTLIL::State::S0); + return result; +} + +RTLIL::Const RTLIL::const_eqx(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool signed2, int result_len) +{ + RTLIL::Const arg1_ext = arg1; + RTLIL::Const arg2_ext = arg2; + RTLIL::Const result(RTLIL::State::S0, result_len); + + int width = max(GetSize(arg1_ext), GetSize(arg2_ext)); + extend_u0(arg1_ext, width, signed1 && signed2); + extend_u0(arg2_ext, width, signed1 && signed2); + + for (auto i = 0; i < arg1_ext.size(); i++) { + if (arg1_ext.at(i) != arg2_ext.at(i)) + return result; + } + + result.set(0, RTLIL::State::S1); + return result; +} + +RTLIL::Const RTLIL::const_nex(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool signed2, int result_len) +{ + RTLIL::Const result = RTLIL::const_eqx(arg1, arg2, signed1, signed2, result_len); + if (result.front() == RTLIL::State::S0) + result.set(0, RTLIL::State::S1); + else if (result.front() == RTLIL::State::S1) + result.set(0, RTLIL::State::S0); + return result; +} + +RTLIL::Const RTLIL::const_ge(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool signed2, int result_len) +{ + int undef_bit_pos = -1; + bool y = const2big(arg1, signed1, undef_bit_pos) >= const2big(arg2, signed2, undef_bit_pos); + RTLIL::Const result(undef_bit_pos >= 0 ? RTLIL::State::Sx : y ? RTLIL::State::S1 : RTLIL::State::S0); + if (GetSize(result) < result_len) + result.resize(result_len, RTLIL::State::S0); + return result; +} + +RTLIL::Const RTLIL::const_gt(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool signed2, int result_len) +{ + int undef_bit_pos = -1; + bool y = const2big(arg1, signed1, undef_bit_pos) > const2big(arg2, signed2, undef_bit_pos); + RTLIL::Const result(undef_bit_pos >= 0 ? RTLIL::State::Sx : y ? RTLIL::State::S1 : RTLIL::State::S0); + if (GetSize(result) < result_len) + result.resize(result_len, RTLIL::State::S0); + return result; +} + +RTLIL::Const RTLIL::const_add(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool signed2, int result_len) +{ + int undef_bit_pos = -1; + BigInteger y = const2big(arg1, signed1, undef_bit_pos) + const2big(arg2, signed2, undef_bit_pos); + return big2const(y, result_len >= 0 ? result_len : max(GetSize(arg1), GetSize(arg2)), undef_bit_pos); +} + +RTLIL::Const RTLIL::const_sub(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool signed2, int result_len) +{ + int undef_bit_pos = -1; + BigInteger y = const2big(arg1, signed1, undef_bit_pos) - const2big(arg2, signed2, undef_bit_pos); + return big2const(y, result_len >= 0 ? result_len : max(GetSize(arg1), GetSize(arg2)), undef_bit_pos); +} + +RTLIL::Const RTLIL::const_mul(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool signed2, int result_len) +{ + int undef_bit_pos = -1; + BigInteger y = const2big(arg1, signed1, undef_bit_pos) * const2big(arg2, signed2, undef_bit_pos); + return big2const(y, result_len >= 0 ? result_len : max(GetSize(arg1), GetSize(arg2)), min(undef_bit_pos, 0)); +} + +// truncating division +RTLIL::Const RTLIL::const_div(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool signed2, int result_len) +{ + int undef_bit_pos = -1; + BigInteger a = const2big(arg1, signed1, undef_bit_pos); + BigInteger b = const2big(arg2, signed2, undef_bit_pos); + if (b.isZero()) + return RTLIL::Const(RTLIL::State::Sx, result_len); + bool result_neg = (a.getSign() == BigInteger::negative) != (b.getSign() == BigInteger::negative); + a = a.getSign() == BigInteger::negative ? -a : a; + b = b.getSign() == BigInteger::negative ? -b : b; + return big2const(result_neg ? -(a / b) : (a / b), result_len >= 0 ? result_len : max(GetSize(arg1), GetSize(arg2)), min(undef_bit_pos, 0)); +} + +// truncating modulo +RTLIL::Const RTLIL::const_mod(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool signed2, int result_len) +{ + int undef_bit_pos = -1; + BigInteger a = const2big(arg1, signed1, undef_bit_pos); + BigInteger b = const2big(arg2, signed2, undef_bit_pos); + if (b.isZero()) + return RTLIL::Const(RTLIL::State::Sx, result_len); + bool result_neg = a.getSign() == BigInteger::negative; + a = a.getSign() == BigInteger::negative ? -a : a; + b = b.getSign() == BigInteger::negative ? -b : b; + return big2const(result_neg ? -(a % b) : (a % b), result_len >= 0 ? result_len : max(GetSize(arg1), GetSize(arg2)), min(undef_bit_pos, 0)); +} + +RTLIL::Const RTLIL::const_divfloor(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool signed2, int result_len) +{ + int undef_bit_pos = -1; + BigInteger a = const2big(arg1, signed1, undef_bit_pos); + BigInteger b = const2big(arg2, signed2, undef_bit_pos); + if (b.isZero()) + return RTLIL::Const(RTLIL::State::Sx, result_len); + + bool result_pos = (a.getSign() == BigInteger::negative) == (b.getSign() == BigInteger::negative); + a = a.getSign() == BigInteger::negative ? -a : a; + b = b.getSign() == BigInteger::negative ? -b : b; + BigInteger result; + + if (result_pos || a == 0) { + result = a / b; + } else { + // bigint division with negative numbers is wonky, make sure we only negate at the very end + result = -((a + b - 1) / b); + } + return big2const(result, result_len >= 0 ? result_len : max(GetSize(arg1), GetSize(arg2)), min(undef_bit_pos, 0)); +} + +RTLIL::Const RTLIL::const_modfloor(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool signed2, int result_len) +{ + int undef_bit_pos = -1; + BigInteger a = const2big(arg1, signed1, undef_bit_pos); + BigInteger b = const2big(arg2, signed2, undef_bit_pos); + if (b.isZero()) + return RTLIL::Const(RTLIL::State::Sx, result_len); + + BigInteger::Sign a_sign = a.getSign(); + BigInteger::Sign b_sign = b.getSign(); + a = a_sign == BigInteger::negative ? -a : a; + b = b_sign == BigInteger::negative ? -b : b; + BigInteger truncated = a_sign == BigInteger::negative ? -(a % b) : (a % b); + BigInteger modulo; + + if (truncated == 0 || (a_sign == b_sign)) { + modulo = truncated; + } else { + modulo = b_sign == BigInteger::negative ? truncated - b : truncated + b; + } + return big2const(modulo, result_len >= 0 ? result_len : max(GetSize(arg1), GetSize(arg2)), min(undef_bit_pos, 0)); +} + +RTLIL::Const RTLIL::const_pow(const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool signed2, int result_len) +{ + int undef_bit_pos = -1; + + BigInteger a = const2big(arg1, signed1, undef_bit_pos); + BigInteger b = const2big(arg2, signed2, undef_bit_pos); + BigInteger y = 1; + + if (a == 0 && b < 0) + return RTLIL::Const(RTLIL::State::Sx, result_len); + + if (a == 0 && b > 0) + return RTLIL::Const(RTLIL::State::S0, result_len); + + if (b < 0) + { + if (a < -1 || a > 1) + y = 0; + if (a == -1) + y = (-b % 2) == 0 ? 1 : -1; + } + + if (b > 0) + { + // Power-modulo with 2^result_len as modulus + BigInteger modulus = 1; + int modulus_bits = (result_len >= 0 ? result_len : 1024); + for (int i = 0; i < modulus_bits; i++) + modulus *= 2; + + bool flip_result_sign = false; + if (a < 0) { + a *= -1; + if (b % 2 == 1) + flip_result_sign = true; + } + + while (b > 0) { + if (b % 2 == 1) + y = (y * a) % modulus; + b = b / 2; + a = (a * a) % modulus; + } + + if (flip_result_sign) + y *= -1; + } + + return big2const(y, result_len >= 0 ? result_len : max(GetSize(arg1), GetSize(arg2)), min(undef_bit_pos, 0)); +} + +RTLIL::Const RTLIL::const_pos(const RTLIL::Const &arg1, const RTLIL::Const&, bool signed1, bool, int result_len) +{ + RTLIL::Const arg1_ext = arg1; + extend_u0(arg1_ext, result_len, signed1); + + return arg1_ext; +} + +RTLIL::Const RTLIL::const_buf(const RTLIL::Const &arg1, const RTLIL::Const&, bool signed1, bool, int result_len) +{ + RTLIL::Const arg1_ext = arg1; + extend_u0(arg1_ext, result_len, signed1); + + return arg1_ext; +} + +RTLIL::Const RTLIL::const_neg(const RTLIL::Const &arg1, const RTLIL::Const&, bool signed1, bool, int result_len) +{ + RTLIL::Const arg1_ext = arg1; + RTLIL::Const zero(RTLIL::State::S0, 1); + + return RTLIL::const_sub(zero, arg1_ext, true, signed1, result_len); +} + +RTLIL::Const RTLIL::const_mux(const RTLIL::Const &arg1, const RTLIL::Const &arg2, const RTLIL::Const &arg3) +{ + log_assert(arg2.size() == arg1.size()); + if (arg3[0] == State::S0) + return arg1; + else if (arg3[0] == State::S1) + return arg2; + + RTLIL::Const ret = arg1; + for (auto i = 0; i < ret.size(); i++) + if (ret[i] != arg2[i]) + ret.set(i, State::Sx); + return ret; +} + +RTLIL::Const RTLIL::const_pmux(const RTLIL::Const &arg1, const RTLIL::Const &arg2, const RTLIL::Const &arg3) +{ + if (arg3.is_fully_zero()) + return arg1; + + if (!arg3.is_onehot()) + return RTLIL::Const(State::Sx, arg1.size()); + + for (auto i = 0; i < arg3.size(); i++) + if (arg3[i] == State::S1) + return RTLIL::Const(std::vector(arg2.begin() + i*arg1.size(), arg2.begin() + (i+1)*arg1.size())); + + log_abort(); // unreachable +} + +RTLIL::Const RTLIL::const_bmux(const RTLIL::Const &arg1, const RTLIL::Const &arg2) +{ + std::vector t = arg1.to_bits(); + + for (int i = GetSize(arg2)-1; i >= 0; i--) + { + RTLIL::State sel = arg2.at(i); + std::vector new_t; + if (sel == State::S0) + new_t = std::vector(t.begin(), t.begin() + GetSize(t)/2); + else if (sel == State::S1) + new_t = std::vector(t.begin() + GetSize(t)/2, t.end()); + else + for (int j = 0; j < GetSize(t)/2; j++) + new_t.push_back(t[j] == t[j + GetSize(t)/2] ? t[j] : RTLIL::Sx); + t.swap(new_t); + } + + return t; +} + +RTLIL::Const RTLIL::const_demux(const RTLIL::Const &arg1, const RTLIL::Const &arg2) +{ + int width = GetSize(arg1); + int s_width = GetSize(arg2); + std::vector res; + for (int i = 0; i < (1 << s_width); i++) + { + bool ne = false; + bool x = false; + for (int j = 0; j < s_width; j++) { + bool bit = i & 1 << j; + if (arg2[j] == (bit ? RTLIL::S0 : RTLIL::S1)) + ne = true; + else if (arg2[j] != RTLIL::S0 && arg2[j] != RTLIL::S1) + x = true; + } + if (ne) { + for (int j = 0; j < width; j++) + res.push_back(State::S0); + } else if (x) { + for (int j = 0; j < width; j++) + res.push_back(arg1[j] == State::S0 ? State::S0 : State::Sx); + } else { + for (int j = 0; j < width; j++) + res.push_back(arg1[j]); + } + } + return res; +} + +RTLIL::Const RTLIL::const_bweqx(const RTLIL::Const &arg1, const RTLIL::Const &arg2) +{ + log_assert(arg2.size() == arg1.size()); + RTLIL::Const result(RTLIL::State::S0, arg1.size()); + for (auto i = 0; i < arg1.size(); i++) + result.set(i, arg1[i] == arg2[i] ? State::S1 : State::S0); + + return result; +} + +RTLIL::Const RTLIL::const_bwmux(const RTLIL::Const &arg1, const RTLIL::Const &arg2, const RTLIL::Const &arg3) +{ + log_assert(arg2.size() == arg1.size()); + log_assert(arg3.size() == arg1.size()); + RTLIL::Const result(RTLIL::State::Sx, arg1.size()); + for (auto i = 0; i < arg1.size(); i++) { + if (arg3[i] != State::Sx || arg1[i] == arg2[i]) + result.set(i, arg3[i] == State::S1 ? arg2[i] : arg1[i]); + } + + return result; +} + +YOSYS_NAMESPACE_END diff --git a/chips/yosys/kernel/cellaigs.cc b/chips/yosys/kernel/cellaigs.cc new file mode 100644 index 0000000000000000000000000000000000000000..91da8286cd8a3285bafd3f1eeabc715cb1e8d207 --- /dev/null +++ b/chips/yosys/kernel/cellaigs.cc @@ -0,0 +1,531 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/cellaigs.h" + +YOSYS_NAMESPACE_BEGIN + +AigNode::AigNode() +{ + portbit = -1; + inverter = false; + left_parent = -1; + right_parent = -1; +} + +bool AigNode::operator==(const AigNode &other) const +{ + if (portname != other.portname) return false; + if (portbit != other.portbit) return false; + if (inverter != other.inverter) return false; + if (left_parent != other.left_parent) return false; + if (right_parent != other.right_parent) return false; + return true; +} + +Hasher AigNode::hash_into(Hasher h) const +{ + h.eat(portname); + h.eat(portbit); + h.eat(inverter); + h.eat(left_parent); + h.eat(right_parent); + return h; +} + +bool Aig::operator==(const Aig &other) const +{ + return name == other.name; +} + +Hasher Aig::hash_into(Hasher h) const +{ + h.eat(name); + return h; +} + +struct AigMaker +{ + Aig *aig; + Cell *cell; + idict aig_indices; + + AigMaker(Aig *aig, Cell *cell) : aig(aig), cell(cell) {} + + int node2index(const AigNode &node) + { + if (node.left_parent > node.right_parent) { + AigNode n(node); + std::swap(n.left_parent, n.right_parent); + return node2index(n); + } + + if (!aig_indices.count(node)) { + aig_indices.expect(node, GetSize(aig->nodes)); + aig->nodes.push_back(node); + } + + return aig_indices.at(node); + } + + int bool_node(bool value) + { + AigNode node; + node.inverter = value; + return node2index(node); + } + + int inport(IdString portname, int portbit = 0, bool inverter = false) + { + if (portbit >= GetSize(cell->getPort(portname))) { + IdString signed_param = cell->twines().find( + cell->twines().str(portname) + "_SIGNED"); + if (signed_param != IdString::Null && cell->parameters.count(signed_param) && cell->getParam(signed_param).as_bool()) + return inport(portname, GetSize(cell->getPort(portname))-1, inverter); + return bool_node(inverter); + } + + AigNode node; + node.portname = portname; + node.portbit = portbit; + node.inverter = inverter; + return node2index(node); + } + + vector inport_vec(IdString portname, int width) + { + vector vec; + for (int i = 0; i < width; i++) + vec.push_back(inport(portname, i)); + return vec; + } + + int not_inport(IdString portname, int portbit = 0) + { + return inport(portname, portbit, true); + } + + int not_gate(int A) + { + AigNode node(aig_indices[A]); + node.outports.clear(); + node.inverter = !node.inverter; + return node2index(node); + } + + int and_gate(int A, int B, bool inverter = false) + { + if (A == B) + return inverter ? not_gate(A) : A; + + const AigNode &nA = aig_indices[A]; + const AigNode &nB = aig_indices[B]; + + AigNode nB_inv(nB); + nB_inv.inverter = !nB_inv.inverter; + + if (nA == nB_inv) + return bool_node(inverter); + + bool nA_bool = nA.portbit < 0 && nA.left_parent < 0 && nA.right_parent < 0; + bool nB_bool = nB.portbit < 0 && nB.left_parent < 0 && nB.right_parent < 0; + + if (nA_bool && nB_bool) { + bool bA = nA.inverter; + bool bB = nB.inverter; + return bool_node(inverter != (bA && bB)); + } + + if (nA_bool) { + bool bA = nA.inverter; + if (inverter) + return bA ? not_gate(B) : bool_node(true); + return bA ? B : bool_node(false); + } + + if (nB_bool) { + bool bB = nB.inverter; + if (inverter) + return bB ? not_gate(A) : bool_node(true); + return bB ? A : bool_node(false); + } + + AigNode node; + node.inverter = inverter; + node.left_parent = A; + node.right_parent = B; + return node2index(node); + } + + int nand_gate(int A, int B) + { + return and_gate(A, B, true); + } + + int or_gate(int A, int B) + { + int not_a = not_gate(A); + int not_b = not_gate(B); + return nand_gate(not_a, not_b); + } + + int nor_gate(int A, int B) + { + int not_a = not_gate(A); + int not_b = not_gate(B); + return and_gate(not_a, not_b); + } + + int xor_gate(int A, int B) + { + int a_and_b = and_gate(A, B); + int a_nor_b = nor_gate(A, B); + return nor_gate(a_and_b, a_nor_b); + } + + int xnor_gate(int A, int B) + { + int a_and_b = and_gate(A, B); + int a_nor_b = nor_gate(A, B); + return or_gate(a_and_b, a_nor_b); + } + + int andnot_gate(int A, int B) + { + int not_b = not_gate(B); + return and_gate(A, not_b); + } + + int ornot_gate(int A, int B) + { + int not_b = not_gate(B); + return or_gate(A, not_b); + } + + int mux_gate(int A, int B, int S) + { + int not_s = not_gate(S); + int a_active = and_gate(A, not_s); + int b_active = and_gate(B, S); + return or_gate(a_active, b_active); + } + + vector adder(const vector &A, const vector &B, int carry_in, vector *X = nullptr, vector *CO = nullptr) + { + vector Y(GetSize(A)); + log_assert(GetSize(A) == GetSize(B)); + for (int i = 0; i < GetSize(A); i++) { + int a_xor_b = xor_gate(A[i], B[i]); + int a_or_b = or_gate(A[i], B[i]); + int a_and_b = and_gate(A[i], B[i]); + Y[i] = xor_gate(a_xor_b, carry_in); + int tmp = and_gate(a_or_b, carry_in); + int carry_out = or_gate(a_and_b, tmp); + if (X != nullptr) + X->at(i) = a_xor_b; + if (CO != nullptr) + CO->at(i) = carry_out; + carry_in = carry_out; + } + return Y; + } + + void outport(int node, IdString portname, int portbit = 0) + { + if (portbit < GetSize(cell->getPort(portname))) + aig->nodes.at(node).outports.push_back(pair(portname, portbit)); + } + + void outport_bool(int node, IdString portname) + { + outport(node, portname); + for (int i = 1; i < GetSize(cell->getPort(portname)); i++) + outport(bool_node(false), portname, i); + } + + void outport_vec(const vector &vec, IdString portname) + { + for (int i = 0; i < GetSize(vec); i++) + outport(vec.at(i), portname, i); + } +}; + +Aig::Aig(Cell *cell) +{ + if (cell->type.isPublic()) + return; + + AigMaker mk(this, cell); + name = cell->type.str(); + + string mkname_last; + bool mkname_a_signed = false; + bool mkname_b_signed = false; + bool mkname_is_signed = false; + + cell->parameters.sort(); + for (auto p : cell->parameters) + { + if (p.first == ID::A_WIDTH && mkname_a_signed) { + name = mkname_last + stringf(":%d%c", p.second.as_int(), mkname_is_signed ? 'S' : 'U'); + } else if (p.first == ID::B_WIDTH && mkname_b_signed) { + name = mkname_last + stringf(":%d%c", p.second.as_int(), mkname_is_signed ? 'S' : 'U'); + } else { + mkname_last = name; + name += stringf(":%d", p.second.as_int()); + } + + mkname_a_signed = false; + mkname_b_signed = false; + mkname_is_signed = false; + if (p.first == ID::A_SIGNED) { + mkname_a_signed = true; + mkname_is_signed = p.second.as_bool(); + } + if (p.first == ID::B_SIGNED) { + mkname_b_signed = true; + mkname_is_signed = p.second.as_bool(); + } + } + + if (cell->type.in(ID($not), ID($_NOT_), ID($pos), ID($buf), ID($_BUF_))) + { + for (int i = 0; i < GetSize(cell->getPort(ID::Y)); i++) { + int A = mk.inport(ID::A, i); + int Y = cell->type.in(ID($not), ID($_NOT_)) ? mk.not_gate(A) : A; + mk.outport(Y, ID::Y, i); + } + goto optimize; + } + + if (cell->type.in(ID($and), ID($_AND_), ID($_NAND_), ID($or), ID($_OR_), ID($_NOR_), ID($xor), ID($xnor), ID($_XOR_), ID($_XNOR_), ID($_ANDNOT_), ID($_ORNOT_))) + { + for (int i = 0; i < GetSize(cell->getPort(ID::Y)); i++) { + int A = mk.inport(ID::A, i); + int B = mk.inport(ID::B, i); + int Y = cell->type.in(ID($and), ID($_AND_)) ? mk.and_gate(A, B) : + cell->type.in(ID($_NAND_)) ? mk.nand_gate(A, B) : + cell->type.in(ID($or), ID($_OR_)) ? mk.or_gate(A, B) : + cell->type.in(ID($_NOR_)) ? mk.nor_gate(A, B) : + cell->type.in(ID($xor), ID($_XOR_)) ? mk.xor_gate(A, B) : + cell->type.in(ID($xnor), ID($_XNOR_)) ? mk.xnor_gate(A, B) : + cell->type.in(ID($_ANDNOT_)) ? mk.andnot_gate(A, B) : + cell->type.in(ID($_ORNOT_)) ? mk.ornot_gate(A, B) : -1; + mk.outport(Y, ID::Y, i); + } + goto optimize; + } + + if (cell->type.in(ID($mux), ID($_MUX_), ID($_NMUX_))) + { + int S = mk.inport(ID::S); + for (int i = 0; i < GetSize(cell->getPort(ID::Y)); i++) { + int A = mk.inport(ID::A, i); + int B = mk.inport(ID::B, i); + int Y = mk.mux_gate(A, B, S); + if (cell->type == ID($_NMUX_)) + Y = mk.not_gate(Y); + mk.outport(Y, ID::Y, i); + } + goto optimize; + } + + if (cell->type.in(ID($reduce_and), ID($reduce_or), ID($reduce_xor), ID($reduce_xnor), ID($reduce_bool))) + { + int Y = mk.inport(ID::A, 0); + for (int i = 1; i < GetSize(cell->getPort(ID::A)); i++) { + int A = mk.inport(ID::A, i); + if (cell->type == ID($reduce_and)) Y = mk.and_gate(A, Y); + if (cell->type == ID($reduce_or)) Y = mk.or_gate(A, Y); + if (cell->type == ID($reduce_bool)) Y = mk.or_gate(A, Y); + if (cell->type == ID($reduce_xor)) Y = mk.xor_gate(A, Y); + if (cell->type == ID($reduce_xnor)) Y = mk.xor_gate(A, Y); + } + if (cell->type == ID($reduce_xnor)) + Y = mk.not_gate(Y); + mk.outport(Y, ID::Y, 0); + for (int i = 1; i < GetSize(cell->getPort(ID::Y)); i++) + mk.outport(mk.bool_node(false), ID::Y, i); + goto optimize; + } + + if (cell->type.in(ID($logic_not), ID($logic_and), ID($logic_or))) + { + int A = mk.inport(ID::A, 0), Y = -1; + for (int i = 1; i < GetSize(cell->getPort(ID::A)); i++) + A = mk.or_gate(mk.inport(ID::A, i), A); + if (cell->type.in(ID($logic_and), ID($logic_or))) { + int B = mk.inport(ID::B, 0); + for (int i = 1; i < GetSize(cell->getPort(ID::B)); i++) + B = mk.or_gate(mk.inport(ID::B, i), B); + if (cell->type == ID($logic_and)) Y = mk.and_gate(A, B); + if (cell->type == ID($logic_or)) Y = mk.or_gate(A, B); + } else { + if (cell->type == ID($logic_not)) Y = mk.not_gate(A); + } + mk.outport_bool(Y, ID::Y); + goto optimize; + } + + if (cell->type.in(ID($add), ID($sub))) + { + int width = GetSize(cell->getPort(ID::Y)); + vector A = mk.inport_vec(ID::A, width); + vector B = mk.inport_vec(ID::B, width); + int carry = mk.bool_node(false); + if (cell->type == ID($sub)) { + for (auto &n : B) + n = mk.not_gate(n); + carry = mk.not_gate(carry); + } + vector Y = mk.adder(A, B, carry); + mk.outport_vec(Y, ID::Y); + goto optimize; + } + + if (cell->type.in(ID($lt), ID($gt), ID($le), ID($ge))) + { + int width = std::max(GetSize(cell->getPort(ID::A)), + GetSize(cell->getPort(ID::B))) + 1; + vector A = mk.inport_vec(ID::A, width); + vector B = mk.inport_vec(ID::B, width); + + if (cell->type.in(ID($gt), ID($ge))) + std::swap(A, B); + + int carry = mk.bool_node(!cell->type.in(ID($le), ID($ge))); + for (auto &n : B) + n = mk.not_gate(n); + vector Y = mk.adder(A, B, carry); + mk.outport(Y.back(), ID::Y); + for (int i = 1; i < GetSize(cell->getPort(ID::Y)); i++) + mk.outport(mk.bool_node(false), ID::Y, i); + goto optimize; + } + + if (cell->type == ID($alu)) + { + int width = GetSize(cell->getPort(ID::Y)); + vector A = mk.inport_vec(ID::A, width); + vector B = mk.inport_vec(ID::B, width); + int carry = mk.inport(ID::CI); + int binv = mk.inport(ID::BI); + for (auto &n : B) + n = mk.xor_gate(n, binv); + vector X(width), CO(width); + vector Y = mk.adder(A, B, carry, &X, &CO); + for (int i = 0; i < width; i++) + X[i] = mk.xor_gate(A[i], B[i]); + mk.outport_vec(Y, ID::Y); + mk.outport_vec(X, ID::X); + mk.outport_vec(CO, ID::CO); + goto optimize; + } + + if (cell->type.in(ID($eq), ID($ne))) + { + int width = max(GetSize(cell->getPort(ID::A)), GetSize(cell->getPort(ID::B))); + vector A = mk.inport_vec(ID::A, width); + vector B = mk.inport_vec(ID::B, width); + int Y = mk.bool_node(false); + for (int i = 0; i < width; i++) + Y = mk.or_gate(Y, mk.xor_gate(A[i], B[i])); + if (cell->type == ID($eq)) + Y = mk.not_gate(Y); + mk.outport_bool(Y, ID::Y); + goto optimize; + } + + if (cell->type == ID($_AOI3_)) + { + int A = mk.inport(ID::A); + int B = mk.inport(ID::B); + int C = mk.inport(ID::C); + int Y = mk.nor_gate(mk.and_gate(A, B), C); + mk.outport(Y, ID::Y); + goto optimize; + } + + if (cell->type == ID($_OAI3_)) + { + int A = mk.inport(ID::A); + int B = mk.inport(ID::B); + int C = mk.inport(ID::C); + int Y = mk.nand_gate(mk.or_gate(A, B), C); + mk.outport(Y, ID::Y); + goto optimize; + } + + if (cell->type == ID($_AOI4_)) + { + int A = mk.inport(ID::A); + int B = mk.inport(ID::B); + int C = mk.inport(ID::C); + int D = mk.inport(ID::D); + int a_and_b = mk.and_gate(A, B); + int Y = mk.nor_gate(a_and_b, mk.and_gate(C, D)); + mk.outport(Y, ID::Y); + goto optimize; + } + + if (cell->type == ID($_OAI4_)) + { + int A = mk.inport(ID::A); + int B = mk.inport(ID::B); + int C = mk.inport(ID::C); + int D = mk.inport(ID::D); + int a_or_b = mk.or_gate(A, B); + int Y = mk.nand_gate(a_or_b, mk.or_gate(C, D)); + mk.outport(Y, ID::Y); + goto optimize; + } + + name.clear(); + return; + +optimize:; + pool used_old_ids; + vector new_nodes; + dict old_to_new_ids; + old_to_new_ids[-1] = -1; + + for (int i = GetSize(nodes)-1; i >= 0; i--) { + if (!nodes[i].outports.empty()) + used_old_ids.insert(i); + if (!used_old_ids.count(i)) + continue; + if (nodes[i].left_parent >= 0) + used_old_ids.insert(nodes[i].left_parent); + if (nodes[i].right_parent >= 0) + used_old_ids.insert(nodes[i].right_parent); + } + + for (int i = 0; i < GetSize(nodes); i++) { + if (!used_old_ids.count(i)) + continue; + nodes[i].left_parent = old_to_new_ids.at(nodes[i].left_parent); + nodes[i].right_parent = old_to_new_ids.at(nodes[i].right_parent); + old_to_new_ids[i] = GetSize(new_nodes); + new_nodes.push_back(nodes[i]); + } + + new_nodes.swap(nodes); +} + +YOSYS_NAMESPACE_END diff --git a/chips/yosys/kernel/cellaigs.h b/chips/yosys/kernel/cellaigs.h new file mode 100644 index 0000000000000000000000000000000000000000..f6afcde5edb80ad7bd27c464a99420838a350630 --- /dev/null +++ b/chips/yosys/kernel/cellaigs.h @@ -0,0 +1,52 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#ifndef CELLAIGS_H +#define CELLAIGS_H + +#include "kernel/yosys.h" + +YOSYS_NAMESPACE_BEGIN + +struct AigNode +{ + IdString portname; + int portbit; + bool inverter; + int left_parent, right_parent; + vector> outports; + + AigNode(); + bool operator==(const AigNode &other) const; + [[nodiscard]] Hasher hash_into(Hasher h) const; +}; + +struct Aig +{ + string name; + vector nodes; + Aig(Cell *cell); + + bool operator==(const Aig &other) const; + [[nodiscard]] Hasher hash_into(Hasher h) const; +}; + +YOSYS_NAMESPACE_END + +#endif diff --git a/chips/yosys/kernel/celledges.cc b/chips/yosys/kernel/celledges.cc new file mode 100644 index 0000000000000000000000000000000000000000..780e25eba0584cca6a4a70f3e1de0f846b6e0c29 --- /dev/null +++ b/chips/yosys/kernel/celledges.cc @@ -0,0 +1,599 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/celledges.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +void bitwise_unary_op(AbstractCellEdgesDatabase *db, RTLIL::Cell *cell) +{ + bool is_signed = !cell->type.in(ID($buf), ID($barrier)) && cell->getParam(ID::A_SIGNED).as_bool(); + int a_width = GetSize(cell->getPort(ID::A)); + int y_width = GetSize(cell->getPort(ID::Y)); + + for (int i = 0; i < y_width; i++) + { + if (i < a_width) + db->add_edge(cell, ID::A, i, ID::Y, i, -1); + else if (is_signed && a_width > 0) + db->add_edge(cell, ID::A, a_width-1, ID::Y, i, -1); + } +} + +void bitwise_binary_op(AbstractCellEdgesDatabase *db, RTLIL::Cell *cell) +{ + bool is_signed = cell->getParam(ID::A_SIGNED).as_bool(); + int a_width = GetSize(cell->getPort(ID::A)); + int b_width = GetSize(cell->getPort(ID::B)); + int y_width = GetSize(cell->getPort(ID::Y)); + + if (cell->type == ID($and) && !is_signed) { + if (a_width > b_width) + a_width = b_width; + else + b_width = a_width; + } + + for (int i = 0; i < y_width; i++) + { + if (i < a_width) + db->add_edge(cell, ID::A, i, ID::Y, i, -1); + else if (is_signed && a_width > 0) + db->add_edge(cell, ID::A, a_width-1, ID::Y, i, -1); + + if (i < b_width) + db->add_edge(cell, ID::B, i, ID::Y, i, -1); + else if (is_signed && b_width > 0) + db->add_edge(cell, ID::B, b_width-1, ID::Y, i, -1); + } +} + +void arith_neg_op(AbstractCellEdgesDatabase *db, RTLIL::Cell *cell) +{ + bool is_signed = cell->getParam(ID::A_SIGNED).as_bool(); + int a_width = GetSize(cell->getPort(ID::A)); + int y_width = GetSize(cell->getPort(ID::Y)); + + if (is_signed && a_width == 1) + y_width = std::min(y_width, 1); + + for (int i = 0; i < y_width; i++) + for (int k = 0; k <= i && k < a_width; k++) + db->add_edge(cell, ID::A, k, ID::Y, i, -1); +} + +void arith_binary_op(AbstractCellEdgesDatabase *db, RTLIL::Cell *cell) +{ + bool is_signed = cell->getParam(ID::A_SIGNED).as_bool(); + int a_width = GetSize(cell->getPort(ID::A)); + int b_width = GetSize(cell->getPort(ID::B)); + int y_width = GetSize(cell->getPort(ID::Y)); + + if (!is_signed && cell->type != ID($sub)) { + int ab_width = std::max(a_width, b_width); + y_width = std::min(y_width, ab_width+1); + } + + for (int i = 0; i < y_width; i++) + { + for (int k = 0; k <= i; k++) + { + if (k < a_width) + db->add_edge(cell, ID::A, k, ID::Y, i, -1); + + if (k < b_width) + db->add_edge(cell, ID::B, k, ID::Y, i, -1); + } + } +} + +void reduce_op(AbstractCellEdgesDatabase *db, RTLIL::Cell *cell) +{ + int a_width = GetSize(cell->getPort(ID::A)); + + for (int i = 0; i < a_width; i++) + db->add_edge(cell, ID::A, i, ID::Y, 0, -1); +} + +void logic_op(AbstractCellEdgesDatabase *db, RTLIL::Cell *cell) +{ + int a_width = GetSize(cell->getPort(ID::A)); + int b_width = GetSize(cell->getPort(ID::B)); + + for (int i = 0; i < a_width; i++) + db->add_edge(cell, ID::A, i, ID::Y, 0, -1); + for (int i = 0; i < b_width; i++) + db->add_edge(cell, ID::B, i, ID::Y, 0, -1); +} + +void concat_op(AbstractCellEdgesDatabase *db, RTLIL::Cell *cell) +{ + int a_width = GetSize(cell->getPort(ID::A)); + int b_width = GetSize(cell->getPort(ID::B)); + + for (int i = 0; i < a_width; i++) + db->add_edge(cell, ID::A, i, ID::Y, i, -1); + for (int i = 0; i < b_width; i++) + db->add_edge(cell, ID::B, i, ID::Y, a_width + i, -1); +} + +void slice_op(AbstractCellEdgesDatabase *db, RTLIL::Cell *cell) +{ + int offset = cell->getParam(ID::OFFSET).as_int(); + int a_width = GetSize(cell->getPort(ID::A)); + int y_width = GetSize(cell->getPort(ID::Y)); + + for (int i = 0; i < y_width; i++) { + int a_bit = offset + i; + if (a_bit >= 0 && a_bit < a_width) + db->add_edge(cell, ID::A, a_bit, ID::Y, i, -1); + } +} + +void compare_op(AbstractCellEdgesDatabase *db, RTLIL::Cell *cell) +{ + int a_width = GetSize(cell->getPort(ID::A)); + int b_width = GetSize(cell->getPort(ID::B)); + + for (int i = 0; i < a_width; i++) + db->add_edge(cell, ID::A, i, ID::Y, 0, -1); + + for (int i = 0; i < b_width; i++) + db->add_edge(cell, ID::B, i, ID::Y, 0, -1); +} + +void mux_op(AbstractCellEdgesDatabase *db, RTLIL::Cell *cell) +{ + int a_width = GetSize(cell->getPort(ID::A)); + int b_width = GetSize(cell->getPort(ID::B)); + int s_width = GetSize(cell->getPort(ID::S)); + + for (int i = 0; i < a_width; i++) + { + db->add_edge(cell, ID::A, i, ID::Y, i, -1); + + for (int k = i; k < b_width; k += a_width) + db->add_edge(cell, ID::B, k, ID::Y, i, -1); + + for (int k = 0; k < s_width; k++) + db->add_edge(cell, ID::S, k, ID::Y, i, -1); + } +} + +void bmux_op(AbstractCellEdgesDatabase *db, RTLIL::Cell *cell) +{ + int width = GetSize(cell->getPort(ID::Y)); + int a_width = GetSize(cell->getPort(ID::A)); + int s_width = GetSize(cell->getPort(ID::S)); + + for (int i = 0; i < width; i++) + { + for (int k = i; k < a_width; k += width) + db->add_edge(cell, ID::A, k, ID::Y, i, -1); + + for (int k = 0; k < s_width; k++) + db->add_edge(cell, ID::S, k, ID::Y, i, -1); + } +} + +void demux_op(AbstractCellEdgesDatabase *db, RTLIL::Cell *cell) +{ + int width = GetSize(cell->getPort(ID::Y)); + int a_width = GetSize(cell->getPort(ID::A)); + int s_width = GetSize(cell->getPort(ID::S)); + + for (int i = 0; i < width; i++) + { + db->add_edge(cell, ID::A, i % a_width, ID::Y, i, -1); + for (int k = 0; k < s_width; k++) + db->add_edge(cell, ID::S, k, ID::Y, i, -1); + } +} + +void shift_op(AbstractCellEdgesDatabase *db, RTLIL::Cell *cell) +{ + bool is_signed = cell->getParam(ID::A_SIGNED).as_bool(); + bool is_b_signed = cell->getParam(ID::B_SIGNED).as_bool(); + int a_width = GetSize(cell->getPort(ID::A)); + int b_width = GetSize(cell->getPort(ID::B)); + int y_width = GetSize(cell->getPort(ID::Y)); + + // Behavior of the different shift cells: + // + // $shl, $sshl -- shifts left by the amount on B port, B always unsigned + // $shr, $sshr -- ditto right + // $shift, $shiftx -- shifts right by the amount on B port, B optionally signed + // + // Sign extension (if A signed): + // + // $shl, $shr, $shift -- only sign-extends up to size of Y, then shifts in zeroes + // $sshl, $sshr -- fully sign-extends + // $shiftx -- no sign extension + // + // Because $shl, $sshl only shift left, and $shl sign-extens up to size of Y, they + // are effectively the same. + + // the cap below makes sure we don't overflow in the arithmetic further down, though + // it makes the edge data invalid once a_width approaches the order of 2**30 + // (that ever happening is considered improbable) + int b_width_capped = min(b_width, 30); + + int b_high, b_low; + if (!is_b_signed) { + b_high = (1 << b_width_capped) - 1; + b_low = 0; + } else { + b_high = (1 << (b_width_capped - 1)) - 1; + b_low = -(1 << (b_width_capped - 1)); + } + + for (int i = 0; i < y_width; i++){ + // highest position of Y that can change with the value of B + int b_range_upper = 0; + // 1 + highest position of A that can be moved to Y[i] + int a_range_upper; + // lowest position of A that can be moved to Y[i] + int a_range_lower; + + if (cell->type.in(ID($shl), ID($sshl))) { + b_range_upper = a_width + b_high; + if (is_signed) b_range_upper -= 1; + a_range_lower = max(0, i - b_high); + a_range_upper = min(i+1, a_width); + } else if (cell->type.in(ID($shr), ID($sshr)) || (cell->type.in(ID($shift), ID($shiftx)) && !is_b_signed)) { + b_range_upper = a_width; + a_range_lower = min(i, a_width - 1); + a_range_upper = min(i+1 + b_high, a_width); + } else if (cell->type.in(ID($shift), ID($shiftx)) && is_b_signed) { + // can go both ways depending on sign of B + // 2's complement range is different depending on direction + b_range_upper = a_width - b_low; + a_range_lower = max(0, i + b_low); + if (is_signed) + a_range_lower = min(a_range_lower, a_width - 1); + a_range_upper = min(i+1 + b_high, a_width); + } else { + log_assert(false && "unreachable"); + } + + if (i < b_range_upper) { + for (int k = a_range_lower; k < a_range_upper; k++) + db->add_edge(cell, ID::A, k, ID::Y, i, -1); + } else { + // only influence is through sign extension + if (is_signed) + db->add_edge(cell, ID::A, a_width - 1, ID::Y, i, -1); + } + + for (int k = 0; k < b_width_capped; k++) { + // left shifts + if (cell->type.in(ID($shl), ID($sshl))) { + if (a_width == 1 && is_signed) { + int skip = 1 << (k + 1); + int base = skip -1; + if (i % skip != base && i - a_width + 2 < 1 << b_width_capped) + db->add_edge(cell, ID::B, k, ID::Y, i, -1); + } else if (is_signed) { + if (i - a_width + 2 < 1 << b_width_capped) + db->add_edge(cell, ID::B, k, ID::Y, i, -1); + } else { + if (i - a_width + 1 < 1 << b_width_capped) + db->add_edge(cell, ID::B, k, ID::Y, i, -1); + } + // right shifts + } else if (cell->type.in(ID($shr), ID($sshr)) || (cell->type.in(ID($shift), ID($shiftx)) && !is_b_signed)) { + if (is_signed) { + bool shift_in_bulk = i < a_width - 1; + // can we jump into the zero-padding by toggling B[k]? + bool zpad_jump = (((y_width - i) & ((1 << (k + 1)) - 1)) != 0 \ + && (((y_width - i) & ~(1 << k)) < (1 << b_width_capped))); + + if (shift_in_bulk || (cell->type.in(ID($shr), ID($shift), ID($shiftx)) && zpad_jump)) + db->add_edge(cell, ID::B, k, ID::Y, i, -1); + } else { + if (i < a_width) + db->add_edge(cell, ID::B, k, ID::Y, i, -1); + } + // bidirectional shifts (positive B shifts right, negative left) + } else if (cell->type.in(ID($shift), ID($shiftx)) && is_b_signed) { + if (is_signed) { + if (k != b_width_capped - 1) { + bool r_shift_in_bulk = i < a_width - 1; + // assuming B is positive, can we jump into the upper zero-padding by toggling B[k]? + bool r_zpad_jump = (((y_width - i) & ((1 << (k + 1)) - 1)) != 0 \ + && (((y_width - i) & ~(1 << k)) <= b_high)); + // assuming B is negative, can we influence Y[i] by toggling B[k]? + bool l = a_width - 2 - i >= b_low; + if (a_width == 1) { + // in case of a_width==1 we go into more detailed reasoning + l = l && (~(i - a_width) & ((1 << (k + 1)) - 1)) != 0; + } + if (r_shift_in_bulk || r_zpad_jump || l) + db->add_edge(cell, ID::B, k, ID::Y, i, -1); + } else { + if (y_width - i <= b_high || a_width - 2 - i >= b_low) + db->add_edge(cell, ID::B, k, ID::Y, i, -1); + } + } else { + if (a_width - 1 - i >= b_low) + db->add_edge(cell, ID::B, k, ID::Y, i, -1); + } + } else { + log_assert(false && "unreachable"); + } + } + } +} + +void packed_mem_op(AbstractCellEdgesDatabase *db, RTLIL::Cell *cell) +{ + log_assert(cell->type == ID($mem_v2)); + Const rd_clk_enable = cell->getParam(ID::RD_CLK_ENABLE); + int n_rd_ports = cell->getParam(ID::RD_PORTS).as_int(); + int abits = cell->getParam(ID::ABITS).as_int(); + int width = cell->getParam(ID::WIDTH).as_int(); + + for (int i = 0; i < n_rd_ports; i++) { + if (rd_clk_enable[i] != State::S0) { + for (int k = 0; k < width; k++) + db->add_edge(cell, ID::RD_ARST, i, ID::RD_DATA, i * width + k, -1); + continue; + } + + for (int j = 0; j < abits; j++) + for (int k = 0; k < width; k++) + db->add_edge(cell, ID::RD_ADDR, i * abits + j, + ID::RD_DATA, i * width + k, -1); + } +} + +void memrd_op(AbstractCellEdgesDatabase *db, RTLIL::Cell *cell) +{ + log_assert(cell->type.in(ID($memrd), ID($memrd_v2))); + int abits = cell->getParam(ID::ABITS).as_int(); + int width = cell->getParam(ID::WIDTH).as_int(); + + if (cell->getParam(ID::CLK_ENABLE).as_bool()) { + if (cell->type == ID($memrd_v2)) { + for (int k = 0; k < width; k++) + db->add_edge(cell, ID::ARST, 0, ID::DATA, k, -1); + } + return; + } + + for (int j = 0; j < abits; j++) + for (int k = 0; k < width; k++) + db->add_edge(cell, ID::ADDR, j, ID::DATA, k, -1); +} + +void mem_op(AbstractCellEdgesDatabase *db, RTLIL::Cell *cell) +{ + if (cell->type == ID($mem_v2)) + packed_mem_op(db, cell); + else if (cell->type.in(ID($memrd), ID($memrd_v2))) + memrd_op(db, cell); + else if (cell->type.in(ID($memwr), ID($memwr_v2), ID($meminit))) + return; /* no edges here */ + else + log_abort(); +} + +void ff_op(AbstractCellEdgesDatabase *db, RTLIL::Cell *cell) +{ + int width = cell->getPort(ID::Q).size(); + + if (cell->type.in(ID($dlatch), ID($adlatch), ID($dlatchsr))) { + for (int k = 0; k < width; k++) { + db->add_edge(cell, ID::D, k, ID::Q, k, -1); + db->add_edge(cell, ID::EN, 0, ID::Q, k, -1); + } + } + + if (cell->hasPort(ID::CLR)) + for (int k = 0; k < width; k++) + db->add_edge(cell, ID::CLR, 0, ID::Q, k, -1); + if (cell->hasPort(ID::SET)) + for (int k = 0; k < width; k++) + db->add_edge(cell, ID::SET, 0, ID::Q, k, -1); + if (cell->hasPort(ID::ALOAD)) + for (int k = 0; k < width; k++) + db->add_edge(cell, ID::ALOAD, 0, ID::Q, k, -1); + if (cell->hasPort(ID::AD)) + for (int k = 0; k < width; k++) + db->add_edge(cell, ID::AD, k, ID::Q, k, -1); + if (cell->hasPort(ID::ARST)) + for (int k = 0; k < width; k++) + db->add_edge(cell, ID::ARST, 0, ID::Q, k, -1); +} + +void full_op(AbstractCellEdgesDatabase *db, RTLIL::Cell *cell) +{ + std::vector input_ports; + std::vector output_ports; + + for (auto &conn : cell->connections()) + { + RTLIL::IdString port = conn.first; + RTLIL::PortDir dir = cell->port_dir(port); + if (cell->input(port) || dir == RTLIL::PortDir::PD_INOUT) + input_ports.push_back(port); + if (cell->output(port) || dir == RTLIL::PortDir::PD_INOUT) + output_ports.push_back(port); + } + + for (auto out_port : output_ports) + { + int out_width = GetSize(cell->getPort(out_port)); + for (int out_bit = 0; out_bit < out_width; out_bit++) + { + for (auto in_port : input_ports) + { + int in_width = GetSize(cell->getPort(in_port)); + for (int in_bit = 0; in_bit < in_width; in_bit++) + db->add_edge(cell, in_port, in_bit, out_port, out_bit, -1); + } + } + } +} + +void bweqx_op(AbstractCellEdgesDatabase *db, RTLIL::Cell *cell) +{ + int width = GetSize(cell->getPort(ID::Y)); + int a_width = GetSize(cell->getPort(ID::A)); + int b_width = GetSize(cell->getPort(ID::B)); + int max_width = std::min(width, std::min(a_width, b_width)); + + for (int i = 0; i < max_width; i++) { + db->add_edge(cell, ID::A, i, ID::Y, i, -1); + db->add_edge(cell, ID::B, i, ID::Y, i, -1); + } +} + +void bwmux_op(AbstractCellEdgesDatabase *db, RTLIL::Cell *cell) +{ + int width = GetSize(cell->getPort(ID::Y)); + int a_width = GetSize(cell->getPort(ID::A)); + int b_width = GetSize(cell->getPort(ID::B)); + int s_width = GetSize(cell->getPort(ID::S)); + int max_width = std::min(width, std::min(a_width, std::min(b_width, s_width))); + + for (int i = 0; i < max_width; i++) { + db->add_edge(cell, ID::A, i, ID::Y, i, -1); + db->add_edge(cell, ID::B, i, ID::Y, i, -1); + db->add_edge(cell, ID::S, i, ID::Y, i, -1); + } +} + +PRIVATE_NAMESPACE_END + +bool YOSYS_NAMESPACE_PREFIX AbstractCellEdgesDatabase::add_edges_from_cell(RTLIL::Cell *cell) +{ + if (cell->type.in(ID($not), ID($pos), ID($buf), ID($barrier))) { + bitwise_unary_op(this, cell); + return true; + } + + if (cell->type.in(ID($and), ID($or), ID($xor), ID($xnor))) { + bitwise_binary_op(this, cell); + return true; + } + + if (cell->type == ID($neg)) { + arith_neg_op(this, cell); + return true; + } + + if (cell->type.in(ID($add), ID($sub))) { + arith_binary_op(this, cell); + return true; + } + + if (cell->type.in(ID($reduce_and), ID($reduce_or), ID($reduce_xor), ID($reduce_xnor), ID($reduce_bool), ID($logic_not))) { + reduce_op(this, cell); + return true; + } + + if (cell->type.in(ID($logic_and), ID($logic_or))) { + logic_op(this, cell); + return true; + } + + if (cell->type == ID($slice)) { + slice_op(this, cell); + return true; + } + + if (cell->type == ID($concat)) { + concat_op(this, cell); + return true; + } + + if (cell->type.in(ID($shl), ID($shr), ID($sshl), ID($sshr), ID($shift), ID($shiftx))) { + shift_op(this, cell); + return true; + } + + if (cell->type.in(ID($lt), ID($le), ID($eq), ID($ne), ID($eqx), ID($nex), ID($ge), ID($gt))) { + compare_op(this, cell); + return true; + } + + if (cell->type.in(ID($mux), ID($pmux))) { + mux_op(this, cell); + return true; + } + + if (cell->type == ID($bmux)) { + bmux_op(this, cell); + return true; + } + + if (cell->type == ID($demux)) { + demux_op(this, cell); + return true; + } + + if (cell->type == ID($bweqx)) { + bweqx_op(this, cell); + return true; + } + + if (cell->type == ID($bwmux)) { + bwmux_op(this, cell); + return true; + } + + if (cell->type.in(ID($mem_v2), ID($memrd), ID($memrd_v2), ID($memwr), ID($memwr_v2), ID($meminit))) { + mem_op(this, cell); + return true; + } + + if (cell->is_builtin_ff()) { + ff_op(this, cell); + return true; + } + + if (cell->type.in(ID($mul), ID($div), ID($mod), ID($divfloor), ID($modfloor), ID($pow))) { + full_op(this, cell); + return true; + } + + if (cell->type.in(ID($lut), ID($sop), ID($alu), ID($lcu), ID($macc), ID($macc_v2))) { + full_op(this, cell); + return true; + } + + if (cell->type.in( + ID($_BUF_), ID($_NOT_), ID($_AND_), ID($_NAND_), ID($_OR_), ID($_NOR_), + ID($_XOR_), ID($_XNOR_), ID($_ANDNOT_), ID($_ORNOT_), ID($_MUX_), ID($_NMUX_), + ID($_MUX4_), ID($_MUX8_), ID($_MUX16_), ID($_AOI3_), ID($_OAI3_), ID($_AOI4_), + ID($_OAI4_), ID($_TBUF_))) { + full_op(this, cell); + return true; + } + + // FIXME: $specify2 $specify3 $specrule ??? + // FIXME: $equiv $set_tag $get_tag $overwrite_tag $original_tag + + if (cell->type.in(ID($assert), ID($assume), ID($live), ID($fair), ID($cover), ID($initstate), ID($anyconst), ID($anyseq), ID($allconst), ID($allseq))) + return true; // no-op: these have either no inputs or no outputs + + return false; +} diff --git a/chips/yosys/kernel/celledges.h b/chips/yosys/kernel/celledges.h new file mode 100644 index 0000000000000000000000000000000000000000..d5e374f050c78b888e4a4fa55b83c08ab1bcbeff --- /dev/null +++ b/chips/yosys/kernel/celledges.h @@ -0,0 +1,63 @@ +/* -*- c++ -*- + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#ifndef CELLEDGES_H +#define CELLEDGES_H + +#include "kernel/yosys.h" +#include "kernel/sigtools.h" + +YOSYS_NAMESPACE_BEGIN + +struct AbstractCellEdgesDatabase +{ + virtual ~AbstractCellEdgesDatabase() { } + virtual void add_edge(RTLIL::Cell *cell, RTLIL::IdString from_port, int from_bit, RTLIL::IdString to_port, int to_bit, int delay) = 0; + bool add_edges_from_cell(RTLIL::Cell *cell); +}; + +struct FwdCellEdgesDatabase : AbstractCellEdgesDatabase +{ + SigMap &sigmap; + dict> db; + FwdCellEdgesDatabase(SigMap &sigmap) : sigmap(sigmap) { } + + void add_edge(RTLIL::Cell *cell, RTLIL::IdString from_port, int from_bit, RTLIL::IdString to_port, int to_bit, int) override { + SigBit from_sigbit = sigmap(cell->getPort(from_port)[from_bit]); + SigBit to_sigbit = sigmap(cell->getPort(to_port)[to_bit]); + db[from_sigbit].insert(to_sigbit); + } +}; + +struct RevCellEdgesDatabase : AbstractCellEdgesDatabase +{ + SigMap &sigmap; + dict> db; + RevCellEdgesDatabase(SigMap &sigmap) : sigmap(sigmap) { } + + void add_edge(RTLIL::Cell *cell, RTLIL::IdString from_port, int from_bit, RTLIL::IdString to_port, int to_bit, int) override { + SigBit from_sigbit = sigmap(cell->getPort(from_port)[from_bit]); + SigBit to_sigbit = sigmap(cell->getPort(to_port)[to_bit]); + db[to_sigbit].insert(from_sigbit); + } +}; + +YOSYS_NAMESPACE_END + +#endif diff --git a/chips/yosys/kernel/cellhelp.py b/chips/yosys/kernel/cellhelp.py new file mode 100644 index 0000000000000000000000000000000000000000..a92922fe6fe5110a897e777a0276c316b5b36c16 --- /dev/null +++ b/chips/yosys/kernel/cellhelp.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python3 + +from __future__ import annotations +import fileinput +import json +from pathlib import Path + +class SimHelper: + name: str = "" + title: str = "" + ports: str = "" + source: str = "" + desc: list[str] + code: list[str] + group: str = "" + ver: str = "1" + tags: list[str] + + def __init__(self) -> None: + self.desc = [] + self.tags = [] + + def __str__(self) -> str: + printed_fields = [ + "name", "title", "ports", "source", "desc", "code", "group", "ver", + "tags", + ] + # generate C++ struct + val = f"cell_help[{json.dumps(self.name)}] = " + val += "{\n" + for field in printed_fields: + field_val = getattr(self, field) + if isinstance(field_val, list): + field_val = "\n".join(field_val) + field_val = field_val.strip() + val += f' {json.dumps(field_val)},\n' + val += "};\n" + return val + +def simcells_reparse(cell: SimHelper): + # cut manual signature + cell.desc = cell.desc[3:] + + # code-block truth table + new_desc = [] + indent = "" + for line in cell.desc: + if line.startswith("Truth table:"): + indent = " " + new_desc.pop() + new_desc.extend(["::", ""]) + new_desc.append(indent + line) + cell.desc = new_desc + + # set version + cell.ver = "2a" + +simHelper = SimHelper() + +for line in fileinput.input(): + line = line.rstrip() + # special comments + if line.startswith("//-"): + simHelper.desc.append(line[4:] if len(line) > 4 else "") + elif line.startswith("//* "): + _, key, val = line.split(maxsplit=2) + setattr(simHelper, key, val) + + # code parsing + if line.startswith("module "): + clean_line = line[7:].replace("\\", "").replace(";", "") + simHelper.name, simHelper.ports = clean_line.split(maxsplit=1) + simHelper.code = [] + short_filename = Path(fileinput.filename()).name + simHelper.source = f'{short_filename}:{fileinput.filelineno()}' + elif not line.startswith("endmodule"): + line = " " + line + try: + simHelper.code.append(line.replace("\t", " ")) + except AttributeError: + # no module definition, ignore line + pass + if line.startswith("endmodule"): + short_filename = Path(fileinput.filename()).name + if simHelper.ver == "1" and short_filename == "simcells.v": + # default simcells parsing + simcells_reparse(simHelper) + + # check help + if simHelper.desc and simHelper.ver == "1" and short_filename == "simlib.v" and simHelper.desc[1].startswith(' '): + simHelper.desc.pop(1) + + # check group + assert simHelper.group, f"techlibs/common/{simHelper.source}: {simHelper.name} cell missing group" + + # dump + print(simHelper) + # new + simHelper = SimHelper() diff --git a/chips/yosys/kernel/celltypes.h b/chips/yosys/kernel/celltypes.h new file mode 100644 index 0000000000000000000000000000000000000000..c2318d4bc183e0c845ae5f2abcdae13f16b0c853 --- /dev/null +++ b/chips/yosys/kernel/celltypes.h @@ -0,0 +1,562 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#ifndef CELLTYPES_H +#define CELLTYPES_H + +#include "kernel/yosys.h" +#include "kernel/newcelltypes.h" + +YOSYS_NAMESPACE_BEGIN + +struct CellType +{ + RTLIL::IdString type; + pool inputs, outputs; + bool is_evaluable; + bool is_combinatorial; + bool is_synthesizable; +}; + +struct CellTypes +{ + dict cell_types; + + CellTypes() + { + } + + CellTypes(RTLIL::Design *design) + { + setup(design); + } + + void setup(RTLIL::Design *design = NULL) + { + if (design) + setup_design(design); + + setup_internals(); + setup_internals_mem(); + setup_internals_anyinit(); + setup_stdcells(); + setup_stdcells_mem(); + } + + void setup_type(RTLIL::IdString type, const pool &inputs, const pool &outputs, bool is_evaluable = false, bool is_combinatorial = false, bool is_synthesizable = false) + { + CellType ct = {type, inputs, outputs, is_evaluable, is_combinatorial, is_synthesizable}; + cell_types[ct.type] = ct; + } + + template + void setup_type(const N &type_str, const pool &inputs, const pool &outputs, bool is_evaluable = false, bool is_combinatorial = false, bool is_synthesizable = false) + { + setup_type(ID::lookup(type_str), inputs, outputs, is_evaluable, is_combinatorial, is_synthesizable); + } + + void setup_module(RTLIL::Module *module) + { + pool inputs, outputs; + for (auto wire_name : module->ports) { + RTLIL::Wire *wire = module->wire(wire_name); + if (wire->port_input) + inputs.insert(wire->name); + if (wire->port_output) + outputs.insert(wire->name); + } + setup_type(module->name, inputs, outputs); + } + + void setup_design(RTLIL::Design *design) + { + for (auto module : design->modules()) + setup_module(module); + } + + void setup_internals() + { + setup_internals_eval(); + + setup_type(ID($barrier), {ID::A}, {ID::Y}); + + setup_type(ID($tribuf), {ID::A, ID::EN}, {ID::Y}); + + setup_type(ID($assert), {ID::A, ID::EN}, pool()); + setup_type(ID($assume), {ID::A, ID::EN}, pool()); + setup_type(ID($live), {ID::A, ID::EN}, pool()); + setup_type(ID($fair), {ID::A, ID::EN}, pool()); + setup_type(ID($cover), {ID::A, ID::EN}, pool()); + setup_type(ID($initstate), pool(), {ID::Y}); + setup_type(ID($anyconst), pool(), {ID::Y}); + setup_type(ID($anyseq), pool(), {ID::Y}); + setup_type(ID($allconst), pool(), {ID::Y}); + setup_type(ID($allseq), pool(), {ID::Y}); + setup_type(ID($equiv), {ID::A, ID::B}, {ID::Y}); + setup_type(ID($specify2), {ID::EN, ID::SRC, ID::DST}, pool()); + setup_type(ID($specify3), {ID::EN, ID::SRC, ID::DST, ID::DAT}, pool()); + setup_type(ID($specrule), {ID::SRC_EN, ID::DST_EN, ID::SRC, ID::DST}, pool()); + setup_type(ID($print), {ID::EN, ID::ARGS, ID::TRG}, pool()); + setup_type(ID($check), {ID::A, ID::EN, ID::ARGS, ID::TRG}, pool()); + setup_type(ID($set_tag), {ID::A, ID::SET, ID::CLR}, {ID::Y}); + setup_type(ID($get_tag), {ID::A}, {ID::Y}); + setup_type(ID($overwrite_tag), {ID::A, ID::SET, ID::CLR}, pool()); + setup_type(ID($original_tag), {ID::A}, {ID::Y}); + setup_type(ID($future_ff), {ID::A}, {ID::Y}); + setup_type(ID($scopeinfo), {}, {}); + setup_type(ID($input_port), {}, {ID::Y}); + setup_type(ID($connect), {ID::A, ID::B}, {}); + } + + void setup_internals_eval() + { + std::vector unary_ops = { + ID($not), ID($pos), ID($buf), ID($neg), + ID($reduce_and), ID($reduce_or), ID($reduce_xor), ID($reduce_xnor), ID($reduce_bool), + ID($logic_not), ID($slice), ID($lut), ID($sop) + }; + + std::vector binary_ops = { + ID($and), ID($or), ID($xor), ID($xnor), + ID($shl), ID($shr), ID($sshl), ID($sshr), ID($shift), ID($shiftx), + ID($lt), ID($le), ID($eq), ID($ne), ID($eqx), ID($nex), ID($ge), ID($gt), + ID($add), ID($sub), ID($mul), ID($div), ID($mod), ID($divfloor), ID($modfloor), ID($pow), + ID($logic_and), ID($logic_or), ID($concat), ID($macc), + ID($bweqx) + }; + + for (auto type : unary_ops) + setup_type(type, {ID::A}, {ID::Y}, true); + + for (auto type : binary_ops) + setup_type(type, {ID::A, ID::B}, {ID::Y}, true); + + for (auto type : std::vector({ID($mux), ID($pmux), ID($bwmux)})) + setup_type(type, {ID::A, ID::B, ID::S}, {ID::Y}, true); + + for (auto type : std::vector({ID($bmux), ID($demux)})) + setup_type(type, {ID::A, ID::S}, {ID::Y}, true); + + setup_type(ID($lcu), {ID::P, ID::G, ID::CI}, {ID::CO}, true); + setup_type(ID($alu), {ID::A, ID::B, ID::CI, ID::BI}, {ID::X, ID::Y, ID::CO}, true); + setup_type(ID($macc_v2), {ID::A, ID::B, ID::C}, {ID::Y}, true); + setup_type(ID($fa), {ID::A, ID::B, ID::C}, {ID::X, ID::Y}, true); + } + + void setup_internals_ff() + { + setup_type(ID($sr), {ID::SET, ID::CLR}, {ID::Q}); + setup_type(ID($ff), {ID::D}, {ID::Q}); + setup_type(ID($dff), {ID::CLK, ID::D}, {ID::Q}); + setup_type(ID($dffe), {ID::CLK, ID::EN, ID::D}, {ID::Q}); + setup_type(ID($dffsr), {ID::CLK, ID::SET, ID::CLR, ID::D}, {ID::Q}); + setup_type(ID($dffsre), {ID::CLK, ID::SET, ID::CLR, ID::D, ID::EN}, {ID::Q}); + setup_type(ID($adff), {ID::CLK, ID::ARST, ID::D}, {ID::Q}); + setup_type(ID($adffe), {ID::CLK, ID::ARST, ID::D, ID::EN}, {ID::Q}); + setup_type(ID($aldff), {ID::CLK, ID::ALOAD, ID::AD, ID::D}, {ID::Q}); + setup_type(ID($aldffe), {ID::CLK, ID::ALOAD, ID::AD, ID::D, ID::EN}, {ID::Q}); + setup_type(ID($sdff), {ID::CLK, ID::SRST, ID::D}, {ID::Q}); + setup_type(ID($sdffe), {ID::CLK, ID::SRST, ID::D, ID::EN}, {ID::Q}); + setup_type(ID($sdffce), {ID::CLK, ID::SRST, ID::D, ID::EN}, {ID::Q}); + setup_type(ID($dlatch), {ID::EN, ID::D}, {ID::Q}); + setup_type(ID($adlatch), {ID::EN, ID::D, ID::ARST}, {ID::Q}); + setup_type(ID($dlatchsr), {ID::EN, ID::SET, ID::CLR, ID::D}, {ID::Q}); + } + + void setup_internals_anyinit() + { + setup_type(ID($anyinit), {ID::D}, {ID::Q}); + } + + void setup_internals_mem() + { + setup_internals_ff(); + + setup_type(ID($memrd), {ID::CLK, ID::EN, ID::ADDR}, {ID::DATA}); + setup_type(ID($memrd_v2), {ID::CLK, ID::EN, ID::ARST, ID::SRST, ID::ADDR}, {ID::DATA}); + setup_type(ID($memwr), {ID::CLK, ID::EN, ID::ADDR, ID::DATA}, pool()); + setup_type(ID($memwr_v2), {ID::CLK, ID::EN, ID::ADDR, ID::DATA}, pool()); + setup_type(ID($meminit), {ID::ADDR, ID::DATA}, pool()); + setup_type(ID($meminit_v2), {ID::ADDR, ID::DATA, ID::EN}, pool()); + setup_type(ID($mem), {ID::RD_CLK, ID::RD_EN, ID::RD_ADDR, ID::WR_CLK, ID::WR_EN, ID::WR_ADDR, ID::WR_DATA}, {ID::RD_DATA}); + setup_type(ID($mem_v2), {ID::RD_CLK, ID::RD_EN, ID::RD_ARST, ID::RD_SRST, ID::RD_ADDR, ID::WR_CLK, ID::WR_EN, ID::WR_ADDR, ID::WR_DATA}, {ID::RD_DATA}); + + setup_type(ID($fsm), {ID::CLK, ID::ARST, ID::CTRL_IN}, {ID::CTRL_OUT}); + } + + void setup_stdcells() + { + setup_stdcells_eval(); + + setup_type(ID($_TBUF_), {ID::A, ID::E}, {ID::Y}); + } + + void setup_stdcells_eval() + { + setup_type(ID($_BUF_), {ID::A}, {ID::Y}, true); + setup_type(ID($_NOT_), {ID::A}, {ID::Y}, true); + setup_type(ID($_AND_), {ID::A, ID::B}, {ID::Y}, true); + setup_type(ID($_NAND_), {ID::A, ID::B}, {ID::Y}, true); + setup_type(ID($_OR_), {ID::A, ID::B}, {ID::Y}, true); + setup_type(ID($_NOR_), {ID::A, ID::B}, {ID::Y}, true); + setup_type(ID($_XOR_), {ID::A, ID::B}, {ID::Y}, true); + setup_type(ID($_XNOR_), {ID::A, ID::B}, {ID::Y}, true); + setup_type(ID($_ANDNOT_), {ID::A, ID::B}, {ID::Y}, true); + setup_type(ID($_ORNOT_), {ID::A, ID::B}, {ID::Y}, true); + setup_type(ID($_MUX_), {ID::A, ID::B, ID::S}, {ID::Y}, true); + setup_type(ID($_NMUX_), {ID::A, ID::B, ID::S}, {ID::Y}, true); + setup_type(ID($_MUX4_), {ID::A, ID::B, ID::C, ID::D, ID::S, ID::T}, {ID::Y}, true); + setup_type(ID($_MUX8_), {ID::A, ID::B, ID::C, ID::D, ID::E, ID::F, ID::G, ID::H, ID::S, ID::T, ID::U}, {ID::Y}, true); + setup_type(ID($_MUX16_), {ID::A, ID::B, ID::C, ID::D, ID::E, ID::F, ID::G, ID::H, ID::I, ID::J, ID::K, ID::L, ID::M, ID::N, ID::O, ID::P, ID::S, ID::T, ID::U, ID::V}, {ID::Y}, true); + setup_type(ID($_AOI3_), {ID::A, ID::B, ID::C}, {ID::Y}, true); + setup_type(ID($_OAI3_), {ID::A, ID::B, ID::C}, {ID::Y}, true); + setup_type(ID($_AOI4_), {ID::A, ID::B, ID::C, ID::D}, {ID::Y}, true); + setup_type(ID($_OAI4_), {ID::A, ID::B, ID::C, ID::D}, {ID::Y}, true); + } + + void setup_stdcells_mem() + { + std::vector list_np = {'N', 'P'}, list_01 = {'0', '1'}; + + for (auto c1 : list_np) + for (auto c2 : list_np) + setup_type(stringf("$_SR_%c%c_", c1, c2), {ID::S, ID::R}, {ID::Q}); + + setup_type(ID($_FF_), {ID::D}, {ID::Q}); + + for (auto c1 : list_np) + setup_type(stringf("$_DFF_%c_", c1), {ID::C, ID::D}, {ID::Q}); + + for (auto c1 : list_np) + for (auto c2 : list_np) + setup_type(stringf("$_DFFE_%c%c_", c1, c2), {ID::C, ID::D, ID::E}, {ID::Q}); + + for (auto c1 : list_np) + for (auto c2 : list_np) + for (auto c3 : list_01) + setup_type(stringf("$_DFF_%c%c%c_", c1, c2, c3), {ID::C, ID::R, ID::D}, {ID::Q}); + + for (auto c1 : list_np) + for (auto c2 : list_np) + for (auto c3 : list_01) + for (auto c4 : list_np) + setup_type(stringf("$_DFFE_%c%c%c%c_", c1, c2, c3, c4), {ID::C, ID::R, ID::D, ID::E}, {ID::Q}); + + for (auto c1 : list_np) + for (auto c2 : list_np) + setup_type(stringf("$_ALDFF_%c%c_", c1, c2), {ID::C, ID::L, ID::AD, ID::D}, {ID::Q}); + + for (auto c1 : list_np) + for (auto c2 : list_np) + for (auto c3 : list_np) + setup_type(stringf("$_ALDFFE_%c%c%c_", c1, c2, c3), {ID::C, ID::L, ID::AD, ID::D, ID::E}, {ID::Q}); + + for (auto c1 : list_np) + for (auto c2 : list_np) + for (auto c3 : list_np) + setup_type(stringf("$_DFFSR_%c%c%c_", c1, c2, c3), {ID::C, ID::S, ID::R, ID::D}, {ID::Q}); + + for (auto c1 : list_np) + for (auto c2 : list_np) + for (auto c3 : list_np) + for (auto c4 : list_np) + setup_type(stringf("$_DFFSRE_%c%c%c%c_", c1, c2, c3, c4), {ID::C, ID::S, ID::R, ID::D, ID::E}, {ID::Q}); + + for (auto c1 : list_np) + for (auto c2 : list_np) + for (auto c3 : list_01) + setup_type(stringf("$_SDFF_%c%c%c_", c1, c2, c3), {ID::C, ID::R, ID::D}, {ID::Q}); + + for (auto c1 : list_np) + for (auto c2 : list_np) + for (auto c3 : list_01) + for (auto c4 : list_np) + setup_type(stringf("$_SDFFE_%c%c%c%c_", c1, c2, c3, c4), {ID::C, ID::R, ID::D, ID::E}, {ID::Q}); + + for (auto c1 : list_np) + for (auto c2 : list_np) + for (auto c3 : list_01) + for (auto c4 : list_np) + setup_type(stringf("$_SDFFCE_%c%c%c%c_", c1, c2, c3, c4), {ID::C, ID::R, ID::D, ID::E}, {ID::Q}); + + for (auto c1 : list_np) + setup_type(stringf("$_DLATCH_%c_", c1), {ID::E, ID::D}, {ID::Q}); + + for (auto c1 : list_np) + for (auto c2 : list_np) + for (auto c3 : list_01) + setup_type(stringf("$_DLATCH_%c%c%c_", c1, c2, c3), {ID::E, ID::R, ID::D}, {ID::Q}); + + for (auto c1 : list_np) + for (auto c2 : list_np) + for (auto c3 : list_np) + setup_type(stringf("$_DLATCHSR_%c%c%c_", c1, c2, c3), {ID::E, ID::S, ID::R, ID::D}, {ID::Q}); + } + + void clear() + { + cell_types.clear(); + } + + bool cell_known(RTLIL::IdString type) const + { + return cell_types.count(type) != 0; + } + + bool cell_output(RTLIL::IdString type, RTLIL::IdString port) const + { + auto it = cell_types.find(type); + return it != cell_types.end() && it->second.outputs.count(port) != 0; + } + + bool cell_input(RTLIL::IdString type, RTLIL::IdString port) const + { + auto it = cell_types.find(type); + return it != cell_types.end() && it->second.inputs.count(port) != 0; + } + + RTLIL::PortDir cell_port_dir(RTLIL::IdString type, RTLIL::IdString port) const + { + auto it = cell_types.find(type); + if (it == cell_types.end()) + return RTLIL::PD_UNKNOWN; + bool is_input = it->second.inputs.count(port); + bool is_output = it->second.outputs.count(port); + return RTLIL::PortDir(is_input + is_output * 2); + } + + bool cell_evaluable(RTLIL::IdString type) const + { + auto it = cell_types.find(type); + return it != cell_types.end() && it->second.is_evaluable; + } + + static RTLIL::Const eval_not(RTLIL::Const v) + { + for (auto bit : v) + if (bit == State::S0) bit = State::S1; + else if (bit == State::S1) bit = State::S0; + return v; + } + + // Consider using the ConstEval struct instead if you need named ports and/or multiple outputs + static RTLIL::Const eval(RTLIL::IdString type, const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool signed1, bool signed2, int result_len, bool *errp = nullptr) + { + if (type == ID($sshr) && !signed1) + type = ID($shr); + if (type == ID($sshl) && !signed1) + type = ID($shl); + + if (type != ID($sshr) && type != ID($sshl) && type != ID($shr) && type != ID($shl) && type != ID($shift) && type != ID($shiftx) && + type != ID($pos) && type != ID($buf) && type != ID($neg) && type != ID($not)) { + if (!signed1 || !signed2) + signed1 = false, signed2 = false; + } + +#define HANDLE_CELL_TYPE(_t) if (type == constid) return const_ ## _t(arg1, arg2, signed1, signed2, result_len); + HANDLE_CELL_TYPE(not) + HANDLE_CELL_TYPE(and) + HANDLE_CELL_TYPE(or) + HANDLE_CELL_TYPE(xor) + HANDLE_CELL_TYPE(xnor) + HANDLE_CELL_TYPE(reduce_and) + HANDLE_CELL_TYPE(reduce_or) + HANDLE_CELL_TYPE(reduce_xor) + HANDLE_CELL_TYPE(reduce_xnor) + HANDLE_CELL_TYPE(reduce_bool) + HANDLE_CELL_TYPE(logic_not) + HANDLE_CELL_TYPE(logic_and) + HANDLE_CELL_TYPE(logic_or) + HANDLE_CELL_TYPE(shl) + HANDLE_CELL_TYPE(shr) + HANDLE_CELL_TYPE(sshl) + HANDLE_CELL_TYPE(sshr) + HANDLE_CELL_TYPE(shift) + HANDLE_CELL_TYPE(shiftx) + HANDLE_CELL_TYPE(lt) + HANDLE_CELL_TYPE(le) + HANDLE_CELL_TYPE(eq) + HANDLE_CELL_TYPE(ne) + HANDLE_CELL_TYPE(eqx) + HANDLE_CELL_TYPE(nex) + HANDLE_CELL_TYPE(ge) + HANDLE_CELL_TYPE(gt) + HANDLE_CELL_TYPE(add) + HANDLE_CELL_TYPE(sub) + HANDLE_CELL_TYPE(mul) + HANDLE_CELL_TYPE(div) + HANDLE_CELL_TYPE(mod) + HANDLE_CELL_TYPE(divfloor) + HANDLE_CELL_TYPE(modfloor) + HANDLE_CELL_TYPE(pow) + HANDLE_CELL_TYPE(pos) + HANDLE_CELL_TYPE(neg) +#undef HANDLE_CELL_TYPE + + if (type.in(ID($_BUF_), ID($buf))) + return arg1; + if (type == ID($_NOT_)) + return eval_not(arg1); + if (type == ID($_AND_)) + return const_and(arg1, arg2, false, false, 1); + if (type == ID($_NAND_)) + return eval_not(const_and(arg1, arg2, false, false, 1)); + if (type == ID($_OR_)) + return const_or(arg1, arg2, false, false, 1); + if (type == ID($_NOR_)) + return eval_not(const_or(arg1, arg2, false, false, 1)); + if (type == ID($_XOR_)) + return const_xor(arg1, arg2, false, false, 1); + if (type == ID($_XNOR_)) + return const_xnor(arg1, arg2, false, false, 1); + if (type == ID($_ANDNOT_)) + return const_and(arg1, eval_not(arg2), false, false, 1); + if (type == ID($_ORNOT_)) + return const_or(arg1, eval_not(arg2), false, false, 1); + + if (errp != nullptr) { + *errp = true; + return State::Sm; + } + + log_abort(); + } + + // Consider using the ConstEval struct instead if you need named ports and/or multiple outputs + static RTLIL::Const eval(RTLIL::Cell *cell, const RTLIL::Const &arg1, const RTLIL::Const &arg2, bool *errp = nullptr) + { + if (cell->type == ID($slice)) { + int width = cell->parameters.at(ID::Y_WIDTH).as_int(); + int offset = cell->parameters.at(ID::OFFSET).as_int(); + return arg1.extract(offset, width); + } + + if (cell->type == ID($concat)) { + RTLIL::Const ret = arg1; + ret.append(arg2); + return ret; + } + + if (cell->type == ID($bmux)) + { + return const_bmux(arg1, arg2); + } + + if (cell->type == ID($demux)) + { + return const_demux(arg1, arg2); + } + + if (cell->type == ID($bweqx)) + { + return const_bweqx(arg1, arg2); + } + + if (cell->type == ID($lut)) + { + int width = cell->parameters.at(ID::WIDTH).as_int(); + + std::vector t = cell->parameters.at(ID::LUT).to_bits(); + while (GetSize(t) < (1 << width)) + t.push_back(State::S0); + t.resize(1 << width); + + return const_bmux(t, arg1); + } + + if (cell->type == ID($sop)) + { + int width = cell->parameters.at(ID::WIDTH).as_int(); + int depth = cell->parameters.at(ID::DEPTH).as_int(); + std::vector t = cell->parameters.at(ID::TABLE).to_bits(); + + while (GetSize(t) < width*depth*2) + t.push_back(State::S0); + + RTLIL::State default_ret = State::S0; + + for (int i = 0; i < depth; i++) + { + bool match = true; + bool match_x = true; + + for (int j = 0; j < width; j++) { + RTLIL::State a = arg1.at(j); + if (t.at(2*width*i + 2*j + 0) == State::S1) { + if (a == State::S1) match_x = false; + if (a != State::S0) match = false; + } + if (t.at(2*width*i + 2*j + 1) == State::S1) { + if (a == State::S0) match_x = false; + if (a != State::S1) match = false; + } + } + + if (match) + return State::S1; + + if (match_x) + default_ret = State::Sx; + } + + return default_ret; + } + + bool signed_a = cell->parameters.count(ID::A_SIGNED) > 0 && cell->parameters[ID::A_SIGNED].as_bool(); + bool signed_b = cell->parameters.count(ID::B_SIGNED) > 0 && cell->parameters[ID::B_SIGNED].as_bool(); + int result_len = cell->parameters.count(ID::Y_WIDTH) > 0 ? cell->parameters[ID::Y_WIDTH].as_int() : -1; + return eval(cell->type, arg1, arg2, signed_a, signed_b, result_len, errp); + } + + // Consider using the ConstEval struct instead if you need named ports and/or multiple outputs + static RTLIL::Const eval(RTLIL::Cell *cell, const RTLIL::Const &arg1, const RTLIL::Const &arg2, const RTLIL::Const &arg3, bool *errp = nullptr) + { + if (cell->type.in(ID($mux), ID($_MUX_))) + return const_mux(arg1, arg2, arg3); + if (cell->type == ID($_NMUX_)) + return eval_not(const_mux(arg1, arg2, arg3)); + if (cell->type == ID($bwmux)) + return const_bwmux(arg1, arg2, arg3); + if (cell->type == ID($pmux)) + return const_pmux(arg1, arg2, arg3); + if (cell->type == ID($_AOI3_)) + return eval_not(const_or(const_and(arg1, arg2, false, false, 1), arg3, false, false, 1)); + if (cell->type == ID($_OAI3_)) + return eval_not(const_and(const_or(arg1, arg2, false, false, 1), arg3, false, false, 1)); + + log_assert(arg3.size() == 0); + return eval(cell, arg1, arg2, errp); + } + + // Consider using the ConstEval struct instead if you need named ports and/or multiple outputs + static RTLIL::Const eval(RTLIL::Cell *cell, const RTLIL::Const &arg1, const RTLIL::Const &arg2, const RTLIL::Const &arg3, const RTLIL::Const &arg4, bool *errp = nullptr) + { + if (cell->type == ID($_AOI4_)) + return eval_not(const_or(const_and(arg1, arg2, false, false, 1), const_and(arg3, arg4, false, false, 1), false, false, 1)); + if (cell->type == ID($_OAI4_)) + return eval_not(const_and(const_or(arg1, arg2, false, false, 1), const_or(arg3, arg4, false, false, 1), false, false, 1)); + + log_assert(arg4.size() == 0); + return eval(cell, arg1, arg2, arg3, errp); + } +}; + +YOSYS_NAMESPACE_END + +#endif diff --git a/chips/yosys/kernel/compressor_tree.cc b/chips/yosys/kernel/compressor_tree.cc new file mode 100644 index 0000000000000000000000000000000000000000..83d98c6d98a89ac59475e477c28563488e41abac --- /dev/null +++ b/chips/yosys/kernel/compressor_tree.cc @@ -0,0 +1,336 @@ +#include "compressor_tree.h" + +YOSYS_NAMESPACE_BEGIN + +namespace CompressorTree +{ + +std::pair emit_compressor_32(Module *module, SigSpec a, SigSpec b, SigSpec c, int width) +{ + SigSpec sum = module->addWire(NEW_ID, width); + SigSpec cout = module->addWire(NEW_ID, width); + module->addFa(NEW_ID, a, b, c, cout, sum); + + SigSpec carry; + carry.append(State::S0); + carry.append(cout.extract(0, width - 1)); + return {sum, carry}; +} + +std::pair emit_compressor_42(Module *module, SigSpec a, SigSpec b, SigSpec c, SigSpec d, int width) +{ + // First FA: a + b + c -> s0 + SigSpec s0 = module->addWire(NEW_ID, width); + SigSpec cout_h_full = module->addWire(NEW_ID, width); + module->addFa(NEW_ID, a, b, c, cout_h_full, s0); + + // cin[0] = 0, cin[i] = cout_h_full[i-1] + SigSpec cin; + cin.append(State::S0); + if (width > 1) + cin.append(cout_h_full.extract(0, width - 1)); + + // Second FA: s0 + d + cin -> sum + SigSpec sum = module->addWire(NEW_ID, width); + SigSpec carry_full = module->addWire(NEW_ID, width); + module->addFa(NEW_ID, s0, d, cin, carry_full, sum); + + SigSpec carry; + carry.append(State::S0); + if (width > 1) + carry.append(carry_full.extract(0, width - 1)); + + return {sum, carry}; +} + +std::vector generate_partial_products(Module *module, SigSpec a, SigSpec b, bool a_signed, bool b_signed, int width) { + int width_a = GetSize(a); + int width_b = GetSize(b); + std::vector products; + products.reserve(width_a + 3); + + for (int i = 0; i < width_a; i++) { + SigBit ai = a[i]; + + // b_shifted = (0_i ## b) + SigSpec b_shifted = SigSpec(State::S0, i); + b_shifted.append(b); + b_shifted.extend_u0(width, false); + + // row = b_shifted & replicate(a[i], width) + SigSpec ai_rep = SigSpec(ai, width); + SigSpec row = module->addWire(NEW_ID, width); + module->addAnd(NEW_ID, b_shifted, ai_rep, row); + + // Apply Modified Baugh-Wooley inversions for this row + bool row_is_bottom = (i == width_a - 1); + bool any_inversion = (row_is_bottom && b_signed) || a_signed; + + if (any_inversion) { + std::vector mask(width, RTLIL::State::S0); + + for (int j = 0; j < width_b; j++) { + int col = i + j; + if (col < 0 || col >= width) + continue; + bool col_is_right = (j == width_b - 1); + // Flip masks + bool invert = (row_is_bottom && b_signed) ^ (col_is_right && a_signed); + if (invert) + mask[col] = RTLIL::State::S1; + } + + // Skip the xor entirely if the mask is all zeroes + bool nonzero = false; + for (auto s : mask) + if (s == RTLIL::State::S1) { + nonzero = true; + break; + } + if (nonzero) { + SigSpec inverted = module->addWire(NEW_ID, width); + module->addXor(NEW_ID, row, SigSpec(RTLIL::Const(mask)), inverted); + row = inverted; + } + } + + products.push_back({row, 0}); + } + + // Correction constants + auto push_one_at = [&](int col) { + if (col < 0 || col >= width) + return; + std::vector v(width, RTLIL::State::S0); + v[col] = RTLIL::State::S1; + products.push_back({SigSpec(RTLIL::Const(v)), 0}); + }; + + if (b_signed) + push_one_at(width_a - 1); + if (a_signed) + push_one_at(width_b - 1); + if (a_signed || b_signed) { + // Sign-extend the Baugh-Wooley correction to the accumulator width. + int sign_extension_start = width_a + width_b - 1; + if (sign_extension_start < width) { + std::vector v(width, RTLIL::State::S0); + for (int i = sign_extension_start; i < width; i++) + v[i] = RTLIL::State::S1; + products.push_back({SigSpec(RTLIL::Const(v)), 0}); + } + } + + return products; +} + +std::pair reduce_scheduled(Module *module, std::vector operands, int width, Strategy strategy, int *out_compressor_count, int *out_final_depth) { + int levels = 0; + int fa_count = 0; + int c42_count = 0; + int final_depth = 0; + + for (auto &op : operands) + op.sig.extend_u0(width); + + // Only compress operands ready at current level + for (int level = 0; operands.size() > 2; level++) { + // Partition operands into ready and waiting + std::vector ready; + std::vector waiting; + ready.reserve(operands.size()); + for (auto &op : operands) { + if (op.depth <= level) + ready.push_back(op); + else + waiting.push_back(op); + } + + if (ready.size() < 3) { + levels++; + continue; + } + + // Apply compressors to ready operands + std::vector compressed; + compressed.reserve(ready.size()); + size_t i = 0; + + // PREFER_42 attempts 4:2 grouping greedily (falls back to 3:2 for the residual) + // FA_ONLY skips + // DADDA = PREFER_42 (TODO: inspect column heights?) + bool try_42 = (strategy == Strategy::PREFER_42 || strategy == Strategy::DADDA); + + while (i < ready.size()) { + size_t remaining = ready.size() - i; + + if (try_42 && remaining >= 4) { + DepthSig a = ready[i + 0]; + DepthSig b = ready[i + 1]; + DepthSig c = ready[i + 2]; + DepthSig d = ready[i + 3]; + + auto [sum, carry] = emit_compressor_42(module, a.sig, b.sig, c.sig, d.sig, width); + int dmax = std::max({a.depth, b.depth, c.depth, d.depth}); + + compressed.push_back({sum, dmax + 2}); + compressed.push_back({carry, dmax + 2}); + + fa_count += 2; + c42_count += 1; + i += 4; + } else if (remaining >= 3) { + DepthSig a = ready[i + 0]; + DepthSig b = ready[i + 1]; + DepthSig c = ready[i + 2]; + + auto [sum, carry] = emit_compressor_32(module, a.sig, b.sig, c.sig, width); + int dmax = std::max({a.depth, b.depth, c.depth}); + + compressed.push_back({sum, dmax + 1}); + compressed.push_back({carry, dmax + 1}); + + fa_count += 1; + i += 3; + } else { + // Uncompressed operands pass through to next level + for (; i < ready.size(); i++) + compressed.push_back(ready[i]); + break; + } + } + + // Merge compressed with waiting operands + for (auto &op : waiting) + compressed.push_back(op); + + operands = std::move(compressed); + levels++; + } + + if(out_compressor_count) + *out_compressor_count = fa_count; + if (operands.size() == 0) { + if (out_final_depth) + *out_final_depth = 0; + return {SigSpec(State::S0, width), SigSpec(State::S0, width)}; + } + if (operands.size() == 1) { + if (out_final_depth) + *out_final_depth = operands[0].depth; + return {operands[0].sig, SigSpec(State::S0, width)}; + } + + final_depth = std::max(operands[0].depth, operands[1].depth); + if (out_final_depth) + *out_final_depth = final_depth; + log_assert(operands.size() == 2); + log(" CompressorTree::reduce_scheduled: %d levels, %d $fa (%d as 4:2), final depth %d\n", levels, fa_count, c42_count, final_depth); + return {operands[0].sig, operands[1].sig}; +} + +void emit_kogge_stone(Module *module, SigSpec a, SigSpec b, SigSpec y) +{ + int width = GetSize(y); + log_assert(GetSize(a) == width); + log_assert(GetSize(b) == width); + + if (width == 0) + return; + + if (width == 1) { + module->addXorGate(NEW_ID, a[0], b[0], y[0]); + return; + } + + // Bit level gen and prop + std::vector g_pre(width), p_pre(width); + for (int i = 0; i < width; i++) { + SigBit gi = module->addWire(NEW_ID); + SigBit pi = module->addWire(NEW_ID); + module->addAndGate(NEW_ID, a[i], b[i], gi); + module->addXorGate(NEW_ID, a[i], b[i], pi); + g_pre[i] = gi; + p_pre[i] = pi; + } + + // Propagate (g, p) through ceil(log2 W) levels + std::vector g = g_pre; + std::vector p = p_pre; + int num_levels = 0; + + while ((1 << num_levels) < width) + num_levels++; + + for (int k = 1; k <= num_levels; k++) { + int s = 1 << (k - 1); + std::vector g_next(width), p_next(width); + for (int i = 0; i < width; i++) { + if (i < s) { + // Nothing to do + g_next[i] = g[i]; + p_next[i] = p[i]; + } else { + // g_i^k = g_i | (p_i & g_(i-s)) + SigBit and_pg = module->addWire(NEW_ID); + module->addAndGate(NEW_ID, p[i], g[i - s], and_pg); + SigBit gnew = module->addWire(NEW_ID); + module->addOrGate(NEW_ID, g[i], and_pg, gnew); + g_next[i] = gnew; + + // p_i^k = p_i & p_(i-s) + if (k < num_levels) { + SigBit pnew = module->addWire(NEW_ID); + module->addAndGate(NEW_ID, p[i], p[i - s], pnew); + p_next[i] = pnew; + } else { + // Skip last level + p_next[i] = State::Sx; + } + } + } + + g = std::move(g_next); + p = std::move(p_next); + } + + // Sum layer, g[i] is COUT of bit i + // With CIN 0: + // sum[0] = p_pre[0] + // sum[i] = p_pre[i] ^ g[i-1] ... + module->connect(y[0], p_pre[0]); + for (int i = 1; i < width; i++) + module->addXorGate(NEW_ID, p_pre[i], g[i - 1], y[i]); +} + +Cell *emit_final_adder(Module *module, SigSpec a, SigSpec b, SigSpec y, FinalAdder choice) { + switch (choice) { + case FinalAdder::DEFAULT: + case FinalAdder::RIPPLE: { + return module->addAdd(NEW_ID, a, b, y, false); + } + case FinalAdder::PARALLEL_PREFIX: { + emit_kogge_stone(module, a, b, y); + return nullptr; + } + } + log_assert(false && "CompressorTree::emit_final_adder: invalid choice"); + return nullptr; +} + +FinalAdder pick_final_adder(int width, int final_depth, FinalMode mode) { + switch (mode) { + case FinalMode::RIPPLE: return FinalAdder::RIPPLE; + case FinalMode::PREFIX: return FinalAdder::PARALLEL_PREFIX; + case FinalMode::AUTO: + default: { + bool wide = width >= RIPPLE_PREFIX_WIDTH_THRESHOLD; + bool deep = final_depth >= RIPPLE_PREFIX_DEPTH_THRESHOLD; + return (wide && deep) ? FinalAdder::PARALLEL_PREFIX : FinalAdder::DEFAULT; + } + } +} + +} // namespace CompressorTree + +YOSYS_NAMESPACE_END diff --git a/chips/yosys/kernel/compressor_tree.h b/chips/yosys/kernel/compressor_tree.h new file mode 100644 index 0000000000000000000000000000000000000000..d5ca316b1bc52041ce41a8f3d35c3b39102a203e --- /dev/null +++ b/chips/yosys/kernel/compressor_tree.h @@ -0,0 +1,117 @@ +/** + * Generalized compressor-tree utilities for multi-operand addition + * + * Terminology: + * - compressor: $fa viewed as reducing N inputs to M outputs (sum + shifted carry) (N:M compressor) + * - level: A stage of parallel compression operations + * - depth: Maximum number of N:M compressor levels from any input to a signal + * + * Supported compressors: + * - 3:2 compressor + * - 4:2 compressor + * + * References: + * - "Some schemes for parallel multipliers" (https://www.acsel-lab.com/arithmetic/arith6/papers/ARITH6_Dadda.pdf) + * - "Basilisk: Achieving Competitive Performance with Open EDA Tools" (https://arxiv.org/pdf/2405.03523) + * - "Binary Adder Architectures for Cell-Based VLSI and their Synthesis" (https://iis-people.ee.ethz.ch/~zimmi/publications/adder_arch.pdf) + * - "A Suggestion for a Fast Multiplier" (https://www.ece.ucdavis.edu/~vojin/CLASSES/EEC280/Web-page/papers/Arithmetic/Wallace_mult.pdf) + */ + +#ifndef COMPRESSOR_TREE_H +#define COMPRESSOR_TREE_H + +#include "kernel/sigtools.h" +#include "kernel/yosys.h" + +YOSYS_NAMESPACE_BEGIN + +namespace CompressorTree +{ + +// Width and depth thresholds below which a ripple is preferred over parallel-prefix +// NOTE: Based on "Binary Adder Architectures for Cell-Based VLSI and their Synthesis" (Tables 4.7, 4.9) - the threshold +// should be the point where Kogge-Stone isn't strictly less efficient than RCA +constexpr int RIPPLE_PREFIX_WIDTH_THRESHOLD = 16; +constexpr int RIPPLE_PREFIX_DEPTH_THRESHOLD = 5; + +enum class Strategy { + FA_ONLY, // 3:2 compressors + PREFER_42, // Prefer 4:2 grouping when >=4 operands ready + DADDA, // Defer compression until column counts exceed +}; + +struct DepthSig { + SigSpec sig; + int depth; +}; + +enum class FinalAdder { + DEFAULT, // emit $add and let downstream techmap pick + RIPPLE, // emit $add with explicit narrow hint + PARALLEL_PREFIX, // emit $add with PARALLEL_PREFIX +}; + +enum class FinalMode { + AUTO, + RIPPLE, + PREFIX, +}; + +std::pair emit_compressor_32(Module *module, SigSpec a, SigSpec b, SigSpec c, int width); +std::pair emit_compressor_42(Module *module, SigSpec a, SigSpec b, SigSpec c, SigSpec d, int width); + +/** + * generate_partial_products() - Generate partial products for FMA concat + * @module:The Yosys module to which the compressors will be added + * @a: Signal A + * @b: Signal B + * @a_signed: Whether signal A is signed + * @b_signed: Whether signal B is signed + * @width: Target width + * + * Return: Partial-product matrix as a set of depth-0 vectors + */ +std::vector generate_partial_products(Module *module, SigSpec a, SigSpec b, bool a_signed, bool b_signed, int width); + +/** + * reduce_scheduled() - Reduce multiple operands to two using a compressor tree + * @module: The Yosys module to which the compressors will be added + * @operands: Vector of operands to be reduced + * @sigs: Vector of input signals (operands) to be reduced + * @width: Target bit-width to which all operands will be zero-extended + * @strategy: Compression strategy to use + * @out_compressor_count: Optional pointer to return the number of $fa cells emitted + * @out_final_depth: Optional pointer to return the final depth of the scheduled tree + * + * Return: The final two reduced operands, that are to be fed into an adder + */ +std::pair reduce_scheduled(Module *module, std::vector operands, int width, Strategy strategy, int *out_compressor_count = nullptr, int *out_final_depth = nullptr); + +/** + * emit_kogge_stone() - Emit a Kogge-Stone parallel-prefix adder + * @module: The Yosys module to which the gates will be added + * @a: Signal A + * @b: Signal B + * @y: Signal Y = (A + B) mod 2^W + */ +void emit_kogge_stone(Module *module, SigSpec a, SigSpec b, SigSpec y); + +/** + * emit_final_adder() - Emit the final carry-propagate addition between the two reduced vectors + * @module:The Yosys module to which the compressors will be added + * @a: Signal A + * @b: Signal B + * @y: Signal Y + * @choice: Adder type to instantiate + * + * Return: Cell* of the emitted instance + */ +Cell *emit_final_adder(Module *module, SigSpec a, SigSpec b, SigSpec y, FinalAdder choice); + +FinalAdder pick_final_adder(int width, int final_depth, FinalMode mode); + +} // namespace CompressorTree + +YOSYS_NAMESPACE_END + +#endif // COMPRESSOR_TREE_H diff --git a/chips/yosys/kernel/compute_graph.h b/chips/yosys/kernel/compute_graph.h new file mode 100644 index 0000000000000000000000000000000000000000..aeba17f8c1fa03913e6eb21f12fe7b548d7f6b11 --- /dev/null +++ b/chips/yosys/kernel/compute_graph.h @@ -0,0 +1,403 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2024 Jannis Harder + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#ifndef COMPUTE_GRAPH_H +#define COMPUTE_GRAPH_H + +#include +#include "kernel/yosys.h" + +YOSYS_NAMESPACE_BEGIN + +template< + typename Fn, // Function type (deduplicated across whole graph) + typename Attr = std::tuple<>, // Call attributes (present in every node) + typename SparseAttr = std::tuple<>, // Sparse call attributes (optional per node) + typename Key = std::tuple<> // Stable keys to refer to nodes +> +struct ComputeGraph +{ + struct Ref; +private: + + // Functions are deduplicated by assigning unique ids + idict functions; + + struct Node { + int fn_index; + int arg_offset; + int arg_count; + Attr attr; + + Node(int fn_index, Attr &&attr, int arg_offset, int arg_count = 0) + : fn_index(fn_index), arg_offset(arg_offset), arg_count(arg_count), attr(std::move(attr)) {} + + Node(int fn_index, Attr const &attr, int arg_offset, int arg_count = 0) + : fn_index(fn_index), arg_offset(arg_offset), arg_count(arg_count), attr(attr) {} + }; + + + std::vector nodes; + std::vector args; + dict keys_; + dict sparse_attrs; + +public: + template + struct BaseRef + { + protected: + friend struct ComputeGraph; + Graph *graph_; + int index_; + BaseRef(Graph *graph, int index) : graph_(graph), index_(index) { + log_assert(index_ >= 0); + check(); + } + + void check() const { log_assert(index_ < graph_->size()); } + + Node const &deref() const { check(); return graph_->nodes[index_]; } + + public: + ComputeGraph const &graph() const { return graph_; } + int index() const { return index_; } + + int size() const { return deref().arg_count; } + + BaseRef arg(int n) const + { + Node const &node = deref(); + log_assert(n >= 0 && n < node.arg_count); + return BaseRef(graph_, graph_->args[node.arg_offset + n]); + } + + std::vector::const_iterator arg_indices_cbegin() const + { + Node const &node = deref(); + return graph_->args.cbegin() + node.arg_offset; + } + + std::vector::const_iterator arg_indices_cend() const + { + Node const &node = deref(); + return graph_->args.cbegin() + node.arg_offset + node.arg_count; + } + + Fn const &function() const { return graph_->functions[deref().fn_index]; } + Attr const &attr() const { return deref().attr; } + + bool has_sparse_attr() const { return graph_->sparse_attrs.count(index_); } + + SparseAttr const &sparse_attr() const + { + auto found = graph_->sparse_attrs.find(index_); + log_assert(found != graph_->sparse_attrs.end()); + return found->second; + } + }; + + using ConstRef = BaseRef; + + struct Ref : public BaseRef + { + private: + friend struct ComputeGraph; + Ref(ComputeGraph *graph, int index) : BaseRef(graph, index) {} + Node &deref() const { this->check(); return this->graph_->nodes[this->index_]; } + + public: + Ref(BaseRef ref) : Ref(ref.graph_, ref.index_) {} + + void set_function(Fn const &function) const + { + deref().fn_index = this->graph_->functions(function); + } + + Attr &attr() const { return deref().attr; } + + void append_arg(ConstRef arg) const + { + log_assert(arg.graph_ == this->graph_); + append_arg(arg.index()); + } + + void append_arg(int arg) const + { + log_assert(arg >= 0 && arg < this->graph_->size()); + Node &node = deref(); + if (node.arg_offset + node.arg_count != GetSize(this->graph_->args)) + move_args(node); + this->graph_->args.push_back(arg); + node.arg_count++; + } + + operator ConstRef() const + { + return ConstRef(this->graph_, this->index_); + } + + SparseAttr &sparse_attr() const + { + return this->graph_->sparse_attrs[this->index_]; + } + + void clear_sparse_attr() const + { + this->graph_->sparse_attrs.erase(this->index_); + } + + void assign_key(Key const &key) const + { + this->graph_->keys_.emplace(key, this->index_); + } + + private: + void move_args(Node &node) const + { + auto &args = this->graph_->args; + int old_offset = node.arg_offset; + node.arg_offset = GetSize(args); + for (int i = 0; i != node.arg_count; ++i) + args.push_back(args[old_offset + i]); + } + + }; + + bool has_key(Key const &key) const + { + return keys_.count(key); + } + + dict const &keys() const + { + return keys_; + } + + ConstRef operator()(Key const &key) const + { + auto it = keys_.find(key); + log_assert(it != keys_.end()); + return (*this)[it->second]; + } + + Ref operator()(Key const &key) + { + auto it = keys_.find(key); + log_assert(it != keys_.end()); + return (*this)[it->second]; + } + + int size() const { return GetSize(nodes); } + + ConstRef operator[](int index) const { return ConstRef(this, index); } + Ref operator[](int index) { return Ref(this, index); } + + Ref add(Fn const &function, Attr &&attr) + { + int index = GetSize(nodes); + int fn_index = functions(function); + nodes.emplace_back(fn_index, std::move(attr), GetSize(args)); + return Ref(this, index); + } + + Ref add(Fn const &function, Attr const &attr) + { + int index = GetSize(nodes); + int fn_index = functions(function); + nodes.emplace_back(fn_index, attr, GetSize(args)); + return Ref(this, index); + } + + template + Ref add(Fn const &function, Attr const &attr, T &&args) + { + Ref added = add(function, attr); + for (auto arg : args) + added.append_arg(arg); + return added; + } + + template + Ref add(Fn const &function, Attr &&attr, T &&args) + { + Ref added = add(function, std::move(attr)); + for (auto arg : args) + added.append_arg(arg); + return added; + } + + Ref add(Fn const &function, Attr const &attr, std::initializer_list args) + { + Ref added = add(function, attr); + for (auto arg : args) + added.append_arg(arg); + return added; + } + + Ref add(Fn const &function, Attr &&attr, std::initializer_list args) + { + Ref added = add(function, std::move(attr)); + for (auto arg : args) + added.append_arg(arg); + return added; + } + + template + Ref add(Fn const &function, Attr const &attr, T begin, T end) + { + Ref added = add(function, attr); + for (; begin != end; ++begin) + added.append_arg(*begin); + return added; + } + + void compact_args() + { + std::vector new_args; + for (auto &node : nodes) + { + int new_offset = GetSize(new_args); + for (int i = 0; i < node.arg_count; i++) + new_args.push_back(args[node.arg_offset + i]); + node.arg_offset = new_offset; + } + std::swap(args, new_args); + } + + void permute(std::vector const &perm) + { + log_assert(perm.size() <= nodes.size()); + std::vector inv_perm; + inv_perm.resize(nodes.size(), -1); + for (int i = 0; i < GetSize(perm); ++i) + { + int j = perm[i]; + log_assert(j >= 0 && j < GetSize(nodes)); + log_assert(inv_perm[j] == -1); + inv_perm[j] = i; + } + permute(perm, inv_perm); + } + + void permute(std::vector const &perm, std::vector const &inv_perm) + { + log_assert(inv_perm.size() == nodes.size()); + std::vector new_nodes; + new_nodes.reserve(perm.size()); + dict new_sparse_attrs; + for (int i : perm) + { + int j = GetSize(new_nodes); + new_nodes.emplace_back(std::move(nodes[i])); + auto found = sparse_attrs.find(i); + if (found != sparse_attrs.end()) + new_sparse_attrs.emplace(j, std::move(found->second)); + } + + std::swap(nodes, new_nodes); + std::swap(sparse_attrs, new_sparse_attrs); + + compact_args(); + for (int &arg : args) + { + log_assert(arg < GetSize(inv_perm)); + log_assert(inv_perm[arg] >= 0); + arg = inv_perm[arg]; + } + + for (auto &key : keys_) + { + log_assert(key.second < GetSize(inv_perm)); + log_assert(inv_perm[key.second] >= 0); + key.second = inv_perm[key.second]; + } + } + + struct SccAdaptor + { + private: + ComputeGraph const &graph_; + std::vector indices_; + public: + SccAdaptor(ComputeGraph const &graph) : graph_(graph) + { + indices_.resize(graph.size(), -1); + } + + + typedef int node_type; + + struct node_enumerator { + private: + friend struct SccAdaptor; + int current, end; + node_enumerator(int current, int end) : current(current), end(end) {} + + public: + + bool finished() const { return current == end; } + node_type next() { + log_assert(!finished()); + node_type result = current; + ++current; + return result; + } + }; + + node_enumerator enumerate_nodes() { + return node_enumerator(0, GetSize(indices_)); + } + + + struct successor_enumerator { + private: + friend struct SccAdaptor; + std::vector::const_iterator current, end; + successor_enumerator(std::vector::const_iterator current, std::vector::const_iterator end) : + current(current), end(end) {} + + public: + bool finished() const { return current == end; } + node_type next() { + log_assert(!finished()); + node_type result = *current; + ++current; + return result; + } + }; + + successor_enumerator enumerate_successors(int index) const { + auto const &ref = graph_[index]; + return successor_enumerator(ref.arg_indices_cbegin(), ref.arg_indices_cend()); + } + + int &dfs_index(node_type const &node) { return indices_[node]; } + + std::vector const &dfs_indices() { return indices_; } + }; + +}; + + + +YOSYS_NAMESPACE_END + + +#endif diff --git a/chips/yosys/kernel/consteval.h b/chips/yosys/kernel/consteval.h new file mode 100644 index 0000000000000000000000000000000000000000..ed118493a7dd471b6f6f3333dad7af1b4a48f1c9 --- /dev/null +++ b/chips/yosys/kernel/consteval.h @@ -0,0 +1,444 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#ifndef CONSTEVAL_H +#define CONSTEVAL_H + +#include "kernel/rtlil.h" +#include "kernel/sigtools.h" +#include "kernel/celltypes.h" +#include "kernel/macc.h" +#include "kernel/newcelltypes.h" + +YOSYS_NAMESPACE_BEGIN + +/** + * ConstEval provides on-demand constant propagation by traversing input cones + * with caching + */ +struct ConstEval +{ + RTLIL::Module *module; + SigMap assign_map; + SigMap values_map; + SigPool stop_signals; + SigSet sig2driver; + std::set busy; + std::vector stack; + RTLIL::State defaultval; + bool model_barriers = false; // Model $barrier as a buffer + + ConstEval(RTLIL::Module *module, RTLIL::State defaultval = RTLIL::State::Sm) : module(module), assign_map(module), defaultval(defaultval) + { + auto ct = NewCellTypes(); + ct.static_cell_types = StaticCellTypes::Compat::nomem_noff; + + for (auto &it : module->cells_) { + if (!ct.cell_known(it.second->type)) + continue; + for (auto &it2 : it.second->connections()) + if (ct.cell_output(it.second->type, it2.first)) + sig2driver.insert(assign_map(it2.second), it.second); + } + } + + void clear() + { + values_map.clear(); + stop_signals.clear(); + } + + void push() + { + stack.push_back(values_map); + } + + void pop() + { + values_map.swap(stack.back()); + stack.pop_back(); + } + + void set(RTLIL::SigSpec sig, RTLIL::Const value) + { + assign_map.apply(sig); +#ifndef NDEBUG + RTLIL::SigSpec current_val = values_map(sig); + for (int i = 0; i < GetSize(current_val); i++) + log_assert(current_val[i].wire != NULL || current_val[i] == value[i]); +#endif + values_map.add(sig, RTLIL::SigSpec(value)); + } + + void stop(RTLIL::SigSpec sig) + { + assign_map.apply(sig); + stop_signals.add(sig); + } + + bool eval(RTLIL::Cell *cell, RTLIL::SigSpec &undef) + { + if (cell->type == ID($lcu)) + { + RTLIL::SigSpec sig_p = cell->getPort(ID::P); + RTLIL::SigSpec sig_g = cell->getPort(ID::G); + RTLIL::SigSpec sig_ci = cell->getPort(ID::CI); + RTLIL::SigSpec sig_co = values_map(assign_map(cell->getPort(ID::CO))); + + if (sig_co.is_fully_const()) + return true; + + if (!eval(sig_p, undef, cell)) + return false; + + if (!eval(sig_g, undef, cell)) + return false; + + if (!eval(sig_ci, undef, cell)) + return false; + + if (sig_p.is_fully_def() && sig_g.is_fully_def() && sig_ci.is_fully_def()) + { + RTLIL::Const coval(RTLIL::Sx, GetSize(sig_co)); + bool carry = sig_ci.as_bool(); + + for (int i = 0; i < GetSize(coval); i++) { + carry = (sig_g[i] == State::S1) || (sig_p[i] == RTLIL::S1 && carry); + coval.set(i, carry ? State::S1 : State::S0); + } + + set(sig_co, coval); + } + else + set(sig_co, RTLIL::Const(RTLIL::Sx, GetSize(sig_co))); + + return true; + } + + RTLIL::SigSpec sig_a, sig_b, sig_s, sig_y; + + log_assert(cell->hasPort(ID::Y)); + sig_y = values_map(assign_map(cell->getPort(ID::Y))); + if (sig_y.is_fully_const()) + return true; + + if (cell->type == ID($barrier)) + { + if (!model_barriers) { + undef.append(sig_y); + return false; + } + sig_a = cell->getPort(ID::A); + if (!eval(sig_a, undef, cell)) + return false; + set(sig_y, sig_a.as_const()); + return true; + } + + if (cell->hasPort(ID::S)) { + sig_s = cell->getPort(ID::S); + } + + if (cell->hasPort(ID::A)) + sig_a = cell->getPort(ID::A); + + if (cell->hasPort(ID::B)) + sig_b = cell->getPort(ID::B); + + if (cell->type.in(ID($mux), ID($pmux), ID($_MUX_), ID($_NMUX_))) + { + std::vector y_candidates; + int count_set_s_bits = 0; + + if (!eval(sig_s, undef, cell)) + return false; + + for (int i = 0; i < sig_s.size(); i++) + { + RTLIL::State s_bit = sig_s.extract(i, 1).as_const().at(0); + RTLIL::SigSpec b_slice = sig_b.extract(sig_y.size()*i, sig_y.size()); + + if (s_bit == RTLIL::State::Sx || s_bit == RTLIL::State::S1) + y_candidates.push_back(b_slice); + + if (s_bit == RTLIL::State::S1) + count_set_s_bits++; + } + + if (count_set_s_bits == 0) + y_candidates.push_back(sig_a); + + std::vector y_values; + + log_assert(y_candidates.size() > 0); + for (auto &yc : y_candidates) { + if (!eval(yc, undef, cell)) + return false; + if (cell->type == ID($_NMUX_)) + y_values.push_back(RTLIL::const_not(yc.as_const(), Const(), false, false, GetSize(yc))); + else + y_values.push_back(yc.as_const()); + } + + if (y_values.size() > 1) + { + std::vector master_bits = y_values.at(0).to_bits(); + + for (size_t i = 1; i < y_values.size(); i++) { + std::vector slave_bits = y_values.at(i).to_bits(); + log_assert(master_bits.size() == slave_bits.size()); + for (size_t j = 0; j < master_bits.size(); j++) + if (master_bits[j] != slave_bits[j]) + master_bits[j] = RTLIL::State::Sx; + } + + set(sig_y, RTLIL::Const(master_bits)); + } + else + set(sig_y, y_values.front()); + } + else if (cell->type == ID($bmux)) + { + if (!eval(sig_s, undef, cell)) + return false; + + if (sig_s.is_fully_def()) { + int sel = sig_s.as_int(); + int width = GetSize(sig_y); + SigSpec res = sig_a.extract(sel * width, width); + if (!eval(res, undef, cell)) + return false; + set(sig_y, res.as_const()); + } else { + if (!eval(sig_a, undef, cell)) + return false; + set(sig_y, const_bmux(sig_a.as_const(), sig_s.as_const())); + } + } + else if (cell->type == ID($demux)) + { + if (!eval(sig_a, undef, cell)) + return false; + if (sig_a.is_fully_zero()) { + set(sig_y, Const(0, GetSize(sig_y))); + } else { + if (!eval(sig_s, undef, cell)) + return false; + set(sig_y, const_demux(sig_a.as_const(), sig_s.as_const())); + } + } + else if (cell->type == ID($fa)) + { + RTLIL::SigSpec sig_c = cell->getPort(ID::C); + RTLIL::SigSpec sig_x = cell->getPort(ID::X); + int width = GetSize(sig_c); + + if (!eval(sig_a, undef, cell)) + return false; + + if (!eval(sig_b, undef, cell)) + return false; + + if (!eval(sig_c, undef, cell)) + return false; + + RTLIL::Const t1 = const_xor(sig_a.as_const(), sig_b.as_const(), false, false, width); + RTLIL::Const val_y = const_xor(t1, sig_c.as_const(), false, false, width); + + RTLIL::Const t2 = const_and(sig_a.as_const(), sig_b.as_const(), false, false, width); + RTLIL::Const t3 = const_and(sig_c.as_const(), t1, false, false, width); + RTLIL::Const val_x = const_or(t2, t3, false, false, width); + + for (int i = 0; i < GetSize(val_y); i++) + if (val_y[i] == RTLIL::Sx) + val_x.set(i, RTLIL::Sx); + + set(sig_y, val_y); + set(sig_x, val_x); + } + else if (cell->type == ID($alu)) + { + bool signed_a = cell->parameters.count(ID::A_SIGNED) > 0 && cell->parameters[ID::A_SIGNED].as_bool(); + bool signed_b = cell->parameters.count(ID::B_SIGNED) > 0 && cell->parameters[ID::B_SIGNED].as_bool(); + + RTLIL::SigSpec sig_ci = cell->getPort(ID::CI); + RTLIL::SigSpec sig_bi = cell->getPort(ID::BI); + + if (!eval(sig_a, undef, cell)) + return false; + + if (!eval(sig_b, undef, cell)) + return false; + + if (!eval(sig_ci, undef, cell)) + return false; + + if (!eval(sig_bi, undef, cell)) + return false; + + RTLIL::SigSpec sig_x = cell->getPort(ID::X); + RTLIL::SigSpec sig_co = cell->getPort(ID::CO); + + bool any_input_undef = !(sig_a.is_fully_def() && sig_b.is_fully_def() && sig_ci.is_fully_def() && sig_bi.is_fully_def()); + sig_a.extend_u0(GetSize(sig_y), signed_a); + sig_b.extend_u0(GetSize(sig_y), signed_b); + + bool carry = sig_ci[0] == State::S1; + bool b_inv = sig_bi[0] == State::S1; + + for (int i = 0; i < GetSize(sig_y); i++) + { + RTLIL::SigSpec x_inputs = { sig_a[i], sig_b[i], sig_bi[0] }; + + if (!x_inputs.is_fully_def()) { + set(sig_x[i], RTLIL::Sx); + } else { + bool bit_a = sig_a[i] == State::S1; + bool bit_b = (sig_b[i] == State::S1) != b_inv; + bool bit_x = bit_a != bit_b; + set(sig_x[i], bit_x ? State::S1 : State::S0); + } + + if (any_input_undef) { + set(sig_y[i], RTLIL::Sx); + set(sig_co[i], RTLIL::Sx); + } else { + bool bit_a = sig_a[i] == State::S1; + bool bit_b = (sig_b[i] == State::S1) != b_inv; + bool bit_y = (bit_a != bit_b) != carry; + carry = (bit_a && bit_b) || (bit_a && carry) || (bit_b && carry); + set(sig_y[i], bit_y ? State::S1 : State::S0); + set(sig_co[i], carry ? State::S1 : State::S0); + } + } + } + else if (cell->type.in(ID($macc), ID($macc_v2))) + { + Macc macc; + macc.from_cell(cell); + + for (auto &port : macc.terms) { + if (!eval(port.in_a, undef, cell)) + return false; + if (!eval(port.in_b, undef, cell)) + return false; + } + + RTLIL::Const result(0, GetSize(cell->getPort(ID::Y))); + if (!macc.eval(result)) + log_abort(); + + set(cell->getPort(ID::Y), result); + } + else + { + RTLIL::SigSpec sig_c, sig_d; + + if (cell->type.in(ID($_AOI3_), ID($_OAI3_), ID($_AOI4_), ID($_OAI4_))) { + if (cell->hasPort(ID::C)) + sig_c = cell->getPort(ID::C); + if (cell->hasPort(ID::D)) + sig_d = cell->getPort(ID::D); + } + + if (sig_a.size() > 0 && !eval(sig_a, undef, cell)) + return false; + if (sig_b.size() > 0 && !eval(sig_b, undef, cell)) + return false; + if (sig_c.size() > 0 && !eval(sig_c, undef, cell)) + return false; + if (sig_d.size() > 0 && !eval(sig_d, undef, cell)) + return false; + + bool eval_err = false; + RTLIL::Const eval_ret; + if (sig_s.size() > 0 && eval(sig_s, undef, cell)) { + eval_ret = CellTypes::eval(cell, sig_a.as_const(), sig_b.as_const(), sig_s.as_const(), &eval_err); + } else + eval_ret = CellTypes::eval(cell, sig_a.as_const(), sig_b.as_const(), sig_c.as_const(), sig_d.as_const(), &eval_err); + + if (eval_err) + return false; + + set(sig_y, eval_ret); + } + + return true; + } + + bool eval(RTLIL::SigSpec &sig, RTLIL::SigSpec &undef, RTLIL::Cell *busy_cell = NULL) + { + assign_map.apply(sig); + values_map.apply(sig); + + if (sig.is_fully_const()) + return true; + + if (stop_signals.check_any(sig)) { + undef = stop_signals.extract(sig); + return false; + } + + if (busy_cell) { + if (busy.count(busy_cell) > 0) { + undef = sig; + return false; + } + busy.insert(busy_cell); + } + + std::set driver_cells; + sig2driver.find(sig, driver_cells); + for (auto cell : driver_cells) { + if (!eval(cell, undef)) { + if (busy_cell) + busy.erase(busy_cell); + return false; + } + } + + if (busy_cell) + busy.erase(busy_cell); + + values_map.apply(sig); + if (sig.is_fully_const()) + return true; + + if (defaultval != RTLIL::State::Sm) { + for (auto &bit : sig) + if (bit.wire) bit = defaultval; + return true; + } + + for (auto &c : sig.chunks()) + if (c.wire != NULL) + undef.append(c); + return false; + } + + bool eval(RTLIL::SigSpec &sig) + { + RTLIL::SigSpec undef; + return eval(sig, undef); + } +}; + +YOSYS_NAMESPACE_END + +#endif diff --git a/chips/yosys/kernel/constids.inc b/chips/yosys/kernel/constids.inc new file mode 100644 index 0000000000000000000000000000000000000000..439c930e8e68a4af9d657c933b0356c19fe2097b --- /dev/null +++ b/chips/yosys/kernel/constids.inc @@ -0,0 +1,1070 @@ +// These must be in perfect ASCII order!!! + +// Workaround for macos's math.h defining an OVERFLOW macro +#ifdef OVERFLOW +#undef OVERFLOW +#endif + +// Workaround for windows defining IN and OUT macros in minwindef.h which ends +// up getting included for visual studio builds +#ifdef IN +#undef IN +#endif +#ifdef OUT +#undef OUT +#endif + +X($_ALDFFE_NNN_) +X($_ALDFFE_NNP_) +X($_ALDFFE_NPN_) +X($_ALDFFE_NPP_) +X($_ALDFFE_PNN_) +X($_ALDFFE_PNP_) +X($_ALDFFE_PPN_) +X($_ALDFFE_PPP_) +X($_ALDFF_NN_) +X($_ALDFF_NP_) +X($_ALDFF_PN_) +X($_ALDFF_PP_) +X($_ANDNOT_) +X($_AND_) +X($_AOI3_) +X($_AOI4_) +X($_BUF_) +X($_DFFE_NN0N_) +X($_DFFE_NN0P_) +X($_DFFE_NN1N_) +X($_DFFE_NN1P_) +X($_DFFE_NN_) +X($_DFFE_NP0N_) +X($_DFFE_NP0P_) +X($_DFFE_NP1N_) +X($_DFFE_NP1P_) +X($_DFFE_NP_) +X($_DFFE_PN0N_) +X($_DFFE_PN0P_) +X($_DFFE_PN1N_) +X($_DFFE_PN1P_) +X($_DFFE_PN_) +X($_DFFE_PP0N_) +X($_DFFE_PP0P_) +X($_DFFE_PP1N_) +X($_DFFE_PP1P_) +X($_DFFE_PP_) +X($_DFFSRE_NNNN_) +X($_DFFSRE_NNNP_) +X($_DFFSRE_NNPN_) +X($_DFFSRE_NNPP_) +X($_DFFSRE_NPNN_) +X($_DFFSRE_NPNP_) +X($_DFFSRE_NPPN_) +X($_DFFSRE_NPPP_) +X($_DFFSRE_PNNN_) +X($_DFFSRE_PNNP_) +X($_DFFSRE_PNPN_) +X($_DFFSRE_PNPP_) +X($_DFFSRE_PPNN_) +X($_DFFSRE_PPNP_) +X($_DFFSRE_PPPN_) +X($_DFFSRE_PPPP_) +X($_DFFSR_NNN_) +X($_DFFSR_NNP_) +X($_DFFSR_NPN_) +X($_DFFSR_NPP_) +X($_DFFSR_PNN_) +X($_DFFSR_PNP_) +X($_DFFSR_PPN_) +X($_DFFSR_PPP_) +X($_DFF_N) +X($_DFF_NN0_) +X($_DFF_NN1_) +X($_DFF_NP0_) +X($_DFF_NP1_) +X($_DFF_N_) +X($_DFF_PN0_) +X($_DFF_PN1_) +X($_DFF_PP0_) +X($_DFF_PP1_) +X($_DFF_P_) +X($_DLATCHSR_NNN_) +X($_DLATCHSR_NNP_) +X($_DLATCHSR_NPN_) +X($_DLATCHSR_NPP_) +X($_DLATCHSR_PNN_) +X($_DLATCHSR_PNP_) +X($_DLATCHSR_PPN_) +X($_DLATCHSR_PPP_) +X($_DLATCH_NN0_) +X($_DLATCH_NN1_) +X($_DLATCH_NP0_) +X($_DLATCH_NP1_) +X($_DLATCH_N_) +X($_DLATCH_PN0_) +X($_DLATCH_PN1_) +X($_DLATCH_PP0_) +X($_DLATCH_PP1_) +X($_DLATCH_P_) +X($_FF_) +X($_MUX16_) +X($_MUX4_) +X($_MUX8_) +X($_MUX_) +X($_NAND_) +X($_NMUX_) +X($_NOR_) +X($_NOT_) +X($_OAI3_) +X($_OAI4_) +X($_ORNOT_) +X($_OR_) +X($_SDFFCE_NN0N_) +X($_SDFFCE_NN0P_) +X($_SDFFCE_NN1N_) +X($_SDFFCE_NN1P_) +X($_SDFFCE_NP0N_) +X($_SDFFCE_NP0P_) +X($_SDFFCE_NP1N_) +X($_SDFFCE_NP1P_) +X($_SDFFCE_PN0N_) +X($_SDFFCE_PN0P_) +X($_SDFFCE_PN1N_) +X($_SDFFCE_PN1P_) +X($_SDFFCE_PP0N_) +X($_SDFFCE_PP0P_) +X($_SDFFCE_PP1N_) +X($_SDFFCE_PP1P_) +X($_SDFFE_NN0N_) +X($_SDFFE_NN0P_) +X($_SDFFE_NN1N_) +X($_SDFFE_NN1P_) +X($_SDFFE_NP0N_) +X($_SDFFE_NP0P_) +X($_SDFFE_NP1N_) +X($_SDFFE_NP1P_) +X($_SDFFE_PN0N_) +X($_SDFFE_PN0P_) +X($_SDFFE_PN1N_) +X($_SDFFE_PN1P_) +X($_SDFFE_PP0N_) +X($_SDFFE_PP0P_) +X($_SDFFE_PP1N_) +X($_SDFFE_PP1P_) +X($_SDFF_NN0_) +X($_SDFF_NN1_) +X($_SDFF_NP0_) +X($_SDFF_NP1_) +X($_SDFF_PN0_) +X($_SDFF_PN1_) +X($_SDFF_PP0_) +X($_SDFF_PP1_) +X($_SR_NN_) +X($_SR_NP_) +X($_SR_PN_) +X($_SR_PP_) +X($_TBUF_) +X($_XNOR_) +X($_XOR_) +X($__ABC9_DELAY) +X($__ABC9_SCC_BREAKER) +X($__CC_NOT) +X($__COUNT_) +X($__ICE40_CARRY_WRAPPER) +X($__NX_MUL18X18) +X($__NX_MUL36X18) +X($__NX_MUL36X36) +X($__QLF_TDP36K) +X($__QLF_TDP36K_MERGED) +X($__XILINX_SHREG_) +X($abc9_flops) +X($add) +X($adff) +X($adffe) +X($adlatch) +X($aldff) +X($aldffe) +X($allconst) +X($allseq) +X($alu) +X($and) +X($anyconst) +X($anyinit) +X($anyseq) +X($assert) +X($assume) +X($barrier) +X($bmux) +X($buf) +X($bugpoint) +X($bweq) +X($bweqx) +X($bwmux) +X($check) +X($concat) +X($connect) +X($cover) +X($demux) +X($dff) +X($dffe) +X($dffsr) +X($dffsre) +X($div) +X($divfloor) +X($dlatch) +X($dlatchsr) +X($eq) +X($equiv) +X($eqx) +X($fa) +X($fair) +X($false) +X($ff) +X($flowmap_level) +X($fsm) +X($fullskew) +X($future_ff) +X($ge) +X($get_tag) +X($gt) +X($initstate) +X($input) +X($input_port) +X($lcu) +X($le) +X($live) +X($logic_and) +X($logic_not) +X($logic_or) +X($lt) +X($lut) +X($macc) +X($macc_v2) +X($mem) +X($mem_v2) +X($meminit) +X($meminit_v2) +X($memrd) +X($memrd_v2) +X($memwr) +X($memwr_v2) +X($mod) +X($modfloor) +X($mul) +X($mux) +X($ne) +X($neg) +X($nex) +X($not) +X($or) +X($original_tag) +X($output) +X($overwrite_tag) +X($pending) +X($pmux) +X($pos) +X($pow) +X($print) +X($recrem) +X($reduce_and) +X($reduce_bool) +X($reduce_nand) +X($reduce_or) +X($reduce_xnor) +X($reduce_xor) +X($scopeinfo) +X($sdff) +X($sdffce) +X($sdffe) +X($set_tag) +X($setup) +X($setuphold) +X($shift) +X($shiftx) +X($shl) +X($shr) +X($slice) +X($sop) +X($specify2) +X($specify3) +X($specrule) +X($sr) +X($sshl) +X($sshr) +X($state) +X($sub) +X($tribuf) +X($true) +X($undef) +X($xnor) +X($xor) +X(A) +X(A0) +X(A0REG) +X(A1) +X(A1REG) +X(A2) +X(A3) +X(A4) +X(ABITS) +X(ACASCREG) +X(ACCUMCI) +X(ACCUMCO) +X(ACIN) +X(ACOUT) +X(AD) +X(ADDEND_NEGATED) +X(ADDR) +X(ADDSUBBOT) +X(ADDSUBTOP) +X(ADREG) +X(AHOLD) +X(ALOAD) +X(ALOAD_POLARITY) +X(ALUMODE) +X(ALUMODEREG) +X(ALUTYPE) +X(AL_MAP_ADDER) +X(AL_MAP_LUT1) +X(AL_MAP_LUT2) +X(AL_MAP_LUT3) +X(AL_MAP_LUT4) +X(AL_MAP_LUT5) +X(AL_MAP_LUT6) +X(ALn) +X(AND) +X(ANDNOT) +X(ANDTERM) +X(AOI3) +X(AOI4) +X(AREG) +X(ARGS) +X(ARGS_WIDTH) +X(ARSHFT17) +X(ARSHFT17_BYPASS) +X(ARST) +X(ARST_POLARITY) +X(ARST_VALUE) +X(A_BYPASS) +X(A_EN) +X(A_INPUT) +X(A_REG) +X(A_SIGNED) +X(A_SRST_N) +X(A_WIDTH) +X(A_WIDTHS) +X(B) +X(B0) +X(B0REG) +X(B1) +X(B1REG) +X(B2) +X(B3) +X(B4) +X(BCASCREG) +X(BCIN) +X(BCOUT) +X(BHOLD) +X(BI) +X(BITS_USED) +X(BOTADDSUB_CARRYSELECT) +X(BOTADDSUB_LOWERINPUT) +X(BOTADDSUB_UPPERINPUT) +X(BOTOUTPUT_SELECT) +X(BOT_8x8_MULT_REG) +X(BREG) +X(BUF) +X(BUFG) +X(BUFGSR) +X(BUFGTS) +X(B_BYPASS) +X(B_EN) +X(B_INPUT) +X(B_REG) +X(B_SIGNED) +X(B_SRST_N) +X(B_WIDTH) +X(B_WIDTHS) +X(C) +X(CARRYIN) +X(CARRYINREG) +X(CARRYINSEL) +X(CARRYINSELREG) +X(CARRYOUT) +X(CC_L2T4) +X(CC_L2T5) +X(CC_LUT2) +X(CDIN) +X(CDIN_FDBK_SEL) +X(CDOUT) +X(CE) +X(CEA) +X(CEA1) +X(CEA2) +X(CEAD) +X(CEB) +X(CEB1) +X(CEB2) +X(CEC) +X(CED) +X(CEM) +X(CEOUT) +X(CEP) +X(CE_OVER_SRST) +X(CFG1) +X(CFG2) +X(CFG3) +X(CFG4) +X(CFG_ABITS) +X(CFG_DBITS) +X(CFG_INIT) +X(CHOLD) +X(CI) +X(CLK) +X(CLKIN_DIVIDE) +X(CLKPOL) +X(CLK_ENABLE) +X(CLK_POLARITY) +X(CLR) +X(CLR_POLARITY) +X(CO) +X(COLLISION_X_MASK) +X(COMP_INP) +X(CONFIG) +X(CONFIG_WIDTH) +X(COUNT_EXTRACT) +X(COUNT_TO) +X(CREG) +X(CTRL_IN) +X(CTRL_IN_WIDTH) +X(CTRL_OUT) +X(CTRL_OUT_WIDTH) +X(C_ARST_N) +X(C_BYPASS) +X(C_EN) +X(C_REG) +X(C_SIGNED) +X(C_SRST_N) +X(C_WIDTHS) +X(D) +X(DAT) +X(DATA) +X(DAT_DST_PEN) +X(DAT_DST_POL) +X(DELAY) +X(DEPTH) +X(DFF) +X(DHOLD) +X(DIRECTION) +X(DREG) +X(DSP48A) +X(DSP48A1) +X(DSP48E1) +X(DST) +X(DST_EN) +X(DST_PEN) +X(DST_POL) +X(DST_WIDTH) +X(DZ) +X(D_ARST_N) +X(D_BYPASS) +X(D_EN) +X(D_REG) +X(D_SRST_N) +X(E) +X(EDGE_EN) +X(EDGE_POL) +X(EFX_ADD) +X(EN) +X(ENPOL) +X(EN_POLARITY) +X(EQN) +X(F) +X(FDCE) +X(FDCE_1) +X(FDCP) +X(FDCPE) +X(FDCPE_1) +X(FDCPE_N) +X(FDCP_N) +X(FDDCP) +X(FDDCPE) +X(FDPE) +X(FDPE_1) +X(FDRE) +X(FDRE_1) +X(FDRSE) +X(FDRSE_1) +X(FDSE) +X(FDSE_1) +X(FLAVOR) +X(FORMAT) +X(FTCP) +X(FTCP_N) +X(FTDCP) +X(FULL) +X(G) +X(GP_DFF) +X(GP_DFFI) +X(GP_DFFR) +X(GP_DFFRI) +X(GP_DFFS) +X(GP_DFFSI) +X(GP_DFFSR) +X(GP_DFFSRI) +X(GP_DLATCH) +X(GP_DLATCHI) +X(GP_DLATCHR) +X(GP_DLATCHRI) +X(GP_DLATCHS) +X(GP_DLATCHSI) +X(GP_DLATCHSR) +X(GP_DLATCHSRI) +X(GP_INV) +X(GP_SHREG) +X(GSR) +X(H) +X(HAS_CE) +X(HAS_POUT) +X(I) +X(I0) +X(I0_POLARITY) +X(I1) +X(I1_POLARITY) +X(I2) +X(I3) +X(I3_IS_CI) +X(I4) +X(I5) +X(IBUF) +X(IN) +X(INIT) +X(INIT1) +X(INIT2) +X(INIT_FILE) +X(INIT_L00) +X(INIT_L01) +X(INIT_L02) +X(INIT_L03) +X(INIT_L10) +X(INIT_L20) +X(INIT_VALUE) +X(INMODE) +X(INMODEREG) +X(INV) +X(INVERT_OUT) +X(IN_B) +X(IN_ORTERM) +X(IN_PTC) +X(IOBUFE) +X(IRSTBOT) +X(IRSTTOP) +X(IS_C_INVERTED) +X(IS_D_INVERTED) +X(IS_R_INVERTED) +X(IS_S_INVERTED) +X(J) +X(K) +X(L) +X(LAT) +X(LDCP) +X(LDCP_N) +X(LSR) +X(LUT) +X(LUT1) +X(LUT2) +X(LUT3) +X(LUT4) +X(LUT5) +X(LUT6) +X(LUT_INIT) +X(M) +X(MACC_PA) +X(MACROCELL_XOR) +X(MASK) +X(MEMID) +X(MODE_8x8) +X(MODE_BITS) +X(MREG) +X(MUX) +X(MUX16) +X(MUX4) +X(MUX8) +X(N) +X(NADDENDS) +X(NAME) +X(NAND) +X(NEG_TRIGGER) +X(NMUX) +X(NOR) +X(NOT) +X(NPRODUCTS) +X(NV) +X(NX) +X(NX_CY) +X(NX_CY_1BIT) +X(O) +X(OAI3) +X(OAI4) +X(OF) +X(OFFSET) +X(OHOLDBOT) +X(OHOLDTOP) +X(OLOADBOT) +X(OLOADTOP) +X(ONE) +X(OPMODE) +X(OPMODEREG) +X(OPTION_SPLIT) +X(OR) +X(ORNOT) +X(ORSTBOT) +X(ORSTTOP) +X(ORTERM) +X(OUT) +X(OUTA) +X(OUTA_INVERT) +X(OUTA_TAP) +X(OUTB) +X(OUTB_TAP) +X(OVERFLOW) +X(P) +X(PASUB) +X(PASUB_BYPASS) +X(PATTERN) +X(PCIN) +X(PCOUT) +X(PIPELINED) +X(PIPELINE_16x16_MULT_REG1) +X(PIPELINE_16x16_MULT_REG2) +X(PORTID) +X(PORT_A1_ADDR) +X(PORT_A1_CLK) +X(PORT_A1_CLK_EN) +X(PORT_A1_RD_DATA) +X(PORT_A1_WIDTH) +X(PORT_A1_WR_BE) +X(PORT_A1_WR_BE_WIDTH) +X(PORT_A1_WR_DATA) +X(PORT_A1_WR_EN) +X(PORT_A2_ADDR) +X(PORT_A2_CLK) +X(PORT_A2_CLK_EN) +X(PORT_A2_RD_DATA) +X(PORT_A2_WIDTH) +X(PORT_A2_WR_BE) +X(PORT_A2_WR_BE_WIDTH) +X(PORT_A2_WR_DATA) +X(PORT_A2_WR_EN) +X(PORT_A_ADDR) +X(PORT_A_CLK) +X(PORT_A_CLK_EN) +X(PORT_A_RD_DATA) +X(PORT_A_WIDTH) +X(PORT_A_WR_BE) +X(PORT_A_WR_BE_WIDTH) +X(PORT_A_WR_DATA) +X(PORT_A_WR_EN) +X(PORT_B1_ADDR) +X(PORT_B1_CLK) +X(PORT_B1_CLK_EN) +X(PORT_B1_RD_DATA) +X(PORT_B1_WIDTH) +X(PORT_B1_WR_BE) +X(PORT_B1_WR_BE_WIDTH) +X(PORT_B1_WR_DATA) +X(PORT_B1_WR_EN) +X(PORT_B2_ADDR) +X(PORT_B2_CLK) +X(PORT_B2_CLK_EN) +X(PORT_B2_RD_DATA) +X(PORT_B2_WIDTH) +X(PORT_B2_WR_BE) +X(PORT_B2_WR_BE_WIDTH) +X(PORT_B2_WR_DATA) +X(PORT_B2_WR_EN) +X(PORT_B_ADDR) +X(PORT_B_CLK) +X(PORT_B_CLK_EN) +X(PORT_B_RD_DATA) +X(PORT_B_WIDTH) +X(PORT_B_WR_BE) +X(PORT_B_WR_BE_WIDTH) +X(PORT_B_WR_DATA) +X(PORT_B_WR_EN) +X(POUT) +X(PRE) +X(PREG) +X(PRIORITY) +X(PRIORITY_MASK) +X(PRODUCT_NEGATED) +X(P_BYPASS) +X(P_EN) +X(P_SRST_N) +X(Q) +X(QL_DSP2) +X(R) +X(RD_ADDR) +X(RD_ARST) +X(RD_ARST_VALUE) +X(RD_CE_OVER_SRST) +X(RD_CLK) +X(RD_CLK_ENABLE) +X(RD_CLK_POLARITY) +X(RD_COLLISION_X_MASK) +X(RD_DATA) +X(RD_EN) +X(RD_INIT_VALUE) +X(RD_PORTS) +X(RD_SRST) +X(RD_SRST_VALUE) +X(RD_TRANSPARENCY_MASK) +X(RD_TRANSPARENT) +X(RD_WIDE_CONTINUATION) +X(REGINPUTA) +X(REGINPUTB) +X(REGOUTPUT) +X(RESETMODE) +X(RESET_MODE) +X(RESET_TO_MAX) +X(RST) +X(RSTA) +X(RSTB) +X(RSTC) +X(RSTD) +X(RSTM) +X(RSTOUT) +X(RSTP) +X(S) +X(S1) +X(S2) +X(S3) +X(S4) +X(SB_CARRY) +X(SB_LUT4) +X(SB_MAC16) +X(SB_RAM40_4K) +X(SB_RAM40_4KNR) +X(SB_RAM40_4KNRNW) +X(SB_RAM40_4KNW) +X(SD) +X(SEL_MASK) +X(SEL_PATTERN) +X(SET) +X(SET_POLARITY) +X(SGSR) +X(SIGNED) +X(SIGNEXTIN) +X(SIGNEXTOUT) +X(SIZE) +X(SLE) +X(SLn) +X(SRC) +X(SRC_DST_PEN) +X(SRC_DST_POL) +X(SRC_EN) +X(SRC_PEN) +X(SRC_POL) +X(SRC_WIDTH) +X(SRMODE) +X(SRST) +X(SRST_POLARITY) +X(SRST_VALUE) +X(STATE_BITS) +X(STATE_NUM) +X(STATE_NUM_LOG2) +X(STATE_RST) +X(STATE_TABLE) +X(SUB) +X(SUBTRACT) +X(S_WIDTH) +X(T) +X(TABLE) +X(TAG) +X(TDP36K) +X(TOPADDSUB_CARRYSELECT) +X(TOPADDSUB_LOWERINPUT) +X(TOPADDSUB_UPPERINPUT) +X(TOPOUTPUT_SELECT) +X(TOP_8x8_MULT_REG) +X(TRANSPARENCY_MASK) +X(TRANSPARENT) +X(TRANS_NUM) +X(TRANS_TABLE) +X(TRELLIS_FF) +X(TRG) +X(TRG_ENABLE) +X(TRG_POLARITY) +X(TRG_WIDTH) +X(TRUE_INP) +X(TYPE) +X(T_FALL_MAX) +X(T_FALL_MIN) +X(T_FALL_TYP) +X(T_LIMIT2_MAX) +X(T_LIMIT2_MIN) +X(T_LIMIT2_TYP) +X(T_LIMIT_MAX) +X(T_LIMIT_MIN) +X(T_LIMIT_TYP) +X(T_RISE_MAX) +X(T_RISE_MIN) +X(T_RISE_TYP) +X(U) +X(UF) +X(UP) +X(USE_DPORT) +X(USE_MULT) +X(USE_PATTERN_DETECT) +X(USE_SIMD) +X(UUT) +X(V) +X(WIDTH) +X(WORDS) +X(WR_ADDR) +X(WR_CLK) +X(WR_CLK_ENABLE) +X(WR_CLK_POLARITY) +X(WR_DATA) +X(WR_EN) +X(WR_PORTS) +X(WR_PRIORITY_MASK) +X(WR_WIDE_CONTINUATION) +X(X) +X(XNOR) +X(XOR) +X(Y) +X(Y_WIDTH) +X(Z) +X(ZERO) +X(_TECHMAP_BITS_CONNMAP_) +X(_TECHMAP_CELLNAME_) +X(_TECHMAP_CELLTYPE_) +X(_TECHMAP_PLACEHOLDER_) +X(_TECHMAP_REPLACE_) +X(__glift_weight) +X(_const0_) +X(_const1_) +X(_dff_) +X(_id) +X(_techmap_special_) +X(a) +X(a_i) +X(abc9_box) +X(abc9_box_id) +X(abc9_box_seq) +X(abc9_bypass) +X(abc9_carry) +X(abc9_cell) +X(abc9_deferred_box) +X(abc9_flop) +X(abc9_keep) +X(abc9_lut) +X(abc9_mergeability) +X(abc9_scc_id) +X(abc9_script) +X(abcgroup) +X(acc_fir) +X(acc_fir_i) +X(add_carry) +X(aiger2_zbuf) +X(allconst) +X(allseq) +X(always_comb) +X(always_ff) +X(always_latch) +X(anyconst) +X(anyseq) +X(architecture) +X(area) +X(b) +X(b_i) +X(blackbox) +X(bottom_bound) +X(bugpoint_keep) +X(c) +X(capacitance) +X(cells_not_processed) +X(chain) +X(clk) +X(clk2fflogic) +X(clkbuf_driver) +X(clkbuf_inhibit) +X(clkbuf_inv) +X(clkbuf_sink) +X(clock_i) +X(cxxrtl_blackbox) +X(cxxrtl_comb) +X(cxxrtl_edge) +X(cxxrtl_sync) +X(cxxrtl_template) +X(cxxrtl_width) +X(defaultvalue) +X(dff) +X(dffsre) +X(dft_tag) +X(dly_b) +X(dly_b_o) +X(dsp_t1_10x9x32) +X(dynports) +X(enum_base_type) +X(enum_type) +X(equiv_merged) +X(equiv_region) +X(extract_order) +X(f_mode) +X(feedback) +X(feedback_i) +X(first) +X(flags_ff) +X(flags_fi) +X(flags_if) +X(force_downto) +X(force_upto) +X(fsm_encoding) +X(fsm_export) +X(full_case) +X(gate) +X(gate_cost_equivalent) +X(gclk) +X(gentb_clock) +X(gentb_constant) +X(gentb_skip) +X(glift) +X(gold) +X(hdlname) +X(hierconn) +X(i) +X(ieee754Equal) +X(init) +X(initial_top) +X(interface_modport) +X(interface_type) +X(interfaces_replaced_in_module) +X(invertible_pin) +X(iopad_external_pin) +X(isFinite) +X(isInfinite) +X(isNaN) +X(isNegative) +X(isNormal) +X(isPositive) +X(isSubnormal) +X(isZero) +X(is_inferred) +X(is_interface) +X(is_signed) +X(it) +X(keep) +X(keep_hierarchy) +X(lessThan) +X(lessThanOrEqual) +X(lib_whitebox) +X(library) +X(load_acc) +X(load_acc_i) +X(localparam) +X(logic_block) +X(lram) +X(lut) +X(lut_keep) +X(maximize) +X(mem2reg) +X(minimize) +X(module) +X(module_not_derived) +X(nQ) +X(nRST) +X(nSET) +X(netlist) +X(no_ram) +X(no_rw_check) +X(noblackbox) +X(nogsr) +X(nolatches) +X(nomem2reg) +X(nomeminit) +X(nosync) +X(nowrshmsk) +X(o) +X(o_ff) +X(o_fi) +X(o_if) +X(offset) +X(onehot) +X(output_select) +X(output_select_i) +X(p_class) +X(parallel_case) +X(parameter) +X(promoted_if) +X(qNV) +X(raise_error) +X(ram_block) +X(ram_style) +X(ramstyle) +X(reg) +X(register_inputs) +X(register_inputs_i) +X(replaced_by_gclk) +X(reprocess_after) +X(reset) +X(reset_i) +X(rm) +X(rom_block) +X(rom_style) +X(romstyle) +X(round) +X(round_i) +X(rtlil) +X(sNV) +X(saturate_enable) +X(saturate_enable_i) +X(scopename) +X(sdffsre) +X(shift_right) +X(shift_right_i) +X(single_bit_vector) +X(smtlib2_comb_expr) +X(smtlib2_module) +X(smtlibEqual) +X(src) +X(sta_arrival) +X(submod) +X(subtract) +X(subtract_i) +X(symfpu) +X(symfpu_inv) +X(symfpu_post) +X(symfpu_pre) +X(syn_ramstyle) +X(syn_romstyle) +X(techmap_autopurge) +X(techmap_celltype) +X(techmap_chtype) +X(techmap_maccmap) +X(techmap_simplemap) +X(techmap_wrap) +X(test) +X(to_delete) +X(top) +X(top_bound) +X(trg_on_gclk) +X(trigger) +X(unique) +X(unsigned_a) +X(unsigned_a_i) +X(unsigned_b) +X(unsigned_b_i) +X(unsupported_sva) +X(use_dsp) +X(value) +X(via_celltype) +X(wand) +X(whitebox) +X(width) +X(wildcard_port_conns) +X(wiretype) +X(wor) +X(xprop_decoder) +X(y) +X(z) +X(z_o) diff --git a/chips/yosys/kernel/cost.cc b/chips/yosys/kernel/cost.cc new file mode 100644 index 0000000000000000000000000000000000000000..230afdeb1f2b59de0cd20ab1a06f6b9e99c7409c --- /dev/null +++ b/chips/yosys/kernel/cost.cc @@ -0,0 +1,215 @@ +#include "kernel/cost.h" +#include "kernel/macc.h" + +USING_YOSYS_NAMESPACE + +unsigned int CellCosts::get(RTLIL::Module *mod) +{ + if (mod_cost_cache_.count(mod->name)) + return mod_cost_cache_.at(mod->name); + + unsigned int module_cost = 1; + for (auto c : mod->cells()) { + unsigned int new_cost = module_cost + get(c); + module_cost = new_cost >= module_cost ? new_cost : INT_MAX; + } + + mod_cost_cache_[mod->name] = module_cost; + return module_cost; +} + +static unsigned int y_coef(RTLIL::IdString type) +{ + if ( + // equality + type.in(ID($bweqx), ID($nex), ID($eqx)) || + // basic logic + type.in(ID($and), ID($or), ID($xor), ID($xnor), ID($not)) || + // mux + type.in(ID($bwmux), ID($mux)) || + // others + type == ID($tribuf)) { + return 1; + } else if (type == ID($neg)) { + return 4; + } else if (type == ID($demux)) { + return 2; + } else if (type == ID($fa)) { + return 5; + } else if (type.in(ID($add), ID($sub), ID($alu))) { + // multi-bit adders + return 8; + } else if (type.in(ID($shl), ID($sshl))) { + // left shift + return 10; + } + return 0; +} + +static unsigned int max_inp_coef(RTLIL::IdString type) +{ + if ( + // binop reduce + type.in(ID($reduce_and), ID($reduce_or), ID($reduce_xor), ID($reduce_xnor), ID($reduce_bool)) || + // others + type.in(ID($logic_not), ID($pmux), ID($bmux))) { + return 1; + } else if ( + // equality + type.in(ID($eq), ID($ne)) || + // logic + type.in(ID($logic_and), ID($logic_or))) { + return 2; + } else if (type == ID($lcu)) { + return 5; + } else if (type.in(ID($lt), ID($le), ID($ge), ID($gt))) { + // comparison + return 7; + } + return 0; +} + +static unsigned int sum_coef(RTLIL::IdString type) +{ + if (type.in(ID($shr), ID($sshr))) { + // right shift + return 4; + } else if (type.in(ID($shift), ID($shiftx))) { + // shift + return 8; + } + return 0; +} + +static unsigned int is_div_mod(RTLIL::IdString type) +{ + return (type == ID($div) || type == ID($divfloor) || type == ID($mod) || type == ID($modfloor)); +} + +static bool is_free(RTLIL::IdString type) +{ + return ( + // tags + type.in(ID($overwrite_tag), ID($set_tag), ID($original_tag), ID($get_tag)) || + // formal + type.in(ID($check), ID($equiv), ID($initstate), ID($assert), ID($assume), ID($live), ID($cover), ID($fair)) || + type.in(ID($allseq), ID($allconst), ID($anyseq), ID($anyconst), ID($anyinit)) || + // utilities + type.in(ID($scopeinfo), ID($print)) || + // real but free + type.in(ID($concat), ID($slice), ID($pos)) || + // specify + type.in(ID($specrule), ID($specify2), ID($specify3))); +} + +unsigned int max_inp_width(RTLIL::Cell *cell) +{ + unsigned int max = 0; + RTLIL::IdString input_width_params[] = { + ID::WIDTH, + ID::A_WIDTH, + ID::B_WIDTH, + ID::S_WIDTH, + }; + + if (cell->type == ID($bmux)) + return cell->getParam(ID::WIDTH).as_int() << cell->getParam(ID::S_WIDTH).as_int(); + + for (RTLIL::IdString param : input_width_params) + if (cell->hasParam(param)) + max = std::max(max, (unsigned int)cell->getParam(param).as_int()); + return max; +} + +unsigned int port_width_sum(RTLIL::Cell *cell) +{ + unsigned int sum = 0; + RTLIL::IdString port_width_params[] = { + ID::WIDTH, ID::A_WIDTH, ID::B_WIDTH, ID::S_WIDTH, ID::Y_WIDTH, + }; + + for (auto param : port_width_params) + if (cell->hasParam(param)) + sum += cell->getParam(param).as_int(); + + return sum; +} + +unsigned int CellCosts::get(RTLIL::Cell *cell) +{ + + // simple 1-bit cells + if (cmos_gate_cost().count(cell->type)) + return 1; + + if (design_ && design_->module(cell->type) && cell->parameters.empty()) { + log_debug("%s is a module, recurse\n", cell->name); + return get(design_->module(cell->type)); + } else if (cell->is_builtin_ff()) { + log_assert(cell->hasPort(ID::Q) && "Weird flip flop"); + log_debug("%s is ff\n", cell->name); + return cell->getParam(ID::WIDTH).as_int(); + } else if (cell->type.in(ID($mem), ID($mem_v2))) { + log_debug("%s is mem\n", cell->name); + return cell->getParam(ID::WIDTH).as_int() * cell->getParam(ID::SIZE).as_int(); + } else if (y_coef(cell->type)) { + // linear with Y_WIDTH or WIDTH + log_assert((cell->hasParam(ID::Y_WIDTH) || cell->hasParam(ID::WIDTH)) && "Unknown width"); + auto param = cell->hasParam(ID::Y_WIDTH) ? ID::Y_WIDTH : ID::WIDTH; + int width = cell->getParam(param).as_int(); + if (cell->type == ID($demux)) + width <<= cell->getParam(ID::S_WIDTH).as_int(); + log_debug("%s Y*coef %d * %d\n", cell->name, width, y_coef(cell->type)); + return width * y_coef(cell->type); + } else if (sum_coef(cell->type)) { + // linear with sum of port widths + unsigned int sum = port_width_sum(cell); + log_debug("%s sum*coef %d * %d\n", cell->name, sum, sum_coef(cell->type)); + return sum * sum_coef(cell->type); + } else if (max_inp_coef(cell->type)) { + // linear with largest input width + unsigned int max = max_inp_width(cell); + log_debug("%s max*coef %d * %d\n", cell->name, max, max_inp_coef(cell->type)); + return max * max_inp_coef(cell->type); + } else if (is_div_mod(cell->type) || cell->type == ID($mul)) { + // quadratic with sum of port widths + unsigned int sum = port_width_sum(cell); + unsigned int coef = cell->type == ID($mul) ? 3 : 5; + log_debug("%s coef*(sum**2) %d * %d\n", cell->name, coef, sum * sum); + return coef * sum * sum; + } else if (cell->type.in(ID($macc), ID($macc_v2))) { + // quadratic per term + unsigned int cost_sum = 0; + Macc macc; + macc.from_cell(cell); + unsigned int y_width = cell->getParam(ID::Y_WIDTH).as_int(); + for (auto &term: macc.terms) { + if (term.in_b.empty()) { + // neglect addends + continue; + } + unsigned a_width = term.in_a.size(), b_width = term.in_b.size(); + unsigned int sum = a_width + b_width + std::min(y_width, a_width + b_width); + cost_sum += 3 * sum * sum; + } + return cost_sum; + } else if (cell->type == ID($lut)) { + int width = cell->getParam(ID::WIDTH).as_int(); + unsigned int cost = 1U << (unsigned int)width; + log_debug("%s is 2**%d\n", cell->name, width); + return cost; + } else if (cell->type == ID($sop)) { + int width = cell->getParam(ID::WIDTH).as_int(); + int depth = cell->getParam(ID::DEPTH).as_int(); + log_debug("%s is (2*%d + 1)*%d\n", cell->name, width, depth); + return (2 * width + 1) * depth; + } else if (is_free(cell->type)) { + log_debug("%s is free\n", cell->name); + return 0; + } + // TODO: $fsm + // ignored: $pow $memrd $memwr $meminit (and v2 counterparts) + + log_warning("Can't determine cost of %s cell (%d parameters).\n", cell->type.unescape(), GetSize(cell->parameters)); + return 1; +} diff --git a/chips/yosys/kernel/cost.h b/chips/yosys/kernel/cost.h new file mode 100644 index 0000000000000000000000000000000000000000..15d74d7b30ecab86c0c1fb9684cd33040083e42f --- /dev/null +++ b/chips/yosys/kernel/cost.h @@ -0,0 +1,99 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#ifndef COST_H +#define COST_H + +#include "kernel/yosys.h" + +YOSYS_NAMESPACE_BEGIN + +struct CellCosts +{ + + private: + dict mod_cost_cache_; + Design *design_ = nullptr; + + public: + CellCosts(RTLIL::Design *design) : design_(design) { } + + static const dict& default_gate_cost() { + // Default size heuristics for several common PDK standard cells + // used by abc and stat + static const dict db = { + { ID($_BUF_), 1 }, + { ID($_NOT_), 2 }, + { ID($_AND_), 4 }, + { ID($_NAND_), 4 }, + { ID($_OR_), 4 }, + { ID($_NOR_), 4 }, + { ID($_ANDNOT_), 4 }, + { ID($_ORNOT_), 4 }, + { ID($_XOR_), 5 }, + { ID($_XNOR_), 5 }, + { ID($_AOI3_), 6 }, + { ID($_OAI3_), 6 }, + { ID($_AOI4_), 7 }, + { ID($_OAI4_), 7 }, + { ID($_MUX_), 4 }, + { ID($_NMUX_), 4 }, + }; + return db; + } + + static const dict& cmos_gate_cost() { + // Estimated CMOS transistor counts for several common PDK standard cells + // used by stat and optionally by abc + static const dict db = { + { ID($_BUF_), 1 }, + { ID($_NOT_), 2 }, + { ID($_AND_), 6 }, + { ID($_NAND_), 4 }, + { ID($_OR_), 6 }, + { ID($_NOR_), 4 }, + { ID($_ANDNOT_), 6 }, + { ID($_ORNOT_), 6 }, + { ID($_XOR_), 12 }, + { ID($_XNOR_), 12 }, + { ID($_AOI3_), 6 }, + { ID($_OAI3_), 6 }, + { ID($_AOI4_), 8 }, + { ID($_OAI4_), 8 }, + { ID($_MUX_), 12 }, + { ID($_NMUX_), 10 }, + { ID($_DFF_P_), 16 }, + { ID($_DFF_N_), 16 }, + }; + return db; + } + + // Get the cell cost for a cell based on its parameters. + // This cost is an *approximate* upper bound for the number of gates that + // the cell will get mapped to with "opt -fast; techmap" + // The intended usage is for flattening heuristics and similar situations + unsigned int get(RTLIL::Cell *cell); + // Sum up the cell costs of all cells in the module + // and all its submodules recursively + unsigned int get(RTLIL::Module *mod); +}; + +YOSYS_NAMESPACE_END + +#endif diff --git a/chips/yosys/kernel/driver.cc b/chips/yosys/kernel/driver.cc new file mode 100644 index 0000000000000000000000000000000000000000..48b5ff185378ed29ba827d5092562e36be005484 --- /dev/null +++ b/chips/yosys/kernel/driver.cc @@ -0,0 +1,835 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "kernel/yosys.h" +#include "kernel/hashlib.h" +#define CXXOPTS_VECTOR_DELIMITER '\0' +#include "libs/cxxopts/include/cxxopts.hpp" +#include +#include + +#ifdef YOSYS_ENABLE_READLINE +# include +# include +#endif + +#ifdef YOSYS_ENABLE_EDITLINE +# include +#endif + +#ifdef YOSYS_ENABLE_TCL +# include +#endif + +#ifdef YOSYS_ENABLE_PYTHON +# include +# include +namespace py = pybind11; +#endif + +#include +#include +#include +#include +#include +#ifndef __STDC_FORMAT_MACROS +# define __STDC_FORMAT_MACROS +#endif +#include + +#if defined (__linux__) || defined(__FreeBSD__) +# include +# include +# include +#endif + +#ifdef __FreeBSD__ +# include +# include +#endif + +#if !defined(_WIN32) || defined(__MINGW32__) +# include +#endif + +#include +#include + +USING_YOSYS_NAMESPACE + +#if defined(YOSYS_ENABLE_READLINE) || defined(YOSYS_ENABLE_EDITLINE) +int yosys_history_offset = 0; +std::string yosys_history_file; +#endif + +void yosys_atexit() +{ +#if defined(YOSYS_ENABLE_READLINE) || defined(YOSYS_ENABLE_EDITLINE) + if (!yosys_history_file.empty()) { +#if defined(YOSYS_ENABLE_READLINE) + if (yosys_history_offset > 0) { + history_truncate_file(yosys_history_file.c_str(), 100); + append_history(where_history() - yosys_history_offset, yosys_history_file.c_str()); + } else + write_history(yosys_history_file.c_str()); +#else + write_history(yosys_history_file.c_str()); +#endif + } + + clear_history(); +#if defined(YOSYS_ENABLE_READLINE) + HIST_ENTRY **hist_list = history_list(); + if (hist_list != NULL) + free(hist_list); +#endif +#endif +} + +#if defined(__OpenBSD__) +namespace Yosys { +extern char *yosys_argv0; +extern char yosys_path[PATH_MAX]; +}; +#endif +#ifdef YOSYS_ENABLE_TCL +namespace Yosys { + extern int yosys_tcl_interp_init(Tcl_Interp *interp); + extern void yosys_tcl_activate_repl(); +}; +#endif + +namespace Yosys { + extern bool log_stderr_sink_forced; +}; + +class ColorConsoleLogSink : public LogSink +{ +public: + explicit ColorConsoleLogSink(bool err, bool quiet) : error_output(err), quiet_warnings(quiet) {} + void log(const LogMessage &msg) override; + bool should_log(const LogMessage &msg) const override; + void flush() override; + FILE *file_handle() override { return error_output ? nullptr : stdout; } +private: + bool error_output; + bool quiet_warnings; +}; + +bool no_color = false; + +bool is_colored(FILE *file) +{ + if (no_color) + return false; + +#if defined(_WIN32) + HANDLE handle = reinterpret_cast(_get_osfhandle(_fileno(file))); + DWORD mode; + return handle != INVALID_HANDLE_VALUE && + GetConsoleMode(handle, &mode); +#else + return isatty(fileno(file)); +#endif +} + +void ColorConsoleLogSink::flush() +{ + fflush(stdout); + fflush(stderr); +} + +bool next_print_log = true; + +void ColorConsoleLogSink::log(const LogMessage &msg) +{ + FILE *f = (error_output || msg.severity == LogSeverity::Error) ? stderr : stdout; + + if (logger().get_log_time() && next_print_log) { + std::string time_str = stringf("[%05d.%06d] ", int(msg.timestamp_us / 1'000'000), int(msg.timestamp_us % 1'000'000)); + fmt::print(f, fg(fmt::terminal_color::blue), "{}", time_str); + next_print_log = false; + } + + if (!msg.src.filename.empty()) + fmt::print(f, fg(fmt::terminal_color::bright_cyan), "{}:{}: ", msg.src.filename, msg.src.start_line); + + switch (msg.severity) { + case LogSeverity::Warning: + fmt::print(f, fg(fmt::terminal_color::bright_yellow), "{}", msg.prefix); + fmt::print(f, fg(fmt::terminal_color::blue) | fmt::emphasis::bold, "{}", msg.message); + break; + + case LogSeverity::Error: + case LogSeverity::NonFatalError: + fmt::print(f, fg(fmt::terminal_color::bright_red), "{}", msg.prefix); + fmt::print(f, fg(fmt::terminal_color::blue) | fmt::emphasis::bold, "{}", msg.message); + break; + + case LogSeverity::Header: + fmt::print(f, fg(fmt::terminal_color::cyan) | fmt::emphasis::bold, "{}", msg.prefix); + fmt::print(f, fg(fmt::terminal_color::white) | fmt::emphasis::bold, "{}", msg.message); + break; + + case LogSeverity::Highlight: + fmt::print(f, fg(fmt::terminal_color::cyan) | fmt::emphasis::bold, "{}{}", msg.prefix, msg.message); + break; + + case LogSeverity::Comment: + case LogSeverity::Debug: + fmt::print(f, fg(fmt::terminal_color::bright_black), "{}{}", msg.prefix, msg.message); + break; + + case LogSeverity::Info: + default: + if (!msg.prefix.empty()) + fmt::print(f, fg(fmt::terminal_color::bright_black), "{}", msg.prefix); + fmt::print(f, "{}", msg.message); + break; + } + if (!msg.message.empty()) + next_print_log = msg.message.back() == '\n'; +} + +bool ColorConsoleLogSink::should_log(const LogMessage &msg) const +{ + return (!error_output) || (msg.severity == LogSeverity::Error || msg.severity == LogSeverity::NonFatalError || + (msg.severity == LogSeverity::Warning && !quiet_warnings) || + log_stderr_sink_forced); +} + +#ifdef _WIN32 +int wmain(int argc, wchar_t **wargv) +{ + // Configure ASCII functions like fopen() to use UTF-8 filenames. + // See https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/setlocale-wsetlocale?view=msvc-170#utf-8-support +#ifdef _UCRT + setlocale(LC_ALL, ".UTF-8"); +#endif + // Configure the Win32 console to use UTF-8. + SetConsoleCP(CP_UTF8); + SetConsoleOutputCP(CP_UTF8); + + std::vector uargs; + for (int i = 0; i < argc; i++) { + int usize = WideCharToMultiByte(CP_UTF8, 0, wargv[i], -1, NULL, 0, NULL, NULL); + char *uarg = (char *)malloc(usize); + WideCharToMultiByte(CP_UTF8, 0, wargv[i], -1, uarg, usize, NULL, NULL); + uargs.push_back(uarg); + } + uargs.push_back(NULL); + char **argv = uargs.data(); +#else +int main(int argc, char **argv) +{ +#endif + auto wall_clock_start = std::chrono::steady_clock::now(); + std::string frontend_command = "auto"; + std::string backend_command = "auto"; + std::vector vlog_defines; + std::vector passes_commands; + std::vector frontend_files; + std::vector plugin_filenames; + std::vector special_args; + std::string output_filename = ""; + std::string scriptfile = ""; + std::string depsfile = ""; + std::string topmodule = ""; + std::string perffile = ""; + bool scriptfile_tcl = false; + bool scriptfile_python = false; + bool print_banner = true; + bool print_stats = true; + bool call_abort = false; + bool timing_details = false; + bool run_shell = true; + bool run_tcl_shell = false; + bool mode_v = false; + bool mode_q = false; + bool quiet_warnings = false; + bool log_stderr = false; + no_color = std::getenv("NO_COLOR") != nullptr; + + cxxopts::Options options(argv[0], "Yosys Open SYnthesis Suite"); + options.set_width(SIZE_MAX); + + options.add_options("operation") + ("b,backend", "use for the output file specified on the command line", + cxxopts::value(), "") + ("f,frontend", "use for the input files on the command line", + cxxopts::value(), "") + ("s,scriptfile", "execute the commands in ", + cxxopts::value(), "") +#ifdef YOSYS_ENABLE_TCL + ("c,tcl-scriptfile", "execute the commands in the TCL (see 'help tcl' for details)", + cxxopts::value(),"") + ("C,tcl-interactive", "enters TCL interactive shell mode") +#endif // YOSYS_ENABLE_TCL +#ifdef YOSYS_ENABLE_PYTHON + ("y,py-scriptfile", "execute the Python