Merge pull request #122 from Silimate/optimize_cell_accessors

rtlil: add fast Cell accessors and SigSpec::const_ratio()
This commit is contained in:
Akash Levy 2026-03-13 16:45:26 -07:00 committed by GitHub
commit 521b1db5ee
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 43 additions and 4 deletions

View File

@ -4564,6 +4564,32 @@ const RTLIL::Const &RTLIL::Cell::getParam(RTLIL::IdString paramname) const
throw std::out_of_range("Cell::getParam()");
}
// NOTE: as_int() silently truncates >32-bit values and reinterprets string-typed Const values
std::map<std::string, int> RTLIL::Cell::getParamsAsInts() const
{
std::map<std::string, int> result;
for (auto &param : parameters) {
std::string key = param.first.str();
if (key.size() > 0 && key[0] == '\\')
key = key.substr(1);
result[key] = param.second.as_int();
}
return result;
}
double RTLIL::Cell::maxInputConstRatio() const
{
double max_ratio = 0.0;
for (auto &conn : connections_) {
if (input(conn.first)) {
double ratio = conn.second.const_ratio();
if (ratio > max_ratio)
max_ratio = ratio;
}
}
return max_ratio;
}
void RTLIL::Cell::sort()
{
connections_.sort(sort_by_id_str());
@ -5605,13 +5631,18 @@ bool RTLIL::SigSpec::is_chunk() const
return ++it == cs.end();
}
bool RTLIL::SigSpec::is_mostly_const(double const_ratio_threshold) const
double RTLIL::SigSpec::const_ratio() const
{
int constbits = 0;
for (auto &chunk : chunks())
if (chunk.width > 0 && chunk.wire == NULL)
constbits += chunk.width;
return (constbits > size() * const_ratio_threshold);
return empty() ? 0.0 : static_cast<double>(constbits) / size();
}
bool RTLIL::SigSpec::is_mostly_const(double const_ratio_threshold) const
{
return (const_ratio() > const_ratio_threshold);
}
bool RTLIL::SigSpec::known_driver() const

View File

@ -1684,8 +1684,9 @@ public:
bool known_driver() const;
// const_ratio_threshold is expected in [0.0, 1.0]
// boundary is exclusive, returns true only if const bit ratio > const_ratio_threshold
// Constant bit ratio helpers: const_ratio() returns [0.0, 1.0],
// is_mostly_const() returns true if const_ratio() > threshold
double const_ratio() const;
bool is_mostly_const(double const_ratio_threshold = 0.5) const;
bool is_fully_const() const;
bool is_fully_zero() const;
@ -2531,6 +2532,13 @@ public:
void setParam(RTLIL::IdString paramname, RTLIL::Const value);
const RTLIL::Const &getParam(RTLIL::IdString paramname) const;
// Primitive-type parameter accessors for efficient Python interop.
// NOTE: silently truncates wide (>32-bit) parameters and reinterprets string-typed Const values
std::map<std::string, int> getParamsAsInts() const;
// Returns the maximum const_ratio() across all input ports, 0.0 if no input ports
double maxInputConstRatio() const;
void sort();
void check();
void fixup_parameters(bool set_a_signed = false, bool set_b_signed = false);