42using SILICON::yosys::SerializationContext;
43using namespace SILICON::yosys::detail;
48 const std::size_t index,
49 const std::size_t expectedWidth)
51 const auto& bus =
requireBus(component, input, index);
55 const bool requiresConnection = input;
56 if (bus.size() != expectedWidth
57 || (requiresConnection && std::ranges::contains(bus,
nullptr))) {
58 throw std::runtime_error(
59 std::format(
"Cannot export '{}': {} bus {} must be a {}{}-bit bus",
60 component.
typeName(), input ?
"input" :
"output", index,
61 requiresConnection ?
"connected " :
"", expectedWidth));
67 const std::size_t index)
73 const std::size_t expectedOutputs)
75 if (component.
inputBuses().size() != expectedInputs
76 || component.
outputBuses().size() != expectedOutputs) {
77 throw std::runtime_error(std::format(
78 "Cannot export malformed '{}': unexpected bus count", component.
typeName()));
88 const std::string_view operation,
const bool invert =
false)
90 if (gate.getPropertyValue<
bool>(
"bitwise").value_or(
false)
91 || gate.getPropertyValue<
int>(
"size").value_or(1) <= 1)
97 const auto reduced = invert ? context.
allocateBits(1) : context.
bits(output);
98 emitUnary(context,
"reduce", operation, context.
bits(input), reduced);
100 emitUnary(context,
"invert",
"$not", reduced, context.
bits(output));
107 throw std::runtime_error(std::format(
108 "Component type '{}' does not support Yosys serialization",
typeName()));
115 if (!snapshot || snapshot->empty() || width == 0)
116 throw std::runtime_error(
"Cannot export ROM without resolved binary contents");
118 const auto derivedCount = (snapshot->size() * 8 + width - 1) / width;
119 if (!std::has_single_bit(count)
120 || (snapshot->size() != (count * width + 7) / 8 && derivedCount != count))
121 throw std::runtime_error(
"Cannot export ROM with invalid packed word count");
122 const auto addressWidth = std::max<std::size_t>(1, std::bit_width(count - 1));
125 throw std::runtime_error(
"Cannot export malformed ROM buses");
127 std::string init(count * width,
'0');
128 for (std::size_t bit = 0; bit < init.size(); ++bit) {
129 const auto byte = bit / 8 < snapshot->size()
130 ?
static_cast<unsigned char>((*snapshot)[bit / 8]) : 0;
131 init[init.size() - bit - 1] = (
byte & (1u << (bit % 8))) ?
'1' :
'0';
135 Json address = count == 1 ? Json::array({
"0"})
136 : context.
inputBits(*
this,0, addressWidth);
139 if (binaryDocument && !binaryDocument->empty())
143 Json{{
"ABITS", p(addressWidth)}, {
"INIT", init},
145 {
"OFFSET", p(0)}, {
"RD_ARST_VALUE", std::string(width,
'x')},
146 {
"RD_CE_OVER_SRST",
"0"}, {
"RD_CLK_ENABLE",
"0"},
147 {
"RD_CLK_POLARITY",
"0"}, {
"RD_COLLISION_X_MASK",
"0"},
148 {
"RD_INIT_VALUE", std::string(width,
'x')}, {
"RD_PORTS", p(1)},
149 {
"RD_SRST_VALUE", std::string(width,
'x')},
150 {
"RD_TRANSPARENCY_MASK",
"0"}, {
"RD_WIDE_CONTINUATION",
"0"},
151 {
"SIZE", p(count)}, {
"WIDTH", p(width)}, {
"WR_CLK_ENABLE",
"0"},
152 {
"WR_CLK_POLARITY",
"0"}, {
"WR_PORTS", p(0)},
153 {
"WR_PRIORITY_MASK",
"0"}, {
"WR_WIDE_CONTINUATION",
"0"}},
154 Json{{
"RD_ADDR",
"input"}, {
"RD_ARST",
"input"}, {
"RD_CLK",
"input"},
155 {
"RD_DATA",
"output"}, {
"RD_EN",
"input"}, {
"RD_SRST",
"input"},
156 {
"WR_ADDR",
"input"}, {
"WR_CLK",
"input"}, {
"WR_DATA",
"input"},
158 Json{{
"RD_ADDR", address}, {
"RD_ARST", Json::array({
"0"})},
159 {
"RD_CLK", Json::array({
"x"})}, {
"RD_DATA", readData},
160 {
"RD_EN", Json::array({
"1"})}, {
"RD_SRST", Json::array({
"0"})},
161 {
"WR_ADDR", Json::array()}, {
"WR_CLK", Json::array()},
162 {
"WR_DATA", Json::array()}, {
"WR_EN", Json::array()}},
164 context.
addCell(
"hold",
"$dlatch",
165 Json{{
"EN_POLARITY", p(1)}, {
"WIDTH", p(width)}},
166 Json{{
"D",
"input"}, {
"EN",
"input"}, {
"Q",
"output"}},
167 Json{{
"D", readData}, {
"EN", context.
inputBits(*
this, 1, 1)},
174 throw std::runtime_error(
"Cannot export a malformed constant component");
178 Json bits = Json::array();
179 for (
const State state : value) {
185 throw std::runtime_error(
"Cannot export an ERROR constant to Yosys");
201 throw std::runtime_error(
"Cannot export boundary I/O without a port role");
207 if (emitReductionGate(context, *
this,
"$reduce_and"))
213 && std::ranges::any_of(
inputBuses(), [](
const Bus& bus) {
return bus.
size() > 1; });
226 if (emitReductionGate(context, *
this,
"$reduce_or"))
232 && std::ranges::any_of(
inputBuses(), [](
const Bus& bus) {
return bus.
size() > 1; });
245 const auto& input =
requireBus(*
this,
true, 0);
246 const auto& output =
requireBus(*
this,
false, 0);
247 if (input.size() != output.size() && output.size() != 1) {
248 throw std::runtime_error(
249 "Cannot export 'NotGate': output must be scalar or match the input width");
252 emitUnary(context,
"not", input.size() == output.size() ?
"$not" :
"$logic_not",
253 context.
bits(input), context.
bits(output));
258 if (emitReductionGate(context, *
this,
"$reduce_and",
true))
268 if (emitReductionGate(context, *
this,
"$reduce_or",
true))
278 if (emitReductionGate(context, *
this,
"$reduce_xor"))
297 throw std::runtime_error(
298 "Cannot export malformed 'Extender': expected 1 input and 1 output");
303 if (!inSize || !outSize || !mode || *inSize < 1 || *outSize < 1
305 throw std::runtime_error(
306 "Cannot export malformed 'Extender': buses do not match its properties");
308 const auto& input =
requireBusWidth(*
this,
true, 0,
static_cast<std::size_t
>(*inSize));
317 directions({{
"A",
"input"}, {
"Y",
"output"}}),
318 Json{{
"A", context.
bits(input)}, {
"Y", context.
bits(output)}});
324 throw std::runtime_error(
325 "Cannot export malformed 'Complementer': expected 1 input and 1 output");
328 if (!width || *width < 1) {
329 throw std::runtime_error(
330 "Cannot export malformed 'Complementer': buses do not match its size property");
332 const auto busWidth =
static_cast<std::size_t
>(*width);
336 context.
addCell(
"complement",
"$neg",
340 directions({{
"A",
"input"}, {
"Y",
"output"}}),
341 Json{{
"A", context.
bits(input)}, {
"Y", context.
bits(output)}});
347 throw std::runtime_error(
348 "Cannot export malformed 'HalfAdder': expected 2 inputs and 2 outputs");
352 directions({{
"A",
"input"}, {
"B",
"input"}, {
"SUM",
"output"}, {
"COUT",
"output"}}),
362 throw std::runtime_error(
363 "Cannot export malformed 'FullAdder': expected 3 inputs and 2 outputs");
370 {
"COUT",
"output"}}),
381 throw std::runtime_error(
382 "Cannot export malformed 'AdderNBits': expected 2 inputs and 2 outputs");
384 if (!width || *width < 1) {
385 throw std::runtime_error(
386 "Cannot export malformed 'AdderNBits': buses do not match its size property");
388 const auto busWidth =
static_cast<std::size_t
>(*width);
398 directions({{
"A",
"input"}, {
"B",
"input"}, {
"SUM",
"output"}, {
"COUT",
"output"}}),
400 {
"B", context.
bits(b)},
401 {
"SUM", context.
bits(sum)},
402 {
"COUT", context.
bits(carry)}});
410 if (!width || *width < 1 || !sign)
411 throw std::runtime_error(
"Cannot export malformed 'Multiplier': invalid properties");
418 directions({{
"A",
"input"}, {
"B",
"input"}, {
"PRODUCT",
"output"}}),
420 {
"B", context.
bits(b)},
421 {
"PRODUCT", context.
bits(product)}});
429 if (!width || *width < 1 || !sign)
430 throw std::runtime_error(
"Cannot export malformed 'Divider': invalid properties");
443 {
"B", context.
bits(b)},
444 {
"div", context.
bits(quotient)},
445 {
"mod", context.
bits(remainder)}});
455 if (!width || *width < 1 || !amountWidth || *amountWidth < 1 || !mode
457 throw std::runtime_error(
"Cannot export malformed 'Shifter': invalid properties");
462 const auto type = *mode ==
LEFT_MODE ?
"$shl" : (*isSigned ?
"$sshr" :
"$shr");
470 directions({{
"A",
"input"}, {
"B",
"input"}, {
"Y",
"output"}}),
472 {
"B", context.
bits(amount)},
473 {
"Y", context.
bits(result)}});
483 if (!width || *width < 1 || !mode || !isSigned)
484 throw std::runtime_error(
"Cannot export malformed 'Comparator': invalid properties");
486 static constexpr std::array MODES{
487 std::pair<std::string_view, std::string_view>{
"==",
"$eq"},
488 std::pair<std::string_view, std::string_view>{
"<",
"$lt"},
489 std::pair<std::string_view, std::string_view>{
"<=",
"$le"},
490 std::pair<std::string_view, std::string_view>{
">",
"$gt"},
491 std::pair<std::string_view, std::string_view>{
">=",
"$ge"},
493 const auto cellType = std::ranges::find_if(
494 MODES, [&mode](
const auto& entry) {
return entry.first == *mode; });
495 if (cellType == MODES.end())
496 throw std::runtime_error(
"Cannot export malformed 'Comparator': invalid mode");
498 const auto busWidth =
static_cast<std::size_t
>(*width);
504 "compare", cellType->second,
505 Json{{
"A_SIGNED", SerializationContext::parameter(*isSigned, 1)},
506 {
"B_SIGNED", SerializationContext::parameter(*isSigned, 1)},
507 {
"A_WIDTH", SerializationContext::parameter(*width)},
508 {
"B_WIDTH", SerializationContext::parameter(*width)},
509 {
"Y_WIDTH", SerializationContext::parameter(1)}},
510 directions({{
"A",
"input"}, {
"B",
"input"}, {
"Y",
"output"}}),
511 Json{{
"A", context.
bits(a)}, {
"B", context.
bits(b)}, {
"Y", context.
bits(y)}});
520 if (busWidth < 1 || selectionWidth < 1
521 || selectionWidth >= std::numeric_limits<std::size_t>::digits) {
522 throw std::runtime_error(
"Cannot export malformed multiplexer properties");
524 const std::size_t laneCount = std::size_t{1} << selectionWidth;
526 const std::size_t dataCount =
527 table.empty() ? laneCount
528 :
static_cast<std::size_t
>(*std::ranges::max_element(table)) + 1;
529 const std::size_t selectionIndex = dataCount;
532 std::vector<Json> lanes;
533 lanes.reserve(laneCount);
534 for (std::size_t lane = 0; lane < laneCount; ++lane)
535 lanes.push_back(context.
bits(
536 requireBusWidth(*
this,
true, table.empty() ? lane : table.at(lane), busWidth)));
537 const auto& selection =
requireBusWidth(*
this,
true, selectionIndex, selectionWidth);
540 context.
addCell(
"mux",
"$bmux",
543 directions({{
"A",
"input"}, {
"S",
"input"}, {
"Y",
"output"}}),
545 {
"S", context.
bits(selection)},
546 {
"Y", context.
bits(output)}});
559 context.
addCell(
"demux",
"$demux",
562 directions({{
"A",
"input"}, {
"S",
"input"}, {
"Y",
"output"}}),
573 context.
addCell(
"decode",
"$demux",
576 directions({{
"A",
"input"}, {
"S",
"input"}, {
"Y",
"output"}}),
590 for (std::size_t port = 0; port <
outputBuses().size(); ++port) {
591 const auto [offset, width] =
slices.at(port);
592 Json bits = Json::array();
593 for (
unsigned int bit = 0; bit < width; ++bit)
594 bits.push_back(input.at(offset + bit));
595 inputs.push_back(std::move(bits));
619 [[nodiscard]]
bool connected(
const Json& bits)
621 return bits.size() == 1 && bits[0].is_number_integer();
624 [[nodiscard]]
bool positiveClock(
const Component& component)
627 if (!edge || (*edge !=
"PET" && *edge !=
"NET"))
628 throw std::runtime_error(std::format(
629 "Cannot export '{}': invalid triggerEdge property", component.
typeName()));
630 return *edge ==
"PET";
633 void emitDff(SerializationContext& context,
const Component& component, Json data,
634 std::optional<Json> enable, Json clock, Json clear, Json preset,
635 const Bus& q,
const Bus& qn,
const std::string_view baseCell,
636 const std::string_view controlledCell,
const std::string_view instanceName)
638 const bool hasControls = connected(clear) || connected(preset);
641 Json portDirections =
directions({{
"D",
"input"}, {
"CLK",
"input"}});
642 Json connections{{
"D", std::move(data)}, {
"CLK", std::move(clock)}};
645 portDirections[
"EN"] =
"input";
646 connections[
"EN"] = std::move(*enable);
651 portDirections[
"SET"] =
"input";
652 portDirections[
"CLR"] =
"input";
653 connections[
"SET"] = std::move(preset);
654 connections[
"CLR"] = std::move(clear);
656 portDirections[
"Q"] =
"output";
657 portDirections[
"QN"] =
"output";
658 connections[
"Q"] = context.
bits(q);
659 connections[
"QN"] = context.
bits(qn);
660 context.
addCell(instanceName, hasControls ? controlledCell : baseCell,
661 std::move(parameters), std::move(portDirections),
662 std::move(connections));
672 emitDff(context, *
this, context.
inputBits(*
this, 0, 1), std::nullopt,
683 emitDff(context, *
this, context.
inputBits(*
this, 0, 1), context.
inputBits(*
this, 1, 1),
697 directions({{
"D",
"input"}, {
"EN",
"input"}, {
"Q",
"output"}, {
"QN",
"output"}}),
700 {
"Q", context.
bits(q)},
701 {
"QN", context.
bits(qn)}});
726 {
"Q", context.
bits(q)},
727 {
"QN", context.
bits(qn)}});
735 if (!widthProperty || *widthProperty <= 1 || !inputType || !outputType
738 throw std::runtime_error(
"Cannot export malformed 'Register': invalid properties");
740 const auto width =
static_cast<std::size_t
>(*widthProperty);
743 const auto expectedInputs = parallelIn && !parallelOut ? 5U : 4U;
745 throw std::runtime_error(
"Cannot export malformed 'Register': unexpected bus count");
747 const auto expectedDataWidth = parallelIn ? width : 1;
748 const auto expectedOutputWidth = parallelOut ? width : 1;
752 const auto& clear =
requireBus(*
this,
true, 3);
753 if (clear.size() != 1)
754 throw std::runtime_error(
"Cannot export malformed 'Register': clear must be one bit");
755 const auto& output =
requireBusWidth(*
this,
false, 0, expectedOutputWidth);
760 Json connections{{
"DATA", context.
bits(data)},
761 {
"CLK", context.
bits(clock)},
762 {
"EN", context.
bits(enable)},
764 {
"OUT", context.
bits(output)}};
766 if (parallelIn && !parallelOut) {
776 std::move(connections));
783 const auto cellName = parallelIn ?
"pipo" : parallelOut ?
"sipo" :
"siso";
784 context.
addCell(cellName, cellType, std::move(parameters),
790 std::move(connections));
799 throw std::runtime_error(
"Subcircuit serialization requires a circuit resolver");
void serializeYosys(SILICON::yosys::SerializationContext &context) const override
Lower this component into native Yosys netlist cells.
void serializeYosys(SILICON::yosys::SerializationContext &context) const override
Lower this component into native Yosys netlist cells.
Base class for all digital circuit components.
const std::vector< Bus > & inputBuses() const
Gets all input buses without copying.
virtual std::string_view typeName() const =0
Gets the component type name.
std::optional< T > getPropertyValue(std::string_view key) const
Gets a property value with type deduction.
std::vector< Bus > outputs
Output buses produced by this component.
const std::vector< Bus > & outputBuses() const
Gets all output buses without copying.
std::vector< Bus > inputs
Input buses connected to this component.
virtual ComponentMetadata metadata() const
Gets catalog metadata for this component type.
virtual void serializeYosys(SILICON::yosys::SerializationContext &context) const
Lower this component into native Yosys netlist cells.
void serializeYosys(SILICON::yosys::SerializationContext &context) const override
Lower this component into native Yosys netlist cells.
void serializeYosys(SILICON::yosys::SerializationContext &context) const override
Lower this component into native Yosys netlist cells.
void serializeYosys(SILICON::yosys::SerializationContext &context) const override
Lower this component into native Yosys netlist cells.
void serializeYosys(SILICON::yosys::SerializationContext &context) const override
Lower this component into native Yosys netlist cells.
Base class for combinational logic gates.
void serializeYosys(SILICON::yosys::SerializationContext &context) const override
Lower this component into native Yosys netlist cells.
void serializeYosys(SILICON::yosys::SerializationContext &context) const override
Lower this component into native Yosys netlist cells.
void serializeYosys(SILICON::yosys::SerializationContext &context) const override
Lower this component into native Yosys netlist cells.
void serializeYosys(SILICON::yosys::SerializationContext &context) const override
Lower this component into native Yosys netlist cells.
void serializeYosys(SILICON::yosys::SerializationContext &context) const override
Lower this component into native Yosys netlist cells.
std::size_t resolvedWordCount() const noexcept
void serializeYosys(SILICON::yosys::SerializationContext &context) const override
Lower this component into native Yosys netlist cells.
std::shared_ptr< const std::string > binaryContentsSnapshot() const noexcept
void serializeYosys(SILICON::yosys::SerializationContext &context) const override
Lower this component into native Yosys netlist cells.
static constexpr std::string_view SERIAL_TYPE
static constexpr std::string_view PARALLEL_TYPE
Mutable module-building interface passed to component serializers.
Json bits(const core::Bus &bus, std::string_view nullValue="x") const
Convert a Silicon bus to a Yosys least-significant-bit-first vector.
Json allocateBits(std::size_t width)
Allocate module-local temporary signal bits.
static std::string parameter(std::uint64_t value, std::size_t width=32)
Encode an unsigned Yosys parameter as a fixed-width binary string.
void addCell(std::string_view suffix, std::string_view type, Json parameters, Json portDirections, Json connections, Json attributes=Json::object())
Emit one native Yosys cell for the current Silicon component.
static Json concatenate(const std::vector< Json > &vectors)
Concatenate bit vectors in their existing LSB-first order.
const CircuitResolver * circuitResolver() const noexcept
std::vector< Bus > outputsForPorts(const std::vector< CircuitPort > &ports) const
std::vector< Bus > inputsForPorts(const std::vector< CircuitPort > &ports) const
void serializeYosys(SILICON::yosys::SerializationContext &context) const override
Lower this component into native Yosys netlist cells.
void serializeYosys(SILICON::yosys::SerializationContext &context) const override
Lower this component into native Yosys netlist cells.
Mutable module-building interface passed to component serializers.
void addPort(std::string name, std::string_view direction, const core::Bus &bus)
Register a named top-level input or output port.
void addSubcircuitInstance(std::string_view slug, const std::vector< core::Bus > &inputs, const std::vector< core::Bus > &outputs, const core::CircuitResolver *resolver)
Emit a hierarchical instance and recursively serialize its definition.
Json bits(const core::Bus &bus, std::string_view nullValue="x") const
Convert a Silicon bus to a Yosys least-significant-bit-first vector.
Json allocateBits(std::size_t width)
Allocate module-local temporary signal bits.
std::string componentIdentifier() const
Stable name of the component being serialized within its module.
Json inputBits(const core::Component &component, std::size_t index, std::size_t expectedWidth) const
Encode a component input, applying its declared unconnected-input default.
void addCell(std::string_view suffix, std::string_view type, Json parameters, Json portDirections, Json connections, Json attributes=Json::object())
Emit one native Yosys cell for the current Silicon component.
const Bus & requireBusWidth(const Component &component, const bool input, const std::size_t index, const std::size_t expectedWidth)
void requireBusCounts(const Component &component, const std::size_t expectedInputs, const std::size_t expectedOutputs)
const Bus & requireScalarBus(const Component &component, const bool input, const std::size_t index)
std::vector< State > BusValue
constexpr std::string_view BINARY_DOCUMENT
constexpr std::string_view ADDER
constexpr std::string_view PISO
constexpr std::string_view DFFSRE
constexpr std::string_view DIVIDER
constexpr std::string_view SISO
constexpr std::string_view DFFSR
constexpr std::string_view PIPO
constexpr std::string_view JKFF
constexpr std::string_view DLATCH
constexpr std::string_view MULTIPLIER
constexpr std::string_view FULL_ADDER
constexpr std::string_view SIPO
constexpr std::string_view DFF
constexpr std::string_view DFFE
constexpr std::string_view HALF_ADDER
void emitGateFold(SerializationContext &context, const Component &component, const std::string_view operation, const bool invert)
Json directions(std::initializer_list< std::pair< std::string_view, std::string_view > > values)
const Bus & requireBus(const Component &component, const bool input, const std::size_t index)
void emitLogicalGateFold(SerializationContext &context, const Component &component, const std::string_view operation)
void emitUnary(SerializationContext &context, const std::string_view suffix, const std::string_view type, const Json &input, const Json &output)
nlohmann::ordered_json Json