3
0
Fork 0
mirror of https://github.com/YosysHQ/yosys synced 2026-05-19 08:29:38 +00:00

Merge commit 'ab316c14d2' into abc-liberty-args

This commit is contained in:
Tianji Liu 2026-05-07 18:12:49 +08:00
commit f8a50e7174
371 changed files with 15324 additions and 3587 deletions

View file

@ -20,7 +20,7 @@
#include "kernel/yosys.h"
#include "kernel/sigtools.h"
#include "kernel/celledges.h"
#include "kernel/celltypes.h"
#include "kernel/newcelltypes.h"
#include "kernel/utils.h"
#include "kernel/log_help.h"

View file

@ -1,5 +1,6 @@
#include "kernel/yosys.h"
#include "kernel/celltypes.h"
#include "kernel/newcelltypes.h"
#include "kernel/ff.h"
USING_YOSYS_NAMESPACE
@ -123,7 +124,7 @@ struct LibertyStubber {
return;
}
if (RTLIL::builtin_ff_cell_types().count(base_name))
if (StaticCellTypes::categories.is_ff(base_name))
return liberty_flop(base, derived, f);
auto& base_type = ct.cell_types[base_name];

View file

@ -18,7 +18,7 @@
*/
#include "kernel/yosys.h"
#include "kernel/celltypes.h"
#include "kernel/newcelltypes.h"
#include "kernel/sigtools.h"
#include "kernel/log_help.h"
@ -488,7 +488,7 @@ static int parse_comma_list(std::set<RTLIL::IdString> &tokens, const std::string
}
}
static int select_op_expand(RTLIL::Design *design, RTLIL::Selection &lhs, std::vector<expand_rule_t> &rules, std::set<RTLIL::IdString> &limits, int max_objects, char mode, CellTypes &ct, bool eval_only)
static int select_op_expand(RTLIL::Design *design, RTLIL::Selection &lhs, std::vector<expand_rule_t> &rules, std::set<RTLIL::IdString> &limits, int max_objects, char mode, NewCellTypes &ct, bool eval_only)
{
int sel_objects = 0;
bool is_input, is_output;
@ -564,7 +564,7 @@ static void select_op_expand(RTLIL::Design *design, const std::string &arg, char
std::vector<expand_rule_t> rules;
std::set<RTLIL::IdString> limits;
CellTypes ct;
NewCellTypes ct;
if (mode != 'x')
ct.setup(design);

View file

@ -310,6 +310,8 @@ struct SetundefPass : public Pass {
RTLIL::SigSpec sig = undriven_signals.export_all();
for (auto &c : sig.chunks()) {
if (!design->selected(module, c.wire))
continue;
RTLIL::Wire * wire;
if (c.wire->width == c.width) {
wire = c.wire;
@ -328,12 +330,12 @@ struct SetundefPass : public Pass {
SigMap sigmap(module);
SigPool undriven_signals;
for (auto &it : module->wires_)
undriven_signals.add(sigmap(it.second));
for (auto wire : module->selected_wires())
undriven_signals.add(sigmap(wire));
for (auto &it : module->wires_)
if (it.second->port_input)
undriven_signals.del(sigmap(it.second));
for (auto wire : module->selected_wires())
if (wire->port_input)
undriven_signals.del(sigmap(wire));
CellTypes ct(design);
for (auto &it : module->cells_)
@ -367,6 +369,14 @@ struct SetundefPass : public Pass {
if (!cell->is_builtin_ff())
continue;
bool cell_selected = design->selected(module, cell);
bool wire_selected = false;
for (auto bit : sigmap(cell->getPort(ID::Q)))
if (bit.wire && design->selected(module, bit.wire))
wire_selected = true;
if (!cell_selected && !wire_selected)
continue;
for (auto bit : sigmap(cell->getPort(ID::Q)))
ffbits.insert(bit);
}
@ -502,14 +512,21 @@ struct SetundefPass : public Pass {
}
}
for (auto &it : module->cells_)
if (!it.second->get_bool_attribute(ID::xprop_decoder))
it.second->rewrite_sigspecs(worker);
for (auto &it : module->processes)
it.second->rewrite_sigspecs(worker);
for (auto cell : module->selected_cells())
if (!cell->get_bool_attribute(ID::xprop_decoder))
cell->rewrite_sigspecs(worker);
for (auto proc : module->selected_processes())
proc->rewrite_sigspecs(worker);
for (auto &it : module->connections_) {
worker(it.first);
worker(it.second);
SigSpec lhs = it.first;
bool selected = false;
for (auto &chunk : lhs.chunks())
if (chunk.wire && module->design->selected(module, chunk.wire))
selected = true;
if (selected) {
worker(it.first);
worker(it.second);
}
}
if (worker.next_bit_mode == MODE_ANYSEQ || worker.next_bit_mode == MODE_ANYCONST)

View file

@ -561,7 +561,7 @@ struct statdata_t {
}
}
if (tech == "xilinx") {
if (tech == "xilinx" || tech == "analogdevices") {
log("\n");
log(" Estimated number of LCs: %10u\n", estimate_xilinx_lc());
}
@ -628,7 +628,7 @@ struct statdata_t {
first_line = false;
}
log("\n }\n");
if (tech == "xilinx") {
if (tech == "xilinx" || tech == "analogdevices") {
log(" \"estimated_num_lc\": %u,\n", estimate_xilinx_lc());
}
if (tech == "cmos") {
@ -710,7 +710,7 @@ struct statdata_t {
log("\n");
log(" }");
}
if (tech == "xilinx") {
if (tech == "xilinx" || tech == "analogdevices") {
log(",\n");
log(" \"estimated_num_lc\": %u", estimate_xilinx_lc());
}
@ -908,7 +908,7 @@ struct StatPass : public Pass {
log("\n");
log(" -tech <technology>\n");
log(" print area estimate for the specified technology. Currently supported\n");
log(" values for <technology>: xilinx, cmos\n");
log(" values for <technology>: xilinx, analogdevices, cmos\n");
log("\n");
log(" -width\n");
log(" annotate internal cell types with their word width.\n");
@ -968,7 +968,7 @@ struct StatPass : public Pass {
if (!json_mode)
log_header(design, "Printing statistics.\n");
if (techname != "" && techname != "xilinx" && techname != "cmos" && !json_mode)
if (techname != "" && techname != "xilinx" && techname != "analogdevices" && techname != "cmos" && !json_mode)
log_cmd_error("Unsupported technology: '%s'\n", techname);
if (json_mode) {

View file

@ -18,7 +18,7 @@
*/
#include "kernel/yosys.h"
#include "kernel/celltypes.h"
#include "kernel/newcelltypes.h"
#include "kernel/sigtools.h"
#include "kernel/utils.h"
#include "kernel/log_help.h"

View file

@ -463,6 +463,10 @@ struct XpropWorker
return;
}
if (cell->type.in(ID($scopeinfo))) {
return;
}
log_warning("Unhandled cell %s (%s) during maybe-x marking\n", log_id(cell), log_id(cell->type));
mark_outputs_maybe_x(cell);
}

View file

@ -5,6 +5,7 @@
#include "kernel/yosys_common.h"
#include "kernel/sigtools.h"
#include "kernel/satgen.h"
#include "kernel/newcelltypes.h"
YOSYS_NAMESPACE_BEGIN

View file

@ -174,7 +174,7 @@ struct EquivInductPass : public Pass {
log("Only selected $equiv cells are proven and only selected cells are used to\n");
log("perform the proof.\n");
log("\n");
EquivBasicConfig::help("4");
log("%s", EquivBasicConfig::help("4"));
log("\n");
log("This command is very effective in proving complex sequential circuits, when\n");
log("the internal state of the circuit quickly propagates to $equiv cells.\n");

View file

@ -428,7 +428,7 @@ struct EquivSimplePass : public Pass {
log("\n");
log("This command tries to prove $equiv cells using a simple direct SAT approach.\n");
log("\n");
EquivSimpleConfig::help("1");
log("%s", EquivSimpleConfig::help("1"));
log("\n");
}
void execute(std::vector<std::string> args, Design *design) override

View file

@ -9,7 +9,6 @@ OBJS += passes/opt/opt_muxtree.o
OBJS += passes/opt/opt_reduce.o
OBJS += passes/opt/opt_dff.o
OBJS += passes/opt/opt_share.o
OBJS += passes/opt/opt_clean.o
OBJS += passes/opt/opt_expr.o
OBJS += passes/opt/opt_hier.o
@ -40,3 +39,5 @@ PEEPOPT_PATTERN += passes/opt/peepopt_formal_clockgateff.pmg
passes/opt/peepopt_pm.h: passes/pmgen/pmgen.py $(PEEPOPT_PATTERN)
$(P) mkdir -p $(dir $@) && $(PYTHON_EXECUTABLE) $< -o $@ -p peepopt $(filter-out $<,$^)
endif
include $(YOSYS_SRC)/passes/opt/opt_clean/Makefile.inc

View file

@ -38,6 +38,9 @@ struct ExclusiveDatabase
pool<Cell*> reduce_or;
for (auto cell : module->cells()) {
if (cell->type == ID($eq)) {
SigSpec y_sig = sigmap(cell->getPort(ID::Y));
if (GetSize(y_sig) == 0)
continue;
nonconst_sig = sigmap(cell->getPort(ID::A));
const_sig = sigmap(cell->getPort(ID::B));
if (!const_sig.is_fully_const()) {
@ -45,12 +48,15 @@ struct ExclusiveDatabase
continue;
std::swap(nonconst_sig, const_sig);
}
y_port = sigmap(cell->getPort(ID::Y));
y_port = y_sig[0];
}
else if (cell->type == ID($logic_not)) {
SigSpec y_sig = sigmap(cell->getPort(ID::Y));
if (GetSize(y_sig) == 0)
continue;
nonconst_sig = sigmap(cell->getPort(ID::A));
const_sig = Const(State::S0, GetSize(nonconst_sig));
y_port = sigmap(cell->getPort(ID::Y));
y_port = y_sig[0];
}
else if (cell->type == ID($reduce_or)) {
reduce_or.insert(cell);
@ -84,7 +90,10 @@ struct ExclusiveDatabase
}
if (nonconst_sig.empty())
continue;
y_port = sigmap(cell->getPort(ID::Y));
SigSpec y_sig = sigmap(cell->getPort(ID::Y));
if (GetSize(y_sig) == 0)
continue;
y_port = y_sig[0];
sig_cmp_prev[y_port] = std::make_pair(nonconst_sig,std::move(values));
}
}

View file

@ -1,793 +0,0 @@
/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
*
* 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/register.h"
#include "kernel/sigtools.h"
#include "kernel/log.h"
#include "kernel/celltypes.h"
#include "kernel/ffinit.h"
#include <stdlib.h>
#include <stdio.h>
#include <set>
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
using RTLIL::id2cstr;
struct keep_cache_t
{
Design *design;
dict<Module*, bool> cache;
bool purge_mode = false;
void reset(Design *design = nullptr, bool purge_mode = false)
{
this->design = design;
this->purge_mode = purge_mode;
cache.clear();
}
bool query(Module *module)
{
log_assert(design != nullptr);
if (module == nullptr)
return false;
if (cache.count(module))
return cache.at(module);
cache[module] = true;
if (!module->get_bool_attribute(ID::keep)) {
bool found_keep = false;
for (auto cell : module->cells())
if (query(cell, true /* ignore_specify */)) {
found_keep = true;
break;
}
for (auto wire : module->wires())
if (wire->get_bool_attribute(ID::keep)) {
found_keep = true;
break;
}
cache[module] = found_keep;
}
return cache[module];
}
bool query(Cell *cell, bool ignore_specify = false)
{
if (cell->type.in(ID($assert), ID($assume), ID($live), ID($fair), ID($cover)))
return true;
if (cell->type.in(ID($overwrite_tag)))
return true;
if (!ignore_specify && cell->type.in(ID($specify2), ID($specify3), ID($specrule)))
return true;
if (cell->type == ID($print) || cell->type == ID($check))
return true;
if (cell->has_keep_attr())
return true;
if (!purge_mode && cell->type == ID($scopeinfo))
return true;
if (cell->module && cell->module->design)
return query(cell->module->design->module(cell->type));
return false;
}
};
keep_cache_t keep_cache;
CellTypes ct_reg, ct_all;
int count_rm_cells, count_rm_wires;
void rmunused_module_cells(Module *module, bool verbose)
{
SigMap sigmap(module);
dict<IdString, pool<Cell*>> mem2cells;
pool<IdString> mem_unused;
pool<Cell*> queue, unused;
pool<SigBit> used_raw_bits;
dict<SigBit, pool<Cell*>> wire2driver;
dict<SigBit, vector<string>> driver_driver_logs;
FfInitVals ffinit(&sigmap, module);
SigMap raw_sigmap;
for (auto &it : module->connections_) {
for (int i = 0; i < GetSize(it.second); i++) {
if (it.second[i].wire != nullptr)
raw_sigmap.add(it.first[i], it.second[i]);
}
}
for (auto &it : module->memories) {
mem_unused.insert(it.first);
}
for (Cell *cell : module->cells()) {
if (cell->type.in(ID($memwr), ID($memwr_v2), ID($meminit), ID($meminit_v2))) {
IdString mem_id = cell->getParam(ID::MEMID).decode_string();
mem2cells[mem_id].insert(cell);
}
}
for (auto &it : module->cells_) {
Cell *cell = it.second;
for (auto &it2 : cell->connections()) {
if (ct_all.cell_known(cell->type) && !ct_all.cell_output(cell->type, it2.first))
continue;
for (auto raw_bit : it2.second) {
if (raw_bit.wire == nullptr)
continue;
auto bit = sigmap(raw_bit);
if (bit.wire == nullptr && ct_all.cell_known(cell->type))
driver_driver_logs[raw_sigmap(raw_bit)].push_back(stringf("Driver-driver conflict "
"for %s between cell %s.%s and constant %s in %s: Resolved using constant.",
log_signal(raw_bit), log_id(cell), log_id(it2.first), log_signal(bit), log_id(module)));
if (bit.wire != nullptr)
wire2driver[bit].insert(cell);
}
}
if (keep_cache.query(cell))
queue.insert(cell);
else
unused.insert(cell);
}
for (auto &it : module->wires_) {
Wire *wire = it.second;
if (wire->port_output || wire->get_bool_attribute(ID::keep)) {
for (auto bit : sigmap(wire))
for (auto c : wire2driver[bit])
queue.insert(c), unused.erase(c);
for (auto raw_bit : SigSpec(wire))
used_raw_bits.insert(raw_sigmap(raw_bit));
}
}
while (!queue.empty())
{
pool<SigBit> bits;
pool<IdString> mems;
for (auto cell : queue) {
for (auto &it : cell->connections())
if (!ct_all.cell_known(cell->type) || ct_all.cell_input(cell->type, it.first))
for (auto bit : sigmap(it.second))
bits.insert(bit);
if (cell->type.in(ID($memrd), ID($memrd_v2))) {
IdString mem_id = cell->getParam(ID::MEMID).decode_string();
if (mem_unused.count(mem_id)) {
mem_unused.erase(mem_id);
mems.insert(mem_id);
}
}
}
queue.clear();
for (auto bit : bits)
for (auto c : wire2driver[bit])
if (unused.count(c))
queue.insert(c), unused.erase(c);
for (auto mem : mems)
for (auto c : mem2cells[mem])
if (unused.count(c))
queue.insert(c), unused.erase(c);
}
unused.sort(RTLIL::sort_by_name_id<RTLIL::Cell>());
for (auto cell : unused) {
if (verbose)
log_debug(" removing unused `%s' cell `%s'.\n", cell->type, cell->name);
module->design->scratchpad_set_bool("opt.did_something", true);
if (cell->is_builtin_ff())
ffinit.remove_init(cell->getPort(ID::Q));
module->remove(cell);
count_rm_cells++;
}
for (auto it : mem_unused)
{
if (verbose)
log_debug(" removing unused memory `%s'.\n", it);
delete module->memories.at(it);
module->memories.erase(it);
}
for (auto &it : module->cells_) {
Cell *cell = it.second;
for (auto &it2 : cell->connections()) {
if (ct_all.cell_known(cell->type) && !ct_all.cell_input(cell->type, it2.first))
continue;
for (auto raw_bit : raw_sigmap(it2.second))
used_raw_bits.insert(raw_bit);
}
}
for (auto it : driver_driver_logs) {
if (used_raw_bits.count(it.first))
for (auto msg : it.second)
log_warning("%s\n", msg);
}
}
int count_nontrivial_wire_attrs(RTLIL::Wire *w)
{
int count = w->attributes.size();
count -= w->attributes.count(ID::src);
count -= w->attributes.count(ID::hdlname);
count -= w->attributes.count(ID(scopename));
count -= w->attributes.count(ID::unused_bits);
return count;
}
// Should we pick `s2` over `s1` to represent a signal?
bool compare_signals(RTLIL::SigBit &s1, RTLIL::SigBit &s2, SigPool &regs, SigPool &conns, pool<RTLIL::Wire*> &direct_wires)
{
RTLIL::Wire *w1 = s1.wire;
RTLIL::Wire *w2 = s2.wire;
if (w1 == NULL || w2 == NULL)
return w2 == NULL;
if (w1->port_input != w2->port_input)
return w2->port_input;
if ((w1->port_input && w1->port_output) != (w2->port_input && w2->port_output))
return !(w2->port_input && w2->port_output);
if (w1->name.isPublic() && w2->name.isPublic()) {
if (regs.check(s1) != regs.check(s2))
return regs.check(s2);
if (direct_wires.count(w1) != direct_wires.count(w2))
return direct_wires.count(w2) != 0;
if (conns.check_any(s1) != conns.check_any(s2))
return conns.check_any(s2);
}
if (w1 == w2)
return s2.offset < s1.offset;
if (w1->port_output != w2->port_output)
return w2->port_output;
if (w1->name[0] != w2->name[0])
return w2->name.isPublic();
int attrs1 = count_nontrivial_wire_attrs(w1);
int attrs2 = count_nontrivial_wire_attrs(w2);
if (attrs1 != attrs2)
return attrs2 > attrs1;
return w2->name.lt_by_name(w1->name);
}
bool check_public_name(RTLIL::IdString id)
{
if (id.begins_with("$"))
return false;
const std::string &id_str = id.str();
if (id.begins_with("\\_") && (id.ends_with("_") || id_str.find("_[") != std::string::npos))
return false;
if (id_str.find(".$") != std::string::npos)
return false;
return true;
}
bool rmunused_module_signals(RTLIL::Module *module, bool purge_mode, bool verbose)
{
// `register_signals` and `connected_signals` will help us decide later on
// on picking representatives out of groups of connected signals
SigPool register_signals;
SigPool connected_signals;
if (!purge_mode)
for (auto &it : module->cells_) {
RTLIL::Cell *cell = it.second;
if (ct_reg.cell_known(cell->type)) {
bool clk2fflogic = cell->get_bool_attribute(ID(clk2fflogic));
for (auto &it2 : cell->connections())
if (clk2fflogic ? it2.first == ID::D : ct_reg.cell_output(cell->type, it2.first))
register_signals.add(it2.second);
}
for (auto &it2 : cell->connections())
connected_signals.add(it2.second);
}
SigMap assign_map(module);
// construct a pool of wires which are directly driven by a known celltype,
// this will influence our choice of representatives
pool<RTLIL::Wire*> direct_wires;
{
pool<RTLIL::SigSpec> direct_sigs;
for (auto &it : module->cells_) {
RTLIL::Cell *cell = it.second;
if (ct_all.cell_known(cell->type))
for (auto &it2 : cell->connections())
if (ct_all.cell_output(cell->type, it2.first))
direct_sigs.insert(assign_map(it2.second));
}
for (auto &it : module->wires_) {
if (direct_sigs.count(assign_map(it.second)) || it.second->port_input)
direct_wires.insert(it.second);
}
}
// weight all options for representatives with `compare_signals`,
// the one that wins will be what `assign_map` maps to
for (auto &it : module->wires_) {
RTLIL::Wire *wire = it.second;
for (int i = 0; i < wire->width; i++) {
RTLIL::SigBit s1 = RTLIL::SigBit(wire, i), s2 = assign_map(s1);
if (compare_signals(s2, s1, register_signals, connected_signals, direct_wires))
assign_map.add(s1);
}
}
// we are removing all connections
module->connections_.clear();
// used signals sigmapped
SigPool used_signals;
// used signals pre-sigmapped
SigPool raw_used_signals;
// used signals sigmapped, ignoring drivers (we keep track of this to set `unused_bits`)
SigPool used_signals_nodrivers;
// gather the usage information for cells
for (auto &it : module->cells_) {
RTLIL::Cell *cell = it.second;
for (auto &it2 : cell->connections_) {
assign_map.apply(it2.second); // modify the cell connection in place
raw_used_signals.add(it2.second);
used_signals.add(it2.second);
if (!ct_all.cell_output(cell->type, it2.first))
used_signals_nodrivers.add(it2.second);
}
}
// gather the usage information for ports, wires with `keep`,
// also gather init bits
dict<RTLIL::SigBit, RTLIL::State> init_bits;
for (auto &it : module->wires_) {
RTLIL::Wire *wire = it.second;
if (wire->port_id > 0) {
RTLIL::SigSpec sig = RTLIL::SigSpec(wire);
raw_used_signals.add(sig);
assign_map.apply(sig);
used_signals.add(sig);
if (!wire->port_input)
used_signals_nodrivers.add(sig);
}
if (wire->get_bool_attribute(ID::keep)) {
RTLIL::SigSpec sig = RTLIL::SigSpec(wire);
assign_map.apply(sig);
used_signals.add(sig);
}
auto it2 = wire->attributes.find(ID::init);
if (it2 != wire->attributes.end()) {
RTLIL::Const &val = it2->second;
SigSpec sig = assign_map(wire);
for (int i = 0; i < GetSize(val) && i < GetSize(sig); i++)
if (val[i] != State::Sx)
init_bits[sig[i]] = val[i];
wire->attributes.erase(it2);
}
}
// set init attributes on all wires of a connected group
for (auto wire : module->wires()) {
bool found = false;
Const val(State::Sx, wire->width);
for (int i = 0; i < wire->width; i++) {
auto it = init_bits.find(RTLIL::SigBit(wire, i));
if (it != init_bits.end()) {
val.set(i, it->second);
found = true;
}
}
if (found)
wire->attributes[ID::init] = val;
}
// now decide for each wire if we should be deleting it
pool<RTLIL::Wire*> del_wires_queue;
for (auto wire : module->wires())
{
SigSpec s1 = SigSpec(wire), s2 = assign_map(s1);
log_assert(GetSize(s1) == GetSize(s2));
Const initval;
if (wire->attributes.count(ID::init))
initval = wire->attributes.at(ID::init);
if (GetSize(initval) != GetSize(wire))
initval.resize(GetSize(wire), State::Sx);
if (initval.is_fully_undef())
wire->attributes.erase(ID::init);
if (GetSize(wire) == 0) {
// delete zero-width wires, unless they are module ports
if (wire->port_id == 0)
goto delete_this_wire;
} else
if (wire->port_id != 0 || wire->get_bool_attribute(ID::keep) || !initval.is_fully_undef()) {
// do not delete anything with "keep" or module ports or initialized wires
} else
if (!purge_mode && check_public_name(wire->name) && (raw_used_signals.check_any(s1) || used_signals.check_any(s2) || s1 != s2)) {
// do not get rid of public names unless in purge mode or if the wire is entirely unused, not even aliased
} else
if (!raw_used_signals.check_any(s1)) {
// delete wires that aren't used by anything directly
goto delete_this_wire;
}
if (0)
{
delete_this_wire:
del_wires_queue.insert(wire);
}
else
{
RTLIL::SigSig new_conn;
for (int i = 0; i < GetSize(s1); i++)
if (s1[i] != s2[i]) {
if (s2[i] == State::Sx && (initval[i] == State::S0 || initval[i] == State::S1)) {
s2[i] = initval[i];
initval.set(i, State::Sx);
}
new_conn.first.append(s1[i]);
new_conn.second.append(s2[i]);
}
if (new_conn.first.size() > 0) {
if (initval.is_fully_undef())
wire->attributes.erase(ID::init);
else
wire->attributes.at(ID::init) = initval;
module->connect(new_conn);
}
if (!used_signals_nodrivers.check_all(s2)) {
std::string unused_bits;
for (int i = 0; i < GetSize(s2); i++) {
if (s2[i].wire == NULL)
continue;
if (!used_signals_nodrivers.check(s2[i])) {
if (!unused_bits.empty())
unused_bits += " ";
unused_bits += stringf("%d", i);
}
}
if (unused_bits.empty() || wire->port_id != 0)
wire->attributes.erase(ID::unused_bits);
else
wire->attributes[ID::unused_bits] = RTLIL::Const(unused_bits);
} else {
wire->attributes.erase(ID::unused_bits);
}
}
}
int del_temp_wires_count = 0;
for (auto wire : del_wires_queue) {
if (ys_debug() || (check_public_name(wire->name) && verbose))
log_debug(" removing unused non-port wire %s.\n", wire->name);
else
del_temp_wires_count++;
}
module->remove(del_wires_queue);
count_rm_wires += GetSize(del_wires_queue);
if (verbose && del_temp_wires_count)
log_debug(" removed %d unused temporary wires.\n", del_temp_wires_count);
if (!del_wires_queue.empty())
module->design->scratchpad_set_bool("opt.did_something", true);
return !del_wires_queue.empty();
}
bool rmunused_module_init(RTLIL::Module *module, bool verbose)
{
bool did_something = false;
CellTypes fftypes;
fftypes.setup_internals_mem();
SigMap sigmap(module);
dict<SigBit, State> qbits;
for (auto cell : module->cells())
if (fftypes.cell_known(cell->type) && cell->hasPort(ID::Q))
{
SigSpec sig = cell->getPort(ID::Q);
for (int i = 0; i < GetSize(sig); i++)
{
SigBit bit = sig[i];
if (bit.wire == nullptr || bit.wire->attributes.count(ID::init) == 0)
continue;
Const init = bit.wire->attributes.at(ID::init);
if (i >= GetSize(init) || init[i] == State::Sx || init[i] == State::Sz)
continue;
sigmap.add(bit);
qbits[bit] = init[i];
}
}
for (auto wire : module->wires())
{
if (wire->attributes.count(ID::init) == 0)
continue;
Const init = wire->attributes.at(ID::init);
for (int i = 0; i < GetSize(wire) && i < GetSize(init); i++)
{
if (init[i] == State::Sx || init[i] == State::Sz)
continue;
SigBit wire_bit = SigBit(wire, i);
SigBit mapped_wire_bit = sigmap(wire_bit);
if (wire_bit == mapped_wire_bit)
goto next_wire;
if (mapped_wire_bit.wire) {
if (qbits.count(mapped_wire_bit) == 0)
goto next_wire;
if (qbits.at(mapped_wire_bit) != init[i])
goto next_wire;
}
else {
if (mapped_wire_bit == State::Sx || mapped_wire_bit == State::Sz)
goto next_wire;
if (mapped_wire_bit != init[i]) {
log_warning("Initial value conflict for %s resolving to %s but with init %s.\n", log_signal(wire_bit), log_signal(mapped_wire_bit), log_signal(init[i]));
goto next_wire;
}
}
}
if (verbose)
log_debug(" removing redundant init attribute on %s.\n", log_id(wire));
wire->attributes.erase(ID::init);
did_something = true;
next_wire:;
}
if (did_something)
module->design->scratchpad_set_bool("opt.did_something", true);
return did_something;
}
void rmunused_module(RTLIL::Module *module, bool purge_mode, bool verbose, bool rminit)
{
if (verbose)
log("Finding unused cells or wires in module %s..\n", module->name);
std::vector<RTLIL::Cell*> delcells;
for (auto cell : module->cells()) {
if (cell->type.in(ID($pos), ID($_BUF_), ID($buf)) && !cell->has_keep_attr()) {
bool is_signed = cell->type == ID($pos) && cell->getParam(ID::A_SIGNED).as_bool();
RTLIL::SigSpec a = cell->getPort(ID::A);
RTLIL::SigSpec y = cell->getPort(ID::Y);
a.extend_u0(GetSize(y), is_signed);
if (a.has_const(State::Sz)) {
SigSpec new_a;
SigSpec new_y;
for (int i = 0; i < GetSize(a); ++i) {
SigBit b = a[i];
if (b == State::Sz)
continue;
new_a.append(b);
new_y.append(y[i]);
}
a = std::move(new_a);
y = std::move(new_y);
}
if (!y.empty())
module->connect(y, a);
delcells.push_back(cell);
} else if (cell->type.in(ID($connect)) && !cell->has_keep_attr()) {
RTLIL::SigSpec a = cell->getPort(ID::A);
RTLIL::SigSpec b = cell->getPort(ID::B);
if (a.has_const() && !b.has_const())
std::swap(a, b);
module->connect(a, b);
delcells.push_back(cell);
} else if (cell->type.in(ID($input_port)) && !cell->has_keep_attr()) {
delcells.push_back(cell);
}
}
for (auto cell : delcells) {
if (verbose) {
if (cell->type == ID($connect))
log_debug(" removing connect cell `%s': %s <-> %s\n", cell->name,
log_signal(cell->getPort(ID::A)), log_signal(cell->getPort(ID::B)));
else if (cell->type == ID($input_port))
log_debug(" removing input port marker cell `%s': %s\n", cell->name,
log_signal(cell->getPort(ID::Y)));
else
log_debug(" removing buffer cell `%s': %s = %s\n", cell->name,
log_signal(cell->getPort(ID::Y)), log_signal(cell->getPort(ID::A)));
}
module->remove(cell);
}
if (!delcells.empty())
module->design->scratchpad_set_bool("opt.did_something", true);
rmunused_module_cells(module, verbose);
while (rmunused_module_signals(module, purge_mode, verbose)) { }
if (rminit && rmunused_module_init(module, verbose))
while (rmunused_module_signals(module, purge_mode, verbose)) { }
}
struct OptCleanPass : public Pass {
OptCleanPass() : Pass("opt_clean", "remove unused cells and wires") { }
void help() override
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" opt_clean [options] [selection]\n");
log("\n");
log("This pass identifies wires and cells that are unused and removes them. Other\n");
log("passes often remove cells but leave the wires in the design or reconnect the\n");
log("wires but leave the old cells in the design. This pass can be used to clean up\n");
log("after the passes that do the actual work.\n");
log("\n");
log("This pass only operates on completely selected modules without processes.\n");
log("\n");
log(" -purge\n");
log(" also remove internal nets if they have a public name\n");
log("\n");
}
void execute(std::vector<std::string> args, RTLIL::Design *design) override
{
bool purge_mode = false;
log_header(design, "Executing OPT_CLEAN pass (remove unused cells and wires).\n");
log_push();
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++) {
if (args[argidx] == "-purge") {
purge_mode = true;
continue;
}
break;
}
extra_args(args, argidx, design);
keep_cache.reset(design, purge_mode);
ct_reg.setup_internals_mem();
ct_reg.setup_internals_anyinit();
ct_reg.setup_stdcells_mem();
ct_all.setup(design);
count_rm_cells = 0;
count_rm_wires = 0;
for (auto module : design->selected_whole_modules_warn()) {
if (module->has_processes_warn())
continue;
rmunused_module(module, purge_mode, true, true);
}
if (count_rm_cells > 0 || count_rm_wires > 0)
log("Removed %d unused cells and %d unused wires.\n", count_rm_cells, count_rm_wires);
design->optimize();
design->check();
keep_cache.reset();
ct_reg.clear();
ct_all.clear();
log_pop();
request_garbage_collection();
}
} OptCleanPass;
struct CleanPass : public Pass {
CleanPass() : Pass("clean", "remove unused cells and wires") { }
void help() override
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" clean [options] [selection]\n");
log("\n");
log("This is identical to 'opt_clean', but less verbose.\n");
log("\n");
log("When commands are separated using the ';;' token, this command will be executed\n");
log("between the commands.\n");
log("\n");
log("When commands are separated using the ';;;' token, this command will be executed\n");
log("in -purge mode between the commands.\n");
log("\n");
}
void execute(std::vector<std::string> args, RTLIL::Design *design) override
{
bool purge_mode = false;
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++) {
if (args[argidx] == "-purge") {
purge_mode = true;
continue;
}
break;
}
extra_args(args, argidx, design);
keep_cache.reset(design);
ct_reg.setup_internals_mem();
ct_reg.setup_internals_anyinit();
ct_reg.setup_stdcells_mem();
ct_all.setup(design);
count_rm_cells = 0;
count_rm_wires = 0;
for (auto module : design->selected_unboxed_whole_modules()) {
if (module->has_processes())
continue;
rmunused_module(module, purge_mode, ys_debug(), true);
}
log_suppressed();
if (count_rm_cells > 0 || count_rm_wires > 0)
log("Removed %d unused cells and %d unused wires.\n", count_rm_cells, count_rm_wires);
design->optimize();
design->check();
keep_cache.reset();
ct_reg.clear();
ct_all.clear();
request_garbage_collection();
}
} CleanPass;
PRIVATE_NAMESPACE_END

View file

@ -0,0 +1,10 @@
OPT_CLEAN_OBJS =
OPT_CLEAN_OBJS += passes/opt/opt_clean/cells_all.o
OPT_CLEAN_OBJS += passes/opt/opt_clean/cells_temp.o
OPT_CLEAN_OBJS += passes/opt/opt_clean/wires.o
OPT_CLEAN_OBJS += passes/opt/opt_clean/inits.o
OPT_CLEAN_OBJS += passes/opt/opt_clean/opt_clean.o
$(OPT_CLEAN_OBJS): passes/opt/opt_clean/opt_clean.h
OBJS += $(OPT_CLEAN_OBJS)

View file

@ -0,0 +1,373 @@
/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
*
* 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/ffinit.h"
#include "kernel/yosys_common.h"
#include "passes/opt/opt_clean/opt_clean.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
unsigned int hash_bit(const SigBit &bit) {
return static_cast<unsigned int>(hash_ops<SigBit>::hash(bit).yield());
}
SigMap wire_sigmap(const RTLIL::Module* mod) {
SigMap map;
for (auto &it : mod->connections_) {
for (int i = 0; i < GetSize(it.second); i++) {
if (it.second[i].wire != nullptr)
map.add(it.first[i], it.second[i]);
}
}
return map;
}
struct WireDrivers;
// Maps from a SigBit to a unique driver cell.
struct WireDriver {
using Accumulated = WireDrivers;
SigBit bit;
int driver_cell;
};
// Maps from a SigBit to one or more driver cells.
struct WireDrivers {
WireDrivers() : driver_cell(0) {}
WireDrivers(WireDriver driver) : bit(driver.bit), driver_cell(driver.driver_cell) {}
WireDrivers(SigBit bit) : bit(bit), driver_cell(0) {}
WireDrivers(WireDrivers &&other) = default;
class const_iterator {
public:
const_iterator(const WireDrivers &drivers, bool end)
: driver_cell(drivers.driver_cell), in_extra_cells(end) {
if (drivers.extra_driver_cells) {
if (end) {
extra_it = drivers.extra_driver_cells->end();
} else {
extra_it = drivers.extra_driver_cells->begin();
}
}
}
int operator*() const {
if (in_extra_cells)
return **extra_it;
return driver_cell;
}
const_iterator& operator++() {
if (in_extra_cells)
++*extra_it;
else
in_extra_cells = true;
return *this;
}
bool operator!=(const const_iterator &other) const {
return !(*this == other);
}
bool operator==(const const_iterator &other) const {
return in_extra_cells == other.in_extra_cells &&
extra_it == other.extra_it;
}
private:
std::optional<pool<int>::iterator> extra_it;
int driver_cell;
bool in_extra_cells;
};
const_iterator begin() const { return const_iterator(*this, false); }
const_iterator end() const { return const_iterator(*this, true); }
SigBit bit;
int driver_cell;
std::unique_ptr<pool<int>> extra_driver_cells;
};
struct WireDriversKeyEquality {
bool operator()(const WireDrivers &a, const WireDrivers &b) const {
return a.bit == b.bit;
}
};
struct WireDriversCollisionHandler {
void operator()(WireDrivers &incumbent, WireDrivers &new_value) const {
log_assert(new_value.extra_driver_cells == nullptr);
if (!incumbent.extra_driver_cells)
incumbent.extra_driver_cells.reset(new pool<int>());
incumbent.extra_driver_cells->insert(new_value.driver_cell);
}
};
using Wire2Drivers = ShardedHashtable<WireDriver, WireDriversKeyEquality, WireDriversCollisionHandler>;
struct ConflictLogs {
ShardedVector<std::pair<SigBit, std::string>> logs;
ConflictLogs(ParallelDispatchThreadPool::Subpool &subpool) : logs(subpool) {}
void print_warnings(pool<SigBit>& used_raw_bits, const SigMap& wire_map, const RTLIL::Module* mod, CleanRunContext &clean_ctx) {
if (!logs.empty()) {
// We could do this in parallel but hopefully this is rare.
for (auto [_, cell] : mod->cells_) {
for (auto &[port, sig] : cell->connections()) {
if (clean_ctx.ct_all.cell_known(cell->type) && !clean_ctx.ct_all.cell_input(cell->type, port))
continue;
for (auto raw_bit : wire_map(sig))
used_raw_bits.insert(raw_bit);
}
}
for (std::pair<SigBit, std::string> &it : logs) {
if (used_raw_bits.count(it.first))
log_warning("%s\n", it.second);
}
}
}
};
struct CellTraversal {
ConcurrentWorkQueue<int> queue;
Wire2Drivers wire2driver;
dict<std::string, pool<int>> mem2cells;
CellTraversal(int num_threads) : queue(num_threads), wire2driver(), mem2cells() {}
};
struct CellAnalysis {
ShardedVector<Wire*> keep_wires;
std::vector<std::atomic<bool>> unused;
CellAnalysis(AnalysisContext& actx)
: keep_wires(actx.subpool), unused(actx.mod->cells_size()) {}
pool<SigBit> analyze_kept_wires(CellTraversal& traversal, const SigMap& sigmap, const SigMap& wire_map, int num_threads) {
// Also enqueue cells that drive kept wires into cell_queue
// and mark those cells as used
// and mark all bits of those wires as used
pool<SigBit> used_raw_bits;
int i = 0;
for (Wire *wire : keep_wires) {
for (auto bit : sigmap(wire)) {
const WireDrivers *drivers = traversal.wire2driver.find({{bit}, hash_bit(bit)});
if (drivers != nullptr)
for (int cell_index : *drivers)
if (unused[cell_index].exchange(false, std::memory_order_relaxed)) {
ThreadIndex fake_thread_index = {i++ % num_threads};
traversal.queue.push(fake_thread_index, cell_index);
}
}
for (auto raw_bit : SigSpec(wire))
used_raw_bits.insert(wire_map(raw_bit));
}
return used_raw_bits;
}
void mark_used_and_enqueue(int cell_idx, ConcurrentWorkQueue<int>& queue, const ParallelDispatchThreadPool::RunCtx &ctx) {
if (unused[cell_idx].exchange(false, std::memory_order_relaxed))
queue.push(ctx, cell_idx);
}
};
ConflictLogs explore(CellAnalysis& analysis, CellTraversal& traversal, const SigMap& wire_map, AnalysisContext& actx, CleanRunContext &clean_ctx) {
ConflictLogs logs(actx.subpool);
Wire2Drivers::Builder wire2driver_builder(actx.subpool);
ShardedVector<std::pair<std::string, int>> mem2cells_vector(actx.subpool);
// Enqueue kept cells into traversal.queue
// Prepare input cone traversal into traversal.wire2driver
// Prepare "input cone" traversal from memory to write port or meminit as analysis.mem2cells
// Also check driver conflicts
// Also mark cells unused to true unless keep (we override this later)
actx.subpool.run([&analysis, &traversal, &logs, &wire_map, &mem2cells_vector, &wire2driver_builder, &actx, &clean_ctx](const ParallelDispatchThreadPool::RunCtx &ctx) {
for (int i : ctx.item_range(actx.mod->cells_size())) {
Cell *cell = actx.mod->cell_at(i);
if (cell->type.in(ID($memwr), ID($memwr_v2), ID($meminit), ID($meminit_v2)))
mem2cells_vector.insert(ctx, {cell->getParam(ID::MEMID).decode_string(), i});
for (auto &it2 : cell->connections()) {
if (clean_ctx.ct_all.cell_known(cell->type) && !clean_ctx.ct_all.cell_output(cell->type, it2.first))
continue;
for (auto raw_bit : it2.second) {
if (raw_bit.wire == nullptr)
continue;
auto bit = actx.assign_map(raw_bit);
if (bit.wire == nullptr && clean_ctx.ct_all.cell_known(cell->type)) {
std::string msg = stringf("Driver-driver conflict "
"for %s between cell %s.%s and constant %s in %s: Resolved using constant.",
log_signal(raw_bit), cell->name.unescape(), it2.first.unescape(), log_signal(bit), actx.mod->name.unescape());
logs.logs.insert(ctx, {wire_map(raw_bit), msg});
}
if (bit.wire != nullptr)
wire2driver_builder.insert(ctx, {{bit, i}, hash_bit(bit)});
}
}
bool keep = clean_ctx.keep_cache.query(cell);
analysis.unused[i].store(!keep, std::memory_order_relaxed);
if (keep)
traversal.queue.push(ctx, i);
}
for (int i : ctx.item_range(actx.mod->wires_size())) {
Wire *wire = actx.mod->wire_at(i);
if (wire->port_output || wire->get_bool_attribute(ID::keep))
analysis.keep_wires.insert(ctx, wire);
}
});
// Finish by merging per-thread collected data
actx.subpool.run([&wire2driver_builder](const ParallelDispatchThreadPool::RunCtx &ctx) {
wire2driver_builder.process(ctx);
});
traversal.wire2driver = wire2driver_builder;
for (std::pair<std::string, int> &mem2cell : mem2cells_vector)
traversal.mem2cells[mem2cell.first].insert(mem2cell.second);
return logs;
}
struct MemAnalysis {
std::vector<std::atomic<bool>> unused;
dict<std::string, int> indices;
MemAnalysis(const RTLIL::Module* mod) : unused(mod->memories.size()), indices() {
for (int i = 0; i < GetSize(mod->memories); ++i) {
indices[mod->memories.element(i)->first.str()] = i;
unused[i].store(true, std::memory_order_relaxed);
}
}
};
void fixup_unused_cells_and_mems(CellAnalysis& analysis, MemAnalysis& mem_analysis, CellTraversal& traversal, AnalysisContext& actx, CleanRunContext &clean_ctx) {
// Processes the cell queue in batches, traversing input cones by enqueuing more cells
// Discover and mark used memories and cells
actx.subpool.run([&analysis, &mem_analysis, &traversal, &actx, &clean_ctx](const ParallelDispatchThreadPool::RunCtx &ctx) {
pool<SigBit> bits;
pool<std::string> mems;
while (true) {
std::vector<int> cell_indices = traversal.queue.pop_batch(ctx);
if (cell_indices.empty())
return;
for (auto cell_index : cell_indices) {
Cell *cell = actx.mod->cell_at(cell_index);
for (auto &it : cell->connections())
if (!clean_ctx.ct_all.cell_known(cell->type) || clean_ctx.ct_all.cell_input(cell->type, it.first))
for (auto bit : actx.assign_map(it.second))
bits.insert(bit);
if (cell->type.in(ID($memrd), ID($memrd_v2))) {
std::string mem_id = cell->getParam(ID::MEMID).decode_string();
if (mem_analysis.indices.count(mem_id)) {
int mem_index = mem_analysis.indices[mem_id];
// Memory fixup
if (mem_analysis.unused[mem_index].exchange(false, std::memory_order_relaxed))
mems.insert(mem_id);
}
}
}
for (auto bit : bits) {
// Cells fixup
const WireDrivers *drivers = traversal.wire2driver.find({{bit}, hash_bit(bit)});
if (drivers != nullptr)
for (int cell_idx : *drivers)
analysis.mark_used_and_enqueue(cell_idx, traversal.queue, ctx);
}
bits.clear();
for (auto mem : mems) {
if (traversal.mem2cells.count(mem) == 0)
continue;
// Cells fixup
for (int cell_idx : traversal.mem2cells.at(mem))
analysis.mark_used_and_enqueue(cell_idx, traversal.queue, ctx);
}
mems.clear();
}
});
}
pool<Cell*> all_unused_cells(const Module *mod, const CellAnalysis& analysis, Wire2Drivers& wire2driver, ParallelDispatchThreadPool::Subpool &subpool) {
pool<Cell*> unused_cells;
ShardedVector<int> sharded_unused_cells(subpool);
subpool.run([mod, &analysis, &wire2driver, &sharded_unused_cells](const ParallelDispatchThreadPool::RunCtx &ctx) {
// Parallel destruction of `wire2driver`
wire2driver.clear(ctx);
for (int i : ctx.item_range(mod->cells_size()))
if (analysis.unused[i].load(std::memory_order_relaxed))
sharded_unused_cells.insert(ctx, i);
});
for (int cell_index : sharded_unused_cells)
unused_cells.insert(mod->cell_at(cell_index));
unused_cells.sort(RTLIL::sort_by_name_id<RTLIL::Cell>());
return unused_cells;
}
void remove_cells(RTLIL::Module* mod, FfInitVals& ffinit, const pool<Cell*>& cells, bool verbose, RmStats& stats) {
for (auto cell : cells) {
if (verbose)
log_debug(" removing unused `%s' cell `%s'.\n", cell->type, cell->name);
mod->design->scratchpad_set_bool("opt.did_something", true);
if (cell->is_builtin_ff())
ffinit.remove_init(cell->getPort(ID::Q));
mod->remove(cell);
stats.count_rm_cells++;
}
}
void remove_mems(RTLIL::Module* mod, const MemAnalysis& mem_analysis, bool verbose) {
for (const auto &it : mem_analysis.indices) {
if (!mem_analysis.unused[it.second].load(std::memory_order_relaxed))
continue;
RTLIL::IdString id(it.first);
if (verbose)
log_debug(" removing unused memory `%s'.\n", id.unescape());
delete mod->memories.at(id);
mod->memories.erase(id);
}
}
PRIVATE_NAMESPACE_END
YOSYS_NAMESPACE_BEGIN
void rmunused_module_cells(Module *module, ParallelDispatchThreadPool::Subpool &subpool, CleanRunContext &clean_ctx)
{
AnalysisContext actx(module, subpool);
// Used for logging warnings only
SigMap wire_map = wire_sigmap(module);
CellAnalysis analysis(actx);
CellTraversal traversal(subpool.num_threads());
// Mark all unkept cells as unused initially
// and queue up cell traversal from those cells
auto logs = explore(analysis, traversal, wire_map, actx, clean_ctx);
// Mark cells that drive kept wires into cell_queue and those bits as used
// and queue up cell traversal from those cells
pool<SigBit> used_raw_bits = analysis.analyze_kept_wires(traversal, actx.assign_map, wire_map, subpool.num_threads());
// Mark all memories as unused initially
MemAnalysis mem_analysis(module);
// Marked all used cells and mems as used by traversing with cell queue
fixup_unused_cells_and_mems(analysis, mem_analysis, traversal, actx, clean_ctx);
// Analyses are now fully correct
// unused_cells.contains(foo) iff analysis.used[foo] == true
// wire2driver is passed in only to destroy it
pool<Cell*> unused_cells = all_unused_cells(module, analysis, traversal.wire2driver, subpool);
FfInitVals ffinit;
ffinit.set_parallel(&actx.assign_map, subpool.thread_pool(), module);
// Now we know what to kill
remove_cells(module, ffinit, unused_cells, clean_ctx.flags.verbose, clean_ctx.stats);
remove_mems(module, mem_analysis, clean_ctx.flags.verbose);
logs.print_warnings(used_raw_bits, wire_map, module, clean_ctx);
}
YOSYS_NAMESPACE_END

View file

@ -0,0 +1,104 @@
/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
*
* 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/opt/opt_clean/opt_clean.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
bool is_signed(RTLIL::Cell* cell) {
return cell->type == ID($pos) && cell->getParam(ID::A_SIGNED).as_bool();
}
bool trim_buf(RTLIL::Cell* cell, ShardedVector<RTLIL::SigSig>& new_connections, const ParallelDispatchThreadPool::RunCtx &ctx) {
RTLIL::SigSpec a = cell->getPort(ID::A);
RTLIL::SigSpec y = cell->getPort(ID::Y);
a.extend_u0(GetSize(y), is_signed(cell));
if (a.has_const(State::Sz)) {
RTLIL::SigSpec new_a;
RTLIL::SigSpec new_y;
for (int i = 0; i < GetSize(a); ++i) {
RTLIL::SigBit b = a[i];
if (b == State::Sz)
return false;
new_a.append(b);
new_y.append(y[i]);
}
a = std::move(new_a);
y = std::move(new_y);
}
if (!y.empty())
new_connections.insert(ctx, {y, a});
return true;
}
bool remove(ShardedVector<RTLIL::Cell*>& cells, RTLIL::Module* mod, bool verbose) {
bool did_something = false;
for (RTLIL::Cell *cell : cells) {
if (verbose) {
if (cell->type == ID($connect))
log_debug(" removing connect cell `%s': %s <-> %s\n", cell->name,
log_signal(cell->getPort(ID::A)), log_signal(cell->getPort(ID::B)));
else if (cell->type == ID($input_port))
log_debug(" removing input port marker cell `%s': %s\n", cell->name,
log_signal(cell->getPort(ID::Y)));
else
log_debug(" removing buffer cell `%s': %s = %s\n", cell->name,
log_signal(cell->getPort(ID::Y)), log_signal(cell->getPort(ID::A)));
}
mod->remove(cell);
did_something = true;
}
return did_something;
}
PRIVATE_NAMESPACE_END
YOSYS_NAMESPACE_BEGIN
void remove_temporary_cells(RTLIL::Module *module, ParallelDispatchThreadPool::Subpool &subpool, bool verbose)
{
ShardedVector<RTLIL::Cell*> delcells(subpool);
ShardedVector<RTLIL::SigSig> new_connections(subpool);
const RTLIL::Module *const_module = module;
subpool.run([const_module, &delcells, &new_connections](const ParallelDispatchThreadPool::RunCtx &ctx) {
for (int i : ctx.item_range(const_module->cells_size())) {
RTLIL::Cell *cell = const_module->cell_at(i);
if (cell->type.in(ID($pos), ID($_BUF_), ID($buf)) && !cell->has_keep_attr()) {
if (trim_buf(cell, new_connections, ctx))
delcells.insert(ctx, cell);
} else if (cell->type.in(ID($connect)) && !cell->has_keep_attr()) {
RTLIL::SigSpec a = cell->getPort(ID::A);
RTLIL::SigSpec b = cell->getPort(ID::B);
if (a.has_const() && !b.has_const())
std::swap(a, b);
new_connections.insert(ctx, {a, b});
delcells.insert(ctx, cell);
} else if (cell->type.in(ID($input_port)) && !cell->has_keep_attr()) {
delcells.insert(ctx, cell);
}
}
});
for (RTLIL::SigSig &connection : new_connections) {
module->connect(connection);
}
if (remove(delcells, module, verbose))
module->design->scratchpad_set_bool("opt.did_something", true);
}
YOSYS_NAMESPACE_END

View file

@ -0,0 +1,137 @@
/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
*
* 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/opt/opt_clean/opt_clean.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
ShardedVector<std::pair<SigBit, State>> build_inits(AnalysisContext& actx) {
ShardedVector<std::pair<SigBit, State>> results(actx.subpool);
actx.subpool.run([&results, &actx](const ParallelDispatchThreadPool::RunCtx &ctx) {
for (int i : ctx.item_range(actx.mod->cells_size())) {
RTLIL::Cell *cell = actx.mod->cell_at(i);
if (StaticCellTypes::Compat::internals_mem_ff(cell->type) && cell->hasPort(ID::Q))
{
SigSpec sig = cell->getPort(ID::Q);
for (int i = 0; i < GetSize(sig); i++)
{
SigBit bit = sig[i];
if (bit.wire == nullptr || bit.wire->attributes.count(ID::init) == 0)
continue;
Const init = bit.wire->attributes.at(ID::init);
if (i >= GetSize(init) || init[i] == State::Sx || init[i] == State::Sz)
continue;
results.insert(ctx, {bit, init[i]});
}
}
}
});
return results;
}
dict<SigBit, State> qbits_from_inits(ShardedVector<std::pair<SigBit, State>>& inits, SigMap& assign_map) {
dict<SigBit, State> qbits;
for (std::pair<SigBit, State> &p : inits) {
assign_map.add(p.first);
qbits[p.first] = p.second;
}
return qbits;
}
ShardedVector<RTLIL::Wire*> deferred_init_transfer(const dict<SigBit, State>& qbits, AnalysisContext& actx) {
ShardedVector<RTLIL::Wire*> wire_results(actx.subpool);
actx.subpool.run([&actx, &qbits, &wire_results](const ParallelDispatchThreadPool::RunCtx &ctx) {
for (int j : ctx.item_range(actx.mod->wires_size())) {
RTLIL::Wire *wire = actx.mod->wire_at(j);
if (wire->attributes.count(ID::init) == 0)
continue;
Const init = wire->attributes.at(ID::init);
for (int i = 0; i < GetSize(wire) && i < GetSize(init); i++)
{
if (init[i] == State::Sx || init[i] == State::Sz)
continue;
SigBit wire_bit = SigBit(wire, i);
SigBit mapped_wire_bit = actx.assign_map(wire_bit);
if (wire_bit == mapped_wire_bit)
goto next_wire;
if (mapped_wire_bit.wire) {
if (qbits.count(mapped_wire_bit) == 0)
goto next_wire;
if (qbits.at(mapped_wire_bit) != init[i])
goto next_wire;
}
else {
if (mapped_wire_bit == State::Sx || mapped_wire_bit == State::Sz)
goto next_wire;
if (mapped_wire_bit != init[i]) {
log_warning("Initial value conflict for %s resolving to %s but with init %s.\n", log_signal(wire_bit), log_signal(mapped_wire_bit), log_signal(init[i]));
goto next_wire;
}
}
}
wire_results.insert(ctx, wire);
next_wire:;
}
});
return wire_results;
}
bool remove_redundant_inits(ShardedVector<RTLIL::Wire*> wires, bool verbose) {
bool did_something = false;
for (RTLIL::Wire *wire : wires) {
if (verbose)
log_debug(" removing redundant init attribute on %s.\n", log_id(wire));
wire->attributes.erase(ID::init);
did_something = true;
}
return did_something;
}
PRIVATE_NAMESPACE_END
YOSYS_NAMESPACE_BEGIN
bool rmunused_module_init(RTLIL::Module *module, ParallelDispatchThreadPool::Subpool &subpool, bool verbose)
{
AnalysisContext actx(module, subpool);
ShardedVector<std::pair<SigBit, State>> inits = build_inits(actx);
dict<SigBit, State> qbits = qbits_from_inits(inits, actx.assign_map);
ShardedVector<RTLIL::Wire*> inits_to_transfer = deferred_init_transfer(qbits, actx);
bool did_something = remove_redundant_inits(inits_to_transfer, verbose);
if (did_something)
module->design->scratchpad_set_bool("opt.did_something", true);
return did_something;
}
YOSYS_NAMESPACE_END

View file

@ -0,0 +1,167 @@
/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
*
* 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/rtlil.h"
#include "kernel/sigtools.h"
#include "kernel/threading.h"
#include "kernel/celltypes.h"
#include "kernel/yosys_common.h"
#ifndef OPT_CLEAN_KEEP_CACHE_H
#define OPT_CLEAN_KEEP_CACHE_H
YOSYS_NAMESPACE_BEGIN
struct KeepCache
{
dict<Module*, bool> keep_modules;
bool purge_mode;
KeepCache(bool purge_mode, ParallelDispatchThreadPool &thread_pool, const std::vector<RTLIL::Module *> &selected_modules)
: purge_mode(purge_mode) {
std::vector<RTLIL::Module *> scan_modules_worklist;
dict<RTLIL::Module *, std::vector<RTLIL::Module*>> dependents;
std::vector<RTLIL::Module *> propagate_kept_modules_worklist;
for (RTLIL::Module *module : selected_modules) {
if (keep_modules.count(module))
continue;
bool keep = scan_module(module, thread_pool, dependents, ALL_CELLS, scan_modules_worklist);
keep_modules[module] = keep;
if (keep)
propagate_kept_modules_worklist.push_back(module);
}
while (!scan_modules_worklist.empty()) {
RTLIL::Module *module = scan_modules_worklist.back();
scan_modules_worklist.pop_back();
if (keep_modules.count(module))
continue;
bool keep = scan_module(module, thread_pool, dependents, MINIMUM_CELLS, scan_modules_worklist);
keep_modules[module] = keep;
if (keep)
propagate_kept_modules_worklist.push_back(module);
}
while (!propagate_kept_modules_worklist.empty()) {
RTLIL::Module *module = propagate_kept_modules_worklist.back();
propagate_kept_modules_worklist.pop_back();
for (RTLIL::Module *dependent : dependents[module]) {
if (keep_modules[dependent])
continue;
keep_modules[dependent] = true;
propagate_kept_modules_worklist.push_back(dependent);
}
}
}
bool query(Cell *cell) const
{
if (keep_cell(cell, purge_mode))
return true;
if (cell->type.in(ID($specify2), ID($specify3), ID($specrule)))
return true;
if (cell->module && cell->module->design) {
RTLIL::Module *cell_module = cell->module->design->module(cell->type);
return cell_module != nullptr && keep_modules.at(cell_module);
}
return false;
}
private:
enum ScanCells {
// Scan every cell to see if it uses a module that is kept.
ALL_CELLS,
// Stop scanning cells if we determine early that this module is kept.
MINIMUM_CELLS,
};
bool scan_module(Module *module, ParallelDispatchThreadPool &thread_pool, dict<RTLIL::Module *, std::vector<RTLIL::Module*>> &dependents,
ScanCells scan_cells, std::vector<Module*> &worklist) const
{
MonotonicFlag keep_module;
if (module->get_bool_attribute(ID::keep)) {
if (scan_cells == MINIMUM_CELLS)
return true;
keep_module.set();
}
ParallelDispatchThreadPool::Subpool subpool(thread_pool, ThreadPool::work_pool_size(0, module->cells_size(), 1000));
ShardedVector<Module*> deps(subpool);
const RTLIL::Module *const_module = module;
bool purge_mode = this->purge_mode;
subpool.run([purge_mode, const_module, scan_cells, &deps, &keep_module](const ParallelDispatchThreadPool::RunCtx &ctx) {
bool keep = false;
for (int i : ctx.item_range(const_module->cells_size())) {
Cell *cell = const_module->cell_at(i);
if (keep_cell(cell, purge_mode)) {
if (scan_cells == MINIMUM_CELLS) {
keep_module.set();
return;
}
keep = true;
}
if (const_module->design) {
RTLIL::Module *cell_module = const_module->design->module(cell->type);
if (cell_module != nullptr)
deps.insert(ctx, cell_module);
}
}
if (keep) {
keep_module.set();
return;
}
for (int i : ctx.item_range(const_module->wires_size())) {
Wire *wire = const_module->wire_at(i);
if (wire->get_bool_attribute(ID::keep)) {
keep_module.set();
return;
}
}
});
if (scan_cells == MINIMUM_CELLS && keep_module.load())
return true;
for (Module *dep : deps) {
dependents[dep].push_back(module);
worklist.push_back(dep);
}
return keep_module.load();
}
static bool keep_cell(Cell *cell, bool purge_mode)
{
if (cell->type.in(ID($assert), ID($assume), ID($live), ID($fair), ID($cover)))
return true;
if (cell->type.in(ID($overwrite_tag)))
return true;
if (cell->type == ID($print) || cell->type == ID($check))
return true;
if (cell->has_keep_attr())
return true;
if (!purge_mode && cell->type == ID($scopeinfo))
return true;
return false;
}
};
YOSYS_NAMESPACE_END
#endif /* OPT_CLEAN_KEEP_CACHE_H */

View file

@ -0,0 +1,151 @@
/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
*
* 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/register.h"
#include "kernel/log.h"
#include "passes/opt/opt_clean/opt_clean.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
void rmunused_module(RTLIL::Module *module, bool rminit, CleanRunContext &clean_ctx)
{
if (clean_ctx.flags.verbose)
log("Finding unused cells or wires in module %s..\n", module->name);
// Use no more than one worker per thousand cells, rounded down, so
// we only start multithreading with at least 2000 cells.
int num_worker_threads = ThreadPool::work_pool_size(0, module->cells_size(), 10000);
ParallelDispatchThreadPool::Subpool subpool(clean_ctx.thread_pool, num_worker_threads);
remove_temporary_cells(module, subpool, clean_ctx.flags.verbose);
rmunused_module_cells(module, subpool, clean_ctx);
while (rmunused_module_signals(module, subpool, clean_ctx)) { }
if (rminit && rmunused_module_init(module, subpool, clean_ctx.flags.verbose))
while (rmunused_module_signals(module, subpool, clean_ctx)) { }
}
struct OptCleanPass : public Pass {
OptCleanPass() : Pass("opt_clean", "remove unused cells and wires") { }
void help() override
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" opt_clean [options] [selection]\n");
log("\n");
log("This pass identifies wires and cells that are unused and removes them. Other\n");
log("passes often remove cells but leave the wires in the design or reconnect the\n");
log("wires but leave the old cells in the design. This pass can be used to clean up\n");
log("after the passes that do the actual work.\n");
log("\n");
log("This pass only operates on completely selected modules without processes.\n");
log("\n");
log(" -purge\n");
log(" also remove internal nets if they have a public name\n");
log("\n");
}
void execute(std::vector<std::string> args, RTLIL::Design *design) override
{
bool purge_mode = false;
log_header(design, "Executing OPT_CLEAN pass (remove unused cells and wires).\n");
log_push();
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++) {
if (args[argidx] == "-purge") {
purge_mode = true;
continue;
}
break;
}
extra_args(args, argidx, design);
{
std::vector<RTLIL::Module*> selected_modules;
for (auto module : design->selected_whole_modules_warn())
if (!module->has_processes_warn())
selected_modules.push_back(module);
CleanRunContext clean_ctx(design, selected_modules, {purge_mode, true});
for (auto module : selected_modules)
rmunused_module(module, true, clean_ctx);
clean_ctx.stats.log();
design->optimize();
design->check();
}
log_pop();
request_garbage_collection();
}
} OptCleanPass;
struct CleanPass : public Pass {
CleanPass() : Pass("clean", "remove unused cells and wires") { }
void help() override
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" clean [options] [selection]\n");
log("\n");
log("This is identical to 'opt_clean', but less verbose.\n");
log("\n");
log("When commands are separated using the ';;' token, this command will be executed\n");
log("between the commands.\n");
log("\n");
log("When commands are separated using the ';;;' token, this command will be executed\n");
log("in -purge mode between the commands.\n");
log("\n");
}
void execute(std::vector<std::string> args, RTLIL::Design *design) override
{
bool purge_mode = false;
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++) {
if (args[argidx] == "-purge") {
purge_mode = true;
continue;
}
break;
}
extra_args(args, argidx, design);
{
std::vector<RTLIL::Module*> selected_modules;
for (auto module : design->selected_unboxed_whole_modules())
if (!module->has_processes())
selected_modules.push_back(module);
CleanRunContext clean_ctx(design, selected_modules, {purge_mode, ys_debug()});
for (auto module : selected_modules)
rmunused_module(module, true, clean_ctx);
log_suppressed();
clean_ctx.stats.log();
design->optimize();
design->check();
}
request_garbage_collection();
}
} CleanPass;
PRIVATE_NAMESPACE_END

