From a25645afa62e0537f4baf18a66a317bb1ce8a81f Mon Sep 17 00:00:00 2001 From: Florent Kermarrec Date: Fri, 16 Nov 2018 16:03:23 +0100 Subject: [PATCH] utils: add litex_read_verilog utility generate Migen's modules from verilog files --- litex/utils/litex_read_verilog.py | 60 +++++++++++++++++++++++++++++++ setup.py | 1 + 2 files changed, 61 insertions(+) create mode 100755 litex/utils/litex_read_verilog.py diff --git a/litex/utils/litex_read_verilog.py b/litex/utils/litex_read_verilog.py new file mode 100755 index 00000000..b939d2f6 --- /dev/null +++ b/litex/utils/litex_read_verilog.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python3 +import os +import sys +import json + +from litex.build import tools + +def main(): + if len(sys.argv) < 2: + print("usage: litex_read_verilog verilog_file [module]") + exit(1) + + verilog_file = sys.argv[1] + json_file = verilog_file + ".json" + module = None if len(sys.argv) < 3 else sys.argv[2] + + # use yosys to convert verilog to json + yosys_v2j = "\n".join([ + "read_verilog -sv {}".format(verilog_file), + "write_json {}.json".format(verilog_file) + ]) + tools.write_to_file("yosys_v2j.ys", yosys_v2j) + os.system("yosys -q yosys_v2j.ys") + + # load json and convert to migen module + f = open(json_file, "r") + j = json.load(f) + + # create list of modules + modules = [module] if module is not None else j["modules"].keys() + + # create migen definitions + for module in modules: + migen_def = [] + migen_def.append("class {}(Module):".format(module)) + migen_def.append(" "*4 + "def __init__(self):") + for name, info in j["modules"][module]["ports"].items(): + length = "" if len(info["bits"]) == 1 else len(info["bits"]) + migen_def.append(" " * 8 + "self.{} = Signal({})".format(name, length)) + migen_def.append("") + migen_def.append(" "*4 + "# # #") + migen_def.append("") + migen_def.append(" "*4 + "self.specials += Instance(\"{}\",".format(module)) + for name, info in j["modules"][module]["ports"].items(): + io_prefix = { + "input": "i", + "output": "o", + "inout": "io" + }[info["direction"]] + migen_def.append(" "*8 + "{}_{}=self.{},".format(io_prefix, name, name)) + migen_def.append(" "*4 + ")") + migen_def.append("") + print("\n".join(migen_def)) + + # keep things clean after us + os.system("rm " + json_file) + + +if __name__ == "__main__": + main() diff --git a/setup.py b/setup.py index bf3c743b..ed0dd4d3 100755 --- a/setup.py +++ b/setup.py @@ -40,6 +40,7 @@ setup( "litex_term=litex.utils.litex_term:main", "litex_server=litex.utils.litex_server:main", "litex_sim=litex.utils.litex_sim:main", + "litex_read_verilog=litex.utils.litex_read_verilog:main", "litex_simple=litex.boards.targets.simple:main", ], }, -- 2.30.2