utils/vlog: verilog to xml utility scripts

Signed-off-by: Tim 'mithro' Ansell <me@mith.ro>
Signed-off-by: Alessandro Comodi <acomodi@antmicro.com>
diff --git a/vlog_to_pbtype.py b/vlog_to_pbtype.py
index ed301ba..09452aa 100755
--- a/vlog_to_pbtype.py
+++ b/vlog_to_pbtype.py
@@ -139,6 +139,14 @@
         return "BLK_IG-" + mod.name
 
 
+def strip_name(name):
+    if '\\' in name:
+        ts = name.find('\\')
+        tf = name.rfind('\\')
+        return name[ts+1:tf]
+    return name
+
+
 def make_pb_content(mod, xml_parent, mod_pname, is_submode=False):
     """Build the pb_type content - child pb_types, timing and direct interconnect,
     but not IO. This may be put directly inside <pb_type>, or inside <mode>."""
@@ -174,7 +182,7 @@
     if (not is_blackbox) or is_submode:
         # Process cells. First build the list of cnames.
         for cname, i_of in mod.cells:
-            pb_name = i_of
+            pb_name = strip_name(i_of)
             module_file = yj.get_module_file(i_of)
             module_path = os.path.dirname(module_file)
             module_basename = os.path.basename(module_file)
@@ -196,18 +204,12 @@
             inp_cons = mod.cell_conns(cname, "input")
             for pin, net in inp_cons:
                 drvs = mod.net_drivers(net)
-                if len(drvs) == 0:
-                    print(
-                        "ERROR: pin {}.{} has no driver, interconnect will be missing"
-                        .format(pb_name, pin)
-                    )
-                    assert False
-                elif len(drvs) > 1:
-                    print(
-                        "ERROR: pin {}.{} has multiple drivers, interconnect will be overspecified"
-                        .format(pb_name, pin)
-                    )
-                    assert False
+                assert len(drvs) > 0, (
+                    "ERROR: pin {}.{} has no driver, interconnect will be missing\n{}".
+                    format(pb_name, pin, mod))
+                assert len(drvs) < 2, (
+                    "ERROR: pin {}.{} has multiple drivers, interconnect will be overspecified".
+                    format(pb_name, pin))
                 for drv_cell, drv_pin in drvs:
                     interconn.append(((drv_cell, drv_pin), (cname, pin)))
 
@@ -220,6 +222,19 @@
                         #in those cells.
                         interconn.append(((cname, pin), (sink_cell, sink_pin)))
 
+        # Direct pin->pin connections
+        for net in mod.nets:
+            drv = mod.conn_io(net, "input")
+            if not drv:
+                continue
+            assert len(drv) == 1, (
+                    "ERROR: net {} has multiple drivers {}, interconnect will be overspecified".
+                    format(net, drv))
+            for snk in mod.conn_io(net, "output"):
+                conn = ((mod.name, drv[0]), (mod.name,snk))
+                interconn.append(conn)
+
+
         ic_xml = ET.SubElement(xml_parent, "interconnect")
         # Process interconnect
         for source, dest in interconn:
diff --git a/yosys/json.py b/yosys/json.py
index 0fe8622..d3ce457 100755
--- a/yosys/json.py
+++ b/yosys/json.py
@@ -8,6 +8,7 @@
 
 import os, sys
 import json
+import pprint
 
 
 class YosysModule:
@@ -15,6 +16,10 @@
         self.name = name
         self.data = module_data
 
+    def __str__(self):
+        return "YosysModule({},\n{})".format(
+            self.name, pprint.pformat(self.data))
+
     @property
     def ports(self):
         """List of ports on a module.
@@ -49,6 +54,11 @@
             clist.append((cell, cdata["type"]))
         return clist
 
+    @property
+    def nets(self):
+        """List the net ids avaliable in the design."""
+        return list(sorted(set(n['bits'][0] for n in self.data["netnames"].values())))
+
     def cell_type(self, cell):
         """Return the type of a given cell"""
         for cname, cdata in self.data["cells"].items():
@@ -254,3 +264,4 @@
         src = self.module(module).attr("src")
         cpos = src.rfind(":")
         return src[0:cpos]
+
diff --git a/yosys/run.py b/yosys/run.py
index 1f19b1e..f8096f2 100755
--- a/yosys/run.py
+++ b/yosys/run.py
@@ -13,6 +13,8 @@
 def get_output(params):
     """Run Yosys with given command line parameters, and return stdout as a string"""
     cmd = [get_yosys()] + params
+    if int(os.environ.get("V", "0")):
+        print(cmd)
     return subprocess.check_output(cmd).decode("utf-8")
 
 
@@ -112,7 +114,7 @@
         return None
 
 
-def do_select(infiles, module, expr):
+def do_select(infiles, module, expr, prep=False, flatten=False):
     """
     Run a Yosys select command (given the expression and input files) on a module
     and return the result as a list of pins
