SILICON
Loading...
Searching...
No Matches
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
18#include "netlist.hpp"
19
20#include <algorithm>
21#include <cctype>
22#include <format>
23#include <map>
24#include <ranges>
25#include <set>
26#include <stdexcept>
27#include <string>
28#include <unordered_map>
29#include <utility>
30
31#include <boost/graph/adjacency_list.hpp>
32
33#include <core/circuit.hpp>
35#include <core/component.hpp>
37#include <core/subcircuit.hpp>
39
40namespace SILICON::yosys {
41
42using namespace SILICON::core;
43
44namespace {
45
46 struct ModuleInterface {
47 std::string moduleName;
48 std::vector<CircuitPort> inputs;
49 std::vector<CircuitPort> outputs;
50 };
51
52 struct ForcedPort {
53 std::string name;
54 std::string direction;
55 Bus bus;
56 };
57
58 class DesignBuilder;
59
60 [[nodiscard]] std::string fallbackPortName(const bool input, const std::size_t index)
61 {
62 return std::format("{}_{}", input ? "input" : "output", index);
63 }
64
65 [[nodiscard]] std::string identifierPart(const std::string_view value)
66 {
67 std::string result;
68 result.reserve(value.size());
69 for (const char character : value) {
70 const bool valid = (character >= 'a' && character <= 'z')
71 || (character >= 'A' && character <= 'Z')
72 || (character >= '0' && character <= '9') || character == '_';
73 if (valid)
74 result += character;
75 else if (result.empty() || result.back() != '_')
76 result += '_';
77 }
78 if (result.empty())
79 return "component";
80 if (result.front() >= '0' && result.front() <= '9')
81 result.insert(0, "component_");
82 return result;
83 }
84
85 [[nodiscard]] std::string readableCellType(std::string type)
86 {
87 if (type.starts_with("SILICON_"))
88 type.erase(0, std::string_view("SILICON_").size());
89 while (!type.empty() && type.front() == '$')
90 type.erase(type.begin());
91 std::ranges::transform(type, type.begin(), [](const unsigned char character) {
92 return static_cast<char>(std::tolower(character));
93 });
94 return identifierPart(type);
95 }
96
97} // namespace
98
100 DesignBuilder* design = nullptr;
101 Json* module = nullptr;
102 std::map<std::uint64_t, int> wireSignals;
103 std::set<std::string> portNames;
104 std::set<std::string> cellNames;
105 std::set<std::string> netNames;
106 int nextSignal = 2;
108 std::string componentType;
109
110 [[nodiscard]] int signalFor(const Wire_ptr& wire)
111 {
112 if (!wire)
113 throw std::logic_error("Cannot allocate a numeric Yosys signal for a null wire");
114 const auto id = wire->getId();
115 if (const auto it = wireSignals.find(id); it != wireSignals.end())
116 return it->second;
117 const int signal = nextSignal++;
118 wireSignals.emplace(id, signal);
119 return signal;
120 }
121
122 [[nodiscard]] std::string uniquePortName(std::string requested,
123 const std::string_view direction)
124 {
125 if (requested.empty())
126 requested = direction == "input" ? "input" : "output";
127 if (portNames.insert(requested).second)
128 return requested;
129
130 for (std::size_t suffix = 2;; ++suffix) {
131 auto candidate = std::format("{}_{}", requested, suffix);
132 if (portNames.insert(candidate).second)
133 return candidate;
134 }
135 }
136};
137
138namespace {
139
140 class DesignBuilder {
141 public:
142 Json modules = Json::object();
143 std::map<std::string, ModuleInterface> subcircuitInterfaces;
144 std::set<std::string> moduleNames;
145
146 void serializeModule(const Circuit& circuit, const std::string& moduleName,
147 const std::vector<ForcedPort>& forcedPorts = {})
148 {
149 // Reserve names before recursion. Otherwise a child whose slug equals an active
150 // parent could be emitted and silently overwritten when the parent finishes.
151 if (!moduleNames.insert(moduleName).second)
152 throw std::runtime_error(
153 std::format("Duplicate Yosys module name '{}'", moduleName));
154
155 Json module = Json{{"attributes", Json::object()},
156 {"ports", Json::object()},
157 {"cells", Json::object()},
158 {"netnames", Json::object()}};
159 SerializationContext::Impl impl;
160 impl.design = this;
161 impl.module = &module;
162 SerializationContext context(impl);
163
164 for (const auto& port : forcedPorts)
165 context.addPort(port.name, port.direction, port.bus);
166
167 const auto& graph = circuit.getGraph();
168 for (const auto vertex : boost::make_iterator_range(boost::vertices(graph))) {
169 const auto& component = graph[vertex].component;
170 if (!component)
171 continue;
172 impl.vertex = vertex;
173 impl.componentType = component->typeName();
174 component->serializeYosys(context);
175 }
176
177 // When a cell directly drives a module output, name the instance after that
178 // public signal. This is more useful in generated HDL than a graph vertex.
179 Json renamedCells = Json::object();
180 std::set<std::string> renamedCellNames;
181 for (const auto& [cellName, cell] : module["cells"].items()) {
182 std::string readableName = cellName;
183 for (const auto& [portName, port] : module["ports"].items()) {
184 for (const auto& [cellPort, direction] : cell.at("port_directions").items()) {
185 if (direction == "output"
186 && cell.at("connections").at(cellPort) == port.at("bits")) {
187 readableName =
188 std::format("{}_{}", identifierPart(portName),
189 readableCellType(cell.at("type").get<std::string>()));
190 break;
191 }
192 }
193 if (readableName != cellName)
194 break;
195 }
196 const auto baseName = readableName;
197 for (std::size_t index = 2; !renamedCellNames.insert(readableName).second;
198 ++index)
199 readableName = std::format("{}_{}", baseName, index);
200 renamedCells[readableName] = cell;
201 }
202 module["cells"] = std::move(renamedCells);
203
204 // A component output that is also a module port should use the shorter port
205 // name. Keeping both public aliases makes write_verilog emit a redundant wire
206 // and assignment.
207 for (const auto& [portName, port] : module["ports"].items()) {
208 for (auto net = module["netnames"].begin(); net != module["netnames"].end();) {
209 if (net.key() != portName && net.value().at("bits") == port.at("bits"))
210 net = module["netnames"].erase(net);
211 else
212 ++net;
213 }
214 }
215
216 modules[moduleName] = std::move(module);
217 }
218
219 [[nodiscard]] ModuleInterface
220 ensureSubcircuit(const std::string_view slug,
221 const SILICON::core::CircuitResolver* resolver)
222 {
223 const std::string slugString(slug);
224 if (slugString.empty())
225 throw std::runtime_error("Cannot export a subcircuit with an empty slug");
226 if (const auto it = subcircuitInterfaces.find(slugString);
227 it != subcircuitInterfaces.end()) {
228 return it->second;
229 }
230
231 if (!resolver)
232 throw std::runtime_error("Subcircuit serialization requires a circuit resolver");
233 auto definition = resolver->resolve(slugString);
234
235 ModuleInterface interface;
236 interface.moduleName = slugString;
237 interface.inputs = definition.inputs;
238 interface.outputs = definition.outputs;
239
240 std::set<std::string> names;
241 auto makeUnique = [&names](std::string name, const std::string_view fallback) {
242 if (name.empty())
243 name = fallback;
244 if (names.insert(name).second)
245 return name;
246 for (std::size_t index = 2;; ++index) {
247 auto candidate = std::format("{}_{}", name, index);
248 if (names.insert(candidate).second)
249 return candidate;
250 }
251 };
252 for (std::size_t index = 0; index < interface.inputs.size(); ++index)
253 interface.inputs[index].name =
254 makeUnique(interface.inputs[index].name, fallbackPortName(true, index));
255 for (std::size_t index = 0; index < interface.outputs.size(); ++index)
256 interface.outputs[index].name =
257 makeUnique(interface.outputs[index].name, fallbackPortName(false, index));
258
259 // Publish the interface before walking the definition so repeated, non-recursive
260 // instances reuse exactly the same module and connection names.
261 subcircuitInterfaces.emplace(slugString, interface);
262
263 std::vector<ForcedPort> ports;
264 for (const auto& port : interface.inputs)
265 ports.push_back({port.name, "input", port.bus});
266 for (const auto& port : interface.outputs)
267 ports.push_back({port.name, "output", port.bus});
268
269 serializeModule(definition.circuit, interface.moduleName, ports);
270 return interface;
271 }
272 };
273
274} // namespace
275
276Json SerializationContext::bits(const Bus& bus, const std::string_view nullValue) const
277{
278 // Both Silicon and Yosys enumerate vector connections least-significant bit first,
279 // so no reversal is needed here. Yosys represents constants as JSON strings.
280 Json result = Json::array();
281 for (const auto& wire : bus) {
282 if (wire)
283 result.push_back(impl.signalFor(wire));
284 else
285 result.push_back(std::string(nullValue));
286 }
287 return result;
288}
289
290Json SerializationContext::inputBits(const Component& component, const std::size_t index,
291 const std::size_t expectedWidth) const
292{
293 const auto& buses = component.inputBuses();
294 if (index >= buses.size() || buses[index].size() != expectedWidth) {
295 throw std::runtime_error(
296 std::format("Cannot export '{}': input bus {} must be a {}-bit bus",
297 component.typeName(), index, expectedWidth));
298 }
299
300 const auto defaultState = component.unconnectedInputDefault(index);
301 if (!defaultState && std::ranges::contains(buses[index], nullptr)) {
302 throw std::runtime_error(
303 std::format("Cannot export '{}': input bus {} must be connected",
304 component.typeName(), index));
305 }
306
307 const bool binaryDefault =
308 defaultState && (*defaultState == State::LOW || *defaultState == State::HIGH);
309 const std::string defaultBit =
310 binaryDefault ? formatValue(BusValue{*defaultState}, BusValueFormat::Raw) : "x";
311 return bits(buses[index], defaultBit);
312}
313
315{
316 Json result = Json::array();
317 for (std::size_t bit = 0; bit < width; ++bit)
318 result.push_back(impl.nextSignal++);
319 return result;
320}
321
322Json SerializationContext::concatenate(const std::vector<Json>& vectors)
323{
324 Json result = Json::array();
325 for (const auto& vector : vectors)
326 for (const auto& bit : vector)
327 result.push_back(bit);
328 return result;
329}
330
331std::string SerializationContext::parameter(const std::uint64_t value,
332 const std::size_t width)
333{
334 if (width == 0)
335 throw std::invalid_argument("Yosys parameter width must be positive");
336 // write_json serializes RTLIL constants MSB-first even though connection arrays are
337 // LSB-first. Keeping this distinction here avoids duplicating bit-order logic.
339}
340
342{
343 return std::format("{}_{}", identifierPart(impl.componentType), impl.vertex);
344}
345
346void SerializationContext::addCell(const std::string_view suffix,
347 const std::string_view type, Json parameters,
348 Json portDirections, Json connections, Json attributes)
349{
350 const bool isConstant =
351 type == "$pos" && connections.contains("A")
352 && std::ranges::all_of(connections.at("A"),
353 [](const Json& bit) { return bit.is_string(); });
354 const auto baseName =
355 std::format("{}_{}", identifierPart(impl.componentType), impl.vertex);
356 std::string name =
357 suffix.empty() ? baseName : std::format("{}_{}", baseName, identifierPart(suffix));
358 if (isConstant)
359 name = "$" + name;
360 if (!impl.cellNames.insert(name).second) {
361 for (std::size_t index = 2;; ++index) {
362 auto candidate = std::format("{}_{}", name, index);
363 if (impl.cellNames.insert(candidate).second) {
364 name = std::move(candidate);
365 break;
366 }
367 }
368 }
369
370 // Yosys input connections may contain constants such as "x", but output
371 // connections must be signals. Silicon represents an unused pin with a null wire,
372 // which bits() encodes as "x" without knowing the port direction. Give every such
373 // output bit an anonymous module-local signal so disconnected outputs remain valid
374 // without becoming visible circuit ports.
375 for (const auto& [port, direction] : portDirections.items()) {
376 if (direction != "output" || !connections.contains(port))
377 continue;
378 for (auto& bit : connections.at(port)) {
379 if (bit.is_string())
380 bit = impl.nextSignal++;
381 }
382 }
383
384 for (const auto& [port, direction] : portDirections.items()) {
385 if (isConstant || direction != "output" || !connections.contains(port))
386 continue;
387 std::string netName = std::format("{}_{}", baseName, identifierPart(port));
388 for (std::size_t index = 2; !impl.netNames.insert(netName).second; ++index)
389 netName = std::format("{}_{}_{}", baseName, identifierPart(port), index);
390 (*impl.module)["netnames"][netName] = Json{
391 {"hide_name", 0}, {"bits", connections.at(port)}, {"attributes", Json::object()}};
392 }
393
394 (*impl.module)["cells"][name] = Json{{"hide_name", isConstant ? 1 : 0},
395 {"type", type},
396 {"parameters", std::move(parameters)},
397 {"attributes", std::move(attributes)},
398 {"port_directions", std::move(portDirections)},
399 {"connections", std::move(connections)}};
400}
401
402void SerializationContext::addPort(std::string name, const std::string_view direction,
403 const Bus& bus)
404{
405 if (direction != "input" && direction != "output" && direction != "inout")
406 throw std::invalid_argument("Invalid Yosys port direction");
407 name = impl.uniquePortName(std::move(name), direction);
408 impl.netNames.insert(name);
409 const Json portBits = bits(bus);
410 (*impl.module)["ports"][name] = Json{{"direction", direction}, {"bits", portBits}};
411 (*impl.module)["netnames"][name] =
412 Json{{"hide_name", 0}, {"bits", portBits}, {"attributes", Json::object()}};
413}
414
416 const std::string_view slug, const std::vector<Bus>& inputs,
417 const std::vector<Bus>& outputs, const SILICON::core::CircuitResolver* resolver)
418{
419 const auto interface = impl.design->ensureSubcircuit(slug, resolver);
420 if (inputs.size() != interface.inputs.size()
421 || outputs.size() != interface.outputs.size()) {
422 throw std::runtime_error(std::format("Subcircuit '{}' interface mismatch: expected "
423 "{} inputs and {} outputs, got {} and {}",
424 slug, interface.inputs.size(),
425 interface.outputs.size(), inputs.size(),
426 outputs.size()));
427 }
428
429 Json portDirections = Json::object();
430 Json connections = Json::object();
431 for (std::size_t index = 0; index < inputs.size(); ++index) {
432 portDirections[interface.inputs[index].name] = "input";
433 connections[interface.inputs[index].name] = bits(inputs[index]);
434 }
435 for (std::size_t index = 0; index < outputs.size(); ++index) {
436 portDirections[interface.outputs[index].name] = "output";
437 connections[interface.outputs[index].name] = bits(outputs[index]);
438 }
439 addCell("instance", interface.moduleName, Json::object(), std::move(portDirections),
440 std::move(connections));
441}
442
443std::string serialize(const Circuit& circuit, const std::string_view moduleName)
444{
445 DesignBuilder builder;
446 builder.serializeModule(circuit, std::string(moduleName));
447 Json design = Json{{"creator", std::format("Silicon {}", SILICON_VERSION)},
448 {"modules", std::move(builder.modules)}};
449 return design.dump(2);
450}
451
452} // namespace SILICON::yosys
virtual SubcircuitDefinition resolve(std::string_view slug) const =0
Represents a digital circuit as a directed graph of components.
Definition circuit.hpp:125
const CircuitGraph & getGraph() const
Gets the underlying circuit graph.
Definition circuit.hpp:349
Base class for all digital circuit components.
const std::vector< Bus > & inputBuses() const
Gets all input buses without copying.
virtual std::string_view typeName() const =0
Gets the component type name.
std::optional< State > unconnectedInputDefault(unsigned int input) const
Gets the state used when an input has no connected wire.
void addPort(std::string name, std::string_view direction, const core::Bus &bus)
Register a named top-level input or output port.
Definition netlist.cpp:402
void addSubcircuitInstance(std::string_view slug, const std::vector< core::Bus > &inputs, const std::vector< core::Bus > &outputs, const core::CircuitResolver *resolver)
Emit a hierarchical instance and recursively serialize its definition.
Definition netlist.cpp:415
Json bits(const core::Bus &bus, std::string_view nullValue="x") const
Convert a Silicon bus to a Yosys least-significant-bit-first vector.
Definition netlist.cpp:276
Json allocateBits(std::size_t width)
Allocate module-local temporary signal bits.
Definition netlist.cpp:314
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
std::string componentIdentifier() const
Stable name of the component being serialized within its module.
Definition netlist.cpp:341
Json inputBits(const core::Component &component, std::size_t index, std::size_t expectedWidth) const
Encode a component input, applying its declared unconnected-input default.
Definition netlist.cpp:290
void addCell(std::string_view suffix, std::string_view type, Json parameters, Json portDirections, Json connections, Json attributes=Json::object())
Emit one native Yosys cell for the current Silicon component.
Definition netlist.cpp:346
static Json concatenate(const std::vector< Json > &vectors)
Concatenate bit vectors in their existing LSB-first order.
Definition netlist.cpp:322
RTLIL::SigSpec port(RTLIL::Module *module, RTLIL::Cell *cell, RTLIL::IdString key, int expected)
std::shared_ptr< Wire > Wire_ptr
Definition wire.hpp:116
boost::graph_traits< CircuitGraph >::vertex_descriptor VertexDescriptor
Descriptor type for vertices in the circuit graph.
Definition circuit.hpp:94
BusValue busValueFromInteger(const BigInt &value, const std::size_t width)
Builds an LSB-first BusValue from the low width bits of an integer. Negative values use two's complem...
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
Definition wire.hpp:120
QVariant value(const QSettings &settings, const Definition &setting)
Reads a setting value, falling back to its declared default when unset.
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
int signalFor(const Wire_ptr &wire)
Definition netlist.cpp:110
std::map< std::uint64_t, int > wireSignals
Definition netlist.cpp:102
std::string uniquePortName(std::string requested, const std::string_view direction)
Definition netlist.cpp:122