View file

@ -0,0 +1,92 @@
/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
*
* 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/rtlil.h"
#include "kernel/threading.h"
#include "passes/opt/opt_clean/keep_cache.h"
#ifndef OPT_CLEAN_SHARED_H
#define OPT_CLEAN_SHARED_H
YOSYS_NAMESPACE_BEGIN
struct AnalysisContext {
SigMap assign_map;
const RTLIL::Module *mod;
ParallelDispatchThreadPool::Subpool &subpool;
AnalysisContext(RTLIL::Module* m, ParallelDispatchThreadPool::Subpool &p) : assign_map(m), mod(m), subpool(p) {}
};
struct RmStats {
int count_rm_cells = 0;
int count_rm_wires = 0;
void log()
{
if (count_rm_cells > 0 || count_rm_wires > 0)
YOSYS_NAMESPACE_PREFIX log("Removed %d unused cells and %d unused wires.\n", count_rm_cells, count_rm_wires);
}
};
struct Flags {
bool purge = false;
bool verbose = false;
};
struct CleanRunContext {
static constexpr auto ct_reg = StaticCellTypes::Categories::join(
StaticCellTypes::Compat::mem_ff,
StaticCellTypes::categories.is_anyinit);
NewCellTypes ct_all;
RmStats stats;
ParallelDispatchThreadPool thread_pool;
KeepCache keep_cache;
Flags flags;
private:
// Helper to compute thread pool size
static int compute_thread_pool_size(const std::vector<RTLIL::Module*>& selected_modules) {
int thread_pool_size = 0;
for (auto module : selected_modules)
thread_pool_size = std::max(thread_pool_size,
ThreadPool::work_pool_size(0, module->cells_size(), 10000));
return thread_pool_size;
}
public:
CleanRunContext(RTLIL::Design* design, const std::vector<RTLIL::Module*>& selected_modules, Flags f)
: thread_pool(compute_thread_pool_size(selected_modules)),
keep_cache(f.purge, thread_pool, selected_modules),
flags(f)
{
ct_all.setup(design);
}
~CleanRunContext() {
ct_all.clear();
}
};
void remove_temporary_cells(RTLIL::Module *module, ParallelDispatchThreadPool::Subpool &subpool, bool verbose);
void rmunused_module_cells(Module *module, ParallelDispatchThreadPool::Subpool &subpool, CleanRunContext &clean_ctx);
bool rmunused_module_signals(RTLIL::Module *module, ParallelDispatchThreadPool::Subpool &subpool, CleanRunContext &clean_ctx);
bool rmunused_module_init(RTLIL::Module *module, ParallelDispatchThreadPool::Subpool &subpool, bool verbose);
YOSYS_NAMESPACE_END
#endif /* OPT_CLEAN_SHARED_H */