@@ -122,15 +124,28 @@
     infiles: List of Verilog source files to pass to Yosys
     module: Name of module to run command on
     expr: Yosys selector expression for select command
+
+    prep: Run prep command before selecting.
+    flatten: Flatten module when running prep.
     """
-    """TODO: All of these functions involve a fairly large number of calls to Yosys
-    Although performance here is unlikely to be a major priority any time soon,
-    it might be worth investigating better options?"""
+
+    # TODO: All of these functions involve a fairly large number of calls to
+    # Yosys. Although performance here is unlikely to be a major priority any
+    # time soon, it might be worth investigating better options?
+
+    f = ""
+    if flatten:
+        f = "-flatten"
+
+    p = ""
+    if prep:
+        p = "prep -top {} {};".format(module, f)
+    else:
+        p = "proc;"
 
     outfile = tempfile.mktemp()
-    sel_cmd = "prep -top {} -flatten; cd {}; select -write {} {}".format(
-        module, module, outfile, expr
-    )
+    sel_cmd = "{} cd {}; select -write {} {}".format(
+        p, module, outfile, expr)
     commands(sel_cmd, infiles)
     pins = []
     with open(outfile, 'r') as f:
@@ -154,9 +169,8 @@
     module: Name of module to run command on
     innet: Name of input net to find sinks of
     """
-    return do_select(
-        infiles, module, "{} %coe* o:* %i {} %d".format(innet, innet)
-    )
+    return do_select(infiles, module, "{} %co* o:* %i {} %d".format(
+        innet, innet))
 
 
 def list_clocks(infiles, module):
@@ -167,7 +181,9 @@
     infiles: List of Verilog source files to pass to Yosys
     module: Name of module to run command on
     """
-    return do_select(infiles, module, "c:* %x:+[CLK] a:CLOCK=1 %u c:* %d")
+    return do_select(
+        infiles, module,
+        "c:* %x:+[CLK]:+[clk]:+[clock]:+[CLOCK] a:CLOCK=1 %u c:* %d x:* %i")
 
 
 def get_clock_assoc_signals(infiles, module, clk):
@@ -181,7 +197,45 @@
     """
     return do_select(
         infiles, module,
-        "select -list {} %x* i:* o:* %u %i a:ASSOC_CLOCK={} %u {} %d".format(
-            clk, clk, clk
-        )
-    )
+        "select -list {} %a %co* %x i:* o:* %u %i a:ASSOC_CLOCK={} %u {} %d".format(
+            clk, clk, clk))
+
+
+# Find things which affect the given output
+# show w:*D_IN_0 %a %ci*
+
+# Find things which are affected by the given clock.
+# show w:*INPUT_CLK %a %co*
+
+# Find things which are affect by the given signal - combinational only.
+# select -list w:*INPUT_CLK %a %co* %x x:* %i
+
+
+def get_related_output_for_input(infiles, module, signal):
+    """.
+
+    Inputs
+    -------
+    infiles: List of Verilog source files to pass to Yosys
+    module: Name of module to run command on
+    clk: Name of clock to find associated signals
+    """
+    return do_select(
+        infiles, module,
+        "select -list w:*{} %a %co* o:* %i".format(
+            signal))
+
+
+def get_related_inputs_for_input(infiles, module, signal):
+    """.
+
+    Inputs
+    -------
+    infiles: List of Verilog source files to pass to Yosys
+    module: Name of module to run command on
+    clk: Name of clock to find associated signals
+    """
+    return [x for x in do_select(
+        infiles, module,
+        "select -list w:*{} %a %co* %x i:* %i".format(
+            signal)) if x != signal]