Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions openfpga/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ if (OPENFPGA_WITH_YOSYS STREQUAL "ON")
add_dependencies(libopenfpga yosys)
target_link_libraries(libopenfpga
libyosys
${CMAKE_DL_LIBS}
)
endif()

Expand Down
117 changes: 89 additions & 28 deletions openfpga/src/yosys_wrapper/yosys_main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,52 +2,113 @@

#include "yosys_main.h"

#if defined(__unix__) || defined(__APPLE__)
#include <dlfcn.h>
#endif
#include <filesystem>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>

#include "command_exit_codes.h"
#include "kernel/yosys.h"
#include "vtr_log.h"

namespace openfpga {

/**
* Runs a Yosys synthesis script directly via the C++ API.
* @param script_path The filesystem path to the Yosys script (e.g.,
* "synth.ys").
* @return true if successful, false otherwise.
*/
int yosys_script_mode_wrapper(const std::string& script_path) {
try {
// 1. Initialize global Yosys state and log systems
Yosys::yosys_setup();
Yosys::log_errfile = stderr;
Yosys::log_streams.push_back(&std::cout);

// 2. Instantiate a persistent design container
// This holds the AST, Netlist, and Design modules in memory
Yosys::RTLIL::Design* design = new Yosys::RTLIL::Design;
/* What Yosys reports through log_error(), which would otherwise end the whole
* process with exit(1): the message that Yosys keeps of its last error */
struct YosysFailure : public std::runtime_error {
explicit YosysFailure(const std::string& what) : std::runtime_error(what) {}
};

// 3. Execute the script frontend pass directly on your design object.
// Yosys treats scripts as frontend passes (similar to "read_verilog").
VTR_LOG("Processing yosys script file: %s\n", script_path.c_str());
Yosys::run_frontend(script_path, "script", design);
/* The folder of the file that holds this code: the openfpga executable, or the
* Python module that was loaded. Yosys looks for its share/ folder and for
* yosys-abc next to the running executable, which is python for the module */
static std::string folder_of_this_code() {
#if defined(__unix__) || defined(__APPLE__)
Dl_info info;
if (dladdr(reinterpret_cast<void*>(&folder_of_this_code), &info) == 0 ||

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can use std::filesystem::current_path()

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

std::filesystem::current_path() is the working directory of the process, which is not where Yosys's files are. So I kept dladdr for this one.

In the openfpga shell nothing more is needed. Yosys finds share/ and yosys-abc next to the executable, where the CMake step puts them.

The Python modules (_openfpga.so and openfpga_shell.so) are a different case. The running executable is python, so Yosys looks next to python and finds nothing, and every yosys command fails. The CMake step already places share/ and yosys-abc in build/openfpga, next to both modules. dladdr gives the folder the module was loaded from, and locate_yosys_files looks there. That uses the layout CMake already creates and adds nothing to it.

The lookup only takes over when Yosys did not find share/ or yosys-abc by itself, so the environment variable ABC and Yosys's own folders still win. It is compiled only for Unix and macOS (unix, APPLE). Elsewhere Yosys keeps its default lookup.

info.dli_fname == nullptr) {
return std::string();
}
std::string file(info.dli_fname);
size_t slash = file.rfind('/');
return slash == std::string::npos ? std::string(".") : file.substr(0, slash);
#else
/* No dladdr: Yosys keeps looking next to the executable */
return std::string();
#endif
}

// 4. Verify design integrity after script completion
design->check();
/* Where Yosys finds what it needs when it is not in an executable of its own:
* share/ and yosys-abc in the folder of this code (OpenFPGA's build links them
* there). What Yosys found by itself (the environment variable ABC, its own
* folders) is kept */
static void locate_yosys_files() {
namespace fs = std::filesystem;
std::string folder = folder_of_this_code();
if (folder.empty()) {
return;
}
std::error_code ec;
if (!fs::is_directory(Yosys::yosys_share_dirname, ec) &&
fs::is_directory(fs::path(folder) / "share", ec)) {
Yosys::yosys_share_dirname = folder + "/share/";
}
if (!fs::is_regular_file(Yosys::yosys_abc_executable, ec) &&
fs::is_regular_file(fs::path(folder) / "yosys-abc", ec)) {
Yosys::yosys_abc_executable = folder + "/yosys-abc";
}
}

// 5. Clean up allocated design context memory safely
delete design;
static void throw_yosys_failure() { throw YosysFailure(Yosys::log_last_error); }

// 6. Safely tear down global state structures
Yosys::yosys_shutdown();
/* Yosys is set up once for the life of the process. It cannot be set up
* again after yosys_shutdown(): its passes are not registered a second time.
* The process ends and Yosys goes with it */
static void start_yosys_once() {
static bool started = false;
if (started) {
return;
}
Yosys::yosys_setup();
locate_yosys_files();
Yosys::log_errfile = stderr;
Yosys::log_streams.push_back(&std::cout);
/* An error of a command (log_cmd_error) is an exception ... */
Yosys::log_cmd_error_throw = true;
/* ... and so is any other error (log_error): this hook runs before exit(1) */
Yosys::log_error_atexit = throw_yosys_failure;
started = true;
}

int yosys_script_mode_wrapper(const std::string& script_path) {
start_yosys_once();
/* A design of its own for each script: what an earlier script left is gone */
std::unique_ptr<Yosys::RTLIL::Design> design(new Yosys::RTLIL::Design);
try {
VTR_LOG("Processing yosys script file: %s\n", script_path.c_str());
Yosys::run_frontend(script_path, "script", design.get());
design->check();
VTR_LOG("Yosys script execution completed successfully.\n");
return CMD_EXEC_SUCCESS;
} catch (const YosysFailure& e) {
VTR_LOG_ERROR("Yosys failed: %s", e.what());
} catch (const Yosys::log_cmd_error_exception&) {
VTR_LOG_ERROR("Yosys failed: %s", Yosys::log_last_error.c_str());
} catch (const std::exception& e) {
VTR_LOG_ERROR("Error during Yosys execution: %s\n", e.what());
return CMD_EXEC_FATAL_ERROR;
} catch (...) {
VTR_LOG_ERROR("An unhandled Yosys exception occurred.\n");
return CMD_EXEC_FATAL_ERROR;
}
/* The way that the Yosys shell recovers from an error of a command */
while (design->selection_stack.size() > 1) {
design->pop_selection();
}
Yosys::log_reset_stack();
return CMD_EXEC_FATAL_ERROR;
}

} // namespace openfpga
Expand Down
87 changes: 87 additions & 0 deletions openfpga_flow/tasks/python_binding_tests/test_yosys_command.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
"""The `yosys` command of the shell: Yosys runs inside the process, stays set up between commands, and an
error of Yosys is a failed command that does not end the process."""

import re

import pytest

AND2 = """module and2(input a, input b, output y);
assign y = a & b;
endmodule
"""

# Maps to 6-input LUTs and writes a BLIF, like the Yosys step of the flow scripts
SYNTHESIS = """read_verilog and2.v
hierarchy -top and2
proc
flatten
opt
techmap
opt
abc -lut 6
opt_clean -purge
write_blif and2.blif
"""

BROKEN_VERILOG = """module broken(input a, output y);
assign y = a &;
endmodule
"""


@pytest.fixture
def scripts(tmp_path):
"""Yosys scripts of a good run and of the ways that Yosys fails, in the current directory"""
(tmp_path / "and2.v").write_text(AND2)
(tmp_path / "broken.v").write_text(BROKEN_VERILOG)
(tmp_path / "good.ys").write_text(SYNTHESIS)
(tmp_path / "no_file.ys").write_text("read_verilog nothere.v\n")
(tmp_path / "syntax.ys").write_text("read_verilog broken.v\n")
(tmp_path / "no_command.ys").write_text("not_a_yosys_command\n")
# An error that Yosys reports from inside a pass, not from a frontend or a command line
(tmp_path / "in_pass.ys").write_text(
"read_verilog and2.v\nhierarchy -top not_there\n"
)
return tmp_path


FAILURES = ["no_file.ys", "syntax.ys", "no_command.ys", "in_pass.ys"]


def synthesize(shell, tmp_path):
(tmp_path / "and2.blif").unlink(missing_ok=True)
return shell.run_command("yosys --file good.ys")


def test_yosys_maps_a_design_to_luts_and_writes_a_blif(shell, scripts):
assert synthesize(shell, scripts) == 0
blif = (scripts / "and2.blif").read_text()
assert ".model and2" in blif and ".inputs a b" in blif and ".outputs y" in blif
assert re.search(
r"^\.names (a b|b a) y\n11 1$", blif, re.M
) # the AND gate is one LUT


@pytest.mark.parametrize("script", FAILURES)
def test_an_error_of_yosys_fails_the_command_and_leaves_the_process_alive(
shell, scripts, script
):
assert shell.run_command(f"yosys --file {script}") != 0
# The same process runs Yosys again: it was neither shut down nor left half way
assert synthesize(shell, scripts) == 0
assert ".model and2" in (scripts / "and2.blif").read_text()


def test_yosys_runs_many_times_in_one_process_with_failures_between(shell, scripts):
for _ in range(5):
assert synthesize(shell, scripts) == 0
for script in FAILURES:
assert shell.run_command(f"yosys --file {script}") != 0
assert synthesize(shell, scripts) == 0


def test_a_script_does_not_see_the_design_of_the_one_before(shell, scripts):
# A design of its own for each script: the module that was read before is gone
(scripts / "second.ys").write_text("hierarchy -top and2\n")
assert synthesize(shell, scripts) == 0
assert shell.run_command("yosys --file second.ys") != 0
Loading