diff --git a/passes/opt/wreduce.cc b/passes/opt/wreduce.cc index 02678d67680..9c0fcc7e1ea 100644 --- a/passes/opt/wreduce.cc +++ b/passes/opt/wreduce.cc @@ -263,6 +263,19 @@ struct WreduceWorker } } + int reduced_opsize(const SigSpec &inp, bool signed_) + { + int size = GetSize(inp); + if (signed_) { + while (size >= 2 && inp[size - 1] == inp[size - 2]) + size--; + } else { + while (size >= 1 && inp[size - 1] == State::S0) + size--; + } + return size; + } + void run_cell(Cell *cell) { bool did_something = false; @@ -295,6 +308,44 @@ struct WreduceWorker bool port_a_signed = false; bool port_b_signed = false; + // Under certain conditions we are free to choose the signedness of the operands + if (cell->type.in(ID($mul), ID($add), ID($sub)) && + max_port_a_size == GetSize(sig) && + max_port_b_size == GetSize(sig)) { + SigSpec sig_a = mi.sigmap(cell->getPort(ID::A)), sig_b = mi.sigmap(cell->getPort(ID::B)); + + // Remove top bits from sig_a and sig_b which are not visible on the output + sig_a.extend_u0(max_port_a_size); + sig_b.extend_u0(max_port_b_size); + + int signed_size, unsigned_size; + if (cell->type == ID($mul)) { + signed_size = reduced_opsize(sig_a, true) * reduced_opsize(sig_b, true); + unsigned_size = reduced_opsize(sig_a, false) * reduced_opsize(sig_b, false); + } else { + signed_size = max(reduced_opsize(sig_a, true), reduced_opsize(sig_b, true)); + unsigned_size = max(reduced_opsize(sig_a, false), reduced_opsize(sig_b, false)); + } + + if (!port_a_signed && !port_b_signed && signed_size < unsigned_size) { + log("Converting cell %s.%s (%s) from unsigned to signed.\n", + log_id(module), log_id(cell), log_id(cell->type)); + cell->setParam(ID::A_SIGNED, 1); + cell->setParam(ID::B_SIGNED, 1); + port_a_signed = true; + port_b_signed = true; + did_something = true; + } else if (port_a_signed && port_b_signed && unsigned_size < signed_size) { + log("Converting cell %s.%s (%s) from signed to unsigned.\n", + log_id(module), log_id(cell), log_id(cell->type)); + cell->setParam(ID::A_SIGNED, 0); + cell->setParam(ID::B_SIGNED, 0); + port_a_signed = false; + port_b_signed = false; + did_something = true; + } + } + if (max_port_a_size >= 0 && cell->type != ID($shiftx)) run_reduce_inport(cell, 'A', max_port_a_size, port_a_signed, did_something); diff --git a/tests/various/wreduce2.ys b/tests/various/wreduce2.ys new file mode 100644 index 00000000000..496aa97e90e --- /dev/null +++ b/tests/various/wreduce2.ys @@ -0,0 +1,22 @@ +read_verilog <