57using namespace SILICON::core;
58using namespace SILICON::extra;
61 [[noreturn]]
void fail(
const std::string_view context,
const std::string_view message)
63 throw std::runtime_error(
64 std::format(
"Invalid Yosys JSON at {}: {}", context, message));
67 [[nodiscard]] std::string_view binaryDigits(
const Json& value,
68 const std::string_view context)
70 if (!
value.is_string())
71 fail(context,
"expected a binary string or unsigned integer");
72 const auto& digits =
value.get_ref<
const std::string&>();
74 fail(context,
"binary value must not be empty");
75 if (!std::ranges::all_of(
76 digits, [](
const char digit) {
return digit ==
'0' || digit ==
'1'; })) {
77 fail(context,
"expected a fully defined binary string");
82 [[nodiscard]] std::uint64_t parseUnsigned(
const Json& value,
83 const std::string_view context)
85 if (
value.is_number_unsigned())
86 return value.get<std::uint64_t>();
87 if (
value.is_number_integer()) {
88 const auto result =
value.get<std::int64_t>();
90 fail(context,
"expected an unsigned value");
91 return static_cast<std::uint64_t
>(result);
94 BusValueFormat::Unsigned);
95 std::uint64_t result = 0;
96 const auto [end, error] =
97 std::from_chars(decimal.data(), decimal.data() + decimal.size(), result);
98 if (error == std::errc::result_out_of_range)
99 fail(context,
"binary value does not fit in 64 bits");
100 if (error != std::errc{} || end != decimal.data() + decimal.size())
101 fail(context,
"expected a fully defined binary string");
105 [[nodiscard]]
bool isZeroParameter(
const Json& value,
const std::string_view context)
107 if (
value.is_number_integer() ||
value.is_number_unsigned())
108 return parseUnsigned(value, context) == 0;
109 return std::ranges::all_of(binaryDigits(value, context),
110 [](
const char digit) {
return digit ==
'0'; });
113 [[nodiscard]]
const Json& requireObjectMember(
const Json&
object,
114 const std::string_view key,
115 const std::string_view context)
117 if (!
object.is_object())
118 fail(context,
"expected an object");
119 const auto it =
object.find(key);
120 if (it ==
object.end())
121 fail(context, std::format(
"missing '{}'", key));
125 void requireExactMembers(
const Json&
object,
126 const std::span<const std::string_view> names,
127 const std::string_view context,
128 const std::string_view memberKind)
130 if (!
object.is_object())
131 fail(context,
"expected an object");
132 if (
object.size() != names.size())
133 fail(context, std::format(
"cell has missing or unexpected {}s", memberKind));
134 for (
const auto name : names)
135 if (!
object.contains(name))
136 fail(context, std::format(
"missing '{}' {}", name, memberKind));
139 [[nodiscard]]
Bus slice(
const Bus& bus,
const std::size_t offset,
140 const std::size_t width)
142 std::vector<Wire_ptr> wires;
143 wires.reserve(width);
144 for (std::size_t bit = 0; bit <
width; ++bit)
145 wires.push_back(bus[
static_cast<unsigned short>(offset + bit)]);
146 return Bus(std::move(wires));
151 explicit Importer(
Json design) : design(std::move(design)) {}
153 [[nodiscard]]
Circuit run(
const std::optional<std::string_view> requestedModule)
155 const auto& modules = requireObjectMember(design,
"modules",
"design");
156 if (!modules.is_object() || modules.empty())
157 fail(
"design.modules",
"expected at least one module");
159 const auto [name, module] = selectModule(modules, requestedModule);
161 importModule(module);
162 normalizeBusConnections();
167 return Circuit(components,
false);
171 enum class ConnectionRole { Driver, Consumer };
175 Cell(Importer& importer,
const Json& cell, std::string context)
176 : context(std::move(context)),
178 parametersJson(requireObjectMember(cell,
"parameters", this->context)),
179 connectionsJson(requireObjectMember(cell,
"connections", this->context))
181 if (!cell.is_object())
182 fail(this->context,
"expected an object");
183 const auto& typeJson = requireObjectMember(cell,
"type", this->context);
184 if (!typeJson.is_string())
185 fail(std::format(
"{}.type", this->context),
"expected a string");
186 type = typeJson.get<std::string>();
187 if (!parametersJson.is_object())
188 fail(std::format(
"{}.parameters", this->context),
"expected an object");
189 if (!connectionsJson.is_object())
190 fail(std::format(
"{}.connections", this->context),
"expected an object");
193 [[nodiscard]]
const std::string& cellType()
const {
return type; }
194 [[nodiscard]]
const std::string& where()
const {
return context; }
196 void requireConnections(
const std::initializer_list<std::string_view> names)
const
198 requireExactMembers(connectionsJson, std::span(names.begin(), names.size()),
199 context,
"connection");
202 void requireParameters(
const std::initializer_list<std::string_view> names)
const
204 requireExactMembers(parametersJson, std::span(names.begin(), names.size()),
205 context,
"parameter");
208 template <std::
size_t ParameterCount, std::
size_t ConnectionCount>
210 const std::array<std::string_view, ParameterCount>& PARAMETER_NAMES,
211 const std::array<std::string_view, ConnectionCount>& CONNECTION_NAMES)
const
213 requireExactMembers(parametersJson, PARAMETER_NAMES, context,
"parameter");
214 requireExactMembers(connectionsJson, CONNECTION_NAMES, context,
"connection");
217 [[nodiscard]]
const Json& parameter(
const std::string_view name)
const
219 return requireObjectMember(parametersJson, name, context);
222 void requireKnownConnectionNames(
const std::span<const std::string> names)
const
224 for (
const auto& [name, _] : connectionsJson.items())
225 if (!std::ranges::contains(names, name))
226 fail(context, std::format(
"unexpected '{}' connection", name));
229 [[nodiscard]] std::size_t
width(
const std::string_view name)
const
232 parseUnsigned(parameter(name), std::format(
"{}.{}", context, name));
233 if (result == 0 || result > std::numeric_limits<unsigned short>::max())
234 fail(context, std::format(
"'{}' is outside Silicon's supported width", name));
235 return static_cast<std::size_t
>(result);
238 [[nodiscard]]
bool flag(
const std::string_view name)
const
241 parseUnsigned(parameter(name), std::format(
"{}.{}", context, name));
243 fail(context, std::format(
"'{}' must be zero or one", name));
247 [[nodiscard]]
bool zeroParameter(
const std::string_view name)
const
249 return isZeroParameter(parameter(name), std::format(
"{}.{}", context, name));
253 consumer(
const std::string_view port,
254 const std::optional<std::size_t> expectedWidth = std::nullopt)
const
256 return bus(port, ConnectionRole::Consumer, expectedWidth);
259 [[nodiscard]] std::vector<Bus> consumerLanes(
const std::string_view port,
260 const std::size_t laneWidth,
261 const std::size_t laneCount)
const
265 const auto& bits = requireObjectMember(connectionsJson, port, context);
266 const auto expectedWidth = laneWidth * laneCount;
267 if (!bits.is_array() || bits.size() != expectedWidth) {
268 fail(context, std::format(
"'{}' must be {} bits wide", port, expectedWidth));
271 std::vector<Bus> lanes;
272 lanes.reserve(laneCount);
273 for (std::size_t lane = 0; lane < laneCount; ++lane) {
274 Json laneBits = Json::array();
275 for (std::size_t bit = 0; bit < laneWidth; ++bit)
276 laneBits.push_back(bits[lane * laneWidth + bit]);
277 lanes.push_back(importer.readBus(
278 laneBits, ConnectionRole::Consumer,
279 std::format(
"{}.{} lane {}", context, port, lane), laneWidth));
285 driver(
const std::string_view port,
286 const std::optional<std::size_t> expectedWidth = std::nullopt)
const
288 return bus(port, ConnectionRole::Driver, expectedWidth);
291 [[nodiscard]] Bus optionalDriver(
const std::string_view port,
292 const std::size_t width)
const
294 const auto connection = connectionsJson.find(port);
295 if (connection == connectionsJson.end()
296 || (connection->is_array() && connection->empty())) {
297 if (width == 0 || width > std::numeric_limits<unsigned short>::max())
298 fail(context, std::format(
"'{}' is outside Silicon's supported width", port));
300 return Bus(
static_cast<unsigned short>(width));
302 return driver(port, width);
305 [[nodiscard]]
Wire_ptr consumerBit(
const std::string_view port)
const
307 return consumer(port, 1)[0];
310 [[nodiscard]]
Wire_ptr driverBit(
const std::string_view port)
const
312 return driver(port, 1)[0];
315 [[nodiscard]]
bool rawConstant(
const std::string_view port,
316 const std::string_view value,
317 const std::size_t expectedWidth = 1)
const
319 const auto& bits = requireObjectMember(connectionsJson, port, context);
320 if (!bits.is_array() || bits.empty() || bits.size() != expectedWidth)
321 fail(context, std::format(
"'{}' must be {} bit{} wide", port, expectedWidth,
322 expectedWidth == 1 ?
"" :
"s"));
323 return std::ranges::all_of(bits, [value](
const Json& bit) {
324 return bit.is_string() && bit.get_ref<
const std::string&>() == value;
328 [[nodiscard]]
Wire_ptr optionalActiveHighBit(
const std::string_view port)
const
330 return rawConstant(port,
"0") ? nullptr : consumerBit(port);
336 const Json& parametersJson;
337 const Json& connectionsJson;
340 [[nodiscard]] Bus bus(
const std::string_view port,
const ConnectionRole role,
341 const std::optional<std::size_t> expectedWidth)
const
343 return importer.readBus(requireObjectMember(connectionsJson, port, context), role,
344 std::format(
"{}.{}", context, port), expectedWidth);
349 std::string moduleName;
350 std::map<std::uint64_t, Wire_ptr> signals;
351 std::map<State, Wire_ptr> constants;
352 std::map<BusValue, Bus> constantBuses;
353 std::set<std::uint64_t> drivenSignals;
354 std::vector<Component_ptr> components;
356 using BusKey = std::vector<Wire_ptr>;
364 std::size_t inputIndex;
367 [[nodiscard]]
static BusKey busKey(
const Bus& bus)
369 return static_cast<std::vector<Wire_ptr>
>(bus);
372 [[nodiscard]]
static bool fullyConnected(
const BusKey& key)
374 return std::ranges::all_of(key,
375 [](
const Wire_ptr& wire) {
return wire !=
nullptr; });
378 void normalizeBusConnections()
384 std::vector<ProducerBus> producers;
385 std::map<Wire_ptr, std::size_t, std::owner_less<Wire_ptr>> producerByWire;
386 std::map<BusKey, std::vector<ConsumerBus>> consumers;
388 for (
const auto& component : components) {
389 for (
const auto& output : component->outputBuses()) {
390 if (output.size() == 0)
392 const auto producerIndex = producers.size();
393 producers.push_back({busKey(output)});
394 for (
const auto& wire : producers.back().key)
396 producerByWire.try_emplace(wire, producerIndex);
399 for (std::size_t inputIndex = 0; inputIndex < component->inputBuses().size();
401 const auto& input = component->inputBuses()[inputIndex];
402 if (input.size() != 0)
403 consumers[busKey(input)].push_back({component, inputIndex});
410 using Range = std::pair<unsigned int, unsigned int>;
411 std::vector<std::map<Range, Bus>> producerSlices(producers.size());
412 std::map<Wire_ptr, unsigned int, std::owner_less<Wire_ptr>> bitByWire;
413 std::map<Wire_ptr, State, std::owner_less<Wire_ptr>> constantStates;
414 for (std::size_t i = 0; i < producers.size(); ++i)
415 for (
unsigned int bit = 0; bit < producers[i].key.size(); ++bit)
416 bitByWire.try_emplace(producers[i].key[bit], bit);
417 for (
const auto& component : components) {
418 if (
const auto constant =
419 std::dynamic_pointer_cast<ConstantComponent>(component)) {
421 const auto& output = constant->outputBuses().at(0);
422 for (
unsigned int bit = 0; bit < output.size(); ++bit)
423 constantStates.try_emplace(output[bit], value[bit]);
427 std::vector<Component_ptr> helpers;
428 const auto sourceSlice = [&](
const std::size_t producerIndex,
429 const unsigned int offset,
const unsigned int width) {
430 const auto&
source = producers[producerIndex].key;
431 if (offset == 0 && width ==
source.size())
433 auto [slice, inserted] =
434 producerSlices[producerIndex].try_emplace(Range{offset,
width});
436 slice->second = Bus(
static_cast<unsigned short>(width));
437 return slice->second;
439 for (
const auto& [key, occurrences] : consumers) {
440 if (!fullyConnected(key))
446 std::size_t
prefix = key.size();
447 while (prefix > 0 && constantStates.contains(key[prefix - 1])
448 && constantStates.at(key[prefix - 1]) == State::LOW)
450 bool signExtend =
false;
451 if (prefix == key.size()) {
452 while (prefix > 1 && key[prefix - 1] == key[prefix - 2])
457 if (prefix > 0 && prefix < key.size()) {
458 const auto producer = producerByWire.find(key.front());
459 if (producer != producerByWire.end() && !constantStates.contains(key.front())) {
460 const auto offset = bitByWire.at(key.front());
461 const auto&
source = producers[producer->second].key;
462 if (offset + prefix <=
source.size()
463 && std::equal(key.begin(), key.begin() + prefix,
464 source.begin() + offset)) {
465 replacement = Bus(
static_cast<unsigned short>(key.size()));
466 helpers.push_back(std::make_shared<Extender>(
467 sourceSlice(producer->second, offset,
468 static_cast<unsigned int>(prefix)),
476 if (replacement.
size() != 0) {
477 for (
const auto& occurrence : occurrences)
478 occurrence.component->setInput(
479 static_cast<unsigned int>(occurrence.inputIndex), replacement);
483 std::vector<Bus> parts;
484 for (std::size_t start = 0; start < key.size();) {
487 if (constantStates.contains(key[start])) {
488 Json literals = Json::array();
490 while (end < key.size() && constantStates.contains(key[end])) {
491 const auto state = constantStates.at(key[end]);
492 literals.push_back(state == State::LOW ?
"0"
493 : state == State::HIGH ?
"1"
497 if (end - start == 1)
498 parts.emplace_back(Bus{key[start]});
500 parts.push_back(constantBus(literals, moduleContext()));
505 const auto producer = producerByWire.find(key[start]);
506 if (producer == producerByWire.end()) {
507 parts.emplace_back(Bus{key[start++]});
510 const auto producerIndex = producer->second;
511 const auto&
source = producers[producerIndex].key;
512 const auto offset = bitByWire.at(key[start]);
513 std::size_t
width = 1;
514 while (start + width < key.size() && offset + width <
source.size()
515 && key[start + width] == source[offset + width])
519 sourceSlice(producerIndex, offset,
static_cast<unsigned int>(width)));
523 if (parts.size() == 1) {
524 replacement = parts.front();
526 replacement = Bus(
static_cast<unsigned short>(key.size()));
527 auto merger = std::make_shared<WireMerger>();
528 merger->setProperty(
"size",
static_cast<int>(key.size()));
530 for (
const auto& part : parts) {
533 widths += std::to_string(part.size());
535 merger->setProperty(
"widths", widths);
536 merger->setInputs(parts);
537 merger->setOutputs({replacement});
538 helpers.push_back(std::move(merger));
540 for (
const auto& occurrence : occurrences)
541 occurrence.component->setInput(
static_cast<unsigned int>(occurrence.inputIndex),
545 for (std::size_t i = 0; i < producers.size(); ++i) {
546 if (producerSlices[i].empty())
548 std::string specification;
549 std::vector<Bus> outputs;
550 for (
const auto& [range, bus] : producerSlices[i]) {
551 if (!specification.empty())
552 specification +=
',';
553 specification += std::format(
"{}:{}", range.first, range.second);
554 outputs.push_back(bus);
556 auto splitter = std::make_shared<WireSplitter>();
557 splitter->setProperty(
"size",
static_cast<int>(producers[i].key.size()));
558 splitter->setProperty(
"slices", specification);
559 splitter->setInputs({Bus(producers[i].key)});
560 splitter->setOutputs(outputs);
561 helpers.push_back(std::move(splitter));
564 components.insert(components.end(), helpers.begin(), helpers.end());
567 [[nodiscard]] std::pair<std::string, const Json&>
568 selectModule(
const Json& modules,
569 const std::optional<std::string_view> requested)
const
572 const auto it = modules.find(*requested);
573 if (it == modules.end())
574 fail(
"design.modules", std::format(
"module '{}' was not found", *requested));
575 return {std::string(*requested), *it};
578 if (modules.size() == 1)
579 return {modules.begin().key(), modules.begin().value()};
581 const Json* top =
nullptr;
583 for (
const auto& [name, module] : modules.items()) {
584 if (!module.is_object())
585 fail(std::format(
"design.modules.{}", name),
"expected an object");
586 const auto attributes =
module.find("attributes");
587 if (attributes == module.end() || !attributes->is_object())
589 const auto topAttribute = attributes->find(
"top");
590 if (topAttribute == attributes->end()
591 || parseUnsigned(*topAttribute,
592 std::format(
"design.modules.{}.attributes.top", name))
597 fail(
"design.modules",
"more than one module is marked as top");
602 fail(
"design.modules",
"module selection is ambiguous and no top is marked");
603 return {std::move(topName), *top};
606 void importModule(
const Json& module)
608 if (!module.is_object())
609 fail(std::format(
"design.modules.{}", moduleName),
"expected an object");
611 if (
const auto memories = module.find(
"memories");
612 memories != module.end() && (!memories->is_object() || !memories->empty())) {
613 fail(moduleContext(),
"memories are not supported");
616 importPorts(requireObjectMember(module,
"ports", moduleContext()));
617 importCells(requireObjectMember(module,
"cells", moduleContext()));
620 [[nodiscard]] std::string moduleContext()
const
622 return std::format(
"design.modules.{}", moduleName);
625 [[nodiscard]]
Wire_ptr numericWire(
const std::uint64_t signal)
627 auto& wire = signals[signal];
629 wire = std::make_shared<Wire>(State::UNKNOWN);
633 [[nodiscard]]
Wire_ptr constantWire(
const std::string_view value,
634 const std::string_view context)
637 fail(context,
"high-impedance 'z' has no Silicon equivalent");
638 if (value !=
"0" && value !=
"1" && value !=
"x")
639 fail(context, std::format(
"unsupported signal literal '{}'", value));
642 auto& wire = constants[state];
644 wire = std::make_shared<Wire>(state);
645 components.push_back(std::make_shared<ConstantComponent>(wire,
BusValue{state}));
650 [[nodiscard]] Bus constantBus(
const Json& bits,
const std::string_view context)
652 std::string rawValue;
653 rawValue.reserve(bits.size());
654 for (std::size_t bit = bits.size(); bit > 0; --bit) {
655 const auto& digitJson = bits[bit - 1];
656 if (!digitJson.is_string())
657 fail(context,
"expected a fully literal bus");
658 const auto& digit = digitJson.get_ref<
const std::string&>();
660 fail(context,
"high-impedance 'z' has no Silicon equivalent");
661 if (digit !=
"0" && digit !=
"1" && digit !=
"x")
662 fail(context, std::format(
"unsupported signal literal '{}'", digit));
667 auto [it, inserted] = constantBuses.try_emplace(value);
669 it->second = Bus(
static_cast<unsigned short>(bits.size()));
670 components.push_back(std::make_shared<ConstantComponent>(it->second, value));
676 readBus(
const Json& bits,
const ConnectionRole role,
const std::string_view context,
677 const std::optional<std::size_t> expectedWidth = std::nullopt)
679 if (!bits.is_array() || bits.empty())
680 fail(context,
"expected a non-empty bit array");
681 if (expectedWidth && bits.size() != *expectedWidth)
682 fail(context, std::format(
"expected {} bit{}", *expectedWidth,
683 *expectedWidth == 1 ?
"" :
"s"));
685 const bool fullyLiteralConsumer =
686 role == ConnectionRole::Consumer && bits.size() > 1
687 && std::ranges::all_of(bits, [](
const Json& bit) {
return bit.is_string(); });
688 if (fullyLiteralConsumer)
689 return constantBus(bits, context);
691 std::vector<Wire_ptr> wires;
692 wires.reserve(bits.size());
693 for (std::size_t index = 0; index < bits.size(); ++index) {
694 const auto& bit = bits[index];
695 const auto bitContext = std::format(
"{}[{}]", context, index);
696 if (bit.is_number_integer() || bit.is_number_unsigned()) {
697 const auto signal = parseUnsigned(bit, bitContext);
698 if (role == ConnectionRole::Driver && !drivenSignals.insert(signal).second)
699 fail(bitContext, std::format(
"signal {} has more than one driver", signal));
700 wires.push_back(numericWire(signal));
703 if (role == ConnectionRole::Driver || !bit.is_string())
704 fail(bitContext, role == ConnectionRole::Consumer
705 ?
"expected a signal number or literal"
706 :
"expected a numeric signal");
707 wires.push_back(constantWire(bit.get_ref<
const std::string&>(), bitContext));
709 return Bus(std::move(wires));
712 void importPorts(
const Json& ports)
714 if (!ports.is_object())
715 fail(std::format(
"{}.ports", moduleContext()),
"expected an object");
717 for (
const auto& [name, port] : ports.items()) {
718 const auto context = std::format(
"{}.ports.{}", moduleContext(), name);
719 if (!
port.is_object())
720 fail(context,
"expected an object");
721 const auto& directionJson = requireObjectMember(port,
"direction", context);
722 const auto& bitsJson = requireObjectMember(port,
"bits", context);
723 if (!directionJson.is_string())
724 fail(std::format(
"{}.direction", context),
"expected a string");
725 const auto direction = directionJson.get<std::string>();
727 if (direction ==
"inout")
728 fail(context,
"inout ports are not supported");
729 if (direction !=
"input" && direction !=
"output")
730 fail(context, std::format(
"invalid port direction '{}'", direction));
732 if (direction ==
"input") {
734 readBus(bitsJson, ConnectionRole::Driver, std::format(
"{}.bits", context));
736 components.push_back(std::make_shared<DummyInputComponent>(bus, name));
738 components.push_back(std::make_shared<DummyBusInputComponent>(bus, name));
745 std::size_t inputWidth = bitsJson.
size();
746 while (inputWidth > 0 && bitsJson[inputWidth - 1].is_string()
747 && bitsJson[inputWidth - 1].get_ref<const std::string&>() ==
"0") {
751 const bool isUnsignedExtension =
752 inputWidth > 0 && inputWidth < bitsJson.size()
753 && std::ranges::all_of(
754 bitsJson.begin(), bitsJson.begin() + inputWidth,
755 [](
const Json& bit) {
756 return bit.is_number_integer() || bit.is_number_unsigned();
758 if (isUnsignedExtension) {
759 Json inputBits = Json::array();
760 for (std::size_t bit = 0; bit < inputWidth; ++bit)
761 inputBits.push_back(bitsJson[bit]);
763 const Bus input = readBus(inputBits, ConnectionRole::Consumer,
764 std::format(
"{}.bits", context));
765 bus = Bus(
static_cast<unsigned short>(bitsJson.size()));
766 components.push_back(std::make_shared<Extender>(
769 bus = readBus(bitsJson, ConnectionRole::Consumer,
770 std::format(
"{}.bits", context));
774 components.push_back(std::make_shared<DummyOutputComponent>(bus, name));
776 components.push_back(std::make_shared<DummyBusOutputComponent>(bus, name));
781 void importCells(
const Json& cells)
783 if (!
cells.is_object())
784 fail(std::format(
"{}.cells", moduleContext()),
"expected an object");
786 for (
const auto& [name, cell] :
cells.items())
787 if (cell.is_object() && cell.value(
"type", std::string()) ==
"SILICON_ROM")
788 importRom(name, cell);
789 for (
const auto& [name, cell] :
cells.items())
790 if (cell.value(
"type", std::string()) !=
"SILICON_ROM")
791 importCell(name, cell);
794 void importRom(
const std::string_view name,
const Json& raw)
796 Cell cell(*
this, raw, std::format(
"{}.cells.{}", moduleContext(), name));
798 std::array<std::string_view, 7>{
"WIDTH",
"SIZE",
"ABITS",
"INIT",
"ID",
"SYNC",
"CLK_POLARITY"},
799 std::array<std::string_view, 5>{
"ADDR",
"DATA",
"SELECT",
"CLK",
"EN"});
800 const auto width = cell.width(
"WIDTH");
801 const auto count =
static_cast<std::size_t
>(parseUnsigned(cell.parameter(
"SIZE"), cell.where()));
802 const auto abits = cell.width(
"ABITS");
803 if (!std::has_single_bit(count) || count > std::numeric_limits<int>::max()
804 || abits != std::max<std::size_t>(1, std::bit_width(count - 1)))
805 fail(cell.where(),
"invalid canonical ROM geometry");
806 const bool synchronous = cell.flag(
"SYNC");
807 const bool positiveClock = cell.flag(
"CLK_POLARITY");
808 const auto init = binaryDigits(cell.parameter(
"INIT"), cell.where());
809 if (init.size() != count * width)
810 fail(cell.where(),
"invalid canonical ROM initialization");
811 std::string bytes((init.size() + 7) / 8,
'\0');
812 for (std::size_t bit = 0; bit < init.size(); ++bit)
813 if (init[init.size() - bit - 1] ==
'1')
814 bytes[bit / 8] =
static_cast<char>(
static_cast<unsigned char>(bytes[bit / 8]) | (1u << (bit % 8)));
816 const auto&
id = cell.parameter(
"ID");
818 fail(cell.where(),
"canonical ROM identifier must be a string");
819 std::string memoryName =
id.get<std::string>();
820 if (!memoryName.empty() && memoryName.front() ==
'\\')
821 memoryName.erase(0, 1);
822 for (
auto& character : memoryName)
823 if (character ==
'/' || character ==
'\\' ||
static_cast<unsigned char>(character) < 32
824 ||
static_cast<unsigned char>(character) == 127)
826 std::string assetName = std::format(
"{}_{}", moduleName, memoryName);
827 const auto attributes = raw.value(
"attributes", Json::object());
828 if (!attributes.is_object())
829 fail(cell.where(),
"ROM attributes must be an object");
831 attribute != attributes.end()) {
832 if (!attribute->is_string())
833 fail(cell.where(),
"binary document attribute must be a string");
834 assetName = attribute->get<std::string>();
836 fail(cell.where(),
"binary document attribute is not a valid document name");
839 Bus address = cell.consumer(
"ADDR", abits);
840 const Bus select = cell.consumer(
"SELECT", 1);
841 const Bus clockBus = cell.consumer(
"CLK", 1);
842 const Bus enableBus = cell.consumer(
"EN", 1);
843 if (count == 1 && !cell.rawConstant(
"ADDR",
"0", abits))
844 fail(cell.where(),
"one-word ROM requires a constant zero address");
845 if (!synchronous && (!cell.rawConstant(
"CLK",
"0") || !cell.rawConstant(
"EN",
"1")))
846 fail(cell.where(),
"asynchronous ROM has invalid clock or enable");
848 if (synchronous && !positiveClock) {
849 const auto inverted = std::make_shared<Wire>();
850 addWithZeroDelay(std::make_shared<NotGate>(clock, inverted));
853 if (synchronous && count > 1) {
854 std::vector<Wire_ptr> data(address.
begin(), address.
end());
855 while (data.size() < 2)
856 data.push_back(constantWire(
"0", cell.where()));
857 Bus registeredAddress(
static_cast<unsigned short>(data.size()));
858 addWithZeroDelay(std::make_shared<Register>(
859 Bus(std::move(data)), clock, enableBus[0],
nullptr, registeredAddress));
860 address = slice(registeredAddress, 0, abits);
863 auto rom = std::make_shared<ROM>();
864 rom->setProperty(
"dataWidth",
static_cast<int>(width));
865 rom->setProperty(
"binaryContents", assetName);
866 const Bus romOutput = synchronous && count == 1
867 ? Bus(
static_cast<unsigned short>(width))
868 : cell.driver(
"DATA",
width);
869 connectAndAdd(rom, {address, select,
870 readBus(Json::array({
"1"}), ConnectionRole::Consumer, cell.where(), 1)},
872 rom->refreshBinaryContents(std::make_shared<const std::string>(bytes), count);
873 if (synchronous && count == 1) {
874 const Bus registeredData = cell.driver(
"DATA", width);
875 std::vector<Wire_ptr> data(romOutput.
begin(), romOutput.
end());
876 std::vector<Wire_ptr> outputs(registeredData.
begin(), registeredData.
end());
877 while (data.size() < 2) {
878 data.push_back(constantWire(
"0", cell.where()));
879 outputs.push_back(std::make_shared<Wire>());
881 addWithZeroDelay(std::make_shared<Register>(
882 Bus(std::move(data)), clock, enableBus[0],
nullptr, Bus(std::move(outputs))));
886 [[nodiscard]]
static std::vector<Bus>
887 split(
const Bus& packed,
const std::size_t laneWidth,
const std::size_t laneCount)
889 std::vector<Bus> lanes;
890 lanes.reserve(laneCount);
891 for (std::size_t lane = 0; lane < laneCount; ++lane)
892 lanes.push_back(slice(packed, lane * laneWidth, laneWidth));
896 [[nodiscard]]
static std::size_t laneCount(
const std::size_t selectionWidth,
897 const std::string_view type,
898 const std::string_view context)
900 if (selectionWidth >= std::numeric_limits<std::size_t>::digits)
901 fail(context, std::format(
"{} selection width is too large", type));
902 return std::size_t{1} << selectionWidth;
905 void connectAndAdd(
Component_ptr component, std::vector<Bus> inputs,
906 std::vector<Bus> outputs)
908 component->setInputs(inputs);
909 component->setOutputs(outputs);
910 components.push_back(std::move(component));
914 const std::string_view property =
"delay")
916 component->setProperty(property, 0);
917 components.push_back(std::move(component));
920 template <
typename ComponentType>
921 void addMuxLike(
const std::size_t selectionWidth,
const std::size_t busWidth,
922 std::vector<Bus> inputs, std::vector<Bus> outputs)
924 auto component = std::make_shared<ComponentType>();
925 component->setProperty(
"selectionSize",
static_cast<int>(selectionWidth));
926 component->setProperty(
"busSize",
static_cast<int>(busWidth));
927 component->setProperty(
"delay", 0);
928 connectAndAdd(std::move(component), std::move(inputs), std::move(outputs));
931 template <
typename FlipFlopType>
932 void addFlipFlop(std::shared_ptr<FlipFlopType> flipFlop,
const bool positiveClock)
934 flipFlop->setProperty(
"triggerEdge",
935 positiveClock ? std::string(
"PET") : std::string(
"NET"));
936 addWithZeroDelay(std::move(flipFlop),
"propagationDelay");
939 [[nodiscard]] std::pair<Bus, Bus> equalWidthUnary(
const Cell& cell,
940 const std::string_view type)
942 cell.requireConnections({
"A",
"Y"});
943 const auto aWidth = cell.width(
"A_WIDTH");
944 const auto yWidth = cell.width(
"Y_WIDTH");
945 Bus a = cell.consumer(
"A", aWidth);
946 Bus y = cell.driver(
"Y", yWidth);
947 if (aWidth != yWidth)
949 std::format(
"{} requires equal input and output widths", type));
950 return {std::move(a), std::move(y)};
953 template <
typename GateType>
void importBinaryGate(
const Cell& cell)
955 cell.requireConnections({
"A",
"B",
"Y"});
956 const auto aWidth = cell.width(
"A_WIDTH");
957 const auto bWidth = cell.width(
"B_WIDTH");
958 const auto yWidth = cell.width(
"Y_WIDTH");
959 const Bus a = cell.consumer(
"A", aWidth);
960 const Bus b = cell.consumer(
"B", bWidth);
961 const Bus y = cell.driver(
"Y", yWidth);
962 if (aWidth != bWidth || aWidth != yWidth)
963 fail(cell.where(),
"binary gate widths must match its connections");
965 auto gate = std::make_shared<GateType>();
966 gate->setProperty(
"bitwise",
true);
967 gate->setProperty(
"size",
static_cast<int>(yWidth));
968 gate->setProperty(
"delay", 0);
969 connectAndAdd(std::move(gate), {a, b}, {y});
972 template <
typename GateType>
void importFineBinaryGate(
const Cell& cell)
974 cell.requireSchema(std::array<std::string_view, 0>{},
975 std::array<std::string_view, 3>{
"A",
"B",
"Y"});
976 const Bus a = cell.consumer(
"A", 1);
977 const Bus b = cell.consumer(
"B", 1);
978 const Bus y = cell.driver(
"Y", 1);
980 auto gate = std::make_shared<GateType>(std::vector<Wire_ptr>{a[0], b[0]}, y[0]);
981 addWithZeroDelay(std::move(gate));
984 void importNot(
const Cell& cell)
986 const auto [a, y] = equalWidthUnary(cell,
"$not");
987 auto gate = std::make_shared<NotGate>(a[0], y[0]);
988 gate->setProperty(
"size",
static_cast<int>(y.
size()));
989 gate->setInputs({a});
990 gate->setOutputs({y});
991 addWithZeroDelay(std::move(gate));
994 void importSiliconLogic(
const Cell& cell)
996 const auto mode = parseUnsigned(cell.parameter(
"MODE"), cell.where());
998 fail(cell.where(),
"invalid SILICON_LOGIC mode");
999 const auto aWidth = cell.width(
"A_WIDTH");
1001 cell.requireSchema(std::to_array<std::string_view>({
"MODE",
"A_WIDTH"}),
1002 std::to_array<std::string_view>({
"A",
"Y"}));
1003 const Bus a = cell.consumer(
"A", aWidth);
1004 const Bus y = cell.driver(
"Y", 1);
1005 auto gate = std::make_shared<NotGate>(a[0], y[0]);
1006 gate->setInputs({a});
1007 gate->setOutputs({y});
1008 addWithZeroDelay(std::move(gate));
1011 cell.requireSchema(std::to_array<std::string_view>({
"MODE",
"A_WIDTH",
"B_WIDTH"}),
1012 std::to_array<std::string_view>({
"A",
"B",
"Y"}));
1013 const Bus a = cell.consumer(
"A", aWidth);
1014 const Bus b = cell.consumer(
"B", cell.width(
"B_WIDTH"));
1015 const Bus y = cell.driver(
"Y", 1);
1017 auto gate = std::make_shared<AndGate>();
1018 gate->setProperty(
"delay", 0);
1019 connectAndAdd(std::move(gate), {a, b}, {y});
1021 auto gate = std::make_shared<OrGate>();
1022 gate->setProperty(
"delay", 0);
1023 connectAndAdd(std::move(gate), {a, b}, {y});
1027 void importPos(
const Cell& cell)
1029 cell.requireConnections({
"A",
"Y"});
1030 const auto aWidth = cell.width(
"A_WIDTH");
1031 const auto yWidth = cell.width(
"Y_WIDTH");
1032 const Bus a = cell.consumer(
"A", aWidth);
1033 const Bus y = cell.driver(
"Y", yWidth);
1035 if (aWidth != yWidth) {
1036 components.push_back(std::make_shared<Extender>(
1043 auto merger = std::make_shared<WireMerger>();
1044 merger->setProperty(
"size",
static_cast<int>(y.
size()));
1045 connectAndAdd(std::move(merger), split(a, 1, a.
size()), {y});
1048 void importAdd(
const Cell& cell)
1050 cell.requireConnections({
"A",
"B",
"Y"});
1051 const bool signedArithmetic = cell.flag(
"A_SIGNED") && cell.flag(
"B_SIGNED");
1052 const auto aWidth = cell.width(
"A_WIDTH");
1053 const auto bWidth = cell.width(
"B_WIDTH");
1054 const auto yWidth = cell.width(
"Y_WIDTH");
1055 const Bus a = cell.consumer(
"A", aWidth);
1056 const Bus b = cell.consumer(
"B", bWidth);
1057 const Bus y = cell.driver(
"Y", yWidth);
1059 const auto arithmeticWidth = std::max({aWidth, bWidth, yWidth});
1060 const Bus extendedA = resizeArithmeticOperand(a, arithmeticWidth, signedArithmetic);
1061 const Bus extendedB = resizeArithmeticOperand(b, arithmeticWidth, signedArithmetic);
1063 auto sumWires =
static_cast<std::vector<Wire_ptr>
>(y);
1064 while (sumWires.size() < arithmeticWidth)
1065 sumWires.push_back(std::make_shared<Wire>(State::UNKNOWN));
1067 auto adder = std::make_shared<AdderNBits>(std::array<Bus, 2>{extendedA, extendedB},
1068 Bus(std::move(sumWires)),
1069 std::make_shared<Wire>(State::UNKNOWN));
1070 addWithZeroDelay(std::move(adder));
1073 void importSiliconShift(
const Cell& cell)
1076 std::to_array<std::string_view>({
"WIDTH",
"B_WIDTH",
"DIRECTION",
"ARITHMETIC"}),
1077 std::to_array<std::string_view>({
"A",
"B",
"Y"}));
1078 const auto direction = parseUnsigned(cell.parameter(
"DIRECTION"), cell.where());
1079 const auto arithmetic = cell.flag(
"ARITHMETIC");
1080 if (direction > 1 || (direction == 0 && arithmetic))
1081 fail(cell.where(),
"invalid SILICON_SHIFT mode");
1082 const auto width = cell.width(
"WIDTH");
1083 auto shifter = std::make_shared<Shifter>(cell.consumer(
"A", width),
1084 cell.consumer(
"B", cell.width(
"B_WIDTH")),
1085 cell.driver(
"Y", width));
1088 shifter->setProperty(
"signed", arithmetic);
1089 addWithZeroDelay(std::move(shifter));
1092 [[nodiscard]] Bus resizeArithmeticOperand(
const Bus& operand,
const std::size_t width,
1093 const bool signExtend)
1095 if (operand.
size() > width)
1096 return slice(operand, 0, width);
1097 if (operand.
size() == width)
1100 Bus result(
static_cast<unsigned short>(width));
1101 auto extender = std::make_shared<Extender>(
1104 components.push_back(std::move(extender));
1108 void importNeg(
const Cell& cell)
1110 cell.requireConnections({
"A",
"Y"});
1111 const auto aWidth = cell.width(
"A_WIDTH");
1112 const auto yWidth = cell.width(
"Y_WIDTH");
1113 const bool sign = cell.flag(
"A_SIGNED");
1114 const Bus a = cell.consumer(
"A", aWidth);
1115 const Bus y = cell.driver(
"Y", yWidth);
1116 auto complementer = std::make_shared<Complementer>(
1117 resizeArithmeticOperand(a, yWidth, sign), y);
1118 addWithZeroDelay(std::move(complementer));
1121 void importSub(
const Cell& cell)
1123 cell.requireConnections({
"A",
"B",
"Y"});
1124 const auto aWidth = cell.width(
"A_WIDTH");
1125 const auto bWidth = cell.width(
"B_WIDTH");
1126 const auto yWidth = cell.width(
"Y_WIDTH");
1127 const bool signedArithmetic = cell.flag(
"A_SIGNED") && cell.flag(
"B_SIGNED");
1128 const Bus b = cell.consumer(
"B", bWidth);
1129 const Bus y = cell.driver(
"Y", yWidth);
1131 const Bus a = cell.consumer(
"A", aWidth);
1135 const auto arithmeticWidth = std::max({aWidth, bWidth, yWidth});
1136 const Bus extendedA = resizeArithmeticOperand(a, arithmeticWidth, signedArithmetic);
1137 const Bus extendedB = resizeArithmeticOperand(b, arithmeticWidth, signedArithmetic);
1139 Bus complementedB(
static_cast<unsigned short>(arithmeticWidth));
1140 auto complementer = std::make_shared<Complementer>(extendedB, complementedB);
1141 addWithZeroDelay(std::move(complementer));
1143 auto sumWires =
static_cast<std::vector<Wire_ptr>
>(y);
1144 while (sumWires.size() < arithmeticWidth)
1145 sumWires.push_back(std::make_shared<Wire>(State::UNKNOWN));
1146 Bus sum(std::move(sumWires));
1149 std::make_shared<AdderNBits>(std::array<Bus, 2>{extendedA, complementedB}, sum,
1150 std::make_shared<Wire>(State::UNKNOWN));
1151 addWithZeroDelay(std::move(adder));
1154 void importSiliconCompare(
const Cell& cell)
1156 cell.requireSchema(std::to_array<std::string_view>({
"WIDTH",
"MODE",
"SIGNED"}),
1157 std::to_array<std::string_view>({
"A",
"B",
"Y"}));
1158 const auto mode = parseUnsigned(cell.parameter(
"MODE"), cell.where());
1159 static constexpr std::array<std::string_view, 5> MODES{
"==",
"<",
"<=",
">",
">="};
1160 if (mode >= MODES.size())
1161 fail(cell.where(),
"invalid SILICON_COMPARE mode");
1162 const auto width = cell.width(
"WIDTH");
1163 const Bus a = cell.consumer(
"A", width);
1164 const Bus b = cell.consumer(
"B", width);
1165 const Bus y = cell.driver(
"Y", 1);
1166 auto comparator = std::make_shared<Comparator>(std::array<Bus, 2>{a, b}, y[0]);
1167 comparator->setProperty(
"mode", std::string(MODES[mode]));
1168 comparator->setProperty(
"signed", cell.flag(
"SIGNED"));
1169 addWithZeroDelay(std::move(comparator));
1172 void importSiliconGate(
const Cell& cell)
1174 cell.requireParameters({
"MODE",
"WIDTH",
"INPUTS",
"BITWISE"});
1175 const auto mode = parseUnsigned(cell.parameter(
"MODE"), cell.where());
1176 const auto width = cell.width(
"WIDTH");
1177 const auto count = cell.width(
"INPUTS");
1178 const auto bitwise = cell.flag(
"BITWISE");
1179 if (mode > 1 || count < 2 || (!bitwise && width != 1))
1180 fail(cell.where(),
"invalid SILICON_GATE geometry or mode");
1181 std::vector<std::string> names{
"Y"};
1182 std::vector<Bus> inputs;
1183 for (std::size_t i = 0; i < count; ++i) {
1184 names.push_back(std::format(
"A{}", i));
1185 inputs.push_back(cell.consumer(
1186 names.back(), bitwise ? std::optional<std::size_t>(width) : std::nullopt));
1188 cell.requireKnownConnectionNames(names);
1190 mode == 0 ? std::static_pointer_cast<Component>(std::make_shared<AndGate>())
1191 : std::static_pointer_cast<
Component>(std::make_shared<OrGate>());
1192 gate->setProperty(
"size",
static_cast<int>(width));
1193 gate->setProperty(
"bitwise", bitwise);
1194 gate->setProperty(
"delay", 0);
1195 connectAndAdd(std::move(gate), std::move(inputs), {cell.driver(
"Y", width)});
1198 void importSiliconMux(
const Cell& cell)
1201 std::to_array<std::string_view>({
"WIDTH",
"S_WIDTH",
"INPUTS",
"TABLE"}),
1202 std::to_array<std::string_view>({
"A",
"S",
"Y"}));
1203 const auto width = cell.width(
"WIDTH");
1204 const auto selectionWidth = cell.width(
"S_WIDTH");
1205 if (selectionWidth > 15)
1206 fail(cell.where(),
"SILICON_MUX selector is too wide");
1207 const auto lanes = std::size_t{1} << selectionWidth;
1208 const auto count = cell.width(
"INPUTS");
1209 const auto bits = binaryDigits(cell.parameter(
"TABLE"), cell.where());
1210 if (count > lanes || bits.size() != lanes * selectionWidth)
1211 fail(cell.where(),
"invalid SILICON_MUX selection table geometry");
1213 std::vector<bool> seen(count);
1214 for (std::size_t lane = 0; lane < lanes; ++lane) {
1216 bits.substr(bits.size() - (lane + 1) * selectionWidth, selectionWidth);
1217 unsigned int index = 0;
1218 const auto [end, error] =
1219 std::from_chars(word.data(), word.data() + word.size(), index, 2);
1220 if (error != std::errc{} || end != word.data() + word.size() || index >= count)
1222 "SILICON_MUX selection table index is outside its data inputs");
1226 table += std::to_string(index);
1228 if (std::ranges::find(seen,
false) != seen.end())
1229 fail(cell.where(),
"SILICON_MUX contains unused data inputs");
1230 auto mux = std::make_shared<Multiplexer>();
1231 mux->setProperty(
"selectionSize",
static_cast<int>(selectionWidth));
1232 mux->setProperty(
"busSize",
static_cast<int>(width));
1233 mux->setProperty(
"selectionTable", table);
1234 auto inputs = cell.consumerLanes(
"A", width, count);
1235 inputs.push_back(cell.consumer(
"S", selectionWidth));
1236 connectAndAdd(std::move(mux), std::move(inputs), {cell.driver(
"Y", width)});
1239 void importMux(
const Cell& cell)
1241 cell.requireConnections({
"A",
"B",
"S",
"Y"});
1242 const auto width = cell.width(
"WIDTH");
1243 const Bus a = cell.consumer(
"A", width);
1244 const Bus b = cell.consumer(
"B", width);
1245 const Bus s = cell.consumer(
"S", 1);
1246 const Bus y = cell.driver(
"Y", width);
1248 std::vector<Bus> inputs{a, b, s};
1249 addMuxLike<Multiplexer>(1, width, std::move(inputs), {y});
1252 void importBmux(
const Cell& cell)
1254 cell.requireConnections({
"A",
"S",
"Y"});
1255 const auto width = cell.width(
"WIDTH");
1256 const auto selectionWidth = cell.width(
"S_WIDTH");
1257 const auto lanes = laneCount(selectionWidth,
"$bmux", cell.where());
1258 if (lanes > std::numeric_limits<std::size_t>::max() / width)
1259 fail(cell.where(),
"$bmux packed input width is too large");
1260 const Bus s = cell.consumer(
"S", selectionWidth);
1261 const Bus y = cell.driver(
"Y", width);
1265 std::vector<Bus> inputs = cell.consumerLanes(
"A", width, lanes);
1266 inputs.push_back(s);
1267 addMuxLike<Multiplexer>(selectionWidth, width, std::move(inputs), {y});
1270 void importDemux(
const Cell& cell)
1272 cell.requireConnections({
"A",
"S",
"Y"});
1273 const auto width = cell.width(
"WIDTH");
1274 const auto selectionWidth = cell.width(
"S_WIDTH");
1275 const auto lanes = laneCount(selectionWidth,
"$demux", cell.where());
1276 if (lanes > std::numeric_limits<std::size_t>::max() / width)
1277 fail(cell.where(),
"$demux packed output width is too large");
1278 const Bus a = cell.consumer(
"A", width);
1279 const Bus s = cell.consumer(
"S", selectionWidth);
1280 const Bus y = cell.driver(
"Y", width * lanes);
1282 if (width == 1 && cell.rawConstant(
"A",
"1")) {
1283 auto decoder = std::make_shared<Decoder>(a, s, y);
1284 decoder->setProperty(
"delay", 0);
1285 components.push_back(std::move(decoder));
1289 auto outputs =
width == 1 ? std::vector<Bus>{y} : split(y, width, lanes);
1290 addMuxLike<Demultiplexer>(selectionWidth, width, {a, s}, std::move(outputs));
1293 void importAdffe(
const Cell& cell)
1295 cell.requireConnections({
"CLK",
"ARST",
"EN",
"D",
"Q"});
1298 if (cell.width(
"WIDTH") != 1)
1299 fail(cell.where(),
"only scalar $adffe cells may remain after legalization");
1300 if (!cell.flag(
"EN_POLARITY") || !cell.flag(
"ARST_POLARITY"))
1301 fail(cell.where(),
"only active-high EN and ARST are supported");
1302 if (!cell.zeroParameter(
"ARST_VALUE"))
1303 fail(cell.where(),
"only an all-zero asynchronous reset value is supported");
1305 auto dff = std::make_shared<EFlipFlop>(
1306 cell.consumerBit(
"D"), cell.consumerBit(
"EN"), cell.consumerBit(
"CLK"),
1307 cell.consumerBit(
"ARST"),
nullptr, cell.driverBit(
"Q"),
1308 std::make_shared<Wire>());
1309 addFlipFlop(std::move(dff), cell.flag(
"CLK_POLARITY"));
1312 template <
bool Enabled,
bool SetReset>
void importSiliconDff(
const Cell& cell)
1314 static constexpr auto PARAMETER_NAMES = [] {
1315 std::array<std::string_view, 1 + Enabled + 2 * SetReset> names{};
1316 std::size_t index = 0;
1317 names[index++] =
"CLK_POLARITY";
1318 if constexpr (Enabled)
1319 names[index++] =
"EN_POLARITY";
1320 if constexpr (SetReset) {
1321 names[index++] =
"SET_POLARITY";
1322 names[index] =
"CLR_POLARITY";
1326 static constexpr auto CONNECTION_NAMES = [] {
1327 std::array<std::string_view, 4 + Enabled + 2 * SetReset> names{};
1328 std::size_t index = 0;
1329 names[index++] =
"D";
1330 if constexpr (Enabled)
1331 names[index++] =
"EN";
1332 names[index++] =
"CLK";
1333 if constexpr (SetReset) {
1334 names[index++] =
"SET";
1335 names[index++] =
"CLR";
1337 names[index++] =
"Q";
1338 names[index] =
"QN";
1341 cell.requireSchema(PARAMETER_NAMES, CONNECTION_NAMES);
1343 if constexpr (Enabled) {
1344 if (!cell.flag(
"EN_POLARITY"))
1345 fail(cell.where(),
"SILICON enabled flip-flops require active-high EN");
1347 if constexpr (SetReset) {
1348 if (!cell.flag(
"SET_POLARITY") || !cell.flag(
"CLR_POLARITY"))
1349 fail(cell.where(),
"SILICON flip-flops require active-high SET and CLR");
1352 const bool positive = cell.flag(
"CLK_POLARITY");
1353 const auto d = cell.consumerBit(
"D");
1354 const auto clock = cell.consumerBit(
"CLK");
1355 const auto enable = [&] {
1356 if constexpr (Enabled)
1357 return cell.consumerBit(
"EN");
1360 const auto set = [&] {
1361 if constexpr (SetReset)
1362 return cell.optionalActiveHighBit(
"SET");
1365 const auto clear = [&] {
1366 if constexpr (SetReset)
1367 return cell.optionalActiveHighBit(
"CLR");
1370 const auto q = cell.driverBit(
"Q");
1371 const auto qn = cell.driverBit(
"QN");
1373 if constexpr (Enabled)
1374 addFlipFlop(std::make_shared<EFlipFlop>(d, enable, clock, clear, set, q, qn),
1377 addFlipFlop(std::make_shared<DFlipFlop>(d, clock, clear, set, q, qn), positive);
1380 void importSiliconJkff(
const Cell& cell)
1382 static constexpr auto PARAMETERS = std::to_array<std::string_view>(
1383 {
"CLK_POLARITY",
"SET_POLARITY",
"CLR_POLARITY"});
1384 static constexpr auto CONNECTIONS =
1385 std::to_array<std::string_view>({
"J",
"K",
"CLK",
"SET",
"CLR",
"Q",
"QN"});
1386 cell.requireSchema(PARAMETERS, CONNECTIONS);
1387 if (!cell.flag(
"SET_POLARITY") || !cell.flag(
"CLR_POLARITY"))
1388 fail(cell.where(),
"SILICON_JKFF requires active-high SET and CLR");
1390 auto flipFlop = std::make_shared<JKFlipFlop>(
1391 cell.consumerBit(
"J"), cell.consumerBit(
"K"), cell.consumerBit(
"CLK"),
1392 cell.optionalActiveHighBit(
"CLR"), cell.optionalActiveHighBit(
"SET"),
1393 cell.driverBit(
"Q"), cell.driverBit(
"QN"));
1394 addFlipFlop(std::move(flipFlop), cell.flag(
"CLK_POLARITY"));
1397 void importSiliconDlatch(
const Cell& cell)
1399 static constexpr auto PARAMETERS = std::to_array<std::string_view>({
"EN_POLARITY"});
1400 static constexpr auto CONNECTIONS =
1401 std::to_array<std::string_view>({
"D",
"EN",
"Q",
"QN"});
1402 cell.requireSchema(PARAMETERS, CONNECTIONS);
1403 if (!cell.flag(
"EN_POLARITY"))
1404 fail(cell.where(),
"SILICON_DLATCH requires active-high EN");
1406 auto latch = std::make_shared<DLatch>(cell.consumerBit(
"D"), cell.consumerBit(
"EN"),
1407 cell.driverBit(
"Q"), cell.driverBit(
"QN"));
1408 addWithZeroDelay(std::move(latch),
"propagationDelay");
1411 void importSiliconHalfAdder(
const Cell& cell)
1413 static constexpr std::array<std::string_view, 0> PARAMETERS{};
1414 static constexpr auto CONNECTIONS =
1415 std::to_array<std::string_view>({
"A",
"B",
"SUM",
"COUT"});
1416 cell.requireSchema(PARAMETERS, CONNECTIONS);
1417 auto adder = std::make_shared<HalfAdder>(
1418 std::array<Wire_ptr, 2>{cell.consumerBit(
"A"), cell.consumerBit(
"B")},
1419 cell.driverBit(
"SUM"), cell.driverBit(
"COUT"));
1420 addWithZeroDelay(std::move(adder));
1423 void importSiliconFullAdder(
const Cell& cell)
1425 static constexpr std::array<std::string_view, 0> PARAMETERS{};
1426 static constexpr auto CONNECTIONS =
1427 std::to_array<std::string_view>({
"A",
"B",
"CIN",
"SUM",
"COUT"});
1428 cell.requireSchema(PARAMETERS, CONNECTIONS);
1429 auto adder = std::make_shared<FullAdder>(
1430 std::array<Wire_ptr, 2>{cell.consumerBit(
"A"), cell.consumerBit(
"B")},
1431 cell.consumerBit(
"CIN"), cell.driverBit(
"SUM"), cell.driverBit(
"COUT"));
1432 addWithZeroDelay(std::move(adder));
1435 void importSiliconAdder(
const Cell& cell)
1437 static constexpr auto PARAMETERS =
1438 std::to_array<std::string_view>({
"WIDTH",
"SIGNED"});
1439 static constexpr auto CONNECTIONS =
1440 std::to_array<std::string_view>({
"A",
"B",
"SUM",
"COUT"});
1441 cell.requireSchema(PARAMETERS, CONNECTIONS);
1442 const auto width = cell.width(
"WIDTH");
1443 if (cell.flag(
"SIGNED"))
1444 fail(cell.where(),
"SILICON_ADDER supports unsigned operands only");
1446 const auto a = cell.consumer(
"A", width);
1447 const auto b = cell.consumer(
"B", width);
1448 const auto sum = cell.driver(
"SUM", width);
1449 const auto cout = cell.driverBit(
"COUT");
1450 auto adder = std::make_shared<AdderNBits>(std::array<Bus, 2>{a, b}, sum, cout);
1451 addWithZeroDelay(std::move(adder));
1454 template <
bool multiplication>
void importSiliconMulDiv(
const Cell& cell)
1456 static constexpr auto PARAMETERS =
1457 std::to_array<std::string_view>({
"WIDTH",
"SIGNED"});
1458 if constexpr (multiplication)
1459 cell.requireSchema(PARAMETERS,
1460 std::to_array<std::string_view>({
"A",
"B",
"PRODUCT"}));
1462 cell.requireSchema(PARAMETERS, std::to_array<std::string_view>(
1463 {
"A",
"B",
"div",
"mod"}));
1464 const auto width = cell.width(
"WIDTH");
1465 const bool sign = cell.flag(
"SIGNED");
1466 const auto a = cell.consumer(
"A", width);
1467 const auto b = cell.consumer(
"B", width);
1469 if constexpr (multiplication)
1470 component = std::make_shared<Multiplier>(std::array<Bus, 2>{a, b},
1471 cell.driver(
"PRODUCT", width));
1473 component = std::make_shared<Divider>(std::array<Bus, 2>{a, b},
1474 cell.driver(
"div", width),
1475 cell.driver(
"mod", width));
1476 component->setProperty(
"signed", sign);
1477 addWithZeroDelay(std::move(component));
1480 template <
bool ParallelInput,
bool ParallelOutput>
1481 void importSiliconRegister(
const Cell& cell)
1483 if constexpr (ParallelInput && !ParallelOutput) {
1484 static constexpr auto PARAMETERS = std::to_array<std::string_view>(
1485 {
"WIDTH",
"CLK_POLARITY",
"EN_POLARITY",
"CLR_POLARITY",
"LOAD_POLARITY"});
1486 static constexpr auto CONNECTIONS =
1487 std::to_array<std::string_view>({
"DATA",
"CLK",
"EN",
"CLR",
"LOAD",
"OUT"});
1488 cell.requireSchema(PARAMETERS, CONNECTIONS);
1490 static constexpr auto PARAMETERS = std::to_array<std::string_view>(
1491 {
"WIDTH",
"CLK_POLARITY",
"EN_POLARITY",
"CLR_POLARITY"});
1492 static constexpr auto CONNECTIONS =
1493 std::to_array<std::string_view>({
"DATA",
"CLK",
"EN",
"CLR",
"OUT"});
1494 cell.requireSchema(PARAMETERS, CONNECTIONS);
1497 const auto width = cell.width(
"WIDTH");
1500 std::format(
"{} WIDTH must be greater than one", cell.cellType()));
1501 if (!cell.flag(
"CLK_POLARITY") || !cell.flag(
"EN_POLARITY")
1502 || !cell.flag(
"CLR_POLARITY")) {
1504 std::format(
"{} supports positive polarities only", cell.cellType()));
1506 if constexpr (ParallelInput && !ParallelOutput) {
1507 if (!cell.flag(
"LOAD_POLARITY"))
1509 std::format(
"{} supports positive polarities only", cell.cellType()));
1512 std::vector<Bus> inputs{cell.consumer(
"DATA", ParallelInput ? width : 1),
1513 Bus{cell.consumerBit(
"CLK")}, Bus{cell.consumerBit(
"EN")},
1514 Bus{cell.consumerBit(
"CLR")}};
1515 if constexpr (ParallelInput && !ParallelOutput)
1516 inputs.emplace_back(Bus{cell.consumerBit(
"LOAD")});
1517 std::vector<Bus> outputs{cell.driver(
"OUT", ParallelOutput ? width : 1)};
1519 auto reg = std::make_shared<Register>();
1520 reg->setProperty(
"size",
static_cast<int>(width));
1525 reg->setProperty(
"delay", 0);
1526 connectAndAdd(std::move(reg), std::move(inputs), std::move(outputs));
1529 void importCell(
const std::string_view name,
const Json& cell)
1531 using CellHandler = void (Importer::*)(
const Cell&);
1532 static constexpr auto HANDLERS =
1533 std::to_array<std::pair<std::string_view, CellHandler>>({
1534 {
cells::DFF, &Importer::importSiliconDff<false, false>},
1535 {
cells::DFFE, &Importer::importSiliconDff<true, false>},
1537 {
cells::DFFSR, &Importer::importSiliconDff<false, true>},
1545 {
cells::PIPO, &Importer::importSiliconRegister<true, true>},
1546 {
cells::PISO, &Importer::importSiliconRegister<true, false>},
1547 {
cells::SIPO, &Importer::importSiliconRegister<false, true>},
1548 {
cells::SISO, &Importer::importSiliconRegister<false, false>},
1549 {
"$and", &Importer::importBinaryGate<AndGate>},
1550 {
"$or", &Importer::importBinaryGate<OrGate>},
1551 {
"$xor", &Importer::importBinaryGate<XorGate>},
1552 {
"$not", &Importer::importNot},
1556 {
"$_NAND_", &Importer::importFineBinaryGate<NandGate>},
1557 {
"$_NOR_", &Importer::importFineBinaryGate<NorGate>},
1558 {
"$pos", &Importer::importPos},
1559 {
"$add", &Importer::importAdd},
1560 {
"$neg", &Importer::importNeg},
1561 {
"$sub", &Importer::importSub},
1564 {
"$mux", &Importer::importMux},
1565 {
"$bmux", &Importer::importBmux},
1566 {
"$demux", &Importer::importDemux},
1567 {
"$adffe", &Importer::importAdffe},
1570 Cell view(*
this, cell, std::format(
"{}.cells.{}", moduleContext(), name));
1571 for (
const auto& [type, handler] : HANDLERS) {
1572 if (view.cellType() == type)
1573 return (this->*handler)(view);
1576 const auto& modules = requireObjectMember(design,
"modules",
"design");
1577 if (
const auto dependency = modules.find(view.cellType());
1578 dependency != modules.end()) {
1579 const auto attributes = dependency->find(
"attributes");
1580 const bool blackbox =
1581 attributes != dependency->end() && attributes->is_object()
1582 && attributes->contains(
"blackbox")
1584 attributes->at(
"blackbox"),
1585 std::format(
"design.modules.{}.attributes.blackbox", view.cellType()))
1588 return importSubcircuit(view, *dependency);
1591 if (view.cellType().starts_with(
"SILICON_"))
1592 fail(view.where(), std::format(
"unsupported SILICON technology cell type '{}'",
1594 fail(view.where(), std::format(
"unsupported cell type '{}'", view.cellType()));
1597 void importSubcircuit(
const Cell& cell,
const Json& dependencyModule)
1599 if (!dependencyModule.is_object())
1600 fail(std::format(
"design.modules.{}", cell.cellType()),
"expected an object");
1601 const auto& ports = requireObjectMember(
1602 dependencyModule,
"ports", std::format(
"design.modules.{}", cell.cellType()));
1603 if (!ports.is_object())
1604 fail(std::format(
"design.modules.{}.ports", cell.cellType()),
1605 "expected an object");
1607 std::vector<std::string> portNames;
1608 portNames.reserve(ports.size());
1609 for (
const auto& [portName, _] : ports.items())
1610 portNames.push_back(portName);
1611 cell.requireKnownConnectionNames(portNames);
1613 std::vector<Bus> inputs;
1614 std::vector<Bus> outputs;
1615 std::vector<std::string> inputNames;
1616 std::vector<std::string> outputNames;
1617 for (
const auto& [portName, port] : ports.items()) {
1618 const auto context =
1619 std::format(
"design.modules.{}.ports.{}", cell.cellType(), portName);
1620 if (!
port.is_object())
1621 fail(context,
"expected an object");
1622 const auto& directionJson = requireObjectMember(port,
"direction", context);
1623 const auto& bitsJson = requireObjectMember(port,
"bits", context);
1624 if (!directionJson.is_string() || !bitsJson.is_array() || bitsJson.empty())
1625 fail(context,
"expected a direction and a non-empty bit array");
1627 const auto direction = directionJson.get<std::string>();
1628 if (direction ==
"input") {
1629 inputNames.push_back(portName);
1630 inputs.push_back(cell.consumer(portName, bitsJson.size()));
1631 }
else if (direction ==
"output") {
1632 outputNames.push_back(portName);
1633 outputs.push_back(cell.optionalDriver(portName, bitsJson.size()));
1634 }
else if (direction ==
"inout")
1635 fail(context,
"inout ports are not supported");
1637 fail(context, std::format(
"invalid port direction '{}'", direction));
1641 cell.cellType(), std::move(inputNames), std::move(inputs),
1642 std::move(outputNames), std::move(outputs)));
1654 const std::string_view to)
1658 boost::add_edge(source, target,
graph);
1664 enum class VisitState { Unvisited, Visiting, Visited };
1665 std::vector<VisitState> states(boost::num_vertices(
graph), VisitState::Unvisited);
1669 std::function<void(
Vertex)> visit = [&](
const Vertex vertex) {
1670 if (states[vertex] == VisitState::Visited)
1672 if (states[vertex] == VisitState::Visiting) {
1673 const auto repeated =
graph[vertex].name;
1674 const auto begin = std::ranges::find(stack, repeated);
1676 cycle.push_back(repeated);
1678 for (
const auto& module : cycle) {
1683 throw std::runtime_error(
1684 std::format(
"Recursive Verilog module dependency detected: {}", trace));
1687 states[vertex] = VisitState::Visiting;
1688 stack.push_back(
graph[vertex].name);
1690 for (
const auto& dependency : dependencies)
1693 states[vertex] = VisitState::Visited;
1694 result.push_back(
graph[vertex].name);
1697 auto sortedRoots = roots;
1698 std::ranges::sort(sortedRoots);
1699 sortedRoots.erase(std::ranges::unique(sortedRoots).begin(), sortedRoots.end());
1700 for (
const auto& root : sortedRoots) {
1703 throw std::invalid_argument(std::format(
"Unknown Verilog module '{}'", root));
1717 for (
const auto edge : boost::make_iterator_range(boost::out_edges(*vertex,
graph)))
1718 dependencies.push_back(
graph[boost::target(edge,
graph)].name);
1719 std::ranges::sort(dependencies);
1720 return dependencies;
1726 names.reserve(boost::num_vertices(
graph));
1727 for (
const auto vertex : boost::make_iterator_range(boost::vertices(
graph)))
1728 names.push_back(
graph[vertex].name);
1729 std::ranges::sort(names);
1738std::optional<ModuleDependencyGraph::Vertex>
1743 return std::nullopt;
1750 if (
const auto existing =
findVertex(moduleName))
1760 for (
const auto vertex : boost::make_iterator_range(boost::vertices(
graph)))
1767 const Json design = Json::parse(json);
1768 if (!design.is_object())
1769 throw std::runtime_error(
"Invalid Yosys JSON: design must be an object");
1771 const auto modules = design.find(
"modules");
1772 if (modules == design.end() || !modules->is_object())
1773 throw std::runtime_error(
"Invalid Yosys JSON: design.modules must be an object");
1775 const auto isBlackbox = [](
const std::string& moduleName,
const Json& module) {
1776 const auto attributes =
module.find("attributes");
1780 throw std::runtime_error(std::format(
1781 "Invalid Yosys JSON: design.modules.{}.attributes must be an object",
1783 const auto blackbox =
attributes->find(
"blackbox");
1787 std::format(
"design.modules.{}.attributes.blackbox", moduleName))
1792 for (
const auto& [moduleName, module] : modules->items()) {
1793 if (!module.is_object())
1794 throw std::runtime_error(std::format(
1795 "Invalid Yosys JSON: design.modules.{} must be an object", moduleName));
1796 if (!isBlackbox(moduleName, module))
1800 for (
const auto& [moduleName, module] : modules->items()) {
1803 const auto cells =
module.find("cells");
1804 if (
cells == module.end())
1806 if (!
cells->is_object())
1807 throw std::runtime_error(std::format(
1808 "Invalid Yosys JSON: design.modules.{}.cells must be an object", moduleName));
1810 for (
const auto& [cellName, cell] :
cells->items()) {
1811 if (!cell.is_object())
1812 throw std::runtime_error(std::format(
1813 "Invalid Yosys JSON: design.modules.{}.cells.{} must be an object",
1814 moduleName, cellName));
1815 const auto type = cell.find(
"type");
1816 if (type == cell.end() || !type->is_string())
1817 throw std::runtime_error(std::format(
1818 "Invalid Yosys JSON: design.modules.{}.cells.{}.type must be a string",
1819 moduleName, cellName));
1821 const auto dependency = type->get<std::string>();
1827 }
catch (
const nlohmann::json::exception& error) {
1828 throw std::runtime_error(std::format(
"Invalid Yosys JSON: {}", error.what()));
1833 const std::optional<std::string_view> moduleName)
1836 return Importer(Json::parse(json)).run(moduleName);
1837 }
catch (
const nlohmann::json::exception& error) {
1838 throw std::runtime_error(std::format(
"Invalid Yosys JSON: {}", error.what()));
Represents a digital circuit as a directed graph of components.
static constexpr std::string_view SERIAL_TYPE
static constexpr std::string_view PARALLEL_TYPE
static std::shared_ptr< SubcircuitComponent > imported(std::string slug, std::vector< std::string > inputNames, std::vector< Bus > inputs, std::vector< std::string > outputNames, std::vector< Bus > outputs)
Creates an imported module instance before its project document exists.
Module-instantiation dependency graph for a Yosys JSON design.
std::vector< std::string > ModuleNameList
List of module names.
NameToVertex nameToVertex
Name-to-vertex index kept in sync with graph.
void rebuildNameIndex()
Rebuilds nameToVertex from the current graph.
Graph graph
The dependency graph itself.
bool containsModule(std::string_view moduleName) const
Checks whether a module vertex is present in the graph.
ModuleNameList dependencyOrder(const ModuleNameList &roots) const
Returns the unique dependency closure of roots in dependency-first order.
void addDependency(std::string_view from, std::string_view to)
Records that from instantiates to.
ModuleNameList dependenciesOf(std::string_view moduleName) const
Returns the sorted, unique modules moduleName instantiates.
Vertex ensureVertex(std::string_view moduleName)
Ensures a module vertex exists in this graph (O(1)).
boost::graph_traits< Graph >::vertex_descriptor Vertex
Boost vertex descriptor (an integer index under vecS).
void addModule(std::string_view moduleName)
Ensures a module vertex exists, creating it if necessary.
ModuleNameList modules() const
Returns every declared module name.
std::optional< Vertex > findVertex(std::string_view moduleName) const
int width(RTLIL::Module *module, RTLIL::Cell *cell, RTLIL::IdString key)
RTLIL::SigSpec port(RTLIL::Module *module, RTLIL::Cell *cell, RTLIL::IdString key, int expected)
std::optional< Gate > gate(Cell *cell, SigMap &signals)
std::optional< Mux > mux(Cell *cell, SigMap &signals)
bool flag(RTLIL::Module *module, RTLIL::Cell *cell, RTLIL::IdString key)
std::shared_ptr< Component > Component_ptr
std::shared_ptr< Wire > Wire_ptr
BusValue busValueFromBits(const std::string_view bits)
Strictly decodes an MSB-first raw string containing 0, 1, X, or E.
std::string formatValue(const BusValue &value, const BusValueFormat format, const std::size_t fixedWidth)
Format an LSB-first BusValue for display.
std::vector< State > BusValue
bool isValidDocumentSlug(const std::string_view slug)
QVariant value(const QSettings &settings, const Definition &setting)
Reads a setting value, falling back to its declared default when unset.
constexpr std::string_view BINARY_DOCUMENT
constexpr std::string_view ADDER
constexpr std::string_view MUX
constexpr std::string_view COMPARE
constexpr std::string_view GATE
constexpr std::string_view LOGIC
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 SHIFT
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
Circuit deserialize(const std::string_view json, const std::optional< std::string_view > moduleName)
Deserialize one supported Yosys write_json module into a Silicon circuit.
ModuleDependencyGraph moduleDependencyGraph(const std::string_view json)
Build a module dependency graph from a Yosys write_json document.
nlohmann::ordered_json Json
Per-vertex payload holding the declared module name.