View file

@ -0,0 +1,585 @@
/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
*
* 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/opt/opt_clean/opt_clean.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
// No collision handler for these, since we will use them such that collisions don't happen
struct ShardedSigBit {
using Accumulated = ShardedSigBit;
RTLIL::SigBit bit;
ShardedSigBit() = default;
ShardedSigBit(const RTLIL::SigBit &bit) : bit(bit) {}
};
struct ShardedSigBitEquality {
bool operator()(const ShardedSigBit &b1, const ShardedSigBit &b2) const {
return b1.bit == b2.bit;
}
};
using ShardedSigPool = ShardedHashtable<ShardedSigBit, ShardedSigBitEquality, SetCollisionHandler<ShardedSigBit>>;
struct ShardedSigSpec {
using Accumulated = ShardedSigSpec;
RTLIL::SigSpec spec;
ShardedSigSpec() = default;
ShardedSigSpec(RTLIL::SigSpec spec) : spec(std::move(spec)) {}
ShardedSigSpec(ShardedSigSpec &&) = default;
};
struct ShardedSigSpecEquality {
bool operator()(const ShardedSigSpec &s1, const ShardedSigSpec &s2) const {
return s1.spec == s2.spec;
}
};
using ShardedSigSpecPool = ShardedHashtable<ShardedSigSpec, ShardedSigSpecEquality, SetCollisionHandler<ShardedSigSpec>>;
struct ExactCellWires {
const ShardedSigSpecPool &exact_cells;
const SigMap &assign_map;
dict<RTLIL::Wire *, bool> cache;
ExactCellWires(const ShardedSigSpecPool &exact_cells, const SigMap &assign_map) : exact_cells(exact_cells), assign_map(assign_map) {}
void cache_result_for_bit(const SigBit &bit) {
if (bit.wire != nullptr)
(void)is_exactly_cell_driven(bit.wire);
}
bool is_exactly_cell_driven(RTLIL::Wire *wire) {
if (wire->port_input)
return true;
auto it = cache.find(wire);
if (it != cache.end())
return it->second;
SigSpec sig = assign_map(wire);
bool direct = exact_cells.find({sig, sig.hash_into(Hasher()).yield()}) != nullptr;
cache.insert({wire, direct});
return direct;
}
void cache_all(ShardedVector<RTLIL::SigBit> &bits) {
for (RTLIL::SigBit candidate : bits) {
cache_result_for_bit(candidate);
cache_result_for_bit(assign_map(candidate));
}
}
};
int count_nontrivial_wire_attrs(RTLIL::Wire *w)
{
int count = w->attributes.size();
count -= w->attributes.count(ID::src);
count -= w->attributes.count(ID::hdlname);
count -= w->attributes.count(ID::scopename);
count -= w->attributes.count(ID::unused_bits);
return count;
}
// Should we pick `s2` over `s1` to represent a signal?
bool compare_signals(const RTLIL::SigBit &s1, const RTLIL::SigBit &s2, const ShardedSigPool &regs, const ShardedSigPool &conns, ExactCellWires &cell_wires)
{
if (s1 == s2)
return false;
RTLIL::Wire *w1 = s1.wire;
RTLIL::Wire *w2 = s2.wire;
if (w1 == NULL || w2 == NULL)
return w2 == NULL;
if (w1->port_input != w2->port_input)
return w2->port_input;
if ((w1->port_input && w1->port_output) != (w2->port_input && w2->port_output))
return !(w2->port_input && w2->port_output);
if (w1->name.isPublic() && w2->name.isPublic()) {
ShardedSigPool::AccumulatedValue s1_val = {s1, s1.hash_top().yield()};
ShardedSigPool::AccumulatedValue s2_val = {s2, s2.hash_top().yield()};
bool regs1 = regs.find(s1_val) != nullptr;
bool regs2 = regs.find(s2_val) != nullptr;
if (regs1 != regs2)
return regs2;
bool w1_exact = cell_wires.is_exactly_cell_driven(w1);
bool w2_exact = cell_wires.is_exactly_cell_driven(w2);
if (w1_exact != w2_exact)
return w2_exact;
bool conns1 = conns.find(s1_val) != nullptr;
bool conns2 = conns.find(s2_val) != nullptr;
if (conns1 != conns2)
return conns2;
}
if (w1 == w2)
return s2.offset < s1.offset;
if (w1->port_output != w2->port_output)
return w2->port_output;
if (w1->name[0] != w2->name[0])
return w2->name.isPublic();
int attrs1 = count_nontrivial_wire_attrs(w1);
int attrs2 = count_nontrivial_wire_attrs(w2);
if (attrs1 != attrs2)
return attrs2 > attrs1;
return w2->name.lt_by_name(w1->name);
}
bool check_public_name(RTLIL::IdString id)
{
if (id.begins_with("$"))
return false;
const std::string &id_str = id.str();
if (id.begins_with("\\_") && (id.ends_with("_") || id_str.find("_[") != std::string::npos))
return false;
if (id_str.find(".$") != std::string::npos)
return false;
return true;
}
void add_spec(ShardedSigPool::Builder &builder, const ThreadIndex &thread, const RTLIL::SigSpec &spec) {
for (SigBit bit : spec)
if (bit.wire != nullptr)
builder.insert(thread, {bit, bit.hash_top().yield()});
}
bool check_any(const ShardedSigPool &sigs, const RTLIL::SigSpec &spec) {
for (SigBit b : spec)
if (sigs.find({b, b.hash_top().yield()}) != nullptr)
return true;
return false;
}
bool check_all(const ShardedSigPool &sigs, const RTLIL::SigSpec &spec) {
for (SigBit b : spec)
if (sigs.find({b, b.hash_top().yield()}) == nullptr)
return false;
return true;
}
struct UpdateConnection {
RTLIL::Cell *cell;
RTLIL::IdString port;
RTLIL::SigSpec spec;
};
void fixup_cell_ports(ShardedVector<UpdateConnection> &update_connections)
{
for (UpdateConnection &update : update_connections)
update.cell->connections_.at(update.port) = std::move(update.spec);
}
struct InitBits {
dict<SigBit, RTLIL::State> values;
// Wires that appear in the keys of the `values` dict
pool<Wire*> wires;
// Set init attributes on all wires of a connected group
void apply_normalised_inits() {
for (RTLIL::Wire *wire : wires) {
bool found = false;
Const val(State::Sx, wire->width);
for (int i = 0; i < wire->width; i++) {
auto it = values.find(RTLIL::SigBit(wire, i));
if (it != values.end()) {
val.set(i, it->second);
found = true;
}
}
if (found)
wire->attributes[ID::init] = val;
}
}
};
static InitBits consume_inits(ShardedVector<RTLIL::Wire*> &initialized_wires, const SigMap &assign_map)
{
InitBits init_bits;
for (RTLIL::Wire *initialized_wire : initialized_wires) {
auto it = initialized_wire->attributes.find(ID::init);
RTLIL::Const &val = it->second;
SigSpec sig = assign_map(initialized_wire);
for (int i = 0; i < GetSize(val) && i < GetSize(sig); i++)
if (val[i] != State::Sx && sig[i].wire != nullptr) {
init_bits.values[sig[i]] = val[i];
init_bits.wires.insert(sig[i].wire);
}
initialized_wire->attributes.erase(it);
}
return init_bits;
}
/**
* What kinds of things are signals connected to?
* Helps pick representatives out of groups of connected signals */
struct SigConnKinds {
// Wire bits directly driven by registers (with clk2fflogic exception)
ShardedSigPool raw_registers;
// Wire bits directly connected to any cell port
ShardedSigPool raw_cell_connected;
// Signals exactly driven by a known cell output,
// this will influence only our choice of representatives.
// A signal is exactly driven by a cell output iff all its bits are driven by this output
// and all bits of this output drive a bit of this signal.
// Additionally, all signals that sigmap to this signal are exactly driven by the port, too
ShardedSigSpecPool exact_cells;
SigConnKinds(bool purge_mode, const AnalysisContext& actx, CleanRunContext& clean_ctx) {
ShardedSigPool::Builder raw_register_builder(actx.subpool);
ShardedSigPool::Builder raw_cell_connected_builder(actx.subpool);
ShardedSigSpecPool::Builder exact_cell_output_builder(actx.subpool);
actx.subpool.run([&exact_cell_output_builder, &raw_register_builder, &raw_cell_connected_builder, purge_mode, &actx, &clean_ctx](const ParallelDispatchThreadPool::RunCtx &ctx) {
for (int i : ctx.item_range(actx.mod->cells_size())) {
RTLIL::Cell *cell = actx.mod->cell_at(i);
if (!purge_mode) {
if (clean_ctx.ct_reg(cell->type)) {
// Improve witness signal naming when clk2fflogic used
// see commit message e36c71b5
bool clk2fflogic = cell->get_bool_attribute(ID::clk2fflogic);
for (auto &[port, sig] : cell->connections())
if (clk2fflogic ? port == ID::D : clean_ctx.ct_all.cell_output(cell->type, port))
add_spec(raw_register_builder, ctx, sig);
}
for (auto &[_, sig] : cell->connections())
add_spec(raw_cell_connected_builder, ctx, sig);
}
if (clean_ctx.ct_all.cell_known(cell->type))
for (auto &[port, sig] : cell->connections())
if (clean_ctx.ct_all.cell_output(cell->type, port)) {
RTLIL::SigSpec spec = actx.assign_map(sig);
unsigned int hash = spec.hash_into(Hasher()).yield();
exact_cell_output_builder.insert(ctx, {std::move(spec), hash});
}
}
});
actx.subpool.run([&raw_register_builder, &raw_cell_connected_builder, &exact_cell_output_builder](const ParallelDispatchThreadPool::RunCtx &ctx) {
raw_register_builder.process(ctx);
raw_cell_connected_builder.process(ctx);
exact_cell_output_builder.process(ctx);
});
raw_registers = raw_register_builder;
raw_cell_connected = raw_cell_connected_builder;
exact_cells = exact_cell_output_builder;
}
void clear(const ParallelDispatchThreadPool::RunCtx &ctx) {
raw_registers.clear(ctx);
raw_cell_connected.clear(ctx);
exact_cells.clear(ctx);
}
};
ShardedVector<RTLIL::SigBit> build_candidates(ExactCellWires& cell_wires, const SigConnKinds& sig_analysis, const AnalysisContext& actx) {
ShardedVector<RTLIL::SigBit> candidates(actx.subpool);
actx.subpool.run([&actx, &sig_analysis, &candidates, &cell_wires](const ParallelDispatchThreadPool::RunCtx &ctx) {
std::optional<ExactCellWires> local_cell_wires;
ExactCellWires *this_thread_cell_wires = &cell_wires;
if (ctx.thread_num > 0) {
local_cell_wires.emplace(sig_analysis.exact_cells, actx.assign_map);
this_thread_cell_wires = &local_cell_wires.value();
}
for (int i : ctx.item_range(actx.mod->wires_size())) {
RTLIL::Wire *wire = actx.mod->wire_at(i);
for (int j = 0; j < wire->width; ++j) {
RTLIL::SigBit s1(wire, j);
RTLIL::SigBit s2 = actx.assign_map(s1);
if (compare_signals(s2, s1, sig_analysis.raw_registers, sig_analysis.raw_cell_connected, *this_thread_cell_wires))
candidates.insert(ctx, s1);
}
}
});
return candidates;
}
void update_assign_map(SigMap& assign_map, ShardedVector<RTLIL::SigBit>& sigmap_canonical_candidates, ExactCellWires& cell_wires, const SigConnKinds& sig_analysis) {
for (RTLIL::SigBit candidate : sigmap_canonical_candidates) {
RTLIL::SigBit current_canonical = assign_map(candidate);
// Resolves if two threads in build_candidates found different candidates
// for the same set
// TODO adds effort for single-threaded?
if (compare_signals(current_canonical, candidate, sig_analysis.raw_registers, sig_analysis.raw_cell_connected, cell_wires))
assign_map.add(candidate);
}
}
struct DeferredUpdates {
// Deferred updates to the assign_map
ShardedVector<UpdateConnection> update_connections;
// Wires we should remove init from
ShardedVector<RTLIL::Wire*> initialized_wires;
DeferredUpdates(ParallelDispatchThreadPool::Subpool &subpool) : update_connections(subpool), initialized_wires(subpool) {}
};
struct UsedSignals {
// here, "connected" means "driven or driving something"
// meanwhile, "used" means "driving something"
// sigmapped
ShardedSigPool connected;
// pre-sigmapped
ShardedSigPool raw_connected;
// sigmapped
ShardedSigPool used;
void clear(ParallelDispatchThreadPool::Subpool &subpool) {
subpool.run([this](const ParallelDispatchThreadPool::RunCtx &ctx) {
connected.clear(ctx);
raw_connected.clear(ctx);
used.clear(ctx);
});
}
};
DeferredUpdates analyse_connectivity(UsedSignals& used, SigConnKinds& sig_analysis, const AnalysisContext& actx, CleanRunContext &clean_ctx) {
DeferredUpdates deferred(actx.subpool);
ShardedSigPool::Builder conn_builder(actx.subpool);
ShardedSigPool::Builder raw_conn_builder(actx.subpool);
ShardedSigPool::Builder used_builder(actx.subpool);
// gather the usage information for cells and update cell connections with the altered sigmap
// also gather the usage information for ports, wires with `keep`
// also gather init bits
actx.subpool.run([&deferred, &conn_builder, &raw_conn_builder, &used_builder, &sig_analysis, &actx, &clean_ctx](const ParallelDispatchThreadPool::RunCtx &ctx) {
// Parallel destruction of these sharded structures
sig_analysis.clear(ctx);
for (int i : ctx.item_range(actx.mod->cells_size())) {
RTLIL::Cell *cell = actx.mod->cell_at(i);
for (const auto &[port, sig] : cell->connections_) {
SigSpec spec = actx.assign_map(sig);
if (spec != sig)
deferred.update_connections.insert(ctx, {cell, port, spec});
add_spec(raw_conn_builder, ctx, spec);
add_spec(conn_builder, ctx, spec);
if (!clean_ctx.ct_all.cell_output(cell->type, port))
add_spec(used_builder, ctx, spec);
}
}
for (int i : ctx.item_range(actx.mod->wires_size())) {
RTLIL::Wire *wire = actx.mod->wire_at(i);
if (wire->port_id > 0) {
RTLIL::SigSpec sig = RTLIL::SigSpec(wire);
add_spec(raw_conn_builder, ctx, sig);
actx.assign_map.apply(sig);
add_spec(conn_builder, ctx, sig);
if (!wire->port_input)
add_spec(used_builder, ctx, sig);
}
if (wire->get_bool_attribute(ID::keep)) {
RTLIL::SigSpec sig = RTLIL::SigSpec(wire);
actx.assign_map.apply(sig);
add_spec(conn_builder, ctx, sig);
}
auto it = wire->attributes.find(ID::init);
if (it != wire->attributes.end())
deferred.initialized_wires.insert(ctx, wire);
}
});
actx.subpool.run([&conn_builder, &raw_conn_builder, &used_builder](const ParallelDispatchThreadPool::RunCtx &ctx) {
conn_builder.process(ctx);
raw_conn_builder.process(ctx);
used_builder.process(ctx);
});
used = {conn_builder, raw_conn_builder, used_builder};
return deferred;
}
struct WireDeleter {
pool<RTLIL::Wire*> del_wires_queue;
ShardedVector<RTLIL::Wire*> remove_init;
ShardedVector<std::pair<RTLIL::Wire*, RTLIL::Const>> set_init;
ShardedVector<RTLIL::SigSig> new_connections;
ShardedVector<RTLIL::Wire*> remove_unused_bits;
ShardedVector<std::pair<RTLIL::Wire*, RTLIL::Const>> set_unused_bits;
WireDeleter(UsedSignals& used_sig_analysis, bool purge_mode, const AnalysisContext& actx) :
remove_init(actx.subpool),
set_init(actx.subpool),
new_connections(actx.subpool),
remove_unused_bits(actx.subpool),
set_unused_bits(actx.subpool) {
ShardedVector<RTLIL::Wire*> del_wires(actx.subpool);
actx.subpool.run([&actx, purge_mode, &del_wires, &used_sig_analysis, this](const ParallelDispatchThreadPool::RunCtx &ctx) {
for (int i : ctx.item_range(actx.mod->wires_size())) {
RTLIL::Wire *wire = actx.mod->wire_at(i);
SigSpec s1 = SigSpec(wire), s2 = actx.assign_map(s1);
log_assert(GetSize(s1) == GetSize(s2));
Const initval;
bool has_init_attribute = wire->attributes.count(ID::init);
bool init_changed = false;
if (has_init_attribute)
initval = wire->attributes.at(ID::init);
if (GetSize(initval) != GetSize(wire)) {
initval.resize(GetSize(wire), State::Sx);
init_changed = true;
}
if (GetSize(wire) == 0) {
// delete zero-width wires, unless they are module ports
if (wire->port_id == 0)
goto delete_this_wire;
} else
if (wire->port_id != 0 || wire->get_bool_attribute(ID::keep) || !initval.is_fully_undef()) {
// do not delete anything with "keep" or module ports or initialized wires
} else
if (!purge_mode && check_public_name(wire->name) && (check_any(used_sig_analysis.raw_connected, s1) || check_any(used_sig_analysis.connected, s2) || s1 != s2)) {
// do not get rid of public names unless in purge mode or if the wire is entirely unused, not even aliased
} else
if (!check_any(used_sig_analysis.raw_connected, s1)) {
// delete wires that aren't used by anything directly
goto delete_this_wire;
}
if (0)
{
delete_this_wire:
del_wires.insert(ctx, wire);
}
else
{
RTLIL::SigSig new_conn;
for (int i = 0; i < GetSize(s1); i++)
if (s1[i] != s2[i]) {
if (s2[i] == State::Sx && (initval[i] == State::S0 || initval[i] == State::S1)) {
s2[i] = initval[i];
initval.set(i, State::Sx);
init_changed = true;
}
new_conn.first.append(s1[i]);
new_conn.second.append(s2[i]);
}
if (new_conn.first.size() > 0)
new_connections.insert(ctx, std::move(new_conn));
if (initval.is_fully_undef()) {
if (has_init_attribute)
remove_init.insert(ctx, wire);
} else
if (init_changed)
set_init.insert(ctx, {wire, std::move(initval)});
std::string unused_bits;
if (!check_all(used_sig_analysis.used, s2)) {
for (int i = 0; i < GetSize(s2); i++) {
if (s2[i].wire == NULL)
continue;
SigBit b = s2[i];
if (used_sig_analysis.used.find({b, b.hash_top().yield()}) == nullptr) {
if (!unused_bits.empty())
unused_bits += " ";
unused_bits += stringf("%d", i);
}
}
}
if (unused_bits.empty() || wire->port_id != 0) {
if (wire->attributes.count(ID::unused_bits))
remove_unused_bits.insert(ctx, wire);
} else {
RTLIL::Const unused_bits_const(std::move(unused_bits));
if (wire->attributes.count(ID::unused_bits)) {
RTLIL::Const &unused_bits_attr = wire->attributes.at(ID::unused_bits);
if (unused_bits_attr != unused_bits_const)
set_unused_bits.insert(ctx, {wire, std::move(unused_bits_const)});
} else
set_unused_bits.insert(ctx, {wire, std::move(unused_bits_const)});
}
}
}
});
del_wires_queue.insert(del_wires.begin(), del_wires.end());
}
// Decide for each wire if we should be deleting it
// and fix up attributes
void commit_changes(RTLIL::Module* mod) {
for (RTLIL::Wire *wire : remove_init)
wire->attributes.erase(ID::init);
for (auto &p : set_init)
p.first->attributes[ID::init] = std::move(p.second);
for (auto &conn : new_connections)
mod->connect(std::move(conn));
for (RTLIL::Wire *wire : remove_unused_bits)
wire->attributes.erase(ID::unused_bits);
for (auto &p : set_unused_bits)
p.first->attributes[ID::unused_bits] = std::move(p.second);
}
int delete_wires(RTLIL::Module* mod, bool verbose) {
int deleted_and_unreported = 0;
for (auto wire : del_wires_queue) {
if (ys_debug() || (check_public_name(wire->name) && verbose))
log_debug(" removing unused non-port wire %s.\n", wire->name);
else
deleted_and_unreported++;
}
mod->remove(del_wires_queue);
return deleted_and_unreported;
}
};
PRIVATE_NAMESPACE_END
YOSYS_NAMESPACE_BEGIN
bool rmunused_module_signals(RTLIL::Module *module, ParallelDispatchThreadPool::Subpool &subpool, CleanRunContext &clean_ctx)
{
// Passing actx to function == function does parallel work
// Not passing module as function argument == function does not modify module
// The above sentence signals intent; it's not enforced due to constness laundering in wire_at / cell_at
AnalysisContext actx(module, subpool);
SigConnKinds conn_kinds(clean_ctx.flags.purge, actx, clean_ctx);
ExactCellWires cell_wires(conn_kinds.exact_cells, actx.assign_map);
// Collect sigmap representative candidates as built in parallel
// With parallel runs, this creates redundant candidates that have to resolve in update_assign_map
ShardedVector<RTLIL::SigBit> new_sigmap_rep_candidates = build_candidates(cell_wires, conn_kinds, actx);
// Cache all the cell_wires results that we might possible need. This avoids the results
// changing when we update `assign_map` below.
cell_wires.cache_all(new_sigmap_rep_candidates);
// Modify assign_map to reflect the connectivity we want, not the one we have
// this changes representative selection in assign_map
update_assign_map(actx.assign_map, new_sigmap_rep_candidates, cell_wires, conn_kinds);
// Remove all wire-wire connections
module->connections_.clear();
UsedSignals used;
DeferredUpdates deferred = analyse_connectivity(used, conn_kinds, actx, clean_ctx);
fixup_cell_ports(deferred.update_connections);
// Rip up and re-apply init attributes onto representative wires with x-bits
// in place of unset init bits
consume_inits(deferred.initialized_wires, actx.assign_map).apply_normalised_inits();
WireDeleter deleter(used, clean_ctx.flags.purge, actx);
used.clear(subpool);
deleter.commit_changes(module);
int deleted_and_unreported = deleter.delete_wires(module, clean_ctx.flags.verbose);
int deleted_total = GetSize(deleter.del_wires_queue);
clean_ctx.stats.count_rm_wires += deleted_total;
if (clean_ctx.flags.verbose && deleted_and_unreported)
log_debug(" removed %d unused temporary wires.\n", deleted_and_unreported);
if (deleted_total)
module->design->scratchpad_set_bool("opt.did_something", true);
return deleted_total != 0;
}
YOSYS_NAMESPACE_END

