SILICON
Loading...
Searching...
No Matches
silicon_import.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 "kernel/ffinit.h"
19#include "kernel/register.h"
20#include "kernel/rtlil.h"
21#include "kernel/sigtools.h"
22#include "kernel/yosys.h"
23
24#include <algorithm>
25#include <bit>
26#include <limits>
27#include <optional>
28#include <vector>
29
30USING_YOSYS_NAMESPACE
32
33constexpr int MAX_DECODED_SELECTOR_WIDTH = 10;
34constexpr int DECODER_DENSITY_FACTOR = 4;
35
36// Init attributes may be attached to an alias of the register output.
37bool hasDefinedInit(const RTLIL::SigSpec& signal, RTLIL::Module* module,
38 const SigMap& sigmap)
39{
40 return !FfInitVals(&sigmap, module)(signal).is_fully_undef_x_only();
41}
42
43#include "silicon_import_pm.h"
44
45namespace {
46
47using EqMember = std::pair<RTLIL::Cell*, int>;
48
49// One equality comparison that may become an output of a shared decoder. value
50// is the compared constant and therefore the output index; selector identifies
51// the non-constant side of the equality.
52struct EqCandidate {
53 RTLIL::Cell* cell;
54 RTLIL::SigSpec selector;
55 int value;
56};
57
58struct EqDecoderGroup {
59 RTLIL::SigSpec selector;
60 std::vector<EqMember> members;
61};
62
63std::vector<RTLIL::Cell*> allCells(RTLIL::Module* module)
64{
65 std::vector<RTLIL::Cell*> cells;
66 cells.reserve(module->cells().size());
67 for (auto* cell : module->cells())
68 cells.push_back(cell);
69 return cells;
70}
71
72void collectSelectedCells(pool<RTLIL::Cell*>& selectedCells, RTLIL::Module* module)
73{
74 for (auto* cell : module->selected_cells())
75 selectedCells.insert(cell);
76}
77
78class SignalUsers {
79public:
80 SignalUsers(RTLIL::Module* module, SigMap& sigmap) : sigmap(sigmap)
81 {
82 for (auto port : module->ports)
83 add(module->wire(port), nullptr);
84
85 for (auto* cell : module->cells())
86 for (const auto& connection : cell->connections())
87 add(connection.second, cell);
88 }
89
90 int count(const RTLIL::SigSpec& signal)
91 {
92 pool<RTLIL::Cell*> users;
93 for (const auto bit : sigmap(signal)) {
94 const auto it = this->users.find(bit);
95 if (it == this->users.end())
96 continue;
97 for (auto* user : it->second)
98 users.insert(user);
99 }
100 return GetSize(users);
101 }
102
103private:
104 void add(const RTLIL::SigSpec& signal, RTLIL::Cell* cell)
105 {
106 for (const auto bit : sigmap(signal)) {
107 if (bit.wire == nullptr)
108 continue;
109 this->users[bit].insert(cell);
110 }
111 }
112
113 SigMap& sigmap;
114 dict<RTLIL::SigBit, pool<RTLIL::Cell*>> users;
115};
116
117std::optional<EqCandidate> decodeEquality(RTLIL::Cell* cell, SigMap& sigmap,
118 SignalUsers& users)
119{
120 if (cell->type != ID($eq))
121 return std::nullopt;
122
123 const int aWidth = cell->getParam(ID::A_WIDTH).as_int();
124 const int bWidth = cell->getParam(ID::B_WIDTH).as_int();
125 const int yWidth = cell->getParam(ID::Y_WIDTH).as_int();
126
127 if (aWidth != bWidth || aWidth <= 0 || aWidth > MAX_DECODED_SELECTOR_WIDTH || yWidth != 1)
128 return std::nullopt;
129
130 const auto output = sigmap(cell->getPort(ID::Y));
131 if (GetSize(output) != 1 || users.count(output) <= 1)
132 return std::nullopt;
133
134 const auto a = sigmap(cell->getPort(ID::A));
135 const auto b = sigmap(cell->getPort(ID::B));
136 if (GetSize(a) != aWidth || GetSize(b) != bWidth)
137 return std::nullopt;
138
139 const bool aConstant = a.is_fully_const();
140 const bool bConstant = b.is_fully_const();
141 if (aConstant == bConstant)
142 return std::nullopt;
143
144 // Comparisons without exactly one constant operand, or whose constant contains
145 // an x/z literal, are unsuitable for decoder recovery. SigMap gives structurally
146 // identical selectors the same canonical identity when candidates are grouped.
147 const auto& signal = aConstant ? b : a;
148 const auto& constant = aConstant ? a : b;
149 const auto value = constant.as_const();
150 if (!value.is_fully_def())
151 return std::nullopt;
152
153 return EqCandidate{cell, signal, value.as_int()};
154}
155
156std::vector<EqDecoderGroup> collectEqDecoderGroups(RTLIL::Module* module)
157{
158 /*
159 * Yosys commonly represents a case statement as a bank of $eq cells that
160 * compare one selector against constants:
161 *
162 * $eq(selector, K) -> $demux.outputs[K]
163 *
164 * Recover a sufficiently dense bank with distinct constants as one word-level
165 * decoder. A bank needs at least two members, and comparisons whose results
166 * have only one consumer remain standalone instead of being disguised as an
167 * unnecessarily large decoder.
168 */
169 SigMap sigmap(module);
170 SignalUsers users(module, sigmap);
171
172 dict<RTLIL::SigSpec, std::vector<EqMember>> buckets;
173 for (auto* cell : module->selected_cells()) {
174 const auto candidate = decodeEquality(cell, sigmap, users);
175 if (candidate)
176 buckets[candidate->selector].emplace_back(candidate->cell, candidate->value);
177 }
178
179 std::vector<EqDecoderGroup> groups;
180 for (auto& [selector, bucket] : buckets) {
181 if (GetSize(bucket) < 2)
182 continue;
183
184 pool<int> values;
185 bool unique = true;
186 for (const auto& [cell, value] : bucket) {
187 (void)cell;
188 if (!values.insert(value).second) {
189 unique = false;
190 break;
191 }
192 }
193 if (!unique)
194 continue;
195
196 const int laneCount = 1 << GetSize(selector);
197 if (GetSize(bucket) * DECODER_DENSITY_FACTOR < laneCount)
198 continue;
199
200 std::sort(bucket.begin(), bucket.end(), [](const EqMember& lhs, const EqMember& rhs) {
201 return lhs.first->name.str() < rhs.first->name.str();
202 });
203
204 groups.push_back({selector, std::move(bucket)});
205 }
206
207 std::sort(groups.begin(), groups.end(),
208 [](const EqDecoderGroup& lhs, const EqDecoderGroup& rhs) {
209 return lhs.members.front().first->name.str()
210 < rhs.members.front().first->name.str();
211 });
212
213 return groups;
214}
215
216void raiseDecodedPmux(silicon_import_pm& matcher)
217{
218 auto& state = matcher.st_decoded_pmux;
219
220 // The PMG matcher has proved that every select predicate decodes the same
221 // selector and has materialized a complete, ordered lane table. Reusing the
222 // existing cell preserves its output wiring while changing only its inputs.
223 RTLIL::SigSpec packedData;
224 for (const auto& lane : state.lanes)
225 packedData.append(lane);
226
227 matcher.blacklist(state.pmux);
228 state.pmux->type = ID($bmux);
229 state.pmux->setParam(ID::S_WIDTH, state.selector.size());
230 state.pmux->setPort(ID::A, packedData);
231 state.pmux->setPort(ID::S, state.selector);
232 state.pmux->unsetPort(ID::B);
233
234 log("Raised decoded $pmux cell %s.%s to $bmux.\n", log_id(matcher.module),
235 log_id(state.pmux));
236}
237
238void foldMemrdAddress(silicon_import_pm& matcher)
239{
240 auto& state = matcher.st_memrd_address;
241 matcher.blacklist(state.mem);
242 state.mem->setPort(ID::RD_ADDR, state.reg->getPort(ID::D));
243 state.mem->setPort(ID::RD_EN, state.reg->getPort(ID::EN));
244 log("Folded ROM address register %s and mux %s into %s.\n",
245 log_id(state.reg), log_id(state.mux), log_id(state.mem));
246 matcher.autoremove(state.mux);
247 matcher.autoremove(state.reg);
248}
249
250void raiseEqDecoder(RTLIL::Module* module, const EqDecoderGroup& group)
251{
252 const int laneCount = 1 << GetSize(group.selector);
253
254 // The fresh wire supplies private bits for sparse/unmatched decoder outputs.
255 // Replacing only matched indices preserves the exact Y bits consumed elsewhere.
256 RTLIL::SigSpec outputs(module->addWire(NEW_ID, laneCount));
257 for (const auto& [cell, value] : group.members)
258 outputs[value] = cell->getPort(ID::Y)[0];
259
260 auto* demux = module->addDemux(NEW_ID, RTLIL::Const(RTLIL::State::S1, 1),
261 group.selector, outputs);
262
263 const int memberCount = GetSize(group.members);
264 for (const auto& [cell, value] : group.members) {
265 (void)value;
266 module->remove(cell);
267 }
268
269 log("Raised %d equality cells in %s to decoder %s.\n", memberCount, log_id(module),
270 log_id(demux));
271}
272
273} // namespace
274
275struct SiliconPmuxBmuxPass : public Pass {
276 SiliconPmuxBmuxPass() : Pass("silicon_pmux_bmux", "raise decoded $pmux cells to $bmux")
277 {
278 }
279
280 void help() override
281 {
282 log("\n");
283 log(" silicon_pmux_bmux [selection]\n");
284 log("\n");
285 log("Replace $pmux cells whose mutually-exclusive select inputs compare one\n");
286 log("binary selector against constant values with an equivalent $bmux. Sparse\n");
287 log("choices are filled from the $pmux default input. Priority muxes are left\n");
288 log("unchanged.\n");
289 log("\n");
290 }
291
292 void execute(std::vector<std::string> args, RTLIL::Design* design) override
293 {
294 log_header(design, "Executing SILICON_PMUX_BMUX pass.\n");
295 extra_args(args, 1, design);
296
297 for (auto* module : design->selected_modules()) {
298 silicon_import_pm matcher(module, allCells(module));
299 collectSelectedCells(matcher.ud_decoded_pmux.selected_cells, module);
300 matcher.run_decoded_pmux(raiseDecodedPmux);
301 }
302 }
304
305struct SiliconEqDecoderPass : public Pass {
307 : Pass("silicon_eq_decoder", "raise shared constant equality cells to $demux")
308 {
309 }
310
311 void help() override
312 {
313 log("\n");
314 log(" silicon_eq_decoder [selection]\n");
315 log("\n");
316 log("Replace groups of selected equal-width $eq cells that compare one selector\n");
317 log("against distinct fully-defined constants with an equivalent $demux decoder.\n");
318 log("Groups with fewer than two comparisons or duplicate values are unchanged.\n");
319 log("\n");
320 }
321
322 void execute(std::vector<std::string> args, RTLIL::Design* design) override
323 {
324 log_header(design, "Executing SILICON_EQ_DECODER pass.\n");
325 extra_args(args, 1, design);
326
327 for (auto* module : design->selected_modules())
328 for (const auto& group : collectEqDecoderGroups(module))
329 raiseEqDecoder(module, group);
330 }
332
333struct SiliconMemrdAddressPass : public Pass {
335 : Pass("silicon_memrd_address", "remove redundant ROM address feedback after memory_dff")
336 {
337 }
338
339 void help() override
340 {
341 log("\n silicon_memrd_address [selection]\n\n");
342 log("Fold an enabled address register and its feedback mux into the read\n");
343 log("enable of a synchronous, read-only memory port. Run after memory_dff.\n\n");
344 }
345
346 void execute(std::vector<std::string> args, RTLIL::Design* design) override
347 {
348 log_header(design, "Executing SILICON_MEMRD_ADDRESS pass.\n");
349 extra_args(args, 1, design);
350
351 for (auto* module : design->selected_modules()) {
352 silicon_import_pm matcher(module, allCells(module));
353 collectSelectedCells(matcher.ud_memrd_address.selected_cells, module);
354 matcher.run_memrd_address(foldMemrdAddress);
355 }
356 }
358
359// JSON contract for SILICON_ROM (one cell per read port): WIDTH, SIZE, ABITS,
360// INIT (LSB-first packed bits), ID (unescaped memory identifier), SYNC and
361// CLK_POLARITY are parameters. ADDR, DATA, SELECT, CLK and EN are ports. ADDR
362// has ABITS bits even for SIZE=1; for that case it must be constant zero.
363// SELECT is an optional output latch enable (otherwise one). CLK/EN are zero
364// and one for asynchronous reads. SYNC means the importer places an enabled
365// address register before the ROM (or a data register for SIZE=1). The
366// silicon_mem_slug attribute, when present, is a document *identifier*; the
367// importer alone chooses the project path and creates the binary document.
368struct SiliconMemoryLowerPass : public Pass {
370 : Pass("silicon_memory_lower", "lower supported Yosys memories to SILICON_ROM") {}
371
372 void help() override
373 {
374 log("\n silicon_memory_lower [selection]\n\n");
375 log("Validate read-only $mem_v2 cells and emit one SILICON_ROM per read port.\n");
376 log("Run after memory_dff and silicon_memrd_address.\n\n");
377 }
378
379 void execute(std::vector<std::string> args, RTLIL::Design* design) override
380 {
381 log_header(design, "Executing SILICON_MEMORY_LOWER pass.\n");
382 extra_args(args, 1, design);
383 for (auto* module : design->selected_modules()) {
384 const auto cells = allCells(module);
385 pool<RTLIL::Cell*> selected, removed;
386 collectSelectedCells(selected, module);
387 for (auto* mem : cells) {
388 if (!selected.count(mem) || mem->type != ID($mem_v2)) continue;
389 const auto reject = [&](const char* reason) {
390 log_error("Unsupported ROM %s.%s: %s.\n", log_id(module), log_id(mem), reason);
391 };
392 const int width = mem->getParam(ID::WIDTH).as_int();
393 const int size = mem->getParam(ID::SIZE).as_int();
394 const int abits = mem->getParam(ID::ABITS).as_int();
395 const int ports = mem->getParam(ID::RD_PORTS).as_int();
396 const auto isZero = [](const RTLIL::Const& value) {
397 for (int bit = 0; bit < GetSize(value); ++bit)
398 if (value[bit] != RTLIL::State::S0) return false;
399 return true;
400 };
401 if (width <= 0 || width > std::numeric_limits<unsigned short>::max()
402 || size <= 0 || size > std::numeric_limits<int>::max() / width
403 || (size & (size - 1)) != 0
404 || abits != std::max(1, static_cast<int>(std::bit_width(static_cast<unsigned>(size - 1))))
405 || ports <= 0 || ports > std::numeric_limits<int>::max() / width
406 || ports > std::numeric_limits<int>::max() / std::max(1, abits)
407 || !isZero(mem->getParam(ID::OFFSET))
408 || !isZero(mem->getParam(ID::WR_PORTS)))
409 reject("unsupported geometry or write ports");
410 for (auto key : {ID::RD_CE_OVER_SRST, ID::RD_TRANSPARENCY_MASK,
411 ID::RD_COLLISION_X_MASK, ID::RD_WIDE_CONTINUATION,
412 ID::WR_CLK_ENABLE, ID::WR_CLK_POLARITY,
413 ID::WR_PRIORITY_MASK, ID::WR_WIDE_CONTINUATION})
414 if (!isZero(mem->getParam(key)))
415 reject("unsupported read controls or write behavior");
416 for (auto key : {ID::WR_ADDR, ID::WR_DATA, ID::WR_EN, ID::WR_CLK})
417 if (GetSize(mem->getPort(key)) != 0)
418 reject("memory write connections are not supported");
419 const auto init = mem->getParam(ID::INIT);
420 if (GetSize(init) != size * width || !init.is_fully_def())
421 reject("initialization must fully define every word");
422 const auto addr = mem->getPort(ID::RD_ADDR);
423 const auto data = mem->getPort(ID::RD_DATA);
424 const auto enable = mem->getPort(ID::RD_EN);
425 const auto clock = mem->getPort(ID::RD_CLK);
426 const auto arst = mem->getPort(ID::RD_ARST);
427 const auto srst = mem->getPort(ID::RD_SRST);
428 const auto clkEnable = mem->getParam(ID::RD_CLK_ENABLE);
429 const auto clkPolarity = mem->getParam(ID::RD_CLK_POLARITY);
430 const auto initial = mem->getParam(ID::RD_INIT_VALUE);
431 if (GetSize(addr) != ports * abits || GetSize(data) != ports * width
432 || GetSize(enable) != ports || GetSize(clock) != ports
433 || GetSize(arst) != ports || GetSize(srst) != ports
434 || GetSize(clkEnable) != ports || GetSize(clkPolarity) != ports
435 || GetSize(initial) != ports * width)
436 reject("invalid read port widths");
437
438 for (int port = 0; port < ports; ++port) {
439 const bool sync = clkEnable[port] == RTLIL::State::S1;
440 const bool positive = clkPolarity[port] == RTLIL::State::S1;
441 if ((clkEnable[port] != RTLIL::State::S0 && !sync)
442 || (clkPolarity[port] != RTLIL::State::S0 && !positive))
443 reject("undefined read clock control");
444 if (sync) {
445 for (int bit = 0; bit < width; ++bit)
446 if (initial[port * width + bit] != RTLIL::State::Sx)
447 reject("initialized synchronous read register is unsupported");
448 if (arst[port] != RTLIL::State::S0 || srst[port] != RTLIL::State::S0)
449 reject("synchronous read reset is unsupported");
450 } else if (enable[port] != RTLIL::State::S1) {
451 reject("asynchronous read enable must be constant one");
452 }
453 const auto readAddr = addr.extract(port * abits, abits);
454 const auto readData = data.extract(port * width, width);
455 if (size == 1 && readAddr != RTLIL::SigSpec(RTLIL::State::S0, abits))
456 reject("one-word memory address must be constant zero");
457
458 RTLIL::SigSpec output = readData;
459 RTLIL::SigSpec select(RTLIL::State::S1);
460 for (auto* latch : cells) {
461 if (removed.count(latch) || !selected.count(latch) || latch->type != ID($dlatch)
462 || latch->getPort(ID::D) != readData) continue;
463 if (latch->getParam(ID::EN_POLARITY).as_int() != 1
464 || GetSize(latch->getPort(ID::Q)) != width
465 || GetSize(latch->getPort(ID::EN)) != 1)
466 reject("unsupported ROM output latch");
467 output = latch->getPort(ID::Q);
468 select = latch->getPort(ID::EN);
469 removed.insert(latch);
470 break;
471 }
472
473 auto* rom = module->addCell(NEW_ID, RTLIL::escape_id("SILICON_ROM"));
474 rom->setParam(ID::WIDTH, width);
475 rom->setParam(ID::SIZE, size);
476 rom->setParam(ID::ABITS, abits);
477 rom->setParam(ID::INIT, init);
478 rom->setParam(RTLIL::escape_id("ID"), mem->getParam(ID::MEMID));
479 rom->setParam(RTLIL::escape_id("SYNC"), sync ? 1 : 0);
480 rom->setParam(ID::CLK_POLARITY, positive ? 1 : 0);
481 rom->setPort(ID::ADDR, readAddr);
482 rom->setPort(ID::DATA, output);
483 rom->setPort(RTLIL::escape_id("SELECT"), select);
484 rom->setPort(ID::CLK, sync ? clock.extract(port, 1) : RTLIL::SigSpec(RTLIL::State::S0));
485 rom->setPort(ID::EN, sync ? enable.extract(port, 1) : RTLIL::SigSpec(RTLIL::State::S1));
486 rom->attributes = mem->attributes;
487 }
488 module->remove(mem);
489 }
490 for (auto* latch : removed)
491 module->remove(latch);
492 }
493 }
495
496PRIVATE_NAMESPACE_END
QVariant value(const QSettings &settings, const Definition &setting)
Reads a setting value, falling back to its declared default when unset.
USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN constexpr int MAX_DECODED_SELECTOR_WIDTH
constexpr int DECODER_DENSITY_FACTOR
bool hasDefinedInit(const RTLIL::SigSpec &signal, RTLIL::Module *module, const SigMap &sigmap)
void execute(std::vector< std::string > args, RTLIL::Design *design) override
void execute(std::vector< std::string > args, RTLIL::Design *design) override
void execute(std::vector< std::string > args, RTLIL::Design *design) override
void execute(std::vector< std::string > args, RTLIL::Design *design) override