Skip to content

Commit

Permalink
rtlil: add Const:: as_int_compressed function
Browse files Browse the repository at this point in the history
  • Loading branch information
phsauter authored and widlarizer committed Oct 9, 2024
1 parent 07fb8af commit c53c87e
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
27 changes: 24 additions & 3 deletions kernel/rtlil.cc
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@

#include <string.h>
#include <algorithm>
#include <optional>

YOSYS_NAMESPACE_BEGIN

Expand Down Expand Up @@ -280,9 +281,9 @@ int RTLIL::Const::as_int(bool is_signed) const
return ret;
}

void RTLIL::Const::compress(bool is_signed)
size_t RTLIL::Const::get_min_size(bool is_signed) const
{
if (bits.empty()) return;
if (bits.empty()) return 0;

// back to front (MSB to LSB)
RTLIL::State leading_bit;
Expand All @@ -301,11 +302,31 @@ void RTLIL::Const::compress(bool is_signed)
idx++;
}
// must be at least one bit
idx = (idx == 0) ? 1 : idx;
return (idx == 0) ? 1 : idx;
}

void RTLIL::Const::compress(bool is_signed)
{
size_t idx = get_min_size(is_signed);
bits.erase(bits.begin() + idx, bits.end());
}

std::optional<int> RTLIL::Const::as_int_compress(bool is_signed) const
{
size_t size = get_min_size(is_signed);
if(size == 0 || size > 32)
return std::nullopt;

int32_t ret = 0;
for (size_t i = 0; i < size && i < 32; i++)
if (bits[i] == State::S1)
ret |= 1 << i;
if (is_signed && bits[size-1] == State::S1)
for (size_t i = size; i < 32; i++)
ret |= 1 << i;
return ret;
}

std::string RTLIL::Const::as_string() const
{
std::string ret;
Expand Down
5 changes: 5 additions & 0 deletions kernel/rtlil.h
Original file line number Diff line number Diff line change
Expand Up @@ -703,9 +703,14 @@ struct RTLIL::Const
return ret;
}

// find the MSB without redundant leading bits
size_t get_min_size(bool is_signed) const;

// compress representation to the minimum required bits
void compress(bool is_signed = false);

std::optional<int> as_int_compress(bool is_signed) const;

void extu(int width) {
bits.resize(width, RTLIL::State::S0);
}
Expand Down

0 comments on commit c53c87e

Please sign in to comment.