SILICON
Loading...
Searching...
No Matches
yosys_netlist.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
19
20TEST(YosysTest, PreservesLiteralBmuxLanesAsSizedConstants)
21{
24
25 // The packed A port contains two signal lanes followed by the LSB-first encodings
26 // of 4'b0011 and 4'b0100. Each literal lane should become one four-bit constant.
27 const Json design{
28 {"modules",
29 {{"top",
30 {{"attributes", Json::object()},
31 {"ports",
32 {{"first", {{"direction", "input"}, {"bits", Json::array({2, 3, 4, 5})}}},
33 {"second", {{"direction", "input"}, {"bits", Json::array({6, 7, 8, 9})}}},
34 {"select", {{"direction", "input"}, {"bits", Json::array({10, 11})}}},
35 {"y", {{"direction", "output"}, {"bits", Json::array({12, 13, 14, 15})}}}}},
36 {"cells",
37 {{"mux",
38 {{"type", "$bmux"},
39 {"parameters",
41 {"S_WIDTH", SerializationContext::parameter(2)}}},
42 {"connections",
43 {{"A", Json::array({2, 3, 4, 5, 6, 7, 8, 9, "1", "1", "0", "0", "0", "0",
44 "1", "0"})},
45 {"S", Json::array({10, 11})},
46 {"Y", Json::array({12, 13, 14, 15})}}}}}}},
47 {"netnames", Json::object()}}}}}};
48
49 const Circuit circuit = SILICON::yosys::deserialize(design.dump());
50 EXPECT_EQ(componentTypes(circuit).count("ConstantComponent"), 2);
51 EXPECT_EQ(componentTypes(circuit).count("WireMerger"), 0);
52 EXPECT_EQ(componentTypes(circuit).count("WireSplitter"), 0);
53
54 const auto mux = findComponent<Multiplexer>(circuit);
55 ASSERT_TRUE(mux);
56 ASSERT_EQ(mux->inputBuses().size(), 5);
57
58 std::map<BusValue, std::shared_ptr<ConstantComponent>> constants;
59 for (const auto& component : componentsIn(circuit)) {
60 if (auto constant = std::dynamic_pointer_cast<ConstantComponent>(component)) {
61 ASSERT_EQ(constant->getPropertyValue<int>("size"), 4);
62 constants.emplace(*constant->getPropertyValue<BusValue>("value"), constant);
63 }
64 }
65 ASSERT_TRUE(constants.contains(busValueFromBits("0011")));
66 ASSERT_TRUE(constants.contains(busValueFromBits("0100")));
67 EXPECT_EQ(mux->inputBuses()[2],
68 constants.at(busValueFromBits("0011"))->outputBuses()[0]);
69 EXPECT_EQ(mux->inputBuses()[3],
70 constants.at(busValueFromBits("0100"))->outputBuses()[0]);
71}
72
73TEST(YosysTest, ImportsScalarBmuxAsSeparateLiteralLanesAndRoundTrips)
74{
77
78 const Json design{
79 {"modules",
80 {{"top",
81 {{"attributes", Json::object()},
82 {"ports",
83 {{"select", {{"direction", "input"}, {"bits", Json::array({2, 3})}}},
84 {"y", {{"direction", "output"}, {"bits", Json::array({4})}}}}},
85 {"cells",
86 {{"mux",
87 {{"type", "$bmux"},
88 {"parameters",
90 {"S_WIDTH", SerializationContext::parameter(2)}}},
91 {"connections",
92 {{"A", Json::array({"0", "1", "x", "0"})},
93 {"S", Json::array({2, 3})},
94 {"Y", Json::array({4})}}}}}}},
95 {"netnames", Json::object()}}}}}};
96
97 const Circuit circuit = SILICON::yosys::deserialize(design.dump());
98 EXPECT_EQ(componentTypes(circuit).count("Multiplexer"), 1);
99 // Identical literal lanes share one constant producer.
100 EXPECT_EQ(componentTypes(circuit).count("ConstantComponent"), 3);
101 EXPECT_EQ(componentTypes(circuit).count("WireMerger"), 0);
102 EXPECT_EQ(componentTypes(circuit).count("WireSplitter"), 0);
103
104 const auto mux = findComponent<Multiplexer>(circuit);
105 ASSERT_TRUE(mux);
106 ASSERT_EQ(mux->inputBuses().size(), 5);
107 for (std::size_t lane = 0; lane < 4; ++lane)
108 EXPECT_EQ(mux->inputBuses()[lane].size(), 1);
109 EXPECT_EQ(mux->inputBuses().back().size(), 2);
110 EXPECT_EQ(mux->outputBuses()[0].size(), 1);
111
112 const Circuit restored =
114 const auto restoredMux = findComponent<Multiplexer>(restored);
115 ASSERT_TRUE(restoredMux);
116 ASSERT_EQ(restoredMux->inputBuses().size(), 5);
117 EXPECT_TRUE(std::ranges::all_of(restoredMux->inputBuses() | std::views::take(4),
118 [](const Bus& lane) { return lane.size() == 1; }));
119}
120
121TEST(YosysTest, ImportsNegWithYosysWidthAndSignednessSemanticsWithoutYosys)
122{
123 for (bool sign : {false, true}) {
124 for (int resultWidth : {2, 3, 5}) {
125 SCOPED_TRACE(std::format("signed={} resultWidth={}", sign, resultWidth));
126 auto design = subtractionDesign(3, 3, resultWidth, sign, false);
127 auto& cell = onlyModule(design)["cells"].begin().value();
128 cell["type"] = "$neg";
129 cell["connections"].erase("B");
130 cell["parameters"].erase("B_SIGNED");
131 cell["parameters"].erase("B_WIDTH");
132 const auto circuit =
133 std::make_shared<Circuit>(SILICON::yosys::deserialize(design.dump()));
134 EXPECT_EQ(componentTypes(*circuit).count("Complementer"), 1);
135 EXPECT_EQ(componentTypes(*circuit).count("AdderNBits"), 0);
136 for (unsigned int a = 0; a < 8; ++a) {
137 SCOPED_TRACE(a);
138 const int operand = sign && (a & 4u) ? static_cast<int>(a) - 8
139 : static_cast<int>(a);
140 EXPECT_EQ(evaluateBinaryCircuit(circuit, a, 0),
141 valueFor(resultWidth, static_cast<unsigned int>(-operand)
142 & ((1u << resultWidth) - 1)));
143 }
144 }
145 }
146}
147
148TEST(YosysTest, ImportsSubWithYosysWidthAndSignednessSemantics)
149{
150 const auto import = [](const std::size_t aWidth, const std::size_t bWidth,
151 const std::size_t yWidth, const bool aSigned,
152 const bool bSigned) {
153 return std::make_shared<Circuit>(SILICON::yosys::deserialize(
154 subtractionDesign(aWidth, bWidth, yWidth, aSigned, bSigned).dump()));
155 };
156
157 auto unsignedCircuit = import(3, 5, 4, false, false);
158 auto complementer = findComponent<Complementer>(*unsignedCircuit);
159 auto adder = findComponent<AdderNBits>(*unsignedCircuit);
160 ASSERT_TRUE(complementer);
161 ASSERT_TRUE(adder);
162 auto extender = findComponent<Extender>(*unsignedCircuit);
163 ASSERT_TRUE(extender);
164 EXPECT_EQ(complementer->getPropertyValue<int>("size"), 5);
165 EXPECT_EQ(adder->getPropertyValue<int>("size"), 5);
166 EXPECT_EQ(extender->getPropertyValue<int>("inSize"), 3);
167 EXPECT_EQ(extender->getPropertyValue<int>("outSize"), 5);
168 EXPECT_EQ(extender->getPropertyValue<std::string>("mode"),
169 std::string(Extender::UNSIGNED_MODE));
170 EXPECT_EQ(evaluateBinaryCircuit(unsignedCircuit, 2, 5), valueFor(4, 13));
171
172 // Both signed flags cause sign extension: 3'b110 (-2) - 5'b00011 (3) = -5.
173 auto signedCircuit = import(3, 5, 6, true, true);
174 auto signedExtender = findComponent<Extender>(*signedCircuit);
175 ASSERT_TRUE(signedExtender);
176 EXPECT_EQ(signedExtender->getPropertyValue<std::string>("mode"),
177 std::string(Extender::SIGNED_MODE));
178 EXPECT_EQ(evaluateBinaryCircuit(signedCircuit, 6, 3), valueFor(6, 59));
179
180 // A mixed signedness operation is unsigned in Yosys: 6 - 3 = 3.
181 auto mixedCircuit = import(3, 5, 6, true, false);
182 auto mixedExtender = findComponent<Extender>(*mixedCircuit);
183 ASSERT_TRUE(mixedExtender);
184 EXPECT_EQ(mixedExtender->getPropertyValue<std::string>("mode"),
185 std::string(Extender::UNSIGNED_MODE));
186 EXPECT_EQ(evaluateBinaryCircuit(mixedCircuit, 6, 3), valueFor(6, 3));
187
188 // Arithmetic is evaluated at the widest width and narrowed to the low Y bits.
189 auto narrowedCircuit = import(5, 4, 3, false, false);
190 EXPECT_EQ(evaluateBinaryCircuit(narrowedCircuit, 1, 3), valueFor(3, 6));
191
192 auto addDesign = subtractionDesign(3, 5, 4, false, false);
193 onlyModule(addDesign)["cells"].begin().value()["type"] = "$add";
194 auto addCircuit =
195 std::make_shared<Circuit>(SILICON::yosys::deserialize(addDesign.dump()));
196 auto addExtender = findComponent<Extender>(*addCircuit);
197 ASSERT_TRUE(addExtender);
198 EXPECT_EQ(addExtender->getPropertyValue<int>("inSize"), 3);
199 EXPECT_EQ(addExtender->getPropertyValue<int>("outSize"), 5);
200 EXPECT_EQ(evaluateBinaryCircuit(addCircuit, 2, 5), valueFor(4, 7));
201}
202
203TEST(YosysTest, ImportsAdditionWithMixedWidthsAndSignedness)
204{
205 for (bool aSigned : {false, true}) {
206 for (bool bSigned : {false, true}) {
207 for (int yWidth : {2, 5, 7}) {
208 SCOPED_TRACE(
209 std::format("aSigned={} bSigned={} yWidth={}", aSigned, bSigned, yWidth));
210 auto design = subtractionDesign(3, 5, yWidth, aSigned, bSigned);
211 onlyModule(design)["cells"].begin().value()["type"] = "$add";
212 const auto circuit =
213 std::make_shared<Circuit>(SILICON::yosys::deserialize(design.dump()));
214 EXPECT_EQ(componentTypes(*circuit).count("AdderNBits"), 1);
215 for (unsigned a = 0; a < 8; ++a) {
216 for (unsigned b : {0u, 1u, 15u, 16u, 31u}) {
217 const int lhs = aSigned && bSigned && a >= 4 ? static_cast<int>(a) - 8 : a;
218 const int rhs = aSigned && bSigned && b >= 16 ? static_cast<int>(b) - 32 : b;
219 EXPECT_EQ(evaluateBinaryCircuit(circuit, a, b),
220 valueFor(yWidth, (lhs + rhs) & ((1u << yWidth) - 1)));
221 }
222 }
223 const auto restored = std::make_shared<Circuit>(
225 EXPECT_EQ(evaluateBinaryCircuit(restored, 7, 31),
226 evaluateBinaryCircuit(circuit, 7, 31));
227 }
228 }
229 }
230}
231
232TEST(YosysTest, ImportsComparisonCellsWithYosysWidthAndSignednessSemantics)
233{
234 // legalizeExpressions is a pass-through without the plugin, and the importer
235 // only accepts canonical cells, so these designs cannot be built without it.
236#ifndef SILICON_TEST_YOSYS_PLUGIN_AVAILABLE
237 GTEST_SKIP() << "The SILICON Yosys plugin is unavailable";
238#endif
239
240 struct ComparisonCase {
241 std::string_view type;
242 std::string_view mode;
243 };
244 static constexpr std::array CASES{
245 ComparisonCase{"$eq", "=="}, ComparisonCase{"$lt", "<"},
246 ComparisonCase{"$le", "<="}, ComparisonCase{"$gt", ">"},
247 ComparisonCase{"$ge", ">="},
248 };
249
250 for (const auto& comparison : CASES) {
251 SCOPED_TRACE(comparison.type);
252 auto circuit = std::make_shared<Circuit>(SILICON::yosys::deserialize(
253 legalizeExpressions(comparisonDesign(comparison.type, 3, 5, 1, false, false).dump())));
254 const auto comparator = findComponent<Comparator>(*circuit);
255 ASSERT_TRUE(comparator);
256 EXPECT_EQ(comparator->getPropertyValue<int>("size"), 5);
257 EXPECT_EQ(comparator->getPropertyValue<std::string>("mode"), comparison.mode);
258 EXPECT_EQ(comparator->getPropertyValue<bool>("signed"), false);
259 // Restore the narrow operand's zero padding as a bus extender.
260 EXPECT_TRUE(findComponent<Extender>(*circuit));
261 EXPECT_EQ(componentTypes(*circuit).count("WireMerger"), 0);
262 }
263
264 // 3'b110 is -2 for a signed comparison, but 6 for an unsigned one.
265 auto signedLess = std::make_shared<Circuit>(
266 SILICON::yosys::deserialize(legalizeExpressions(comparisonDesign("$lt", 3, 5, 1, true, true).dump())));
267 EXPECT_EQ(evaluateBinaryCircuit(signedLess, 6, 3), valueFor(1, 1));
268 ASSERT_TRUE(findComponent<Comparator>(*signedLess));
269 EXPECT_EQ(findComponent<Comparator>(*signedLess)->getPropertyValue<bool>("signed"),
270 true);
271
272 auto mixedLess = std::make_shared<Circuit>(
273 SILICON::yosys::deserialize(legalizeExpressions(comparisonDesign("$lt", 3, 5, 1, true, false).dump())));
274 EXPECT_EQ(evaluateBinaryCircuit(mixedLess, 6, 3), valueFor(1, 0));
275 ASSERT_TRUE(findComponent<Comparator>(*mixedLess));
276 EXPECT_EQ(findComponent<Comparator>(*mixedLess)->getPropertyValue<bool>("signed"),
277 false);
278
279 auto wideOutput = std::make_shared<Circuit>(
280 SILICON::yosys::deserialize(legalizeExpressions(comparisonDesign("$ge", 4, 4, 3, false, false).dump())));
281 EXPECT_EQ(evaluateBinaryCircuit(wideOutput, 9, 3), valueFor(3, 1));
282 EXPECT_TRUE(findComponent<Extender>(*wideOutput));
283}
284
285TEST(YosysTest, ImportsIndependentEqualityCells)
286{
289
290#ifndef SILICON_TEST_YOSYS_PLUGIN_AVAILABLE
291 GTEST_SKIP() << "The SILICON Yosys plugin is unavailable";
292#endif
293
294 const Json eqParameters{
295 {"A_SIGNED", SerializationContext::parameter(0, 1)},
296 {"B_SIGNED", SerializationContext::parameter(0, 1)},
297 {"A_WIDTH", SerializationContext::parameter(3)},
298 {"B_WIDTH", SerializationContext::parameter(3)},
299 {"Y_WIDTH", SerializationContext::parameter(1)},
300 };
301 const auto eqCell = [&eqParameters](Json constant, const int output) {
302 return Json{{"type", "$eq"},
303 {"parameters", eqParameters},
304 {"connections",
305 {{"A", Json::array({2, 3, 4})},
306 {"B", std::move(constant)},
307 {"Y", Json::array({output})}}}};
308 };
309 const Json design{
310 {"modules",
311 {{"top",
312 {{"attributes", Json::object()},
313 {"ports",
314 {{"select", {{"direction", "input"}, {"bits", Json::array({2, 3, 4})}}},
315 {"matches", {{"direction", "output"}, {"bits", Json::array({5, 6})}}}}},
316 {"cells",
317 {{"match_one", eqCell(Json::array({"1", "0", "0"}), 5)},
318 {"match_six", eqCell(Json::array({"0", "1", "1"}), 6)}}},
319 {"netnames", Json::object()}}}}}};
320
321 const Circuit circuit = SILICON::yosys::deserialize(legalizeExpressions(design.dump()));
322 EXPECT_EQ(componentTypes(circuit).count("Comparator"), 2);
323}
324
325TEST(YosysTest, ConnectionReaderEnforcesRolesWidthsAndDriverOwnership)
326{
329
330 const Json parameters{{"A_SIGNED", SerializationContext::parameter(0, 1)},
331 {"A_WIDTH", SerializationContext::parameter(1)},
332 {"Y_WIDTH", SerializationContext::parameter(1)}};
333 const auto designWithCells = [](Json cells) {
334 return Json{{"modules",
335 {{"top",
336 {{"attributes", Json::object()},
337 {"ports", Json::object()},
338 {"cells", std::move(cells)},
339 {"netnames", Json::object()}}}}}};
340 };
341 const auto notCell = [&parameters](Json input, Json output) {
342 return Json{{"type", "$not"},
343 {"parameters", parameters},
344 {"connections", {{"A", std::move(input)}, {"Y", std::move(output)}}}};
345 };
346
347 const Json constantConsumer =
348 designWithCells({{"not", notCell(Json::array({"1"}), Json::array({2}))}});
349 EXPECT_NO_THROW((void)SILICON::yosys::deserialize(constantConsumer.dump()));
350
351 const Json constantDriver =
352 designWithCells({{"not", notCell(Json::array({2}), Json::array({"0"}))}});
353 EXPECT_THROW((void)SILICON::yosys::deserialize(constantDriver.dump()),
354 std::runtime_error);
355
356 Json incorrectWidth = constantConsumer;
357 incorrectWidth["modules"]["top"]["cells"]["not"]["parameters"]["A_WIDTH"] =
359 EXPECT_THROW((void)SILICON::yosys::deserialize(incorrectWidth.dump()),
360 std::runtime_error);
361
362 const Json duplicateDriver =
363 designWithCells({{"first", notCell(Json::array({"0"}), Json::array({2}))},
364 {"second", notCell(Json::array({"1"}), Json::array({2}))}});
365 EXPECT_THROW((void)SILICON::yosys::deserialize(duplicateDriver.dump()),
366 std::runtime_error);
367}
368
369TEST(YosysTest, ImportsEveryCellShapeEmittedBySilicon)
370{
371 // Comparator and Shifter export raw Yosys operators that only the plugin
372 // legalizes, so the whole shape sweep needs the plugin.
373#ifndef SILICON_TEST_YOSYS_PLUGIN_AVAILABLE
374 GTEST_SKIP() << "The SILICON Yosys plugin is unavailable";
375#endif
376
377 std::vector<Component_ptr> components;
378 components.push_back(std::make_shared<Extender>(Bus(3), Bus(5)));
379 components.push_back(std::make_shared<Complementer>(Bus(4), Bus(4)));
380 components.push_back(std::make_shared<Comparator>(std::array<Bus, 2>{Bus(4), Bus(4)},
381 std::make_shared<Wire>()));
382 components.push_back(std::make_shared<FullAdder>(
383 std::array<Wire_ptr, 2>{std::make_shared<Wire>(), std::make_shared<Wire>()},
384 std::make_shared<Wire>(), std::make_shared<Wire>(), std::make_shared<Wire>()));
385
386 auto mux = std::make_shared<Multiplexer>(Bus(4), Bus(2), std::make_shared<Wire>());
387 mux->setProperty("busSize", 2);
388 components.push_back(std::move(mux));
389
390 auto demux = std::make_shared<Demultiplexer>(Bus(1), Bus(2), Bus(4));
391 demux->setProperty("busSize", 2);
392 components.push_back(std::move(demux));
393
394 components.push_back(std::make_shared<DFlipFlop>(
395 std::make_shared<Wire>(), std::make_shared<Wire>(), nullptr, nullptr,
396 std::make_shared<Wire>(), std::make_shared<Wire>()));
397 components.push_back(std::make_shared<EFlipFlop>(
398 std::make_shared<Wire>(), std::make_shared<Wire>(), std::make_shared<Wire>(),
399 nullptr, nullptr, std::make_shared<Wire>(), std::make_shared<Wire>()));
400 components.push_back(
401 std::make_shared<DLatch>(std::make_shared<Wire>(), std::make_shared<Wire>(),
402 std::make_shared<Wire>(), std::make_shared<Wire>()));
403 components.push_back(std::make_shared<Register>(Bus(4), std::make_shared<Wire>(),
404 std::make_shared<Wire>(),
405 std::make_shared<Wire>(), Bus(4)));
406 components.push_back(std::make_shared<Register>(Bus(4), std::make_shared<Wire>(),
407 std::make_shared<Wire>(),
408 std::make_shared<Wire>(), Bus(1)));
409 components.push_back(
410 std::make_shared<WireMerger>(std::vector<Bus>{Bus(1), Bus(1)}, Bus(2)));
411
412 for (std::size_t index = 0; index < components.size(); ++index) {
413 SCOPED_TRACE(std::format("component {} ({})", index, components[index]->typeName()));
414 const auto exported = exportComponent(components[index]).dump();
415 EXPECT_NO_THROW({
416 const auto imported = SILICON::yosys::deserialize(legalizeExpressions(exported));
417 const auto reparsed =
418 nlohmann::json::parse(SILICON::yosys::serialize(imported, "top"));
419 EXPECT_TRUE(reparsed.is_object());
420 });
421 }
422}
423
424TEST(YosysTest, SelectsExplicitOrUniqueTopModule)
425{
428
429 const auto moduleWithPort = [](const std::string_view portName) {
430 return Json{{"attributes", Json::object()},
431 {"ports",
432 {{std::string(portName),
433 {{"direction", "input"}, {"bits", Json::array({2, 3})}}}}},
434 {"cells", Json::object()},
435 {"netnames", Json::object()}};
436 };
437 Json topModule = moduleWithPort("selected");
438 topModule["attributes"]["top"] = SerializationContext::parameter(1, 1);
439 const Json design{
440 {"modules", {{"helper", moduleWithPort("helper")}, {"selected", topModule}}}};
441
442 EXPECT_TRUE(findNamedComponent<DummyBusInputComponent>(
443 SILICON::yosys::deserialize(design.dump()), "selected"));
444 EXPECT_TRUE(findNamedComponent<DummyBusInputComponent>(
445 SILICON::yosys::deserialize(design.dump(), "helper"), "helper"));
446
447 Json ambiguous = design;
448 ambiguous["modules"]["selected"]["attributes"] = Json::object();
449 EXPECT_THROW((void)SILICON::yosys::deserialize(ambiguous.dump()), std::runtime_error);
450
451 Json twoTops = design;
452 twoTops["modules"]["helper"]["attributes"]["top"] =
454 EXPECT_THROW((void)SILICON::yosys::deserialize(twoTops.dump()), std::runtime_error);
455 EXPECT_THROW((void)SILICON::yosys::deserialize(design.dump(), "missing"),
456 std::runtime_error);
457}
458
459TEST(YosysTest, BuildsModuleDependencyGraph)
460{
462
463 const Json design{
464 {"modules",
465 {{"top",
466 {{"cells",
467 {{"second_child", {{"type", "child"}}},
468 {"primitive", {{"type", "$and"}}},
469 {"first_child", {{"type", "child"}}},
470 {"helper_instance", {{"type", "helper"}}}}}}},
471 {"helper", {{"cells", {{"leaf_instance", {{"type", "leaf"}}}}}}},
472 {"child", {{"cells", Json::object()}}},
473 {"leaf", Json::object()},
474 {"external", {{"attributes", {{"blackbox", "1"}}}, {"cells", Json::object()}}}}}};
475
476 const auto graph = SILICON::yosys::moduleDependencyGraph(design.dump());
477
478 EXPECT_TRUE(graph.containsModule("top"));
479 EXPECT_TRUE(graph.containsModule("child"));
480 EXPECT_TRUE(graph.containsModule("helper"));
481 EXPECT_TRUE(graph.containsModule("leaf"));
482 EXPECT_FALSE(graph.containsModule("$and"));
483 EXPECT_FALSE(graph.containsModule("primitive"));
484 EXPECT_FALSE(graph.containsModule("external"));
485
486 EXPECT_EQ(graph.modules(),
487 (std::vector<std::string>{"child", "helper", "leaf", "top"}));
488 EXPECT_EQ(graph.dependenciesOf("top"), (std::vector<std::string>{"child", "helper"}));
489 EXPECT_EQ(graph.dependenciesOf("helper"), (std::vector<std::string>{"leaf"}));
490 EXPECT_EQ(graph.dependenciesOf("child"), std::vector<std::string>{});
491 EXPECT_EQ(graph.dependenciesOf("leaf"), std::vector<std::string>{});
492 EXPECT_EQ(graph.dependenciesOf("missing"), std::vector<std::string>{});
493}
494
495TEST(YosysTest, OrdersSelectedModuleDependencyClosure)
496{
498 for (const auto module : {"top", "other", "left", "right", "leaf", "unused"})
499 graph.addModule(module);
500 graph.addDependency("top", "left");
501 graph.addDependency("top", "right");
502 graph.addDependency("left", "leaf");
503 graph.addDependency("right", "leaf");
504 graph.addDependency("other", "right");
505
506 EXPECT_EQ(graph.dependencyOrder({"top", "other"}),
507 (std::vector<std::string>{"leaf", "right", "other", "left", "top"}));
508 EXPECT_THROW((void)graph.dependencyOrder({"missing"}), std::invalid_argument);
509
510 graph.addDependency("leaf", "top");
511 EXPECT_THROW((void)graph.dependencyOrder({"top"}), std::runtime_error);
512}
513
514TEST(YosysTest, ImportsDeclaredModuleCellsAsSubcircuits)
515{
518
519 const Json unaryParameters{{"A_SIGNED", SerializationContext::parameter(0, 1)},
520 {"A_WIDTH", SerializationContext::parameter(1)},
521 {"Y_WIDTH", SerializationContext::parameter(1)}};
522 const Json design{
523 {"modules",
524 {{"leaf",
525 {{"ports",
526 {{"a", {{"direction", "input"}, {"bits", Json::array({2})}}},
527 {"y", {{"direction", "output"}, {"bits", Json::array({3})}}}}},
528 {"cells",
529 {{"invert",
530 {{"type", "$not"},
531 {"parameters", unaryParameters},
532 {"connections", {{"A", Json::array({2})}, {"Y", Json::array({3})}}}}}}}}},
533 {"top",
534 {{"ports",
535 {{"source", {{"direction", "input"}, {"bits", Json::array({4})}}},
536 {"result", {{"direction", "output"}, {"bits", Json::array({5})}}}}},
537 {"cells",
538 {{"child",
539 {{"type", "leaf"},
540 {"parameters", Json::object()},
541 {"connections",
542 {{"a", Json::array({4})}, {"y", Json::array({5})}}}}}}}}}}}};
543
544 const Circuit top = SILICON::yosys::deserialize(design.dump(), "top");
545 EXPECT_EQ(componentTypes(top),
546 (std::multiset<std::string>{"DummyInputComponent", "DummyOutputComponent",
547 "Subcircuit"}));
548 const auto instance = findComponent<SubcircuitComponent>(top);
549 ASSERT_TRUE(instance);
550 EXPECT_EQ(instance->getPropertyValue<std::string>("slug"),
551 std::optional<std::string>("leaf"));
552 ASSERT_EQ(instance->inputBuses().size(), 1);
553 ASSERT_EQ(instance->outputBuses().size(), 1);
554 EXPECT_EQ(instance->inputBuses()[0].size(), 1);
555 EXPECT_EQ(instance->outputBuses()[0].size(), 1);
556 EXPECT_EQ(instance->importedInputNames(), (std::vector<std::string>{"a"}));
557 EXPECT_EQ(instance->importedOutputNames(), (std::vector<std::string>{"y"}));
558
559 const auto serialized = Json::parse(top.serialize());
560 const auto serializedInstance =
561 std::ranges::find_if(serialized.at("components"), [](const Json& component) {
562 return component.value("type", std::string()) == "Subcircuit";
563 });
564 ASSERT_NE(serializedInstance, serialized.at("components").end());
565 EXPECT_EQ(serializedInstance->at("properties").at("slug"), "leaf");
566}
567
568TEST(YosysTest, ImportsUnconnectedModuleOutputsWithoutRelaxingInputValidation)
569{
571 Json design;
572 auto& leaf = design["modules"]["leaf"];
573 leaf["ports"] = {
574 {"a", {{"direction", "input"}, {"bits", Json::array({2})}}},
575 {"unused_bit", {{"direction", "output"}, {"bits", Json::array({3})}}},
576 {"unused_bus", {{"direction", "output"}, {"bits", Json::array({4, 5, 6, 7})}}},
577 {"y", {{"direction", "output"}, {"bits", Json::array({8})}}},
578 };
579 leaf["cells"] = Json::object();
580 auto& top = design["modules"]["top"];
581 top["ports"] = Json::object();
582 top["cells"]["first"] = {
583 {"type", "leaf"},
584 {"parameters", Json::object()},
585 {"connections", {{"a", Json::array({20})}, {"y", Json::array({21})}}}};
586 top["cells"]["second"] = top["cells"]["first"];
587 top["cells"]["second"]["connections"]["y"] = Json::array({22});
588
589 for (bool explicitlyDisconnected : {false, true}) {
590 auto source = design;
591 if (explicitlyDisconnected)
592 for (auto& cell : source["modules"]["top"]["cells"])
593 for (const auto name : {"unused_bit", "unused_bus"})
594 cell["connections"][name] = Json::array();
595 const auto circuit = SILICON::yosys::deserialize(source.dump(), "top");
596 EXPECT_EQ(componentTypes(circuit).count("Subcircuit"), 2);
597 std::set<const Wire*> outputs;
598 for (const auto& component : componentsIn(circuit)) {
599 const auto child = std::dynamic_pointer_cast<SubcircuitComponent>(component);
600 ASSERT_TRUE(child);
601 EXPECT_EQ(child->importedOutputNames(),
602 (std::vector<std::string>{"unused_bit", "unused_bus", "y"}));
603 ASSERT_EQ(child->outputBuses().size(), 3);
604 EXPECT_EQ(child->outputBuses()[0].size(), 1);
605 EXPECT_EQ(child->outputBuses()[1].size(), 4);
606 EXPECT_EQ(child->outputBuses()[2].size(), 1);
607 for (const auto& bus : child->outputBuses())
608 for (const auto& wire : bus) {
609 ASSERT_TRUE(wire);
610 EXPECT_TRUE(outputs.insert(wire.get()).second);
611 EXPECT_NE(wire, child->inputBuses()[0][0]);
612 }
613 }
614 EXPECT_EQ(outputs.size(), 12);
615
616 auto malformed = source;
617 malformed["modules"]["top"]["cells"]["first"]["connections"].erase("a");
618 EXPECT_THROW((void)SILICON::yosys::deserialize(malformed.dump(), "top"),
619 std::runtime_error);
620 for (const auto& [name, bits] : std::vector<std::pair<std::string, Json>>{
621 {"a", Json::array()},
622 {"typo", Json::array({23})},
623 {"y", Json::array({21, 23})},
624 {"unused_bit", nullptr},
625 {"unused_bus", Json::array({"0", "0", "0", "0"})}}) {
626 malformed = source;
627 malformed["modules"]["top"]["cells"]["first"]["connections"][name] = bits;
628 EXPECT_THROW((void)SILICON::yosys::deserialize(malformed.dump(), "top"),
629 std::runtime_error);
630 }
631 }
632}
633
634TEST(YosysTest, RejectsMalformedModuleDependencyGraphInput)
635{
637
638 EXPECT_THROW((void)SILICON::yosys::moduleDependencyGraph("not json"),
639 std::runtime_error);
640 EXPECT_THROW((void)SILICON::yosys::moduleDependencyGraph(Json::object().dump()),
641 std::runtime_error);
642
643 const Json malformedCells{{"modules", {{"top", {{"cells", Json::array()}}}}}};
644 EXPECT_THROW((void)SILICON::yosys::moduleDependencyGraph(malformedCells.dump()),
645 std::runtime_error);
646
647 const Json missingType{
648 {"modules", {{"top", {{"cells", {{"instance", Json::object()}}}}}}}};
649 EXPECT_THROW((void)SILICON::yosys::moduleDependencyGraph(missingType.dump()),
650 std::runtime_error);
651}
652
653TEST(YosysTest, RejectsUnsupportedOrLossyYosysConstructs)
654{
657
658 const Json notParameters{{"A_SIGNED", SerializationContext::parameter(0, 1)},
659 {"A_WIDTH", SerializationContext::parameter(1)},
660 {"Y_WIDTH", SerializationContext::parameter(1)}};
661 const auto designWithCell = [](Json cell) {
662 return Json{{"modules",
663 {{"top",
664 {{"attributes", Json::object()},
665 {"ports", Json::object()},
666 {"cells", {{"cell", std::move(cell)}}},
667 {"netnames", Json::object()}}}}}};
668 };
669
670 const Json highImpedance = designWithCell(
671 Json{{"type", "$not"},
672 {"parameters", notParameters},
673 {"connections", {{"A", Json::array({"z"})}, {"Y", Json::array({2})}}}});
674 EXPECT_THROW((void)SILICON::yosys::deserialize(highImpedance.dump()),
675 std::runtime_error);
676
677 const Json hierarchy = designWithCell(Json{{"type", "child"},
678 {"parameters", Json::object()},
679 {"connections", Json::object()}});
680 EXPECT_THROW((void)SILICON::yosys::deserialize(hierarchy.dump()), std::runtime_error);
681
682 Json memoryDesign{{"modules",
683 {{"top",
684 {{"attributes", Json::object()},
685 {"ports", Json::object()},
686 {"cells", Json::object()},
687 {"memories", {{"memory", {{"width", 1}, {"size", 1}}}}}}}}}};
688 EXPECT_THROW((void)SILICON::yosys::deserialize(memoryDesign.dump()),
689 std::runtime_error);
690}
691
692TEST(YosysTest, RejectsUnsupportedThirdPartyComponent)
693{
694 class Unsupported final : public Component {
695 public:
696 std::string_view typeName() const override { return "Unsupported"; }
697 void simulate(Simulator&) override {}
698 };
699
700 Circuit circuit(std::make_shared<Unsupported>(), false);
701 EXPECT_THROW((void)SILICON::yosys::serialize(circuit, "top"), std::runtime_error);
702}
std::multiset< std::string > componentTypes(const Circuit &circuit)
std::vector< Component_ptr > componentsIn(const Circuit &circuit)
Represents a digital circuit as a directed graph of components.
Definition circuit.hpp:125
std::string serialize() const
Serializes the core circuit model to a JSON string.
Definition circuit.cpp:694
Base class for all digital circuit components.
virtual std::string_view typeName() const =0
Gets the component type name.
virtual void simulate(SILICON::simulation::Simulator &sim)
Executes the component's logic.
static constexpr std::string_view UNSIGNED_MODE
static constexpr std::string_view SIGNED_MODE
Executes event-driven simulation of a Circuit.
Definition simulator.hpp:74
Module-instantiation dependency graph for a Yosys JSON design.
Definition netlist.hpp:58
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.
void addModule(std::string_view moduleName)
Ensures a module vertex exists, creating it if necessary.
Mutable module-building interface passed to component serializers.
Definition netlist.hpp:174
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
BusValue busValueFromBits(const std::string_view bits)
Strictly decodes an MSB-first raw string containing 0, 1, X, or E.
std::vector< State > BusValue
Definition wire.hpp:120
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.
std::string serialize(const Circuit &circuit, const std::string_view moduleName)
Serialize a complete Silicon circuit as Yosys write_json-compatible JSON.
Definition netlist.cpp:443
nlohmann::ordered_json Json
Definition netlist.hpp:44
BusValue valueFor(const Bus &bus, const std::uint64_t value)
Definition tests.hpp:11
TEST(YosysTest, PreservesLiteralBmuxLanesAsSizedConstants)