View file

@ -20,6 +20,7 @@
#include "kernel/register.h"
#include "kernel/sigtools.h"
#include "kernel/celltypes.h"
#include "kernel/newcelltypes.h"
#include "kernel/utils.h"
#include "kernel/log.h"
#include <stdlib.h>
@ -31,7 +32,7 @@ PRIVATE_NAMESPACE_BEGIN
bool did_something;
void replace_undriven(RTLIL::Module *module, const CellTypes &ct)
void replace_undriven(RTLIL::Module *module, const NewCellTypes &ct)
{
SigMap sigmap(module);
SigPool driven_signals;
@ -407,9 +408,6 @@ void replace_const_cells(RTLIL::Design *design, RTLIL::Module *module, bool cons
}
}
CellTypes ct_memcells;
ct_memcells.setup_stdcells_mem();
if (!noclkinv)
for (auto cell : module->cells())
if (design->selected(module, cell)) {
@ -433,7 +431,7 @@ void replace_const_cells(RTLIL::Design *design, RTLIL::Module *module, bool cons
if (cell->type.in(ID($dffe), ID($adffe), ID($aldffe), ID($sdffe), ID($sdffce), ID($dffsre), ID($dlatch), ID($adlatch), ID($dlatchsr)))
handle_polarity_inv(cell, ID::EN, ID::EN_POLARITY, assign_map, invert_map);
if (!ct_memcells.cell_known(cell->type))
if (!StaticCellTypes::Compat::stdcells_mem(cell->type))
continue;
handle_clkpol_celltype_swap(cell, "$_SR_N?_", "$_SR_P?_", ID::S, assign_map, invert_map);
@ -2294,7 +2292,7 @@ struct OptExprPass : public Pass {
}
extra_args(args, argidx, design);
CellTypes ct(design);
NewCellTypes ct(design);
for (auto module : design->selected_modules())
{
log("Optimizing module %s.\n", log_id(module));

View file

@ -39,7 +39,8 @@ struct OptLutInsPass : public Pass {
log("\n");
log(" -tech <technology>\n");
log(" Instead of generic $lut cells, operate on LUT cells specific\n");
log(" to the given technology. Valid values are: xilinx, lattice, gowin.\n");
log(" to the given technology. Valid values are: xilinx, lattice,\n");
log(" gowin, analogdevices.\n");
log("\n");
}
void execute(std::vector<std::string> args, RTLIL::Design *design) override
@ -58,7 +59,7 @@ struct OptLutInsPass : public Pass {
}
extra_args(args, argidx, design);
if (techname != "" && techname != "xilinx" && techname != "lattice" && techname != "ecp5" && techname != "gowin")
if (techname != "" && techname != "xilinx" && techname != "lattice" && techname != "analogdevices" && techname != "gowin")
log_cmd_error("Unsupported technology: '%s'\n", techname);
for (auto module : design->selected_modules())
@ -81,7 +82,7 @@ struct OptLutInsPass : public Pass {
inputs = cell->getPort(ID::A);
output = cell->getPort(ID::Y);
lut = cell->getParam(ID::LUT);
} else if (techname == "xilinx" || techname == "gowin") {
} else if (techname == "xilinx" || techname == "gowin" || techname == "analogdevices") {
if (cell->type == ID(LUT1)) {
inputs = {
cell->getPort(ID(I0)),
@ -126,11 +127,11 @@ struct OptLutInsPass : public Pass {
continue;
}
lut = cell->getParam(ID::INIT);
if (techname == "xilinx")
if (techname == "xilinx" || techname == "analogdevices")
output = cell->getPort(ID::O);
else
output = cell->getPort(ID::F);
} else if (techname == "lattice" || techname == "ecp5") {
} else if (techname == "lattice") {
if (cell->type == ID(LUT4)) {
inputs = {
cell->getPort(ID::A),
@ -236,7 +237,7 @@ struct OptLutInsPass : public Pass {
} else {
// xilinx, gowin
cell->setParam(ID::INIT, new_lut);
if (techname == "xilinx")
if (techname == "xilinx" || techname == "analogdevices")
log_assert(GetSize(new_inputs) <= 6);
else
log_assert(GetSize(new_inputs) <= 4);

View file

@ -21,11 +21,9 @@
#include "kernel/sigtools.h"
#include "kernel/log.h"
#include "kernel/celltypes.h"
#include <cstddef>
#include <stdlib.h>
#include <stdio.h>
#include <unordered_map>
#include <unordered_set>
#include <set>
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
@ -128,7 +126,7 @@ struct OptMuxtreeWorker
// In case of $pmux, port B is multiple slices, concatenated, one per bit of port S
for (int i = 0; i < GetSize(sig_s); i++) {
RTLIL::SigSpec sig = sig_b.extract(i*GetSize(sig_a), GetSize(sig_a));
RTLIL::SigSpec ctrl_sig = assign_map(sig_s.extract(i, 1));
RTLIL::SigSpec ctrl_sig = assign_map(SigSpec{sig_s[i]});
portinfo_t portinfo = used_port_bit(sig, this_mux_idx);
portinfo.ctrl_sig = sig2bits(ctrl_sig, false).front();
portinfo.const_activated = ctrl_sig.is_fully_const() && ctrl_sig.as_bool();
@ -342,14 +340,21 @@ struct OptMuxtreeWorker
// The payload is a reference counter used to manage the list
// When it is non-zero, the signal in known to be inactive
// When it reaches zero, the map element is removed
std::unordered_map<int, int> known_inactive;
std::vector<int> known_inactive;
// database of known active signals
std::unordered_map<int, int> known_active;
std::vector<int> known_active;
// this is just used to keep track of visited muxes in order to prohibit
// endless recursion in mux loops
std::unordered_set<int> visited_muxes;
std::vector<bool> visited_muxes;
// Initialize with the maximum possible sizes
knowledge_t(int num_bits, int num_muxes) {
known_inactive.assign(num_bits, 0);
known_active.assign(num_bits, 0);
visited_muxes.assign(num_muxes, false);
}
};
static void activate_port(knowledge_t &knowledge, int port_idx, const muxinfo_t &muxinfo) {
@ -366,11 +371,10 @@ struct OptMuxtreeWorker
}
static void deactivate_port(knowledge_t &knowledge, int port_idx, const muxinfo_t &muxinfo) {
auto unlearn = [](std::unordered_map<int, int>& knowns, int i) {
auto it = knowns.find(i);
if (it != knowns.end())
if (--it->second == 0)
knowns.erase(it);
auto unlearn = [](std::vector<int>& knowns, int bit_idx) {
if (knowns[bit_idx] > 0) {
--knowns[bit_idx];
}
};
if (port_idx < GetSize(muxinfo.ports)-1 && !muxinfo.ports[port_idx].const_activated)
@ -418,9 +422,9 @@ struct OptMuxtreeWorker
vector<int> input_mux_queue;
for (int m : muxinfo.ports[port_idx].input_muxes) {
if (knowledge.visited_muxes.count(m))
if (knowledge.visited_muxes[m])
continue;
knowledge.visited_muxes.insert(m);
knowledge.visited_muxes[m] = true;
input_mux_queue.push_back(m);
}
for (int m : input_mux_queue) {
@ -453,7 +457,7 @@ struct OptMuxtreeWorker
// Allow revisiting input muxes, since evaluating other ports should
// revisit these input muxes with different activation assumptions
for (int m : input_mux_queue)
knowledge.visited_muxes.erase(m);
knowledge.visited_muxes[m] = false;
// Undo our assumptions that the port is active
deactivate_port(knowledge, port_idx, muxinfo);
@ -475,11 +479,11 @@ struct OptMuxtreeWorker
vector<int> bits = sig2bits(sig, false);
for (int i = 0; i < GetSize(bits); i++) {
if (bits[i] >= 0) {
if (knowledge.known_inactive.count(bits[i]) > 0) {
if (knowledge.known_inactive[bits[i]] > 0) {
sig[i] = State::S0;
did_something = true;
} else
if (knowledge.known_active.count(bits[i]) > 0) {
if (knowledge.known_active[bits[i]] > 0) {
sig[i] = State::S1;
did_something = true;
}
@ -552,7 +556,7 @@ struct OptMuxtreeWorker
portinfo_t &portinfo = muxinfo.ports[port_idx];
if (portinfo.const_deactivated)
continue;
if (knowledge.known_active.count(portinfo.ctrl_sig) > 0) {
if (knowledge.known_active[portinfo.ctrl_sig] > 0) {
eval_mux_port(knowledge, mux_idx, port_idx, limits);
return;
}
@ -566,7 +570,7 @@ struct OptMuxtreeWorker
if (portinfo.const_deactivated)
continue;
if (port_idx < GetSize(muxinfo.ports)-1)
if (knowledge.known_inactive.count(portinfo.ctrl_sig) > 0)
if (knowledge.known_inactive[portinfo.ctrl_sig] > 0)
continue;
eval_mux_port(knowledge, mux_idx, port_idx, limits);
@ -578,8 +582,8 @@ struct OptMuxtreeWorker
void eval_root_mux(int mux_idx)
{
log_assert(glob_evals_left > 0);
knowledge_t knowledge;
knowledge.visited_muxes.insert(mux_idx);
knowledge_t knowledge(GetSize(bit2info), GetSize(mux2info));
knowledge.visited_muxes[mux_idx] = true;
limits_t limits = {};
limits.do_mark_ports_observable = root_enable_muxes.at(mux_idx);
eval_mux(knowledge, mux_idx, limits);

View file

@ -110,22 +110,20 @@ struct OptReduceWorker
RTLIL::SigSpec sig_s = assign_map(cell->getPort(ID::S));
RTLIL::SigSpec new_sig_b, new_sig_s;
pool<RTLIL::SigSpec> handled_sig;
dict<RTLIL::SigSpec, std::vector<RTLIL::SigBit>> grouped_b_to_s;
handled_sig.insert(sig_a);
for (int i = 0; i < sig_s.size(); i++)
{
RTLIL::SigSpec this_b = sig_b.extract(i*sig_a.size(), sig_a.size());
if (handled_sig.count(this_b) > 0)
continue;
RTLIL::SigSpec this_s = sig_s.extract(i, 1);
for (int j = i+1; j < sig_s.size(); j++) {
RTLIL::SigSpec that_b = sig_b.extract(j*sig_a.size(), sig_a.size());
if (this_b == that_b)
this_s.append(sig_s.extract(j, 1));
int port_width = sig_a.size();
for (int i = 0; i < sig_s.size(); i++) {
RTLIL::SigSpec this_b = sig_b.extract(i*port_width, port_width);
if (grouped_b_to_s.count(this_b)) {
grouped_b_to_s[this_b].push_back(sig_s[i]);
} else {
grouped_b_to_s[this_b] = {sig_s[i]};
}
}
for (auto &[this_b, this_s_bit] : grouped_b_to_s) {
RTLIL::SigSpec this_s{this_s_bit};
if (this_s.size() > 1)
{
RTLIL::Cell *reduce_or_cell = module->addCell(NEW_ID, ID($reduce_or));
@ -141,7 +139,6 @@ struct OptReduceWorker
new_sig_b.append(this_b);
new_sig_s.append(this_s);
handled_sig.insert(this_b);
}
if (new_sig_s.size() == 0)

View file

@ -23,6 +23,7 @@
#include "kernel/modtools.h"
#include "kernel/utils.h"
#include "kernel/macc.h"
#include "kernel/newcelltypes.h"
#include <iterator>
USING_YOSYS_NAMESPACE
@ -35,22 +36,20 @@ struct ShareWorkerConfig
{
int limit;
size_t pattern_limit;
bool opt_force;
bool opt_aggressive;
bool opt_fast;
pool<RTLIL::IdString> generic_uni_ops, generic_bin_ops, generic_cbin_ops, generic_other_ops;
StaticCellTypes::Categories::Category generic_uni_ops, generic_bin_ops, generic_cbin_ops, generic_other_ops;
};
struct ShareWorker
{
const ShareWorkerConfig config;
int limit;
pool<RTLIL::IdString> generic_ops;
StaticCellTypes::Categories::Category generic_ops;
RTLIL::Design *design;
RTLIL::Module *module;
CellTypes fwd_ct, cone_ct;
ModWalker modwalker;
pool<RTLIL::Cell*> cells_to_remove;
@ -75,7 +74,7 @@ struct ShareWorker
queue_bits.insert(modwalker.signal_outputs.begin(), modwalker.signal_outputs.end());
for (auto &it : module->cells_)
if (!fwd_ct.cell_known(it.second->type)) {
if (!StaticCellTypes::Compat::internals_nomem_noff(it.second->type)) {
pool<RTLIL::SigBit> &bits = modwalker.cell_inputs[it.second];
queue_bits.insert(bits.begin(), bits.end());
}
@ -95,7 +94,7 @@ struct ShareWorker
queue_bits.insert(bits.begin(), bits.end());
visited_cells.insert(pbit.cell);
}
if (fwd_ct.cell_known(pbit.cell->type) && visited_cells.count(pbit.cell) == 0) {
if (StaticCellTypes::Compat::internals_nomem_noff(pbit.cell->type) && visited_cells.count(pbit.cell) == 0) {
pool<RTLIL::SigBit> &bits = modwalker.cell_inputs[pbit.cell];
terminal_bits.insert(bits.begin(), bits.end());
queue_bits.insert(bits.begin(), bits.end());
@ -363,11 +362,6 @@ struct ShareWorker
not_a_muxed_cell:
continue;
if (config.opt_force) {
shareable_cells.insert(cell);
continue;
}
if (cell->type.in(ID($memrd), ID($memrd_v2))) {
if (cell->parameters.at(ID::CLK_ENABLE).as_bool())
continue;
@ -388,7 +382,7 @@ struct ShareWorker
continue;
}
if (generic_ops.count(cell->type)) {
if (generic_ops(cell->type)) {
if (config.opt_aggressive)
shareable_cells.insert(cell);
continue;
@ -412,7 +406,7 @@ struct ShareWorker
return true;
}
if (config.generic_uni_ops.count(c1->type))
if (config.generic_uni_ops(c1->type))
{
if (!config.opt_aggressive)
{
@ -429,7 +423,7 @@ struct ShareWorker
return true;
}
if (config.generic_bin_ops.count(c1->type) || c1->type == ID($alu))
if (config.generic_bin_ops(c1->type) || c1->type == ID($alu))
{
if (!config.opt_aggressive)
{
@ -449,7 +443,7 @@ struct ShareWorker
return true;
}
if (config.generic_cbin_ops.count(c1->type))
if (config.generic_cbin_ops(c1->type))
{
if (!config.opt_aggressive)
{
@ -511,7 +505,7 @@ struct ShareWorker
{
log_assert(c1->type == c2->type);
if (config.generic_uni_ops.count(c1->type))
if (config.generic_uni_ops(c1->type))
{
if (c1->parameters.at(ID::A_SIGNED).as_bool() != c2->parameters.at(ID::A_SIGNED).as_bool())
{
@ -560,11 +554,11 @@ struct ShareWorker
return supercell;
}
if (config.generic_bin_ops.count(c1->type) || config.generic_cbin_ops.count(c1->type) || c1->type == ID($alu))
if (config.generic_bin_ops(c1->type) || config.generic_cbin_ops(c1->type) || c1->type == ID($alu))
{
bool modified_src_cells = false;
if (config.generic_cbin_ops.count(c1->type))
if (config.generic_cbin_ops(c1->type))
{
int score_unflipped = max(c1->parameters.at(ID::A_WIDTH).as_int(), c2->parameters.at(ID::A_WIDTH).as_int()) +
max(c1->parameters.at(ID::B_WIDTH).as_int(), c2->parameters.at(ID::B_WIDTH).as_int());
@ -758,7 +752,7 @@ struct ShareWorker
recursion_state.insert(cell);
for (auto c : consumer_cells)
if (fwd_ct.cell_known(c->type)) {
if (StaticCellTypes::Compat::internals_nomem_noff(c->type)) {
const pool<RTLIL::SigBit> &bits = find_forbidden_controls(c);
forbidden_controls_cache[cell].insert(bits.begin(), bits.end());
}
@ -897,7 +891,7 @@ struct ShareWorker
return activation_patterns_cache.at(cell);
}
for (auto &pbit : modwalker.signal_consumers[bit]) {
log_assert(fwd_ct.cell_known(pbit.cell->type));
log_assert(StaticCellTypes::Compat::internals_nomem_noff(pbit.cell->type));
if ((pbit.cell->type == ID($mux) || pbit.cell->type == ID($pmux)) && (pbit.port == ID::A || pbit.port == ID::B))
driven_data_muxes.insert(pbit.cell);
else
@ -1214,24 +1208,10 @@ struct ShareWorker
ShareWorker(ShareWorkerConfig config, RTLIL::Design* design) :
config(config), design(design), modwalker(design)
{
generic_ops.insert(config.generic_uni_ops.begin(), config.generic_uni_ops.end());
generic_ops.insert(config.generic_bin_ops.begin(), config.generic_bin_ops.end());
generic_ops.insert(config.generic_cbin_ops.begin(), config.generic_cbin_ops.end());
generic_ops.insert(config.generic_other_ops.begin(), config.generic_other_ops.end());
fwd_ct.setup_internals();
cone_ct.setup_internals();
cone_ct.cell_types.erase(ID($mul));
cone_ct.cell_types.erase(ID($mod));
cone_ct.cell_types.erase(ID($div));
cone_ct.cell_types.erase(ID($modfloor));
cone_ct.cell_types.erase(ID($divfloor));
cone_ct.cell_types.erase(ID($pow));
cone_ct.cell_types.erase(ID($shl));
cone_ct.cell_types.erase(ID($shr));
cone_ct.cell_types.erase(ID($sshl));
cone_ct.cell_types.erase(ID($sshr));
generic_ops = StaticCellTypes::Categories::join(generic_ops, config.generic_uni_ops);
generic_ops = StaticCellTypes::Categories::join(generic_ops, config.generic_bin_ops);
generic_ops = StaticCellTypes::Categories::join(generic_ops, config.generic_cbin_ops);
generic_ops = StaticCellTypes::Categories::join(generic_ops, config.generic_other_ops);
}
void operator()(RTLIL::Module *module) {
@ -1523,14 +1503,6 @@ struct SharePass : public Pass {
log("This pass merges shareable resources into a single resource. A SAT solver\n");
log("is used to determine if two resources are share-able.\n");
log("\n");
log(" -force\n");
log(" Per default the selection of cells that is considered for sharing is\n");
log(" narrowed using a list of cell types. With this option all selected\n");
log(" cells are considered for resource sharing.\n");
log("\n");
log(" IMPORTANT NOTE: If the -all option is used then no cells with internal\n");
log(" state must be selected!\n");
log("\n");
log(" -aggressive\n");
log(" Per default some heuristics are used to reduce the number of cells\n");
log(" considered for resource sharing to only large resources. This options\n");
@ -1557,58 +1529,53 @@ struct SharePass : public Pass {
config.limit = -1;
config.pattern_limit = design->scratchpad_get_int("share.pattern_limit", 1000);
config.opt_force = false;
config.opt_aggressive = false;
config.opt_fast = false;
config.generic_uni_ops.insert(ID($not));
// config.generic_uni_ops.insert(ID($pos));
config.generic_uni_ops.insert(ID($neg));
config.generic_uni_ops.set_id(ID($not));
// config.generic_uni_ops.set_id(ID($pos));
config.generic_uni_ops.set_id(ID($neg));
config.generic_cbin_ops.insert(ID($and));
config.generic_cbin_ops.insert(ID($or));
config.generic_cbin_ops.insert(ID($xor));
config.generic_cbin_ops.insert(ID($xnor));
config.generic_cbin_ops.set_id(ID($and));
config.generic_cbin_ops.set_id(ID($or));
config.generic_cbin_ops.set_id(ID($xor));
config.generic_cbin_ops.set_id(ID($xnor));
config.generic_bin_ops.insert(ID($shl));
config.generic_bin_ops.insert(ID($shr));
config.generic_bin_ops.insert(ID($sshl));
config.generic_bin_ops.insert(ID($sshr));
config.generic_bin_ops.set_id(ID($shl));
config.generic_bin_ops.set_id(ID($shr));
config.generic_bin_ops.set_id(ID($sshl));
config.generic_bin_ops.set_id(ID($sshr));
config.generic_bin_ops.insert(ID($lt));
config.generic_bin_ops.insert(ID($le));
config.generic_bin_ops.insert(ID($eq));
config.generic_bin_ops.insert(ID($ne));
config.generic_bin_ops.insert(ID($eqx));
config.generic_bin_ops.insert(ID($nex));
config.generic_bin_ops.insert(ID($ge));
config.generic_bin_ops.insert(ID($gt));
config.generic_bin_ops.set_id(ID($lt));
config.generic_bin_ops.set_id(ID($le));
config.generic_bin_ops.set_id(ID($eq));
config.generic_bin_ops.set_id(ID($ne));
config.generic_bin_ops.set_id(ID($eqx));
config.generic_bin_ops.set_id(ID($nex));
config.generic_bin_ops.set_id(ID($ge));
config.generic_bin_ops.set_id(ID($gt));
config.generic_cbin_ops.insert(ID($add));
config.generic_cbin_ops.insert(ID($mul));
config.generic_cbin_ops.set_id(ID($add));
config.generic_cbin_ops.set_id(ID($mul));
config.generic_bin_ops.insert(ID($sub));
config.generic_bin_ops.insert(ID($div));
config.generic_bin_ops.insert(ID($mod));
config.generic_bin_ops.insert(ID($divfloor));
config.generic_bin_ops.insert(ID($modfloor));
// config.generic_bin_ops.insert(ID($pow));
config.generic_bin_ops.set_id(ID($sub));
config.generic_bin_ops.set_id(ID($div));
config.generic_bin_ops.set_id(ID($mod));
config.generic_bin_ops.set_id(ID($divfloor));
config.generic_bin_ops.set_id(ID($modfloor));
// config.generic_bin_ops.set_id(ID($pow));
config.generic_uni_ops.insert(ID($logic_not));
config.generic_cbin_ops.insert(ID($logic_and));
config.generic_cbin_ops.insert(ID($logic_or));
config.generic_uni_ops.set_id(ID($logic_not));
config.generic_cbin_ops.set_id(ID($logic_and));
config.generic_cbin_ops.set_id(ID($logic_or));
config.generic_other_ops.insert(ID($alu));
config.generic_other_ops.insert(ID($macc));
config.generic_other_ops.set_id(ID($alu));
config.generic_other_ops.set_id(ID($macc));
log_header(design, "Executing SHARE pass (SAT-based resource sharing).\n");
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++) {
if (args[argidx] == "-force") {
config.opt_force = true;
continue;
}
if (args[argidx] == "-aggressive") {
config.opt_aggressive = true;
continue;

View file

@ -158,7 +158,7 @@ in `select` lines.
Index lines are using the `index <type> expr1 === expr2` syntax. `expr1` is
evaluated during matcher initialization and the same restrictions apply as for
`select` expressions. `expr2` is evaluated when the match is calulated. It is a
`select` expressions. `expr2` is evaluated when the match is calculated. It is a
function of any state variables assigned to by previous blocks. Both expression
are converted to the given type and compared for equality. Only cells for which
all `index` statements in the block pass are considered by the match.

View file

@ -157,6 +157,7 @@ struct Async2syncPass : public Pass {
SigSpec sig_set = ff.sig_set;
SigSpec sig_clr = ff.sig_clr;
SigSpec sig_clr_inv = ff.sig_clr;
if (!ff.pol_set) {
if (!ff.is_fine)
@ -166,24 +167,42 @@ struct Async2syncPass : public Pass {
}
if (ff.pol_clr) {
if (!ff.is_fine)
sig_clr_inv = module->Not(NEW_ID, sig_clr);
else
sig_clr_inv = module->NotGate(NEW_ID, sig_clr);
} else {
if (!ff.is_fine)
sig_clr = module->Not(NEW_ID, sig_clr);
else
sig_clr = module->NotGate(NEW_ID, sig_clr);
}
// At this point, sig_set and sig_clr are now unconditionally
// active-high, and sig_clr_inv is inverted sig_clr
SigSpec set_and_clr;
if (!ff.is_fine)
set_and_clr = module->And(NEW_ID, sig_set, sig_clr);
else
set_and_clr = module->AndGate(NEW_ID, sig_set, sig_clr);
if (!ff.is_fine) {
SigSpec tmp = module->Or(NEW_ID, ff.sig_d, sig_set);
module->addAnd(NEW_ID, tmp, sig_clr, new_d);
tmp = module->And(NEW_ID, tmp, sig_clr_inv);
module->addBwmux(NEW_ID, tmp, Const(State::Sx, ff.width), set_and_clr, new_d);
tmp = module->Or(NEW_ID, new_q, sig_set);
module->addAnd(NEW_ID, tmp, sig_clr, ff.sig_q);
tmp = module->And(NEW_ID, tmp, sig_clr_inv);
module->addBwmux(NEW_ID, tmp, Const(State::Sx, ff.width), set_and_clr, ff.sig_q);
} else {
SigSpec tmp = module->OrGate(NEW_ID, ff.sig_d, sig_set);
module->addAndGate(NEW_ID, tmp, sig_clr, new_d);
tmp = module->AndGate(NEW_ID, tmp, sig_clr_inv);
module->addMuxGate(NEW_ID, tmp, State::Sx, set_and_clr, new_d);
tmp = module->OrGate(NEW_ID, new_q, sig_set);
module->addAndGate(NEW_ID, tmp, sig_clr, ff.sig_q);
tmp = module->AndGate(NEW_ID, tmp, sig_clr_inv);
module->addMuxGate(NEW_ID, tmp, State::Sx, set_and_clr, ff.sig_q);
}
ff.sig_d = new_d;

View file

@ -123,10 +123,14 @@ struct Clk2fflogicPass : public Pass {
return module->Mux(NEW_ID, a, b, s);
}
SigSpec bitwise_sr(Module *module, SigSpec a, SigSpec s, SigSpec r, bool is_fine) {
if (is_fine)
return module->AndGate(NEW_ID, module->OrGate(NEW_ID, a, s), module->NotGate(NEW_ID, r));
else
return module->And(NEW_ID, module->Or(NEW_ID, a, s), module->Not(NEW_ID, r));
if (is_fine) {
return module->MuxGate(NEW_ID, module->AndGate(NEW_ID, module->OrGate(NEW_ID, a, s), module->NotGate(NEW_ID, r)), RTLIL::State::Sx, module->AndGate(NEW_ID, s, r));
} else {
std::vector<SigBit> y;
for (int i = 0; i < a.size(); i++)
y.push_back(module->MuxGate(NEW_ID, module->AndGate(NEW_ID, module->OrGate(NEW_ID, a[i], s[i]), module->NotGate(NEW_ID, r[i])), RTLIL::State::Sx, module->AndGate(NEW_ID, s[i], r[i])));
return y;
}
}
void execute(std::vector<std::string> args, RTLIL::Design *design) override
{

View file

@ -20,6 +20,7 @@
#include "kernel/yosys.h"
#include "kernel/sigtools.h"
#include "kernel/celltypes.h"
#include "kernel/newcelltypes.h"
#include "kernel/mem.h"
#include "kernel/fstdata.h"
#include "kernel/ff.h"
@ -52,9 +53,23 @@ static const std::map<std::string, int> g_units =
{ "zs", -21 },
};
static double stringToTime(std::string str)
struct scaled_time {
uint64_t time;
int scale; // exponent of 10, e.g. -6 = us, -9 = ns
bool end;
};
static uint64_t pow10(int n)
{
if (str=="END") return -1;
int r = 1;
while (n--)
r *= 10;
return r;
}
static scaled_time stringToTime(std::string str)
{
if (str=="END") return {1, 0, true};
char *endptr;
long value = strtol(str.c_str(), &endptr, 10);
@ -65,7 +80,7 @@ static double stringToTime(std::string str)
if (value < 0)
log_error("Time value '%s' must be positive\n", str);
return value * pow(10.0, g_units.at(endptr));
return {(unsigned long)value, g_units.at(endptr), false};
}
struct SimWorker;
@ -109,8 +124,8 @@ struct SimShared
bool hdlname = false;
int rstlen = 1;
FstData *fst = nullptr;
double start_time = 0;
double stop_time = -1;
scaled_time start_time = {0, 0, false};
scaled_time stop_time = {1, 0, true};
SimulationMode sim_mode = SimulationMode::sim;
bool cycles_set = false;
std::vector<std::unique_ptr<OutputWriter>> outputfiles;
@ -215,7 +230,13 @@ struct SimInstance
std::vector<Mem> memories;
dict<Wire*, pair<int, Const>> signal_database;
struct signal_entry_t {
int id;
Const last_value;
SigSpec mapped_sig;
};
dict<Wire*, signal_entry_t> signal_database;
dict<IdString, std::map<int, pair<int, Const>>> trace_mem_database;
dict<std::pair<IdString, int>, Const> trace_mem_init_database;
dict<Wire*, fstHandle> fst_handles;
@ -412,11 +433,11 @@ struct SimInstance
return result;
}
Const get_state(SigSpec sig)
Const get_state_mapped(const SigSpec &mapped_sig)
{
Const::Builder builder(GetSize(sig));
Const::Builder builder(GetSize(mapped_sig));
for (auto bit : sigmap(sig))
for (auto bit : mapped_sig)
if (bit.wire == nullptr)
builder.push_back(bit.data);
else if (state_nets.count(bit))
@ -424,7 +445,12 @@ struct SimInstance
else
builder.push_back(State::Sz);
Const value = builder.build();
return builder.build();
}
Const get_state(SigSpec sig)
{
Const value = get_state_mapped(sigmap(sig));
if (shared->debug)
log("[%s] get %s: %s\n", hiername(), log_signal(sig), log_signal(value));
return value;
@ -990,7 +1016,7 @@ struct SimInstance
if (shared->hide_internal && wire->name[0] == '$')
continue;
signal_database[wire] = make_pair(id, Const());
signal_database[wire] = {id, Const(), sigmap(wire)};
id++;
}
@ -1031,11 +1057,11 @@ struct SimInstance
hdlname.pop_back();
for (auto name : hdlname)
enter_scope("\\" + name);
register_signal(signal_name.c_str(), GetSize(signal.first), signal.first, signal.second.first, registers.count(signal.first)!=0);
register_signal(signal_name.c_str(), GetSize(signal.first), signal.first, signal.second.id, registers.count(signal.first)!=0);
for (auto name : hdlname)
exit_scope();
} else
register_signal(log_id(signal.first->name), GetSize(signal.first), signal.first, signal.second.first, registers.count(signal.first)!=0);
register_signal(log_id(signal.first->name), GetSize(signal.first), signal.first, signal.second.id, registers.count(signal.first)!=0);
}
for (auto &trace_mem : trace_mem_database)
@ -1107,15 +1133,14 @@ struct SimInstance
{
for (auto &it : signal_database)
{
Wire *wire = it.first;
Const value = get_state(wire);
int id = it.second.first;
signal_entry_t &entry = it.second;
Const value = get_state_mapped(entry.mapped_sig);
if (it.second.second == value)
if (entry.last_value == value)
continue;
it.second.second = value;
data->emplace(id, value);
entry.last_value = value;
data->emplace(entry.id, value);
}
for (auto &trace_mem : trace_mem_database)
@ -1234,6 +1259,10 @@ struct SimInstance
bool checkSignals()
{
// No checks performed when using stimulus
if (shared->sim_mode == SimulationMode::sim)
return false;
bool retVal = false;
for(auto &item : fst_handles) {
if (item.second==0) continue; // Ignore signals not found
@ -1243,9 +1272,7 @@ struct SimInstance
log_warning("Signal '%s.%s' size is different in gold and gate.\n", scope, log_id(item.first));
continue;
}
if (shared->sim_mode == SimulationMode::sim) {
// No checks performed when using stimulus
} else if (shared->sim_mode == SimulationMode::gate && !fst_val.is_fully_def()) { // FST data contains X
if (shared->sim_mode == SimulationMode::gate && !fst_val.is_fully_def()) { // FST data contains X
for(int i=0;i<fst_val.size();i++) {
if (fst_val[i]!=State::Sx && fst_val[i]!=sim_val[i]) {
log_warning("Signal '%s.%s' in file %s in simulation %s\n", scope, log_id(item.first), log_signal(fst_val), log_signal(sim_val));
@ -1501,27 +1528,27 @@ struct SimWorker : SimShared
uint64_t startCount = 0;
uint64_t stopCount = 0;
if (start_time==0) {
if (start_time < fst->getStartTime())
if (start_time.time == 0) {
if (start_time.time < fst->getStartTime())
log_warning("Start time is before simulation file start time\n");
startCount = fst->getStartTime();
} else if (start_time==-1)
} else if (start_time.end)
startCount = fst->getEndTime();
else {
startCount = start_time / fst->getTimescale();
startCount = start_time.time * pow10(start_time.scale - fst->getScale());
if (startCount > fst->getEndTime()) {
startCount = fst->getEndTime();
log_warning("Start time is after simulation file end time\n");
}
}
if (stop_time==0) {
if (stop_time < fst->getStartTime())
if (stop_time.time == 0) {
if (stop_time.time < fst->getStartTime())
log_warning("Stop time is before simulation file start time\n");
stopCount = fst->getStartTime();
} else if (stop_time==-1)
} else if (stop_time.end)
stopCount = fst->getEndTime();
else {
stopCount = stop_time / fst->getTimescale();
stopCount = stop_time.time * pow10(stop_time.scale - fst->getScale());
if (stopCount > fst->getEndTime()) {
stopCount = fst->getEndTime();
log_warning("Stop time is after simulation file end time\n");
@ -2161,27 +2188,27 @@ struct SimWorker : SimShared
uint64_t startCount = 0;
uint64_t stopCount = 0;
if (start_time==0) {
if (start_time < fst->getStartTime())
if (start_time.time == 0) {
if (start_time.time < fst->getStartTime())
log_warning("Start time is before simulation file start time\n");
startCount = fst->getStartTime();
} else if (start_time==-1)
} else if (start_time.end)
startCount = fst->getEndTime();
else {
startCount = start_time / fst->getTimescale();
startCount = start_time.time * pow10(start_time.scale - fst->getScale());
if (startCount > fst->getEndTime()) {
startCount = fst->getEndTime();
log_warning("Start time is after simulation file end time\n");
}
}
if (stop_time==0) {
if (stop_time < fst->getStartTime())
if (stop_time.time == 0) {
if (stop_time.time < fst->getStartTime())
log_warning("Stop time is before simulation file start time\n");
stopCount = fst->getStartTime();
} else if (stop_time==-1)
} else if (stop_time.end)
stopCount = fst->getEndTime();
else {
stopCount = stop_time / fst->getTimescale();
stopCount = stop_time.time * pow10(stop_time.scale - fst->getScale());
if (stopCount > fst->getEndTime()) {
stopCount = fst->getEndTime();
log_warning("Stop time is after simulation file end time\n");

View file

@ -55,6 +55,7 @@ OBJS += passes/techmap/extractinv.o
OBJS += passes/techmap/cellmatch.o
OBJS += passes/techmap/clockgate.o
OBJS += passes/techmap/constmap.o
OBJS += passes/techmap/arith_tree.o
endif
ifeq ($(DISABLE_SPAWN),0)

View file

@ -43,7 +43,7 @@
#include "kernel/register.h"
#include "kernel/sigtools.h"
#include "kernel/celltypes.h"
#include "kernel/newcelltypes.h"
#include "kernel/ffinit.h"
#include "kernel/ff.h"
#include "kernel/cost.h"
@ -63,13 +63,19 @@
# include <fcntl.h>
# include <spawn.h>
# include <sys/wait.h>
# include <sys/stat.h>
#endif
#ifndef _WIN32
# include <unistd.h>
# include <dirent.h>
# include <sys/stat.h>
#endif
#if defined(__wasm)
#include <wasi/libc.h>
#endif
#include "frontends/blif/blifparse.h"
#include "liberty_cache.h"
#ifdef YOSYS_LINK_ABC
namespace abc {
@ -130,7 +136,6 @@ struct AbcConfig
std::string delay_target;
std::string sop_inputs;
std::string sop_products;
std::string lutin_shared;
std::vector<std::string> dont_use_cells;
bool cleanup = true;
bool keepff = false;
@ -292,6 +297,8 @@ struct RunAbcState {
bool err = false;
DeferredLogs logs;
dict<int, std::string> pi_map, po_map;
std::string abc_script;
std::string dont_use_args;
RunAbcState(const AbcConfig &config) : config(config) {}
void run(ConcurrentStack<AbcProcess> &process_pool);
@ -1016,89 +1023,95 @@ void AbcModuleState::prepare_module(RTLIL::Design *design, RTLIL::Module *module
log_header(design, "Extracting gate netlist of module `%s' to `%s/input.blif'..\n",
module->name.c_str(), replace_tempdir(run_abc.per_run_tempdir_name, config.global_tempdir_name, run_abc.per_run_tempdir_name, config.show_tempdir).c_str());
std::string abc_script = stringf("read_blif \"%s/input.blif\"; ", run_abc.per_run_tempdir_name);
run_abc.abc_script = stringf("read_blif \"%s/input.blif\"; ", run_abc.per_run_tempdir_name);
if (!config.liberty_files.empty() || !config.genlib_files.empty()) {
std::string dont_use_args;
run_abc.dont_use_args = "";
for (std::string dont_use_cell : config.dont_use_cells) {
dont_use_args += stringf("-X \"%s\" ", dont_use_cell);
run_abc.dont_use_args += stringf("-X \"%s\" ", dont_use_cell);
}
bool first_lib = true;
for (std::string liberty_file : config.liberty_files) {
abc_script += stringf("read_lib %s %s %s -w \"%s\" ; ", dont_use_args, first_lib ? "" : "-m", config.abc_liberty_args, liberty_file);
first_lib = false;
std::string merged_scl = convert_liberty_files_to_merged_scl(config.liberty_files, run_abc.dont_use_args, config.exe_file);
if (!merged_scl.empty()) {
run_abc.abc_script += stringf("read_scl \"%s\" ; ", merged_scl.c_str());
} else if(!config.liberty_files.empty()) {
log_warning("ABC: Merged scl conversion failed, using liberty format\n");
bool first_lib = true;
for (std::string liberty_file : config.liberty_files) {
run_abc.abc_script += stringf("read_lib %s %s %s -w \"%s\" ; ", run_abc.dont_use_args, first_lib ? "" : "-m", config.abc_liberty_args, liberty_file);
first_lib = false;
}
}
for (std::string liberty_file : config.genlib_files)
abc_script += stringf("read_library \"%s\"; ", liberty_file);
run_abc.abc_script += stringf("read_library \"%s\"; ", liberty_file);
if (!config.constr_file.empty())
abc_script += stringf("read_constr -v \"%s\"; ", config.constr_file);
run_abc.abc_script += stringf("read_constr -v \"%s\"; ", config.constr_file);
} else
if (!config.lut_costs.empty())
abc_script += stringf("read_lut %s/lutdefs.txt; ", config.global_tempdir_name);
run_abc.abc_script += stringf("read_lut %s/lutdefs.txt; ", config.global_tempdir_name);
else
abc_script += stringf("read_library %s/stdcells.genlib; ", config.global_tempdir_name);
run_abc.abc_script += stringf("read_library %s/stdcells.genlib; ", config.global_tempdir_name);
if (!config.script_file.empty()) {
const std::string &script_file = config.script_file;
if (script_file[0] == '+') {
for (size_t i = 1; i < script_file.size(); i++)
if (script_file[i] == '\'')
abc_script += "'\\''";
run_abc.abc_script += "'\\''";
else if (script_file[i] == ',')
abc_script += " ";
run_abc.abc_script += " ";
else
abc_script += script_file[i];
run_abc.abc_script += script_file[i];
} else
abc_script += stringf("source %s", script_file);
run_abc.abc_script += stringf("source %s", script_file);
} else if (!config.lut_costs.empty()) {
bool all_luts_cost_same = true;
for (int this_cost : config.lut_costs)
if (this_cost != config.lut_costs.front())
all_luts_cost_same = false;
abc_script += config.fast_mode ? ABC_FAST_COMMAND_LUT : ABC_COMMAND_LUT;
run_abc.abc_script += config.fast_mode ? ABC_FAST_COMMAND_LUT : ABC_COMMAND_LUT;
if (all_luts_cost_same && !config.fast_mode)
abc_script += "; lutpack {S}";
run_abc.abc_script += "; lutpack -S 1";
} else if (!config.liberty_files.empty() || !config.genlib_files.empty())
abc_script += config.constr_file.empty() ?
run_abc.abc_script += config.constr_file.empty() ?
(config.fast_mode ? ABC_FAST_COMMAND_LIB : ABC_COMMAND_LIB) : (config.fast_mode ? ABC_FAST_COMMAND_CTR : ABC_COMMAND_CTR);
else if (config.sop_mode)
abc_script += config.fast_mode ? ABC_FAST_COMMAND_SOP : ABC_COMMAND_SOP;
run_abc.abc_script += config.fast_mode ? ABC_FAST_COMMAND_SOP : ABC_COMMAND_SOP;
else
abc_script += config.fast_mode ? ABC_FAST_COMMAND_DFL : ABC_COMMAND_DFL;
run_abc.abc_script += config.fast_mode ? ABC_FAST_COMMAND_DFL : ABC_COMMAND_DFL;
if (config.script_file.empty() && !config.delay_target.empty())
for (size_t pos = abc_script.find("dretime;"); pos != std::string::npos; pos = abc_script.find("dretime;", pos+1))
abc_script = abc_script.substr(0, pos) + "dretime; retime -o {D};" + abc_script.substr(pos+8);
for (size_t pos = run_abc.abc_script.find("dretime;"); pos != std::string::npos; pos = run_abc.abc_script.find("dretime;", pos+1))
run_abc.abc_script = run_abc.abc_script.substr(0, pos) + "dretime; retime -o {D};" + run_abc.abc_script.substr(pos+8);
for (size_t pos = abc_script.find("{D}"); pos != std::string::npos; pos = abc_script.find("{D}", pos))
abc_script = abc_script.substr(0, pos) + config.delay_target + abc_script.substr(pos+3);
for (size_t pos = run_abc.abc_script.find("{D}"); pos != std::string::npos; pos = run_abc.abc_script.find("{D}", pos))
run_abc.abc_script = run_abc.abc_script.substr(0, pos) + config.delay_target + run_abc.abc_script.substr(pos+3);
for (size_t pos = abc_script.find("{I}"); pos != std::string::npos; pos = abc_script.find("{I}", pos))
abc_script = abc_script.substr(0, pos) + config.sop_inputs + abc_script.substr(pos+3);
for (size_t pos = run_abc.abc_script.find("{I}"); pos != std::string::npos; pos = run_abc.abc_script.find("{I}", pos))
run_abc.abc_script = run_abc.abc_script.substr(0, pos) + config.sop_inputs + run_abc.abc_script.substr(pos+3);
for (size_t pos = abc_script.find("{P}"); pos != std::string::npos; pos = abc_script.find("{P}", pos))
abc_script = abc_script.substr(0, pos) + config.sop_products + abc_script.substr(pos+3);
for (size_t pos = run_abc.abc_script.find("{P}"); pos != std::string::npos; pos = run_abc.abc_script.find("{P}", pos))
run_abc.abc_script = run_abc.abc_script.substr(0, pos) + config.sop_products + run_abc.abc_script.substr(pos+3);
for (size_t pos = abc_script.find("{S}"); pos != std::string::npos; pos = abc_script.find("{S}", pos))
abc_script = abc_script.substr(0, pos) + config.lutin_shared + abc_script.substr(pos+3);
if (config.abc_dress)
abc_script += stringf("; dress \"%s/input.blif\"", run_abc.per_run_tempdir_name);
abc_script += stringf("; write_blif %s/output.blif", run_abc.per_run_tempdir_name);
abc_script = add_echos_to_abc_cmd(abc_script);
run_abc.abc_script += stringf("; dress \"%s/input.blif\"", run_abc.per_run_tempdir_name);
run_abc.abc_script += stringf("; write_blif %s/output.blif", run_abc.per_run_tempdir_name);
run_abc.abc_script = add_echos_to_abc_cmd(run_abc.abc_script);
#if defined(REUSE_YOSYS_ABC_PROCESSES)
if (config.is_yosys_abc())
abc_script += "; echo; echo \"YOSYS_ABC_DONE\"\n";
run_abc.abc_script += "; echo; echo \"YOSYS_ABC_DONE\"\n";
#endif
for (size_t i = 0; i+1 < abc_script.size(); i++)
if (abc_script[i] == ';' && abc_script[i+1] == ' ')
abc_script[i+1] = '\n';
for (size_t i = 0; i+1 < run_abc.abc_script.size(); i++)
if (run_abc.abc_script[i] == ';' && run_abc.abc_script[i+1] == ' ')
run_abc.abc_script[i+1] = '\n';
std::string buffer = stringf("%s/abc.script", run_abc.per_run_tempdir_name);
FILE *f = fopen(buffer.c_str(), "wt");
if (f == nullptr)
log_error("Opening %s for writing failed: %s\n", buffer, strerror(errno));
fprintf(f, "%s\n", abc_script.c_str());
fprintf(f, "%s\n", run_abc.abc_script.c_str());
fclose(f);
if (dff_mode || !clk_str.empty())
@ -1353,7 +1366,7 @@ void RunAbcState::run(ConcurrentStack<AbcProcess> &)
logs.log("Extracted %d gates and %d wires to a netlist network with %d inputs and %d outputs.\n",
count_gates, GetSize(signal_list), count_input, count_output);
if (count_output == 0) {
log("Don't call ABC as there is nothing to map.\n");
logs.log("Don't call ABC as there is nothing to map.\n");
return;
}
int ret;
@ -1367,13 +1380,13 @@ void RunAbcState::run(ConcurrentStack<AbcProcess> &)
string temp_stdouterr_name = stringf("%s/stdouterr.txt", per_run_tempdir_name);
FILE *temp_stdouterr_w = fopen(temp_stdouterr_name.c_str(), "w");
if (temp_stdouterr_w == NULL)
log_error("ABC: cannot open a temporary file for output redirection");
logs.log_error("ABC: cannot open a temporary file for output redirection");
fflush(stdout);
fflush(stderr);
FILE *old_stdout = fopen(temp_stdouterr_name.c_str(), "r"); // need any fd for renumbering
FILE *old_stderr = fopen(temp_stdouterr_name.c_str(), "r"); // need any fd for renumbering
#if defined(__wasm)
#define fd_renumber(from, to) (void)__wasi_fd_renumber(from, to)
#define fd_renumber(from, to) (void)__wasilibc_fd_renumber(from, to)
#else
#define fd_renumber(from, to) dup2(from, to)
#endif
@ -1412,10 +1425,10 @@ void RunAbcState::run(ConcurrentStack<AbcProcess> &)
if (std::optional<AbcProcess> process_opt = process_pool.try_pop_back()) {
process = std::move(process_opt.value());
} else if (std::optional<AbcProcess> process_opt = spawn_abc(config.exe_file.c_str(), logs)) {
process = std::move(process_opt.value());
} else {
return;
}
process = std::move(process_opt.value());
} else {
return;
}
std::string cmd = stringf(
"empty\n"
"source %s\n", tmp_script_name);
@ -1880,7 +1893,7 @@ struct AbcPass : public Pass {
log("%s\n", fold_abc_cmd(ABC_COMMAND_CTR));
log("\n");
log(" for -lut/-luts (only one LUT size):\n");
log("%s\n", fold_abc_cmd(ABC_COMMAND_LUT "; lutpack {S}"));
log("%s\n", fold_abc_cmd(ABC_COMMAND_LUT "; lutpack -S 1"));
log("\n");
log(" for -lut/-luts (different LUT sizes):\n");
log("%s\n", fold_abc_cmd(ABC_COMMAND_LUT));
@ -1948,10 +1961,6 @@ struct AbcPass : public Pass {
log(" maximum number of SOP products.\n");
log(" (replaces {P} in the default scripts above)\n");
log("\n");
log(" -S <num>\n");
log(" maximum number of LUT inputs shared.\n");
log(" (replaces {S} in the default scripts above, default: -S 1)\n");
log("\n");
log(" -lut <width>\n");
log(" generate netlist using luts of (max) the specified width.\n");
log("\n");
@ -2066,11 +2075,6 @@ struct AbcPass : public Pass {
if (design->scratchpad.count("abc.P")) {
config.sop_products = "-P " + design->scratchpad_get_string("abc.P");
}
if (design->scratchpad.count("abc.S")) {
config.lutin_shared = "-S " + design->scratchpad_get_string("abc.S");
} else {
config.lutin_shared = "-S 1";
}
lut_arg = design->scratchpad_get_string("abc.lut", lut_arg);
luts_arg = design->scratchpad_get_string("abc.luts", luts_arg);
config.sop_mode = design->scratchpad_get_bool("abc.sop", false);
@ -2153,10 +2157,6 @@ struct AbcPass : public Pass {
config.sop_products = "-P " + args[++argidx];
continue;
}
if (arg == "-S" && argidx+1 < args.size()) {
config.lutin_shared = "-S " + args[++argidx];
continue;
}
if (arg == "-lut" && argidx+1 < args.size()) {
lut_arg = args[++argidx];
continue;
@ -2468,7 +2468,7 @@ struct AbcPass : public Pass {
continue;
}
CellTypes ct(design);
NewCellTypes ct(design);
std::vector<RTLIL::Cell*> all_cells = mod->selected_cells();
pool<RTLIL::Cell*> unassigned_cells(all_cells.begin(), all_cells.end());

View file

@ -38,53 +38,53 @@ struct Abc9Pass : public ScriptPass
Abc9Pass() : ScriptPass("abc9", "use ABC9 for technology mapping") { }
void on_register() override
{
RTLIL::constpad["abc9.script.default"] = "+&scorr; &sweep; &dc2; &dch -f -r; &ps; &if {C} {W} {D} {R} -v; &mfs";
RTLIL::constpad["abc9.script.default.area"] = "+&scorr; &sweep; &dc2; &dch -f -r; &ps; &if {C} {W} {D} {R} -a -v; &mfs";
RTLIL::constpad["abc9.script.default.fast"] = "+&if {C} {W} {D} {R} -v";
RTLIL::constpad["abc9.script.default"] = "+&scorr; &sweep; &dc2; &dch -f -r; &ps; &if {W} {D} {R} -v; &mfs";
RTLIL::constpad["abc9.script.default.area"] = "+&scorr; &sweep; &dc2; &dch -f -r; &ps; &if {W} {D} {R} -a -v; &mfs";
RTLIL::constpad["abc9.script.default.fast"] = "+&if {W} {D} {R} -v";
// Based on ABC's &flow
RTLIL::constpad["abc9.script.flow"] = "+&scorr; &sweep;" \
"&dch -C 500;" \
/* Round 1 */ \
/* Map 1 */ "&unmap; &if {C} {W} {D} {R} -v; &save; &load; &mfs;" \
/* Map 1 */ "&unmap; &if {W} {D} {R} -v; &save; &load; &mfs;" \
"&st; &dsdb;" \
/* Map 2 */ "&unmap; &if {C} {W} {D} {R} -v; &save; &load; &mfs;" \
/* Map 2 */ "&unmap; &if {W} {D} {R} -v; &save; &load; &mfs;" \
"&st; &syn2 -m -R 10; &dsdb;" \
"&blut -a -K 6;" \
/* Map 3 */ "&unmap; &if {C} {W} {D} {R} -v; &save; &load; &mfs;" \
/* Map 3 */ "&unmap; &if {W} {D} {R} -v; &save; &load; &mfs;" \
/* Round 2 */ \
"&st; &sopb;" \
/* Map 1 */ "&unmap; &if {C} {W} {D} {R} -v; &save; &load; &mfs;" \
/* Map 1 */ "&unmap; &if {W} {D} {R} -v; &save; &load; &mfs;" \
"&st; &dsdb;" \
/* Map 2 */ "&unmap; &if {C} {W} {D} {R} -v; &save; &load; &mfs;" \
/* Map 2 */ "&unmap; &if {W} {D} {R} -v; &save; &load; &mfs;" \
"&st; &syn2 -m -R 10; &dsdb;" \
"&blut -a -K 6;" \
/* Map 3 */ "&unmap; &if {C} {W} {D} {R} -v; &save; &load; &mfs;" \
/* Map 3 */ "&unmap; &if {W} {D} {R} -v; &save; &load; &mfs;" \
/* Round 3 */ \
/* Map 1 */ "&unmap; &if {C} {W} {D} {R} -v; &save; &load; &mfs;" \
/* Map 1 */ "&unmap; &if {W} {D} {R} -v; &save; &load; &mfs;" \
"&st; &dsdb;" \
/* Map 2 */ "&unmap; &if {C} {W} {D} {R} -v; &save; &load; &mfs;" \
/* Map 2 */ "&unmap; &if {W} {D} {R} -v; &save; &load; &mfs;" \
"&st; &syn2 -m -R 10; &dsdb;" \
"&blut -a -K 6;" \
/* Map 3 */ "&unmap; &if {C} {W} {D} {R} -v; &save; &load; &mfs;";
/* Map 3 */ "&unmap; &if {W} {D} {R} -v; &save; &load; &mfs;";
// Based on ABC's &flow2
RTLIL::constpad["abc9.script.flow2"] = "+&scorr; &sweep;" \
/* Comm1 */ "&synch2 -K 6 -C 500; &if -m {C} {W} {D} {R} -v; &mfs "/*"-W 4 -M 500 -C 7000"*/"; &save;"\
/* Comm2 */ "&dch -C 500; &if -m {C} {W} {D} {R} -v; &mfs "/*"-W 4 -M 500 -C 7000"*/"; &save;"\
/* Comm1 */ "&synch2 -K 6 -C 500; &if -m {W} {D} {R} -v; &mfs "/*"-W 4 -M 500 -C 7000"*/"; &save;"\
/* Comm2 */ "&dch -C 500; &if -m {W} {D} {R} -v; &mfs "/*"-W 4 -M 500 -C 7000"*/"; &save;"\
"&load; &st; &sopb -R 10 -C 4; " \
/* Comm3 */ "&synch2 -K 6 -C 500; &if -m "/*"-E 5"*/" {C} {W} {D} {R} -v; &mfs "/*"-W 4 -M 500 -C 7000"*/"; &save;"\
/* Comm2 */ "&dch -C 500; &if -m {C} {W} {D} {R} -v; &mfs "/*"-W 4 -M 500 -C 7000"*/"; &save; "\
/* Comm3 */ "&synch2 -K 6 -C 500; &if -m "/*"-E 5"*/" {W} {D} {R} -v; &mfs "/*"-W 4 -M 500 -C 7000"*/"; &save;"\
/* Comm2 */ "&dch -C 500; &if -m {W} {D} {R} -v; &mfs "/*"-W 4 -M 500 -C 7000"*/"; &save; "\
"&load";
// Based on ABC's &flow3 -m
RTLIL::constpad["abc9.script.flow3"] = "+&scorr; &sweep;" \
"&if {C} {W} {D}; &save; &st; &syn2; &if {C} {W} {D} {R} -v; &save; &load;"\
"&st; &if {C} -g -K 6; &dch -f; &if {C} {W} {D} {R} -v; &save; &load;"\
"&st; &if {C} -g -K 6; &synch2; &if {C} {W} {D} {R} -v; &save; &load;"\
"&if {W} {D}; &save; &st; &syn2; &if {W} {D} {R} -v; &save; &load;"\
"&st; &if -g -K 6; &dch -f; &if {W} {D} {R} -v; &save; &load;"\
"&st; &if -g -K 6; &synch2; &if {W} {D} {R} -v; &save; &load;"\
"&mfs";
// As above, but with &mfs calls as in the original &flow3
RTLIL::constpad["abc9.script.flow3mfs"] = "+&scorr; &sweep;" \
"&if {C} {W} {D}; &save; &st; &syn2; &if {C} {W} {D} {R} -v; &save; &load;"\
"&st; &if {C} -g -K 6; &dch -f; &if {C} {W} {D} {R} -v; &mfs; &save; &load;"\
"&st; &if {C} -g -K 6; &synch2; &if {C} {W} {D} {R} -v; &mfs; &save; &load;"\
"&if {W} {D}; &save; &st; &syn2; &if {W} {D} {R} -v; &save; &load;"\
"&st; &if -g -K 6; &dch -f; &if {W} {D} {R} -v; &mfs; &save; &load;"\
"&st; &if -g -K 6; &synch2; &if {W} {D} {R} -v; &mfs; &save; &load;"\
"&mfs";
}
void help() override
@ -121,20 +121,11 @@ struct Abc9Pass : public ScriptPass
log(" if no -script parameter is given, the following scripts are used:\n");
log("%s\n", fold_abc9_cmd(RTLIL::constpad.at("abc9.script.default").substr(1,std::string::npos)));
log("\n");
log(" -fast\n");
log(" use different default scripts that are slightly faster (at the cost\n");
log(" of output quality):\n");
log("%s\n", fold_abc9_cmd(RTLIL::constpad.at("abc9.script.default.fast").substr(1,std::string::npos)));
log("\n");
log(" -D <picoseconds>\n");
log(" set delay target. the string {D} in the default scripts above is\n");
log(" replaced by this option when used, and an empty string otherwise\n");
log(" (indicating best possible delay).\n");
log("\n");
// log(" -S <num>\n");
// log(" maximum number of LUT inputs shared.\n");
// log(" (replaces {S} in the default scripts above, default: -S 1)\n");
// log("\n");
log(" -lut <width>\n");
log(" generate netlist using luts of (max) the specified width.\n");
log("\n");
@ -226,8 +217,7 @@ struct Abc9Pass : public ScriptPass
exe_cmd << " " << arg << " " << args[++argidx];
continue;
}
if (arg == "-fast" || /* arg == "-dff" || */
/* arg == "-nocleanup" || */ arg == "-showtmp") {
if (arg == "-showtmp") {
exe_cmd << " " << arg;
continue;
}

View file

@ -24,11 +24,15 @@
#include "kernel/register.h"
#include "kernel/log.h"
#include "liberty_cache.h"
#ifndef _WIN32
# include <unistd.h>
# include <dirent.h>
#endif
#if defined(__wasm)
#include <wasi/libc.h>
#endif
#ifdef YOSYS_LINK_ABC
namespace abc {
@ -165,7 +169,7 @@ struct abc9_output_filter
};
void abc9_module(RTLIL::Design *design, std::string script_file, std::string exe_file,
vector<int> lut_costs, bool dff_mode, std::string delay_target, std::string /*lutin_shared*/, bool fast_mode,
vector<int> lut_costs, bool dff_mode, std::string delay_target,
bool show_tempdir, std::string box_file, std::string lut_file,
std::vector<std::string> liberty_files, std::string wire_delay, std::string tempdir_name,
std::string constr_file, std::vector<std::string> dont_use_cells, std::vector<std::string> genlib_files)
@ -181,11 +185,19 @@ void abc9_module(RTLIL::Design *design, std::string script_file, std::string exe
for (std::string dont_use_cell : dont_use_cells) {
dont_use_args += stringf("-X \"%s\" ", dont_use_cell);
}
bool first_lib = true;
for (std::string liberty_file : liberty_files) {
abc9_script += stringf("read_lib %s %s -w \"%s\" ; ", dont_use_args, first_lib ? "" : "-m", liberty_file);
first_lib = false;
std::string merged_scl = convert_liberty_files_to_merged_scl(liberty_files, dont_use_args, exe_file);
if (!merged_scl.empty()) {
abc9_script += stringf("read_scl \"%s\" ; ", merged_scl.c_str());
} else if(!liberty_files.empty()) {
log_warning("ABC: Merged scl conversion failed, using liberty format\n");
bool first_lib = true;
for (std::string liberty_file : liberty_files) {
abc9_script += stringf("read_lib %s %s -w \"%s\" ; ", dont_use_args, first_lib ? "" : "-m", liberty_file);
first_lib = false;
}
}
if (!constr_file.empty())
abc9_script += stringf("read_constr -v \"%s\"; ", constr_file);
} else if (!genlib_files.empty()) {
@ -210,26 +222,18 @@ void abc9_module(RTLIL::Design *design, std::string script_file, std::string exe
} else
abc9_script += stringf("source %s", script_file);
} else if (!lut_costs.empty() || !lut_file.empty()) {
abc9_script += fast_mode ? RTLIL::constpad.at("abc9.script.default.fast").substr(1,std::string::npos)
: RTLIL::constpad.at("abc9.script.default").substr(1,std::string::npos);
abc9_script += RTLIL::constpad.at("abc9.script.default").substr(1,std::string::npos);
} else if (!liberty_files.empty() || !genlib_files.empty()) {
abc9_script += RTLIL::constpad.at("abc9.script.default").substr(1,std::string::npos);
} else
log_abort();
for (size_t pos = abc9_script.find("{D}"); pos != std::string::npos; pos = abc9_script.find("{D}", pos))
abc9_script = abc9_script.substr(0, pos) + delay_target + abc9_script.substr(pos+3);
//for (size_t pos = abc9_script.find("{S}"); pos != std::string::npos; pos = abc9_script.find("{S}", pos))
// abc9_script = abc9_script.substr(0, pos) + lutin_shared + abc9_script.substr(pos+3);
for (size_t pos = abc9_script.find("{W}"); pos != std::string::npos; pos = abc9_script.find("{W}", pos))
abc9_script = abc9_script.substr(0, pos) + wire_delay + abc9_script.substr(pos+3);
std::string C;
if (design->scratchpad.count("abc9.if.C"))
C = "-C " + design->scratchpad_get_string("abc9.if.C");
for (size_t pos = abc9_script.find("{C}"); pos != std::string::npos; pos = abc9_script.find("{C}", pos))
abc9_script = abc9_script.substr(0, pos) + C + abc9_script.substr(pos+3);
std::string R;
if (design->scratchpad.count("abc9.if.R"))
R = "-R " + design->scratchpad_get_string("abc9.if.R");
@ -295,7 +299,7 @@ void abc9_module(RTLIL::Design *design, std::string script_file, std::string exe
FILE *old_stdout = fopen(temp_stdouterr_name.c_str(), "r"); // need any fd for renumbering
FILE *old_stderr = fopen(temp_stdouterr_name.c_str(), "r"); // need any fd for renumbering
#if defined(__wasm)
#define fd_renumber(from, to) (void)__wasi_fd_renumber(from, to)
#define fd_renumber(from, to) (void)__wasilibc_fd_renumber(from, to)
#else
#define fd_renumber(from, to) dup2(from, to)
#endif
@ -369,11 +373,6 @@ struct Abc9ExePass : public Pass {
log(" if no -script parameter is given, the following scripts are used:\n");
log("%s\n", fold_abc9_cmd(RTLIL::constpad.at("abc9.script.default").substr(1,std::string::npos)));
log("\n");
log(" -fast\n");
log(" use different default scripts that are slightly faster (at the cost\n");
log(" of output quality):\n");
log("%s\n", fold_abc9_cmd(RTLIL::constpad.at("abc9.script.default.fast").substr(1,std::string::npos)));
log("\n");
log(" -constr <file>\n");
log(" pass this file with timing constraints to ABC.\n");
log(" use with -liberty.\n");
@ -453,9 +452,9 @@ struct Abc9ExePass : public Pass {
std::string exe_file = yosys_abc_executable;
std::string script_file, clk_str, box_file, lut_file, constr_file;
std::vector<std::string> liberty_files, genlib_files, dont_use_cells;
std::string delay_target, lutin_shared = "-S 1", wire_delay;
std::string delay_target, wire_delay;
std::string tempdir_name;
bool fast_mode = false, dff_mode = false;
bool dff_mode = false;
bool show_tempdir = false;
vector<int> lut_costs;
@ -472,7 +471,6 @@ struct Abc9ExePass : public Pass {
}
lut_arg = design->scratchpad_get_string("abc9.lut", lut_arg);
luts_arg = design->scratchpad_get_string("abc9.luts", luts_arg);
fast_mode = design->scratchpad_get_bool("abc9.fast", fast_mode);
dff_mode = design->scratchpad_get_bool("abc9.dff", dff_mode);
show_tempdir = design->scratchpad_get_bool("abc9.showtmp", show_tempdir);
box_file = design->scratchpad_get_string("abc9.box", box_file);
@ -504,20 +502,12 @@ struct Abc9ExePass : public Pass {
delay_target = "-D " + args[++argidx];
continue;
}
//if (arg == "-S" && argidx+1 < args.size()) {
// lutin_shared = "-S " + args[++argidx];
// continue;
//}
if (arg == "-lut" && argidx+1 < args.size()) {
lut_arg = args[++argidx];
continue;
}
if (arg == "-luts" && argidx+1 < args.size()) {
lut_arg = args[++argidx];
continue;
}
if (arg == "-fast") {
fast_mode = true;
luts_arg = args[++argidx];
continue;
}
if (arg == "-dff") {
@ -622,7 +612,7 @@ struct Abc9ExePass : public Pass {
log_cmd_error("abc9_exe '-genlib' is incompatible with '-dont_use'.\n");
abc9_module(design, script_file, exe_file, lut_costs, dff_mode,
delay_target, lutin_shared, fast_mode, show_tempdir,
delay_target, show_tempdir,
box_file, lut_file, liberty_files, wire_delay, tempdir_name,
constr_file, dont_use_cells, genlib_files);
}

View file

@ -21,8 +21,9 @@
#include "kernel/register.h"
#include "kernel/sigtools.h"
#include "kernel/utils.h"
#include "kernel/celltypes.h"
#include "kernel/newcelltypes.h"
#include "kernel/timinginfo.h"
#include <optional>
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
@ -587,6 +588,7 @@ void break_scc(RTLIL::Module *module)
auto id = it->second;
auto r = ids_seen.insert(id);
cell->attributes.erase(it);
// Cut exactly one representative cell per SCC id.
if (!r.second)
continue;
for (auto &c : cell->connections_) {
@ -710,8 +712,6 @@ void prep_xaiger(RTLIL::Module *module, bool dff)
SigMap sigmap(module);
dict<SigBit, pool<IdString>> bit_drivers, bit_users;
TopoSort<IdString, RTLIL::sort_by_id_str> toposort;
dict<IdString, std::vector<IdString>> box_ports;
for (auto cell : module->cells()) {
@ -750,39 +750,100 @@ void prep_xaiger(RTLIL::Module *module, bool dff)
}
}
}
else if (!yosys_celltypes.cell_known(cell->type))
continue;
// TODO: Speed up toposort -- we care about box ordering only
for (auto conn : cell->connections()) {
if (cell->input(conn.first))
for (auto bit : sigmap(conn.second))
bit_users[bit].insert(cell->name);
if (cell->output(conn.first) && !abc9_flop)
for (auto bit : sigmap(conn.second))
bit_drivers[bit].insert(cell->name);
}
toposort.node(cell->name);
}
if (box_ports.empty())
return;
for (auto &it : bit_users)
if (bit_drivers.count(it.first))
for (auto driver_cell : bit_drivers.at(it.first))
for (auto user_cell : it.second)
toposort.edge(driver_cell, user_cell);
// Build the same topo graph for the initial pass and the optional retry.
auto build_toposort = [&](TopoSort<IdString, RTLIL::sort_by_id_str> &toposort) {
dict<SigBit, pool<IdString>> bit_drivers, bit_users;
if (ys_debug(1))
toposort.analyze_loops = true;
for (auto cell : module->cells()) {
if (cell->type.in(ID($_DFF_N_), ID($_DFF_P_)))
continue;
if (cell->has_keep_attr())
continue;
bool no_loops = toposort.sort();
auto inst_module = design->module(cell->type);
bool abc9_flop = inst_module && inst_module->get_bool_attribute(ID::abc9_flop);
if (abc9_flop && !dff)
continue;
if (!(inst_module && inst_module->get_bool_attribute(ID::abc9_box)) && !yosys_celltypes.cell_known(cell->type))
continue;
// TODO: Speed up toposort -- we care about box ordering only
for (auto conn : cell->connections()) {
if (cell->input(conn.first))
for (auto bit : sigmap(conn.second))
bit_users[bit].insert(cell->name);
if (cell->output(conn.first) && !abc9_flop)
for (auto bit : sigmap(conn.second))
bit_drivers[bit].insert(cell->name);
}
toposort.node(cell->name);
}
// Build producer -> consumer edges on sigmapped nets.
for (auto &it : bit_users)
if (bit_drivers.count(it.first))
for (auto driver_cell : bit_drivers.at(it.first))
for (auto user_cell : it.second)
toposort.edge(driver_cell, user_cell);
if (ys_debug(1))
toposort.analyze_loops = true;
return toposort.sort();
};
// Build TopoSort in a container, as we may need to conditionally rebuild it on retry.
std::optional<TopoSort<IdString, RTLIL::sort_by_id_str>> toposort;
toposort.emplace();
bool no_loops = build_toposort(toposort.value());
// Fallback for residual loops after SCC cutting: insert additional
// breakers on non-box loop cells, then re-run toposort checks.
if (!no_loops) {
SigSpec I, O;
pool<IdString> broken_cells;
for (auto &loop : toposort.value().loops)
for (auto cell_name : loop) {
// Loop reports can overlap; cut each cell at most once.
if (!broken_cells.insert(cell_name).second)
continue;
auto cell = module->cell(cell_name);
log_assert(cell);
auto inst_module = design->module(cell->type);
if (inst_module && inst_module->get_bool_attribute(ID::abc9_box))
continue;
for (auto &c : cell->connections_) {
if (c.second.is_fully_const()) continue;
if (cell->output(c.first)) {
Wire *w = module->addWire(NEW_ID, GetSize(c.second));
I.append(w);
O.append(c.second);
c.second = w;
}
}
}
if (!I.empty()) {
auto cell = module->addCell(NEW_ID, ID($__ABC9_SCC_BREAKER));
log_assert(GetSize(I) == GetSize(O));
cell->setParam(ID::WIDTH, GetSize(I));
cell->setPort(ID::I, std::move(I));
cell->setPort(ID::O, std::move(O));
// Rebuild topo ordering after inserting the additional breakers.
toposort.emplace();
no_loops = build_toposort(toposort.value());
}
}
if (ys_debug(1)) {
unsigned i = 0;
for (auto &it : toposort.loops) {
for (auto &it : toposort.value().loops) {
log(" loop %d\n", i++);
for (auto cell_name : it) {
auto cell = module->cell(cell_name);
@ -806,7 +867,7 @@ void prep_xaiger(RTLIL::Module *module, bool dff)
TimingInfo timing;
int port_id = 1, box_count = 0;
for (auto cell_name : toposort.sorted) {
for (auto cell_name : toposort.value().sorted) {
RTLIL::Cell *cell = module->cell(cell_name);
log_assert(cell);
@ -1559,7 +1620,6 @@ clone_lut:
}
}
//log("ABC RESULTS: internal signals: %8d\n", int(signal_list.size()) - in_wires - out_wires);
log("ABC RESULTS: input signals: %8d\n", in_wires);
log("ABC RESULTS: output signals: %8d\n", out_wires);
@ -1592,7 +1652,7 @@ static void replace_zbufs(Design *design)
if (sig[i] == State::Sz) {
Wire *w = mod->addWire(NEW_ID);
Cell *ud = mod->addCell(NEW_ID, ID($tribuf));
ud->set_bool_attribute(ID(aiger2_zbuf));
ud->set_bool_attribute(ID::aiger2_zbuf);
ud->setParam(ID::WIDTH, 1);
ud->setPort(ID::Y, w);
ud->setPort(ID::EN, State::S0);

View file

@ -18,7 +18,7 @@
*/
#include "kernel/register.h"
#include "kernel/rtlil.h"
#include "kernel/yosys_common.h"
#include "kernel/utils.h"
USING_YOSYS_NAMESPACE
@ -27,7 +27,8 @@ PRIVATE_NAMESPACE_BEGIN
std::vector<Module*> order_modules(Design *design, std::vector<Module *> modules)
{
std::set<Module *> modules_set(modules.begin(), modules.end());
TopoSort<Module*> sort;
using Order = IdString::compare_ptr_by_name<RTLIL::NamedObject>;
TopoSort<Module*, Order> sort;
for (auto m : modules) {
sort.node(m);
@ -49,6 +50,17 @@ struct AbcNewPass : public ScriptPass {
experimental();
}
void on_register() override
{
RTLIL::constpad["abc_new.script.speed"] = "+&st; &dch -r;" \
"&nf; &st; &syn2; &if -g -K 6; &synch2 -r;" \
"&nf; &st; &syn2; &if -g -K 6; &synch2 -r;" \
"&nf; &st; &syn2; &if -g -K 6; &synch2 -r;" \
"&nf; &st; &syn2; &if -g -K 6; &synch2 -r;" \
"&nf; &st; &syn2; &if -g -K 6; &synch2 -r;" \
"&nf";
}
void help() override
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
@ -109,6 +121,11 @@ struct AbcNewPass : public ScriptPass {
}
extra_args(args, argidx, d);
// If no script provided, use a default.
if (abc_exe_options.find("-script") == std::string::npos) {
d->scratchpad_set_string("abc9.script", RTLIL::constpad["abc_new.script.speed"]);
}
log_header(d, "Executing ABC_NEW pass.\n");
log_push();
run_script(d, run_from, run_to);

View file

@ -0,0 +1,426 @@
/**
* Replaces chains of $add/$sub and $macc cells with carry-save adder trees
*
* Terminology:
* - parent: Cells that consume another cell's output
* - chainable: Adds/subs with no carry-out usage
* - chain: Connected path of chainable cells
*/
#include "kernel/macc.h"
#include "kernel/sigtools.h"
#include "kernel/wallace_tree.h"
#include "kernel/yosys.h"
#include <queue>
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
struct Operand {
SigSpec sig;
bool is_signed;
bool negate;
};
struct Traversal {
SigMap sigmap;
dict<SigBit, pool<Cell *>> bit_consumers;
dict<SigBit, int> fanout;
Traversal(Module *module) : sigmap(module)
{
for (auto cell : module->cells())
for (auto &conn : cell->connections())
if (cell->input(conn.first))
for (auto bit : sigmap(conn.second))
bit_consumers[bit].insert(cell);
for (auto &pair : bit_consumers)
fanout[pair.first] = pair.second.size();
for (auto wire : module->wires())
if (wire->port_output)
for (auto bit : sigmap(SigSpec(wire)))
fanout[bit]++;
}
};
struct Cells {
pool<Cell *> addsub;
pool<Cell *> alu;
pool<Cell *> macc;
static bool is_addsub(Cell *cell) { return cell->type == ID($add) || cell->type == ID($sub); }
static bool is_alu(Cell *cell) { return cell->type == ID($alu); }
static bool is_macc(Cell *cell) { return cell->type == ID($macc) || cell->type == ID($macc_v2); }
bool empty() { return addsub.empty() && alu.empty() && macc.empty(); }
Cells(Module *module)
{
for (auto cell : module->cells()) {
if (is_addsub(cell))
addsub.insert(cell);
else if (is_alu(cell))
alu.insert(cell);
else if (is_macc(cell))
macc.insert(cell);
}
}
};
struct AluInfo {
Cells &cells;
Traversal &traversal;
bool is_subtract(Cell *cell)
{
SigSpec bi = traversal.sigmap(cell->getPort(ID::BI));
SigSpec ci = traversal.sigmap(cell->getPort(ID::CI));
return GetSize(bi) == 1 && bi[0] == State::S1 && GetSize(ci) == 1 && ci[0] == State::S1;
}
bool is_add(Cell *cell)
{
SigSpec bi = traversal.sigmap(cell->getPort(ID::BI));
SigSpec ci = traversal.sigmap(cell->getPort(ID::CI));
return GetSize(bi) == 1 && bi[0] == State::S0 && GetSize(ci) == 1 && ci[0] == State::S0;
}
bool is_chainable(Cell *cell)
{
if (!(is_add(cell) || is_subtract(cell)))
return false;
for (auto bit : traversal.sigmap(cell->getPort(ID::X)))
if (traversal.fanout.count(bit) && traversal.fanout[bit] > 0)
return false;
for (auto bit : traversal.sigmap(cell->getPort(ID::CO)))
if (traversal.fanout.count(bit) && traversal.fanout[bit] > 0)
return false;
return true;
}
};
struct Rewriter {
Module *module;
Cells &cells;
Traversal traversal;
AluInfo alu_info;
Rewriter(Module *module, Cells &cells) : module(module), cells(cells), traversal(module), alu_info{cells, traversal} {}
Cell *sole_chainable_consumer(SigSpec sig, const pool<Cell *> &candidates)
{
Cell *consumer = nullptr;
for (auto bit : sig) {
if (!traversal.fanout.count(bit) || traversal.fanout[bit] != 1)
return nullptr;
if (!traversal.bit_consumers.count(bit) || traversal.bit_consumers[bit].size() != 1)
return nullptr;
Cell *c = *traversal.bit_consumers[bit].begin();
if (!candidates.count(c))
return nullptr;
if (consumer == nullptr)
consumer = c;
else if (consumer != c)
return nullptr;
}
return consumer;
}
dict<Cell *, Cell *> find_parents(const pool<Cell *> &candidates)
{
dict<Cell *, Cell *> parent_of;
for (auto cell : candidates) {
Cell *consumer = sole_chainable_consumer(traversal.sigmap(cell->getPort(ID::Y)), candidates);
if (consumer && consumer != cell)
parent_of[cell] = consumer;
}
return parent_of;
}
std::pair<dict<Cell *, pool<Cell *>>, pool<Cell *>> invert_parent_map(const dict<Cell *, Cell *> &parent_of)
{
dict<Cell *, pool<Cell *>> children_of;
pool<Cell *> has_parent;
for (auto &[child, parent] : parent_of) {
children_of[parent].insert(child);
has_parent.insert(child);
}
return {children_of, has_parent};
}
pool<Cell *> collect_chain(Cell *root, const dict<Cell *, pool<Cell *>> &children_of)
{
pool<Cell *> chain;
std::queue<Cell *> q;
q.push(root);
while (!q.empty()) {
Cell *cur = q.front();
q.pop();
if (!chain.insert(cur).second)
continue;
auto it = children_of.find(cur);
if (it != children_of.end())
for (auto child : it->second)
q.push(child);
}
return chain;
}
pool<SigBit> internal_bits(const pool<Cell *> &chain)
{
pool<SigBit> bits;
for (auto cell : chain)
for (auto bit : traversal.sigmap(cell->getPort(ID::Y)))
bits.insert(bit);
return bits;
}
static bool overlaps(SigSpec sig, const pool<SigBit> &bits)
{
for (auto bit : sig)
if (bits.count(bit))
return true;
return false;
}
bool feeds_subtracted_port(Cell *child, Cell *parent)
{
bool parent_subtracts;
if (parent->type == ID($sub))
parent_subtracts = true;
else if (cells.is_alu(parent))
parent_subtracts = alu_info.is_subtract(parent);
else
return false;
if (!parent_subtracts)
return false;
// Check if any bit of child's Y connects to parent's B
SigSpec child_y = traversal.sigmap(child->getPort(ID::Y));
SigSpec parent_b = traversal.sigmap(parent->getPort(ID::B));
for (auto bit : child_y)
for (auto pbit : parent_b)
if (bit == pbit)
return true;
return false;
}
std::vector<Operand> extract_chain_operands(const pool<Cell *> &chain, Cell *root, const dict<Cell *, Cell *> &parent_of, int &neg_compensation)
{
pool<SigBit> chain_bits = internal_bits(chain);
// Propagate negation flags through chain
dict<Cell *, bool> negated;
negated[root] = false;
{
std::queue<Cell *> q;
q.push(root);
while (!q.empty()) {
Cell *cur = q.front();
q.pop();
for (auto cell : chain) {
if (!parent_of.count(cell) || parent_of.at(cell) != cur)
continue;
if (negated.count(cell))
continue;
negated[cell] = negated[cur] ^ feeds_subtracted_port(cell, cur);
q.push(cell);
}
}
}
// Extract leaf operands
std::vector<Operand> operands;
neg_compensation = 0;
for (auto cell : chain) {
bool cell_neg = negated.count(cell) ? negated[cell] : false;
SigSpec a = traversal.sigmap(cell->getPort(ID::A));
SigSpec b = traversal.sigmap(cell->getPort(ID::B));
bool a_signed = cell->getParam(ID::A_SIGNED).as_bool();
bool b_signed = cell->getParam(ID::B_SIGNED).as_bool();
bool b_sub = (cell->type == ID($sub)) || (cells.is_alu(cell) && alu_info.is_subtract(cell));
// Only add operands not produced by other chain cells
if (!overlaps(a, chain_bits)) {
operands.push_back({a, a_signed, cell_neg});
if (cell_neg)
neg_compensation++;
}
if (!overlaps(b, chain_bits)) {
bool neg = cell_neg ^ b_sub;
operands.push_back({b, b_signed, neg});
if (neg)
neg_compensation++;
}
}
return operands;
}
bool extract_macc_operands(Cell *cell, std::vector<Operand> &operands, int &neg_compensation)
{
Macc macc(cell);
neg_compensation = 0;
for (auto &term : macc.terms) {
// Bail on multiplication
if (GetSize(term.in_b) != 0)
return false;
operands.push_back({term.in_a, term.is_signed, term.do_subtract});
if (term.do_subtract)
neg_compensation++;
}
return true;
}
SigSpec extend_operand(SigSpec sig, bool is_signed, int width)
{
if (GetSize(sig) < width) {
SigBit pad;
if (is_signed && GetSize(sig) > 0)
pad = sig[GetSize(sig) - 1];
else
pad = State::S0;
sig.append(SigSpec(pad, width - GetSize(sig)));
}
if (GetSize(sig) > width)
sig = sig.extract(0, width);
return sig;
}
void replace_with_carry_save_tree(std::vector<Operand> &operands, SigSpec result_y, int neg_compensation, const char *desc)
{
int width = GetSize(result_y);
std::vector<SigSpec> extended;
extended.reserve(operands.size() + 1);
for (auto &op : operands) {
SigSpec s = extend_operand(op.sig, op.is_signed, width);
if (op.negate)
s = module->Not(NEW_ID, s);
extended.push_back(s);
}
// Add correction for negated operands (-x = ~x + 1 so 1 per negation)
if (neg_compensation > 0)
extended.push_back(SigSpec(neg_compensation, width));
int compressor_count;
auto [a, b] = wallace_reduce_scheduled(module, extended, width, &compressor_count);
log(" %s -> %d $fa + 1 $add (%d operands, module %s)\n", desc, compressor_count, (int)operands.size(), log_id(module));
// Emit final add
module->addAdd(NEW_ID, a, b, result_y, false);
}
void process_chains()
{
pool<Cell *> candidates;
for (auto cell : cells.addsub)
candidates.insert(cell);
for (auto cell : cells.alu)
if (alu_info.is_chainable(cell))
candidates.insert(cell);
if (candidates.empty())
return;
auto parent_of = find_parents(candidates);
auto [children_of, has_parent] = invert_parent_map(parent_of);
pool<Cell *> to_remove;
for (auto root : candidates) {
if (has_parent.count(root) || to_remove.count(root))
continue; // Not a tree root
pool<Cell *> chain = collect_chain(root, children_of);
if (chain.size() < 2)
continue;
int neg_compensation;
auto operands = extract_chain_operands(chain, root, parent_of, neg_compensation);
if (operands.size() < 3)
continue;
for (auto c : chain)
to_remove.insert(c);
replace_with_carry_save_tree(operands, root->getPort(ID::Y), neg_compensation, "Replaced add/sub chain");
}
for (auto cell : to_remove)
module->remove(cell);
}
void process_maccs()
{
for (auto cell : cells.macc) {
std::vector<Operand> operands;
int neg_compensation;
if (!extract_macc_operands(cell, operands, neg_compensation))
continue;
if (operands.size() < 3)
continue;
replace_with_carry_save_tree(operands, cell->getPort(ID::Y), neg_compensation, "Replaced $macc");
module->remove(cell);
}
}
};
void run(Module *module)
{
Cells cells(module);
if (cells.empty())
return;
Rewriter rewriter{module, cells};
rewriter.process_chains();
rewriter.process_maccs();
}
struct ArithTreePass : public Pass {
ArithTreePass() : Pass("arith_tree", "convert add/sub/macc chains to carry-save adder trees") {}
void help() override
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" arith_tree [selection]\n");
log("\n");
log("This pass replaces chains of $add/$sub cells, $alu cells (with constant\n");
log("BI/CI), and $macc/$macc_v2 cells (without multiplications) with carry-save\n");
log("adder trees using $fa cells and a single final $add.\n");
log("\n");
log("The tree uses Wallace-tree scheduling: at each level, ready operands are\n");
log("grouped into triplets and compressed via full adders, giving\n");
log("O(log_{1.5} N) depth for N input operands.\n");
log("\n");
}
void execute(std::vector<std::string> args, RTLIL::Design *design) override
{
log_header(design, "Executing ARITH_TREE pass.\n");
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++)
break;
extra_args(args, argidx, design);
for (auto module : design->selected_modules()) {
run(module);
}
}
} ArithTreePass;
PRIVATE_NAMESPACE_END

View file

@ -58,6 +58,7 @@ synth -top my_design -booth
#include "kernel/sigtools.h"
#include "kernel/yosys.h"
#include "kernel/macc.h"
#include "kernel/wallace_tree.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
@ -317,36 +318,6 @@ struct BoothPassWorker {
}
}
SigSig WallaceSum(int width, std::vector<SigSpec> summands)
{
for (auto &s : summands)
s.extend_u0(width);
while (summands.size() > 2) {
std::vector<SigSpec> new_summands;
int i;
for (i = 0; i < (int) summands.size() - 2; i += 3) {
SigSpec x = module->addWire(NEW_ID, width);
SigSpec y = module->addWire(NEW_ID, width);
BuildBitwiseFa(module, NEW_ID.str(), summands[i], summands[i + 1],
summands[i + 2], x, y);
new_summands.push_back(y);
new_summands.push_back({x.extract(0, width - 1), State::S0});
}
new_summands.insert(new_summands.begin(), summands.begin() + i, summands.end());
std::swap(summands, new_summands);
}
if (!summands.size())
return SigSig(SigSpec(width, State::S0), SigSpec(width, State::S0));
else if (summands.size() == 1)
return SigSig(summands[0], SigSpec(width, State::S0));
else
return SigSig(summands[0], summands[1]);
}
/*
Build Multiplier.
-------------------------
@ -415,16 +386,16 @@ struct BoothPassWorker {
// Later on yosys will clean up unused constants
// DebugDumpAlignPP(aligned_pp);
SigSig wtree_sum = WallaceSum(z_sz, aligned_pp);
auto [wtree_a, wtree_b] = wallace_reduce_scheduled(module, aligned_pp, z_sz);
// Debug code: Dump out the csa trees
// DumpCSATrees(debug_csa_trees);
// Build the CPA to do the final accumulation.
log_assert(wtree_sum.second[0] == State::S0);
log_assert(wtree_b[0] == State::S0);
if (mapped_cpa)
BuildCPA(module, wtree_sum.first, {State::S0, wtree_sum.second.extract_end(1)}, Z);
BuildCPA(module, wtree_a, wtree_b, Z);
else
module->addAdd(NEW_ID, wtree_sum.first, {wtree_sum.second.extract_end(1), State::S0}, Z);
module->addAdd(NEW_ID, wtree_a, wtree_b, Z);
}
/*

View file

@ -71,6 +71,8 @@ struct ConstmapPass : public Pass {
}
extra_args(args, argidx, design);
if (celltype.empty())
log_cmd_error("Missing required option -cell.\n");
if (design->has(celltype)) {
Module *existing = design->module(celltype);

View file

@ -0,0 +1,145 @@
#ifndef LIBERTY_CACHE_H
#define LIBERTY_CACHE_H
#include "kernel/yosys.h"
#ifdef YOSYS_LINK_ABC
namespace abc {
int Abc_RealMain(int argc, char *argv[]);
}
#endif
YOSYS_NAMESPACE_BEGIN
/*
* convert_liberty_files_to_merged_scl() - Convert multiple Liberty files to a single merged SCL cache file.
* @liberty_files: Vector of liberty file paths to merge
* @dont_use_args: Pre-built ABC -X flags string
* @abc_exe: Path to ABC executable for conversion
*
* Return: Path to merged SCL cache file, or empty string if conversion fails
*/
inline std::string convert_liberty_files_to_merged_scl(const std::vector<std::string> &liberty_files, const std::string &dont_use_args, const std::string &abc_exe)
{
if (liberty_files.empty())
return "";
std::string cache_dir = get_base_tmpdir() + "/yosys-liberty-scl-cache";
if (!create_directory(cache_dir)) {
log_warning("ABC: cannot create cache directory %s, falling back to liberty format\n", cache_dir.c_str());
return "";
}
// Sort to ensure consistent hash regardless of order
std::vector<std::string> sorted_files = liberty_files;
std::sort(sorted_files.begin(), sorted_files.end());
std::string hash_input;
time_t newest_mtime = 0;
for (const std::string &liberty_file : sorted_files) {
struct stat liberty_stat;
if (stat(liberty_file.c_str(), &liberty_stat) != 0) {
log_error("ABC: cannot stat liberty file: %s\n", liberty_file.c_str());
return "";
}
hash_input += liberty_file + "|";
if (liberty_stat.st_mtime > newest_mtime)
newest_mtime = liberty_stat.st_mtime;
}
hash_input += dont_use_args;
unsigned int hash = 0;
for (char c : hash_input)
hash = hash * 31 + c;
std::string merged_scl = stringf("%s/yosys_merged_%08x.scl", cache_dir.c_str(), hash);
bool need_convert = true;
struct stat scl_stat;
// Check if merged SCL exists and is newer than all liberty files
if (stat(merged_scl.c_str(), &scl_stat) == 0) {
if (scl_stat.st_mtime >= newest_mtime) {
log("ABC: using cached merged SCL: %s (%zu files)\n", merged_scl.c_str(), liberty_files.size());
need_convert = false;
}
}
if (need_convert) {
// read_lib -X cell1 -X cell2 file1 ; read_lib -X cell1 -X cell2 -m file2 ; ... ; write_scl merged.scl
std::string temp_scl = merged_scl + ".tmp";
#ifdef YOSYS_LINK_ABC
std::string script_path = stringf("%s/yosys_merged_scl_convert_%08x.script", cache_dir.c_str(), hash);
FILE *f = fopen(script_path.c_str(), "w");
if (f == NULL) {
log_warning("ABC: cannot open %s for writing, falling back to liberty format\n", script_path.c_str());
return "";
}
bool first = true;
for (const std::string &liberty_file : liberty_files) {
fprintf(f, "read_lib %s%s-w \"%s\"\n", dont_use_args.c_str(), first ? "" : "-m ", liberty_file.c_str());
first = false;
}
fprintf(f, "write_scl \"%s\"\n", temp_scl.c_str());
fclose(f);
char *abc_argv[5];
abc_argv[0] = strdup(abc_exe.empty() ? "yosys-abc" : abc_exe.c_str());
abc_argv[1] = strdup("-s");
abc_argv[2] = strdup("-f");
abc_argv[3] = strdup(script_path.c_str());
abc_argv[4] = 0;
int ret = abc::Abc_RealMain(4, abc_argv);
free(abc_argv[0]);
free(abc_argv[1]);
free(abc_argv[2]);
free(abc_argv[3]);
remove(script_path.c_str());
if (ret != 0) {
log_warning("ABC: merged SCL conversion failed (ret=%d), falling back to liberty format\n", ret);
remove(temp_scl.c_str());
return "";
}
#else
std::string abc_script;
bool first = true;
for (const std::string &liberty_file : liberty_files) {
abc_script += stringf("read_lib %s%s-w \\\"%s\\\" ; ", dont_use_args.c_str(), first ? "" : "-m ", liberty_file.c_str());
first = false;
}
abc_script += stringf("write_scl \\\"%s\\\"", temp_scl.c_str());
std::string cmd = stringf("\"%s\" -c \"%s\" 2>&1", abc_exe.c_str(), abc_script.c_str());
std::string abc_output;
int ret = run_command(cmd, [&abc_output](const std::string &line) { abc_output += line + "\n"; });
if (ret != 0) {
log_warning("ABC: merged SCL conversion failed, falling back to liberty format\n");
if (!abc_output.empty()) {
log("ABC: conversion output:\n%s", abc_output.c_str());
}
remove(temp_scl.c_str());
return "";
}
#endif
if (rename(temp_scl.c_str(), merged_scl.c_str()) != 0) {
log_warning("ABC: failed to rename %s to %s, falling back to liberty format\n", temp_scl.c_str(), merged_scl.c_str());
remove(temp_scl.c_str());
return "";
}
}
return merged_scl;
}
YOSYS_NAMESPACE_END
#endif // LIBERTY_CACHE_H

View file

@ -438,6 +438,48 @@ void simplemap_ff(RTLIL::Module *, RTLIL::Cell *cell)
}
}
void simplemap_pmux(RTLIL::Module *module, RTLIL::Cell *cell)
{
RTLIL::SigSpec sig_a = cell->getPort(ID::A);
RTLIL::SigSpec sig_b = cell->getPort(ID::B);
RTLIL::SigSpec sig_s = cell->getPort(ID::S);
RTLIL::SigSpec sig_y = cell->getPort(ID::Y);
int width = GetSize(sig_a);
int s_width = GetSize(sig_s);
// Implement: |S
RTLIL::SigSpec any_s = sig_s;
logic_reduce(module, any_s, cell);
for (int i = 0; i < width; i++) {
RTLIL::SigSpec b_and_bits;
// Implement: B_AND_BITS = B_AND_S[WIDTH*j+i]
for (int j = 0; j < s_width; j++) {
RTLIL::Cell *and_gate = module->addCell(NEW_ID, ID($_AND_));
transfer_src(and_gate, cell);
and_gate->setPort(ID::A, sig_b[j * width + i]);
and_gate->setPort(ID::B, sig_s[j]);
RTLIL::SigSpec and_y = module->addWire(NEW_ID, 1);
and_gate->setPort(ID::Y, and_y);
b_and_bits.append(and_y);
}
// Implement: Y_B[i] = |B_AND_BITS
logic_reduce(module, b_and_bits, cell);
// Implement: Y[i] = |S ? Y_B[i] : A[i]
RTLIL::Cell *mux_gate = module->addCell(NEW_ID, ID($_MUX_));
transfer_src(mux_gate, cell);
mux_gate->setPort(ID::A, sig_a[i]);
mux_gate->setPort(ID::B, b_and_bits);
mux_gate->setPort(ID::S, any_s);
mux_gate->setPort(ID::Y, sig_y[i]);
}
}
void simplemap_get_mappers(dict<IdString, void(*)(RTLIL::Module*, RTLIL::Cell*)> &mappers)
{
mappers[ID($not)] = simplemap_not;
@ -461,6 +503,7 @@ void simplemap_get_mappers(dict<IdString, void(*)(RTLIL::Module*, RTLIL::Cell*)>
mappers[ID($ne)] = simplemap_eqne;
mappers[ID($nex)] = simplemap_eqne;
mappers[ID($mux)] = simplemap_mux;
mappers[ID($pmux)] = simplemap_pmux;
mappers[ID($bwmux)] = simplemap_bwmux;
mappers[ID($tribuf)] = simplemap_tribuf;
mappers[ID($bmux)] = simplemap_bmux;
@ -515,7 +558,7 @@ struct SimplemapPass : public Pass {
log("\n");
log(" $not, $pos, $and, $or, $xor, $xnor\n");
log(" $reduce_and, $reduce_or, $reduce_xor, $reduce_xnor, $reduce_bool\n");
log(" $logic_not, $logic_and, $logic_or, $mux, $tribuf\n");
log(" $logic_not, $logic_and, $logic_or, $mux, $pmux, $tribuf\n");
log(" $sr, $ff, $dff, $dffe, $dffsr, $dffsre, $adff, $adffe, $aldff, $aldffe, $sdff,\n");
log(" $sdffe, $sdffce, $dlatch, $adlatch, $dlatchsr\n");
log("\n");