SILICON
Loading...
Searching...
No Matches
yosys_tool.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 "yosys_tool.hpp"
19#include "cells.hpp"
20
21#include <algorithm>
22#include <array>
23#include <filesystem>
24#include <format>
25#include <fstream>
26#include <future>
27#include <iterator>
28#include <memory>
29#include <optional>
30#include <ranges>
31#include <stdexcept>
32#include <string>
33#include <system_error>
34#include <unordered_set>
35#include <vector>
36
37#include <logging/logger.hpp>
39
40#ifndef __EMSCRIPTEN__
41 #include <boost/asio/io_context.hpp>
42 #include <boost/process/v1/args.hpp>
43 #include <boost/process/v1/async.hpp>
44 #include <boost/process/v1/child.hpp>
45 #include <boost/process/v1/io.hpp>
46 #include <boost/process/v1/search_path.hpp>
47 #include <boost/uuid/random_generator.hpp>
48 #include <boost/uuid/uuid_io.hpp>
49
50 #if defined(_WIN32)
51 #include <windows.h>
52 #elif defined(__APPLE__)
53 #include <mach-o/dyld.h>
54 #endif
55#endif
56
57namespace SILICON::yosys {
58
59namespace {
60
61 const SILICON::logging::Logger yosysLog("yosys");
62
63} // namespace
64
65#ifdef __EMSCRIPTEN__
66
67ScriptResult runScript(const std::string_view script, const ToolOptions& options)
68{
69 (void)script;
70 (void)options;
71 yosysLog.error("External execution is unavailable in Emscripten builds");
72 throw std::runtime_error(
73 "Yosys platform-availability phase failed: external execution is unavailable "
74 "when compiled for Emscripten. See the 'yosys' logs for details.");
75}
76
77std::string readVerilog(const std::string_view source, const ToolOptions& options)
78{
79 const std::array sources{
80 SILICON::core::SourceFile{.path = "source.v", .contents = source}};
81 return readVerilog(sources, "source.v", options);
82}
83
84std::string readVerilog(const std::span<const SILICON::core::SourceFile> sources,
85 const std::string_view entryPath, const ToolOptions& options)
86{
87 (void)sources;
88 (void)entryPath;
89 (void)runScript({}, options);
90 throw std::logic_error("Unreachable after unavailable Yosys execution");
91}
92
93std::string elaborateHierarchy(const std::string_view json, const ToolOptions& options)
94{
95 (void)json;
96 (void)runScript({}, options);
97 throw std::logic_error("Unreachable after unavailable Yosys execution");
98}
99
100std::string writeVerilog(std::string_view json, const ToolOptions& options)
101{
102 (void)json;
103 (void)runScript({}, options);
104 throw std::logic_error("Unreachable after unavailable Yosys execution");
105}
106
107#else
108
109namespace {
110
111 class TemporaryWorkspace {
112 public:
113 TemporaryWorkspace()
114 {
115 const auto temporaryRoot = std::filesystem::temp_directory_path();
116 auto generateUuid = boost::uuids::random_generator{};
117
118 for (unsigned attempt = 0; attempt < 128; ++attempt) {
119 directory =
120 temporaryRoot
121 / std::format("silicon_yosys_{}", boost::uuids::to_string(generateUuid()));
122 std::error_code error;
123 if (std::filesystem::create_directory(directory, error))
124 return;
125 if (error && error != std::errc::file_exists)
126 throw std::runtime_error(
127 std::format("Yosys temporary-workspace creation failed for '{}': {}",
128 directory.string(), error.message()));
129 }
130 throw std::runtime_error(
131 "Yosys temporary-workspace creation failed: no unique directory was available");
132 }
133
134 TemporaryWorkspace(const TemporaryWorkspace&) = delete;
135 TemporaryWorkspace& operator=(const TemporaryWorkspace&) = delete;
136
137 ~TemporaryWorkspace()
138 {
139 std::error_code error;
140 std::filesystem::remove_all(directory, error);
141 }
142
143 [[nodiscard]] const std::filesystem::path& path() const { return directory; }
144
145 private:
146 std::filesystem::path directory;
147 };
148
149 void writeFile(const std::filesystem::path& path, const std::string_view contents,
150 const std::string_view phase)
151 {
152 std::ofstream output(path, std::ios::binary);
153 if (!output)
154 throw std::runtime_error(
155 std::format("Yosys {} failed: could not open '{}'", phase, path.string()));
156 output.write(contents.data(), static_cast<std::streamsize>(contents.size()));
157 if (!output)
158 throw std::runtime_error(
159 std::format("Yosys {} failed: could not write '{}'", phase, path.string()));
160 }
161
162 [[nodiscard]] bool isSafeRelativeSourcePath(const std::string_view path)
163 {
164 if (path.empty() || path.front() == '/' || path.back() == '/' || path.contains('\\')
165 || path.contains("//"))
166 return false;
167
168 const std::filesystem::path filesystemPath(path);
169 if (filesystemPath.has_root_path())
170 return false;
171 for (const auto& component : filesystemPath)
172 if (component == "." || component == "..")
173 return false;
174
175 return std::ranges::none_of(path, [](const unsigned char character) {
176 return character < 0x20 || character == 0x7f;
177 });
178 }
179
180 [[nodiscard]] std::string readFile(const std::filesystem::path& path,
181 const std::string_view phase)
182 {
183 std::ifstream input(path, std::ios::binary);
184 if (!input)
185 throw std::runtime_error(std::format(
186 "Yosys {} failed: could not open generated file '{}'", phase, path.string()));
187 std::string contents{std::istreambuf_iterator<char>(input),
188 std::istreambuf_iterator<char>()};
189 if (input.bad())
190 throw std::runtime_error(std::format(
191 "Yosys {} failed: could not read generated file '{}'", phase, path.string()));
192 return contents;
193 }
194
195 [[nodiscard]] std::string quotePath(const std::filesystem::path& path)
196 {
197 std::string result("\"");
198 for (const char character : path.string()) {
199 if (character == '\\' || character == '"')
200 result += '\\';
201 result += character;
202 }
203 return result + '"';
204 }
205
206 struct TechnologyLibrary {
207 std::filesystem::path cells;
208 std::filesystem::path technologyMap;
209 };
210
211 [[nodiscard]] std::optional<TechnologyLibrary>
212 libraryAt(const std::filesystem::path& directory)
213 {
214 TechnologyLibrary result{directory / "silicon_cells.v",
215 directory / "silicon_techmap.v"};
216 std::error_code error;
217 for (const auto* path : {&result.cells, &result.technologyMap}) {
218 if (!std::filesystem::is_regular_file(*path, error) || error)
219 return std::nullopt;
220 }
221 return result;
222 }
223
224 [[nodiscard]] std::optional<std::filesystem::path> runningExecutable()
225 {
226 #if defined(_WIN32)
227 std::wstring path(32768, L'\0');
228 const DWORD size =
229 GetModuleFileNameW(nullptr, path.data(), static_cast<DWORD>(path.size()));
230 if (size == 0 || size >= path.size())
231 return std::nullopt;
232 path.resize(size);
233 return std::filesystem::path(std::move(path));
234 #elif defined(__APPLE__)
235 std::uint32_t size = 0;
236 (void)_NSGetExecutablePath(nullptr, &size);
237 std::vector<char> path(size);
238 if (_NSGetExecutablePath(path.data(), &size) != 0)
239 return std::nullopt;
240 std::error_code error;
241 auto canonical =
242 std::filesystem::weakly_canonical(std::filesystem::path(path.data()), error);
243 return error ? std::optional(std::filesystem::path(path.data()))
244 : std::optional(std::move(canonical));
245 #else
246 std::error_code error;
247 auto path = std::filesystem::read_symlink("/proc/self/exe", error);
248 return error ? std::nullopt : std::optional(std::move(path));
249 #endif
250 }
251
252 [[nodiscard]] TechnologyLibrary technologyLibrary(const ToolOptions& options)
253 {
254 if (options.technologyLibraryDirectory) {
255 if (const auto result = libraryAt(*options.technologyLibraryDirectory))
256 return *result;
257 throw std::runtime_error(std::format(
258 "Yosys resource-discovery phase failed: configured technology-library "
259 "directory '{}' does not contain silicon_cells.v and silicon_techmap.v",
260 options.technologyLibraryDirectory->string()));
261 }
262
263 std::vector<std::filesystem::path> candidates{
264 std::filesystem::path(SILICON_YOSYS_BUILD_RESOURCE_DIR),
265 std::filesystem::path(SILICON_YOSYS_INSTALL_RESOURCE_DIR),
266 };
267 if (const auto executable = runningExecutable()) {
268 const auto directory = executable->parent_path();
269 candidates.push_back(
270 (directory / ".." / SILICON_YOSYS_INSTALL_RELATIVE_RESOURCE_DIR)
271 .lexically_normal());
272 #if defined(__APPLE__)
273 candidates.push_back((directory / ".." / "Resources" / "yosys").lexically_normal());
274 #endif
275 }
276 for (const auto& candidate : candidates)
277 if (const auto result = libraryAt(candidate))
278 return *result;
279
280 throw std::runtime_error(std::format(
281 "Yosys resource-discovery phase failed: the packaged SILICON technology "
282 "library was not found at '{}' or '{}'",
283 candidates[0].string(), candidates[1].string()));
284 }
285
286 [[nodiscard]] std::optional<std::filesystem::path> verilogPlugin()
287 {
288 std::vector<std::filesystem::path> candidates;
289 #if defined(SILICON_YOSYS_BUILD_PLUGIN) && defined(SILICON_YOSYS_INSTALL_PLUGIN) \
290 && defined(SILICON_YOSYS_INSTALL_RELATIVE_PLUGIN)
291 candidates = {std::filesystem::path(SILICON_YOSYS_BUILD_PLUGIN),
292 std::filesystem::path(SILICON_YOSYS_INSTALL_PLUGIN)};
293 if (const auto executable = runningExecutable()) {
294 candidates.push_back(
295 (executable->parent_path() / ".." / SILICON_YOSYS_INSTALL_RELATIVE_PLUGIN)
296 .lexically_normal());
297 }
298 #endif
299 for (const auto& candidate : candidates) {
300 std::error_code error;
301 if (std::filesystem::is_regular_file(candidate, error) && !error)
302 return candidate;
303 }
304 return std::nullopt;
305 }
306
307 void logCapturedOutput(const ScriptResult& result, const bool failed)
308 {
309 if (!result.standardOutput.empty())
310 yosysLog.info(std::format("stdout:\n{}", result.standardOutput));
311 if (!result.standardError.empty()) {
312 const auto message = std::format("stderr:\n{}", result.standardError);
313 if (failed)
314 yosysLog.error(message);
315 else
316 yosysLog.warning(message);
317 }
318 }
319
320} // namespace
321
322ScriptResult runScript(const std::string_view script, const ToolOptions& options)
323{
324 namespace process = boost::process::v1;
325
326 std::filesystem::path executable;
327 if (options.executable) {
328 std::error_code error;
329 const auto status = std::filesystem::status(*options.executable, error);
330
331 if (error || !std::filesystem::exists(status)
332 || !std::filesystem::is_regular_file(status)) {
333 throw std::runtime_error(std::format(
334 "Yosys executable-validation phase failed: configured executable '{}' is "
335 "missing or invalid. See the 'yosys' logs for details.",
336 options.executable->string()));
337 }
338 executable = *options.executable;
339 } else {
340 executable = process::search_path("yosys").string();
341 if (executable.empty()) {
342 yosysLog.error("Executable 'yosys' was not found on PATH");
343 throw std::runtime_error(
344 "Yosys executable-discovery phase failed: 'yosys' was not found on PATH. "
345 "See the 'yosys' logs for details.");
346 }
347 }
348
349 boost::asio::io_context ioContext;
350 std::future<std::string> standardOutput;
351 std::future<std::string> standardError;
352 std::unique_ptr<process::child> child;
353 try {
354 child = std::make_unique<process::child>(
355 executable.string(), process::args({"-Q", "-p", std::string(script)}),
356 process::std_out > standardOutput, process::std_err > standardError, ioContext);
357 } catch (const std::exception& error) {
358 yosysLog.error(std::format("Process creation failed for '{}': {}",
359 executable.string(), error.what()));
360 throw std::runtime_error(
361 "Yosys process-creation phase failed. See the 'yosys' logs for details.");
362 }
363
364 try {
365 ioContext.run();
366 child->wait();
367 } catch (const std::exception& error) {
368 try {
369 if (child->running())
370 child->terminate();
371 child->wait();
372 } catch (const std::exception&) {
373 }
374 yosysLog.error(std::format("Output capture failed: {}", error.what()));
375 throw std::runtime_error(
376 "Yosys output-capture phase failed. See the 'yosys' logs for details.");
377 }
378
379 ScriptResult result;
380 try {
381 result = {standardOutput.get(), standardError.get()};
382 } catch (const std::exception& error) {
383 yosysLog.error(std::format("Output capture failed after exit status {}: {}",
384 child->exit_code(), error.what()));
385 throw std::runtime_error(
386 "Yosys output-capture phase failed. See the 'yosys' logs for details.");
387 }
388
389 const int exitStatus = child->exit_code();
390 logCapturedOutput(result, exitStatus != 0);
391 if (exitStatus != 0) {
392 yosysLog.error(std::format("Command failed with exit status {}", exitStatus));
393 throw std::runtime_error(std::format(
394 "Yosys script-execution phase failed with exit status {}. See the 'yosys' "
395 "logs for command output.",
396 exitStatus));
397 }
398 return result;
399}
400
401std::string readVerilog(const std::string_view source, const ToolOptions& options)
402{
403 const std::array sources{
404 SILICON::core::SourceFile{.path = "source.v", .contents = source}};
405 return readVerilog(sources, "source.v", options);
406}
407
408std::string readVerilog(const std::span<const SILICON::core::SourceFile> sources,
409 const std::string_view entryPath, const ToolOptions& options)
410{
411 if (!isSafeRelativeSourcePath(entryPath))
412 throw std::invalid_argument("Verilog entry path must be a safe relative path");
413
414 std::unordered_set<std::string, core::TransparentStringHash,
416 paths;
417 for (const auto& source : sources) {
418 if (!isSafeRelativeSourcePath(source.path))
419 throw std::invalid_argument(std::format(
420 "Verilog source path '{}' must be a safe relative path", source.path));
421 if (!paths.emplace(source.path).second)
422 throw std::invalid_argument(
423 std::format("Duplicate Verilog source path: {}", source.path));
424 }
425 if (!paths.contains(entryPath))
426 throw std::invalid_argument(
427 std::format("Verilog entry source is missing: {}", entryPath));
428
429 TemporaryWorkspace workspace;
430 for (const auto& source : sources) {
431 const auto sourcePath = workspace.path() / std::filesystem::path(source.path);
432 std::error_code error;
433 std::filesystem::create_directories(sourcePath.parent_path(), error);
434 if (error)
435 throw std::runtime_error(std::format(
436 "Yosys Verilog-read input-writing phase failed: could not create '{}': {}",
437 sourcePath.parent_path().string(), error.message()));
438 writeFile(sourcePath, source.contents, "Verilog-read input-writing phase");
439 }
440
441 const auto sourcePath = workspace.path() / std::filesystem::path(entryPath);
442 const auto jsonPath = workspace.path() / "design.json";
443
444 (void)runScript(std::format("read_verilog -noautowire {}\n"
445 // Parameterized modules require the frontend AST to derive
446 // each instance. JSON cannot preserve that AST, so resolve
447 // the hierarchy before crossing the JSON boundary. Leave
448 // library-cell validation to elaborateHierarchy.
449 "hierarchy\n"
450 // `proc` converts processes ($dff/$mux cells) so the JSON
451 // backend can emit them; it is required before write_json
452 // without performing SILICON legalization here.
453 "proc\n"
454 "memory_collect\n"
455 "write_json {}\n",
456 quotePath(sourcePath), quotePath(jsonPath)),
457 options);
458 return readFile(jsonPath, "Verilog-read output-reading phase");
459}
460
461std::string elaborateHierarchy(const std::string_view json, const ToolOptions& options)
462{
463 TemporaryWorkspace workspace;
464 const auto inputPath = workspace.path() / "design.json";
465 const auto outputPath = workspace.path() / "elaborated.json";
466 writeFile(inputPath, json, "Yosys-elaboration input-writing phase");
467
468 const auto library = technologyLibrary(options);
469 const auto plugin = verilogPlugin();
470 if (!plugin)
471 throw std::runtime_error(
472 "SILICON Yosys legalization requires the SILICON Yosys plugin");
473 const std::string pluginLoad =
474 std::format("plugin -i {}\n", quotePath(*plugin));
475 const std::string legalization =
476 std::format("silicon_legalize {}\n", quotePath(library.technologyMap));
477
478 (void)runScript(std::format("read_verilog -lib -D SILICON_BLACKBOX {}\n"
479 "read_json {}\n"
480 "{}"
481 "hierarchy -check\n"
482 // The JSON boundary requires processes to be lowered
483 // by the frontend before elaborateHierarchy is called.
484 "muxpack\n"
485 "{}"
486 "write_json {}\n",
487 quotePath(library.cells), quotePath(inputPath), pluginLoad,
488 legalization,
489 quotePath(outputPath)),
490 options);
491 return readFile(outputPath, "Yosys-elaboration output-reading phase");
492}
493
494std::string writeVerilog(std::string_view json, const ToolOptions& options)
495{
496 TemporaryWorkspace workspace;
497 const auto library = technologyLibrary(options);
498 const auto jsonPath = workspace.path() / "design.json";
499 const auto verilogPath = workspace.path() / "design.v";
500 writeFile(jsonPath, json, "Verilog-export input-writing phase");
501
502 const auto plugin = verilogPlugin();
503 const auto muxExport =
504 plugin ? std::format("plugin -i {}\nsilicon_bmux_case\n", quotePath(*plugin))
505 : std::string();
506 // Emit attributes only when a ROM document name must survive Verilog export.
507 const std::string_view backendOptions =
508 json.find(attributes::BINARY_DOCUMENT) != std::string_view::npos
509 ? "-norename -decimal" : "-noattr -norename -decimal";
510
511 (void)runScript(std::format("read_verilog -lib -D SILICON_BLACKBOX {}\n"
512 "read_json {}\n"
513 "hierarchy -check -auto-top\n"
514 "techmap -autoproc -D SILICON_EXPORT_MAP -map {}\n"
515 "opt_expr t:$pos\n"
516 "opt_clean -purge\n"
517 "rename -unescape\n"
518 "opt\n"
519 "{}"
520 "rename -enumerate\n"
521 "write_verilog {} {}\n",
522 quotePath(library.cells), quotePath(jsonPath),
523 quotePath(library.cells), muxExport,
524 backendOptions, quotePath(verilogPath)),
525 options);
526 return readFile(verilogPath, "Verilog-export output-reading phase");
527}
528
529#endif
530
531} // namespace SILICON::yosys
constexpr std::string_view BINARY_DOCUMENT
Definition cells.hpp:51
std::string elaborateHierarchy(const std::string_view json, const ToolOptions &options)
ScriptResult runScript(const std::string_view script, const ToolOptions &options)
std::string writeVerilog(std::string_view json, const ToolOptions &options)
std::string readVerilog(const std::string_view source, const ToolOptions &options)
Transparent equality functor for string-like keys.
Transparent hash functor for string-like keys.
std::optional< std::filesystem::path > executable