SILICON
Loading...
Searching...
No Matches
components.cpp
Go to the documentation of this file.
1/*
2 Copyright (c) 2026. Giulio Cocconi
3
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18/* Per-component lowering from Silicon semantics to native Yosys cells. */
19
20#include "cells.hpp"
21#include "helpers.hpp"
22
24#include <core/flipflops.hpp>
25#include <core/gates.hpp>
26#include <core/io.hpp>
27#include <core/memory.hpp>
28#include <core/register.hpp>
29#include <core/subcircuit.hpp>
33
34#include <limits>
35#include <bit>
36#include <optional>
37#include <ranges>
38
39namespace SILICON::core {
40
42using SILICON::yosys::SerializationContext;
43using namespace SILICON::yosys::detail;
44
46
47 [[nodiscard]] const Bus& requireBusWidth(const Component& component, const bool input,
48 const std::size_t index,
49 const std::size_t expectedWidth)
50 {
51 const auto& bus = requireBus(component, input, index);
52 // A disconnected output is a valid unused pin. The serialization context gives it
53 // a private signal when the cell is emitted. Optional inputs are encoded through
54 // SerializationContext::inputBits(), which also applies their declared default.
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));
62 }
63 return bus;
64 }
65
66 [[nodiscard]] const Bus& requireScalarBus(const Component& component, const bool input,
67 const std::size_t index)
68 {
69 return requireBusWidth(component, input, index, 1);
70 }
71
72 void requireBusCounts(const Component& component, const std::size_t expectedInputs,
73 const std::size_t expectedOutputs)
74 {
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()));
79 }
80 }
81
82} // namespace yosys_component_detail
83
84using namespace yosys_component_detail;
85
86namespace {
87 bool emitReductionGate(SerializationContext& context, const Gate& gate,
88 const std::string_view operation, const bool invert = false)
89 {
90 if (gate.getPropertyValue<bool>("bitwise").value_or(false)
91 || gate.getPropertyValue<int>("size").value_or(1) <= 1)
92 return false;
93
94 requireBusCounts(gate, 1, 1);
95 const auto& input = requireBus(gate, true, 0);
96 const auto& output = requireScalarBus(gate, false, 0);
97 const auto reduced = invert ? context.allocateBits(1) : context.bits(output);
98 emitUnary(context, "reduce", operation, context.bits(input), reduced);
99 if (invert)
100 emitUnary(context, "invert", "$not", reduced, context.bits(output));
101 return true;
102 }
103} // namespace
104
106{
107 throw std::runtime_error(std::format(
108 "Component type '{}' does not support Yosys serialization", typeName()));
109}
110
112{
113 const auto snapshot = binaryContentsSnapshot();
114 const auto width = static_cast<std::size_t>(getPropertyValue<int>("dataWidth").value_or(8));
115 if (!snapshot || snapshot->empty() || width == 0)
116 throw std::runtime_error("Cannot export ROM without resolved binary contents");
117 const auto count = resolvedWordCount();
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));
123 if (inputBuses().size() != 3 || outputBuses().size() != 1
124 || inputBuses()[0].size() != addressWidth || outputBuses()[0].size() != width)
125 throw std::runtime_error("Cannot export malformed ROM buses");
126
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';
132 }
133 const auto p = [](std::uint64_t value) { return SerializationContext::parameter(value); };
134 const auto readData = context.allocateBits(width);
135 Json address = count == 1 ? Json::array({"0"})
136 : context.inputBits(*this,0, addressWidth);
137 Json attributes = Json::object();
138 const auto binaryDocument = getPropertyValue<std::string>("binaryContents");
139 if (binaryDocument && !binaryDocument->empty())
140 attributes[std::string(SILICON::yosys::attributes::BINARY_DOCUMENT)] = *binaryDocument;
141 context.addCell(
142 "memory", "$mem_v2",
143 Json{{"ABITS", p(addressWidth)}, {"INIT", init},
144 {"MEMID", std::format("\\{}", context.componentIdentifier())},
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"},
157 {"WR_EN", "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()}},
163 std::move(attributes));
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)},
168 {"Q", context.bits(outputBuses()[0])}});
169}
170
172{
173 if (outputBuses().empty())
174 throw std::runtime_error("Cannot export a malformed constant component");
175
176 const auto value = getPropertyValue<BusValue>("value").value_or(
177 BusValue(outputBuses()[0].size(), State::UNKNOWN));
178 Json bits = Json::array();
179 for (const State state : value) {
180 switch (state) {
181 case State::LOW: bits.push_back("0"); break;
182 case State::HIGH: bits.push_back("1"); break;
183 case State::UNKNOWN: bits.push_back("x"); break;
184 case State::ERROR:
185 throw std::runtime_error("Cannot export an ERROR constant to Yosys");
186 }
187 }
188 emitUnary(context, "constant", "$pos", std::move(bits), context.bits(outputBuses()[0]));
189}
190
192{
193 const auto role = metadata().portRole;
194 if (role == PortRole::Input) {
195 context.addPort(getPropertyValue<std::string>("name").value_or("input"), "input",
196 outputBuses().at(0));
197 } else if (role == PortRole::Output) {
198 context.addPort(getPropertyValue<std::string>("name").value_or("output"), "output",
199 inputBuses().at(0));
200 } else {
201 throw std::runtime_error("Cannot export boundary I/O without a port role");
202 }
203}
204
206{
207 if (emitReductionGate(context, *this, "$reduce_and"))
208 return;
209
210 const bool logical =
211 !getPropertyValue<bool>("bitwise").value_or(false) && outputBuses().size() == 1
212 && outputBuses()[0].size() == 1
213 && std::ranges::any_of(inputBuses(), [](const Bus& bus) { return bus.size() > 1; });
214 if (logical) {
215 emitLogicalGateFold(context, *this, "$logic_and");
216 return;
217 }
218
219 // Yosys $and cells have exactly two vector inputs. Fold Silicon's arbitrary
220 // number of equally sized inputs from left to right, writing the final value to Y.
221 emitGateFold(context, *this, "$and", false);
222}
223
225{
226 if (emitReductionGate(context, *this, "$reduce_or"))
227 return;
228
229 const bool logical =
230 !getPropertyValue<bool>("bitwise").value_or(false) && outputBuses().size() == 1
231 && outputBuses()[0].size() == 1
232 && std::ranges::any_of(inputBuses(), [](const Bus& bus) { return bus.size() > 1; });
233 if (logical) {
234 emitLogicalGateFold(context, *this, "$logic_or");
235 return;
236 }
237
238 // Build a chain of binary $or cells so multi-input and bitwise Silicon OR gates
239 // retain their original input count and bus width.
240 emitGateFold(context, *this, "$or", false);
241}
242
244{
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");
250 }
251
252 emitUnary(context, "not", input.size() == output.size() ? "$not" : "$logic_not",
253 context.bits(input), context.bits(output));
254}
255
257{
258 if (emitReductionGate(context, *this, "$reduce_and", true))
259 return;
260
261 // First reduce every input with binary $and cells, then invert the reduced vector;
262 // Yosys has no native arbitrary-input NAND cell.
263 emitGateFold(context, *this, "$and", true);
264}
265
267{
268 if (emitReductionGate(context, *this, "$reduce_or", true))
269 return;
270
271 // First reduce every input with binary $or cells, then invert the reduced vector;
272 // this preserves Silicon's arbitrary-input NOR behavior.
273 emitGateFold(context, *this, "$or", true);
274}
275
277{
278 if (emitReductionGate(context, *this, "$reduce_xor"))
279 return;
280
281 // Fold all inputs through binary $xor cells. For more than two inputs this
282 // implements the same odd-parity result as Silicon's XOR gate.
283 emitGateFold(context, *this, "$xor", false);
284}
285
286} // namespace SILICON::core
287
288namespace SILICON::extra {
289using namespace SILICON::core;
293
295{
296 if (inputBuses().size() != 1 || outputBuses().size() != 1)
297 throw std::runtime_error(
298 "Cannot export malformed 'Extender': expected 1 input and 1 output");
299
300 const auto inSize = getPropertyValue<int>("inSize");
301 const auto outSize = getPropertyValue<int>("outSize");
302 const auto mode = getPropertyValue<std::string>("mode");
303 if (!inSize || !outSize || !mode || *inSize < 1 || *outSize < 1
304 || (*mode != SIGNED_MODE && *mode != UNSIGNED_MODE)) {
305 throw std::runtime_error(
306 "Cannot export malformed 'Extender': buses do not match its properties");
307 }
308 const auto& input = requireBusWidth(*this, true, 0, static_cast<std::size_t>(*inSize));
309 const auto& output =
310 requireBusWidth(*this, false, 0, static_cast<std::size_t>(*outSize));
311
312 context.addCell(
313 "extend", "$pos",
314 Json{{"A_SIGNED", SerializationContext::parameter(*mode == SIGNED_MODE, 1)},
315 {"A_WIDTH", SerializationContext::parameter(*inSize)},
316 {"Y_WIDTH", SerializationContext::parameter(*outSize)}},
317 directions({{"A", "input"}, {"Y", "output"}}),
318 Json{{"A", context.bits(input)}, {"Y", context.bits(output)}});
319}
320
322{
323 if (inputBuses().size() != 1 || outputBuses().size() != 1)
324 throw std::runtime_error(
325 "Cannot export malformed 'Complementer': expected 1 input and 1 output");
326
327 const auto width = getPropertyValue<int>("size");
328 if (!width || *width < 1) {
329 throw std::runtime_error(
330 "Cannot export malformed 'Complementer': buses do not match its size property");
331 }
332 const auto busWidth = static_cast<std::size_t>(*width);
333 const auto& input = requireBusWidth(*this, true, 0, busWidth);
334 const auto& output = requireBusWidth(*this, false, 0, busWidth);
335
336 context.addCell("complement", "$neg",
337 Json{{"A_SIGNED", SerializationContext::parameter(0, 1)},
338 {"A_WIDTH", SerializationContext::parameter(*width)},
339 {"Y_WIDTH", SerializationContext::parameter(*width)}},
340 directions({{"A", "input"}, {"Y", "output"}}),
341 Json{{"A", context.bits(input)}, {"Y", context.bits(output)}});
342}
343
345{
346 if (inputBuses().size() != 2 || outputBuses().size() != 2)
347 throw std::runtime_error(
348 "Cannot export malformed 'HalfAdder': expected 2 inputs and 2 outputs");
349
350 context.addCell(
351 "half_adder", SILICON::yosys::cells::HALF_ADDER, Json::object(),
352 directions({{"A", "input"}, {"B", "input"}, {"SUM", "output"}, {"COUT", "output"}}),
353 Json{{"A", context.bits(requireScalarBus(*this, true, 0))},
354 {"B", context.bits(requireScalarBus(*this, true, 1))},
355 {"SUM", context.bits(requireScalarBus(*this, false, 0))},
356 {"COUT", context.bits(requireScalarBus(*this, false, 1))}});
357}
358
360{
361 if (inputBuses().size() != 3 || outputBuses().size() != 2)
362 throw std::runtime_error(
363 "Cannot export malformed 'FullAdder': expected 3 inputs and 2 outputs");
364
365 context.addCell("full_adder", SILICON::yosys::cells::FULL_ADDER, Json::object(),
366 directions({{"A", "input"},
367 {"B", "input"},
368 {"CIN", "input"},
369 {"SUM", "output"},
370 {"COUT", "output"}}),
371 Json{{"A", context.bits(requireScalarBus(*this, true, 0))},
372 {"B", context.bits(requireScalarBus(*this, true, 1))},
373 {"CIN", context.bits(requireScalarBus(*this, true, 2))},
374 {"SUM", context.bits(requireScalarBus(*this, false, 0))},
375 {"COUT", context.bits(requireScalarBus(*this, false, 1))}});
376}
377
379{
380 if (inputBuses().size() != 2 || outputBuses().size() != 2)
381 throw std::runtime_error(
382 "Cannot export malformed 'AdderNBits': expected 2 inputs and 2 outputs");
383 const auto width = getPropertyValue<int>("size");
384 if (!width || *width < 1) {
385 throw std::runtime_error(
386 "Cannot export malformed 'AdderNBits': buses do not match its size property");
387 }
388 const auto busWidth = static_cast<std::size_t>(*width);
389 const auto& a = requireBusWidth(*this, true, 0, busWidth);
390 const auto& b = requireBusWidth(*this, true, 1, busWidth);
391 const auto& sum = requireBusWidth(*this, false, 0, busWidth);
392 const auto& carry = requireScalarBus(*this, false, 1);
393
394 context.addCell(
396 Json{{"WIDTH", SerializationContext::parameter(*width)},
397 {"SIGNED", SerializationContext::parameter(0, 1)}},
398 directions({{"A", "input"}, {"B", "input"}, {"SUM", "output"}, {"COUT", "output"}}),
399 Json{{"A", context.bits(a)},
400 {"B", context.bits(b)},
401 {"SUM", context.bits(sum)},
402 {"COUT", context.bits(carry)}});
403}
404
406{
407 requireBusCounts(*this, 2, 1);
408 const auto width = getPropertyValue<int>("size");
409 const auto sign = getPropertyValue<bool>("signed");
410 if (!width || *width < 1 || !sign)
411 throw std::runtime_error("Cannot export malformed 'Multiplier': invalid properties");
412 const auto& a = requireBusWidth(*this, true, 0, *width);
413 const auto& b = requireBusWidth(*this, true, 1, *width);
414 const auto& product = requireBusWidth(*this, false, 0, *width);
415 context.addCell("multiplier", SILICON::yosys::cells::MULTIPLIER,
416 Json{{"WIDTH", SerializationContext::parameter(*width)},
417 {"SIGNED", SerializationContext::parameter(*sign, 1)}},
418 directions({{"A", "input"}, {"B", "input"}, {"PRODUCT", "output"}}),
419 Json{{"A", context.bits(a)},
420 {"B", context.bits(b)},
421 {"PRODUCT", context.bits(product)}});
422}
423
425{
426 requireBusCounts(*this, 2, 2);
427 const auto width = getPropertyValue<int>("size");
428 const auto sign = getPropertyValue<bool>("signed");
429 if (!width || *width < 1 || !sign)
430 throw std::runtime_error("Cannot export malformed 'Divider': invalid properties");
431 const auto& a = requireBusWidth(*this, true, 0, *width);
432 const auto& b = requireBusWidth(*this, true, 1, *width);
433 const auto& quotient = requireBusWidth(*this, false, 0, *width);
434 const auto& remainder = requireBusWidth(*this, false, 1, *width);
435 context.addCell("divider", SILICON::yosys::cells::DIVIDER,
436 Json{{"WIDTH", SerializationContext::parameter(*width)},
437 {"SIGNED", SerializationContext::parameter(*sign, 1)}},
438 directions({{"A", "input"},
439 {"B", "input"},
440 {"div", "output"},
441 {"mod", "output"}}),
442 Json{{"A", context.bits(a)},
443 {"B", context.bits(b)},
444 {"div", context.bits(quotient)},
445 {"mod", context.bits(remainder)}});
446}
447
449{
450 requireBusCounts(*this, 2, 1);
451 const auto width = getPropertyValue<int>("size");
452 const auto amountWidth = getPropertyValue<int>("amountSize");
453 const auto mode = getPropertyValue<std::string>("mode");
454 const auto isSigned = getPropertyValue<bool>("signed");
455 if (!width || *width < 1 || !amountWidth || *amountWidth < 1 || !mode
456 || (*mode != LEFT_MODE && *mode != RIGHT_MODE) || !isSigned)
457 throw std::runtime_error("Cannot export malformed 'Shifter': invalid properties");
458
459 const auto& value = requireBusWidth(*this, true, 0, *width);
460 const auto& amount = requireBusWidth(*this, true, 1, *amountWidth);
461 const auto& result = requireBusWidth(*this, false, 0, *width);
462 const auto type = *mode == LEFT_MODE ? "$shl" : (*isSigned ? "$sshr" : "$shr");
463 context.addCell(
464 "shifter", type,
465 Json{{"A_SIGNED", SerializationContext::parameter(*isSigned ? 1 : 0, 1)},
466 {"B_SIGNED", SerializationContext::parameter(0, 1)},
467 {"A_WIDTH", SerializationContext::parameter(*width)},
468 {"B_WIDTH", SerializationContext::parameter(*amountWidth)},
469 {"Y_WIDTH", SerializationContext::parameter(*width)}},
470 directions({{"A", "input"}, {"B", "input"}, {"Y", "output"}}),
471 Json{{"A", context.bits(value)},
472 {"B", context.bits(amount)},
473 {"Y", context.bits(result)}});
474}
475
477{
478 requireBusCounts(*this, 2, 1);
479
480 const auto width = getPropertyValue<int>("size");
481 const auto mode = getPropertyValue<std::string>("mode");
482 const auto isSigned = getPropertyValue<bool>("signed");
483 if (!width || *width < 1 || !mode || !isSigned)
484 throw std::runtime_error("Cannot export malformed 'Comparator': invalid properties");
485
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"},
492 };
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");
497
498 const auto busWidth = static_cast<std::size_t>(*width);
499 const auto& a = requireBusWidth(*this, true, 0, busWidth);
500 const auto& b = requireBusWidth(*this, true, 1, busWidth);
501 const auto& y = requireScalarBus(*this, false, 0);
502
503 context.addCell(
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)}});
512}
513
515{
516 // $bmux expects all selectable lanes packed consecutively into A and uses S as
517 // their zero-based index. Silicon exposes one bus per lane at every width.
518 const int busWidth = getPropertyValue<int>("busSize").value_or(1);
519 const int selectionWidth = getPropertyValue<int>("selectionSize").value_or(1);
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");
523 }
524 const std::size_t laneCount = std::size_t{1} << selectionWidth;
525 const auto& table = selectionTableIndices();
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;
530
531 requireBusCounts(*this, dataCount + 1, 1);
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);
538 const auto& output = requireBusWidth(*this, false, 0, busWidth);
539
540 context.addCell("mux", "$bmux",
541 Json{{"WIDTH", SerializationContext::parameter(busWidth)},
542 {"S_WIDTH", SerializationContext::parameter(selectionWidth)}},
543 directions({{"A", "input"}, {"S", "input"}, {"Y", "output"}}),
545 {"S", context.bits(selection)},
546 {"Y", context.bits(output)}});
547}
548
550{
551 // $demux routes A into the S-selected WIDTH-bit slice of Y and clears every other
552 // slice. Pack Silicon's separate output buses in lane order to form that Y vector.
553 const int busWidth = getPropertyValue<int>("busSize").value_or(1);
554 const int selectionWidth = getPropertyValue<int>("selectionSize").value_or(1);
555 std::vector<Json> outputs;
556 for (const auto& output : outputBuses())
557 outputs.push_back(context.bits(output));
558
559 context.addCell("demux", "$demux",
560 Json{{"WIDTH", SerializationContext::parameter(busWidth)},
561 {"S_WIDTH", SerializationContext::parameter(selectionWidth)}},
562 directions({{"A", "input"}, {"S", "input"}, {"Y", "output"}}),
563 Json{{"A", context.bits(requireBus(*this, true, 0))},
564 {"S", context.bits(requireBus(*this, true, 1))},
566}
567
569{
570 // A decoder is a one-bit $demux: the enable signal is its data input and S chooses
571 // which output bit receives it, producing zero on all unselected bits.
572 const int selectionWidth = getPropertyValue<int>("selectionSize").value_or(1);
573 context.addCell("decode", "$demux",
575 {"S_WIDTH", SerializationContext::parameter(selectionWidth)}},
576 directions({{"A", "input"}, {"S", "input"}, {"Y", "output"}}),
577 Json{{"A", context.bits(requireBus(*this, true, 0))},
578 {"S", context.bits(requireBus(*this, true, 1))},
579 {"Y", context.bits(requireBus(*this, false, 0))}});
580}
581
583{
584 // Outputs may be overlapping bus slices. Pack the corresponding source bits
585 // in output-port order so export preserves offsets, widths and repeated bits.
586 const auto input = context.bits(requireBus(*this, true, 0));
587 const auto slices = outputSlices();
588 std::vector<Json> inputs;
589 std::vector<Json> outputs;
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));
596 outputs.push_back(context.bits(outputBuses()[port]));
597 }
598 emitUnary(context, "split", "$pos", SerializationContext::concatenate(inputs),
600}
601
603{
604 // Merge the ordered input buses into one LSB-first vector, then use $pos as a
605 // width-preserving connection to the component's output bus.
606 std::vector<Json> inputs;
607 for (const auto& input : inputBuses())
608 inputs.push_back(context.bits(input));
609 emitUnary(context, "merge", "$pos", SerializationContext::concatenate(inputs),
610 context.bits(requireBus(*this, false, 0)));
611}
612
613} // namespace SILICON::extra
614
615namespace SILICON::core {
616
617namespace {
618
619 [[nodiscard]] bool connected(const Json& bits)
620 {
621 return bits.size() == 1 && bits[0].is_number_integer();
622 }
623
624 [[nodiscard]] bool positiveClock(const Component& component)
625 {
626 const auto edge = component.getPropertyValue<std::string>("triggerEdge");
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";
631 }
632
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)
637 {
638 const bool hasControls = connected(clear) || connected(preset);
639 Json parameters{
640 {"CLK_POLARITY", SerializationContext::parameter(positiveClock(component), 1)}};
641 Json portDirections = directions({{"D", "input"}, {"CLK", "input"}});
642 Json connections{{"D", std::move(data)}, {"CLK", std::move(clock)}};
643 if (enable) {
644 parameters["EN_POLARITY"] = SerializationContext::parameter(1, 1);
645 portDirections["EN"] = "input";
646 connections["EN"] = std::move(*enable);
647 }
648 if (hasControls) {
649 parameters["SET_POLARITY"] = SerializationContext::parameter(1, 1);
650 parameters["CLR_POLARITY"] = SerializationContext::parameter(1, 1);
651 portDirections["SET"] = "input";
652 portDirections["CLR"] = "input";
653 connections["SET"] = std::move(preset);
654 connections["CLR"] = std::move(clear);
655 }
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));
663 }
664
665} // namespace
666
668{
669 requireBusCounts(*this, 4, 2);
670 const auto& q = requireScalarBus(*this, false, 0);
671 const auto& qn = requireScalarBus(*this, false, 1);
672 emitDff(context, *this, context.inputBits(*this, 0, 1), std::nullopt,
673 context.inputBits(*this, 1, 1), context.inputBits(*this, 2, 1),
674 context.inputBits(*this, 3, 1), q, qn, SILICON::yosys::cells::DFF,
676}
677
679{
680 requireBusCounts(*this, 5, 2);
681 const auto& q = requireScalarBus(*this, false, 0);
682 const auto& qn = requireScalarBus(*this, false, 1);
683 emitDff(context, *this, context.inputBits(*this, 0, 1), context.inputBits(*this, 1, 1),
684 context.inputBits(*this, 2, 1), context.inputBits(*this, 3, 1),
685 context.inputBits(*this, 4, 1), q, qn, SILICON::yosys::cells::DFFE,
687}
688
690{
691 requireBusCounts(*this, 2, 2);
692 const auto& q = requireScalarBus(*this, false, 0);
693 const auto& qn = requireScalarBus(*this, false, 1);
694 context.addCell(
696 Json{{"EN_POLARITY", SerializationContext::parameter(1, 1)}},
697 directions({{"D", "input"}, {"EN", "input"}, {"Q", "output"}, {"QN", "output"}}),
698 Json{{"D", context.inputBits(*this, 0, 1)},
699 {"EN", context.inputBits(*this, 1, 1)},
700 {"Q", context.bits(q)},
701 {"QN", context.bits(qn)}});
702}
703
705{
706 requireBusCounts(*this, 5, 2);
707 const auto& q = requireScalarBus(*this, false, 0);
708 const auto& qn = requireScalarBus(*this, false, 1);
709 context.addCell(
711 Json{{"CLK_POLARITY", SerializationContext::parameter(positiveClock(*this), 1)},
712 {"SET_POLARITY", SerializationContext::parameter(1, 1)},
713 {"CLR_POLARITY", SerializationContext::parameter(1, 1)}},
714 directions({{"J", "input"},
715 {"K", "input"},
716 {"CLK", "input"},
717 {"SET", "input"},
718 {"CLR", "input"},
719 {"Q", "output"},
720 {"QN", "output"}}),
721 Json{{"J", context.inputBits(*this, 0, 1)},
722 {"K", context.inputBits(*this, 1, 1)},
723 {"CLK", context.inputBits(*this, 2, 1)},
724 {"SET", context.inputBits(*this, 4, 1)},
725 {"CLR", context.inputBits(*this, 3, 1)},
726 {"Q", context.bits(q)},
727 {"QN", context.bits(qn)}});
728}
729
731{
732 const auto widthProperty = getPropertyValue<int>("size");
733 const auto inputType = getPropertyValue<std::string>("inputType");
734 const auto outputType = getPropertyValue<std::string>("outputType");
735 if (!widthProperty || *widthProperty <= 1 || !inputType || !outputType
736 || (*inputType != PARALLEL_TYPE && *inputType != SERIAL_TYPE)
737 || (*outputType != PARALLEL_TYPE && *outputType != SERIAL_TYPE)) {
738 throw std::runtime_error("Cannot export malformed 'Register': invalid properties");
739 }
740 const auto width = static_cast<std::size_t>(*widthProperty);
741 const bool parallelIn = *inputType == PARALLEL_TYPE;
742 const bool parallelOut = *outputType == PARALLEL_TYPE;
743 const auto expectedInputs = parallelIn && !parallelOut ? 5U : 4U;
744 if (inputBuses().size() != expectedInputs || outputBuses().size() != 1)
745 throw std::runtime_error("Cannot export malformed 'Register': unexpected bus count");
746
747 const auto expectedDataWidth = parallelIn ? width : 1;
748 const auto expectedOutputWidth = parallelOut ? width : 1;
749 const auto& data = requireBusWidth(*this, true, 0, expectedDataWidth);
750 const auto& clock = requireScalarBus(*this, true, 1);
751 const auto& enable = requireScalarBus(*this, true, 2);
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);
756 Json parameters{{"WIDTH", SerializationContext::parameter(width)},
757 {"CLK_POLARITY", SerializationContext::parameter(1, 1)},
758 {"EN_POLARITY", SerializationContext::parameter(1, 1)},
759 {"CLR_POLARITY", SerializationContext::parameter(1, 1)}};
760 Json connections{{"DATA", context.bits(data)},
761 {"CLK", context.bits(clock)},
762 {"EN", context.bits(enable)},
763 {"CLR", context.inputBits(*this, 3, 1)},
764 {"OUT", context.bits(output)}};
765
766 if (parallelIn && !parallelOut) {
767 parameters["LOAD_POLARITY"] = SerializationContext::parameter(1, 1);
768 connections["LOAD"] = context.bits(requireScalarBus(*this, true, 4));
769 context.addCell("piso", SILICON::yosys::cells::PISO, std::move(parameters),
770 directions({{"DATA", "input"},
771 {"CLK", "input"},
772 {"EN", "input"},
773 {"CLR", "input"},
774 {"LOAD", "input"},
775 {"OUT", "output"}}),
776 std::move(connections));
777 return;
778 }
779
780 const auto cellType = parallelIn ? SILICON::yosys::cells::PIPO
781 : parallelOut ? SILICON::yosys::cells::SIPO
783 const auto cellName = parallelIn ? "pipo" : parallelOut ? "sipo" : "siso";
784 context.addCell(cellName, cellType, std::move(parameters),
785 directions({{"DATA", "input"},
786 {"CLK", "input"},
787 {"EN", "input"},
788 {"CLR", "input"},
789 {"OUT", "output"}}),
790 std::move(connections));
791}
792
794{
795 // Resolve the referenced definition by slug, serialize it once as its own Yosys
796 // module, and instantiate that module with this component's buses as named ports.
797 const auto slug = getPropertyValue<std::string>("slug").value_or(std::string());
798 if (!circuitResolver())
799 throw std::runtime_error("Subcircuit serialization requires a circuit resolver");
800 const auto definition = circuitResolver()->resolve(slug);
801 context.addSubcircuitInstance(slug, inputsForPorts(definition.inputs),
802 outputsForPorts(definition.outputs), circuitResolver());
803}
804
805} // namespace SILICON::core
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.
Definition component.cpp:54
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.
Definition gates.hpp:38
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
Definition memory.hpp:80
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
Definition memory.cpp:181
void serializeYosys(SILICON::yosys::SerializationContext &context) const override
Lower this component into native Yosys netlist cells.
static constexpr std::string_view SERIAL_TYPE
Definition register.hpp:33
static constexpr std::string_view PARALLEL_TYPE
Definition register.hpp:32
Mutable module-building interface passed to component serializers.
Definition netlist.hpp:174
Json bits(const core::Bus &bus, std::string_view nullValue="x") const
Convert a Silicon bus to a Yosys least-significant-bit-first vector.
Definition netlist.cpp:276
Json allocateBits(std::size_t width)
Allocate module-local temporary signal bits.
Definition netlist.cpp:314
static std::string parameter(std::uint64_t value, std::size_t width=32)
Encode an unsigned Yosys parameter as a fixed-width binary string.
Definition netlist.cpp:331
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.
Definition netlist.cpp:346
static Json concatenate(const std::vector< Json > &vectors)
Concatenate bit vectors in their existing LSB-first order.
Definition netlist.cpp:322
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.
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.
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.
static constexpr std::string_view UNSIGNED_MODE
static constexpr std::string_view SIGNED_MODE
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.
const std::vector< unsigned short > & selectionTableIndices() const
void serializeYosys(SILICON::yosys::SerializationContext &context) const override
Lower this component into native Yosys netlist cells.
static constexpr std::string_view RIGHT_MODE
static constexpr std::string_view LEFT_MODE
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::vector< std::pair< unsigned int, unsigned int > > outputSlices() const
Definition utils.cpp:148
void serializeYosys(SILICON::yosys::SerializationContext &context) const override
Lower this component into native Yosys netlist cells.
std::vector< std::pair< unsigned int, unsigned int > > slices
Definition utils.hpp:33
Mutable module-building interface passed to component serializers.
Definition netlist.hpp:174
void addPort(std::string name, std::string_view direction, const core::Bus &bus)
Register a named top-level input or output port.
Definition netlist.cpp:402
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.
Definition netlist.cpp:415
Json bits(const core::Bus &bus, std::string_view nullValue="x") const
Convert a Silicon bus to a Yosys least-significant-bit-first vector.
Definition netlist.cpp:276
Json allocateBits(std::size_t width)
Allocate module-local temporary signal bits.
Definition netlist.cpp:314
std::string componentIdentifier() const
Stable name of the component being serialized within its module.
Definition netlist.cpp:341
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.
Definition netlist.cpp:290
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.
Definition netlist.cpp:346
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
Definition wire.hpp:120
constexpr std::string_view BINARY_DOCUMENT
Definition cells.hpp:51
constexpr std::string_view ADDER
Definition cells.hpp:38
constexpr std::string_view PISO
Definition cells.hpp:42
constexpr std::string_view DFFSRE
Definition cells.hpp:34
constexpr std::string_view DIVIDER
Definition cells.hpp:40
constexpr std::string_view SISO
Definition cells.hpp:44
constexpr std::string_view DFFSR
Definition cells.hpp:33
constexpr std::string_view PIPO
Definition cells.hpp:41
constexpr std::string_view JKFF
Definition cells.hpp:35
constexpr std::string_view DLATCH
Definition cells.hpp:32
constexpr std::string_view MULTIPLIER
Definition cells.hpp:39
constexpr std::string_view FULL_ADDER
Definition cells.hpp:37
constexpr std::string_view SIPO
Definition cells.hpp:43
constexpr std::string_view DFF
Definition cells.hpp:30
constexpr std::string_view DFFE
Definition cells.hpp:31
constexpr std::string_view HALF_ADDER
Definition cells.hpp:36
void emitGateFold(SerializationContext &context, const Component &component, const std::string_view operation, const bool invert)
Definition helpers.hpp:107
Json directions(std::initializer_list< std::pair< std::string_view, std::string_view > > values)
Definition helpers.hpp:36
const Bus & requireBus(const Component &component, const bool input, const std::size_t index)
Definition helpers.hpp:44
void emitLogicalGateFold(SerializationContext &context, const Component &component, const std::string_view operation)
Definition helpers.hpp:160
void emitUnary(SerializationContext &context, const std::string_view suffix, const std::string_view type, const Json &input, const Json &output)
Definition helpers.hpp:67
nlohmann::ordered_json Json
Definition netlist.hpp:44