Initial support for <mode>, general tidying up and other small tweaks

Signed-off-by: David Shah <davey1576@gmail.com>
diff --git a/.gitignore b/.gitignore
index fb96a08..7494525 100644
--- a/.gitignore
+++ b/.gitignore
@@ -2,3 +2,5 @@
 *.pyc
 dump.json
 merged.xml
+/pb_type.xml
+/model.xml
diff --git a/tests/lut2/model.xml b/tests/lut2/model.xml
new file mode 100644
index 0000000..cb6470d
--- /dev/null
+++ b/tests/lut2/model.xml
@@ -0,0 +1,12 @@
+<models>
+  <model name="lut2">
+    <input_ports>
+      <port combinational_sink_ports="y" name="a"/>
+      <port combinational_sink_ports="y" name="b"/>
+    </input_ports>
+    <output_ports>
+      <port name="y"/>
+      <port name="co"/>
+    </output_ports>
+  </model>
+</models>
diff --git a/tests/lut2/pb_type.xml b/tests/lut2/pb_type.xml
new file mode 100644
index 0000000..af537d1
--- /dev/null
+++ b/tests/lut2/pb_type.xml
@@ -0,0 +1,7 @@
+<pb_type blif_model=".subckt lut2" name="lut2" num_pb="1">
+  <input equivalent="false" name="a" num_pins="1"/>
+  <input equivalent="false" name="b" num_pins="1"/>
+  <output equivalent="false" name="y" num_pins="1"/>
+  <output equivalent="false" name="co" num_pins="1"/>
+  <interconnect/>
+</pb_type>
diff --git a/tests/lut2/sim.v b/tests/lut2/sim.v
new file mode 100644
index 0000000..a1143b3
--- /dev/null
+++ b/tests/lut2/sim.v
@@ -0,0 +1,5 @@
+module lut2 (input a, b, output y, co);
+parameter [3:0] content = 4'b1000;
+assign y = content[{b, a}];
+assign co = 1'b0;
+endmodule
diff --git a/tests/model.xml b/tests/model.xml
index b12691a..97d527b 100644
--- a/tests/model.xml
+++ b/tests/model.xml
@@ -3,13 +3,13 @@
     <input_ports>
       <port is_clock="1" name="clk"/>
       <port clock="clk" name="rst"/>
-      <port clock="clk" combinational_sink_ports="co" name="a"/>
-      <port clock="clk" combinational_sink_ports="co" name="b"/>
-      <port clock="clk" combinational_sink_ports="co" name="ci"/>
+      <port clock="clk" name="a"/>
+      <port clock="clk" name="b"/>
+      <port clock="clk" name="ci"/>
     </input_ports>
     <output_ports>
       <port clock="clk" name="q"/>
-      <port clock="clk" name="co"/>
+      <port name="co"/>
     </output_ports>
   </model>
 </models>
diff --git a/tests/pb_type.xml b/tests/pb_type.xml
index b190a13..cafd613 100644
--- a/tests/pb_type.xml
+++ b/tests/pb_type.xml
@@ -6,15 +6,28 @@
   <input equivalent="false" name="ci" num_pins="1"/>
   <output equivalent="false" name="q" num_pins="1"/>
   <output equivalent="false" name="co" num_pins="1"/>
-  <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="./adder/pb_type.xml"/>
-  <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="./dff/pb_type.xml"/>
+  <mode name="ADD">
+    <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="adder/pb_type.xml"/>
+    <interconn>
+      <direct input="test_pb.a" name="test_pb_a_to_adder_a" output="adder.a"/>
+      <direct input="test_pb.b" name="test_pb_b_to_adder_b" output="adder.b"/>
+      <direct input="test_pb.ci" name="test_pb_ci_to_adder_ci" output="adder.ci"/>
+      <direct input="adder.co" name="adder_co_to_test_pb_co" output="test_pb.co"/>
+      <direct input="adder.y" name="adder_y_to_dff_d" output="dff.d"/>
+    </interconn>
+  </mode>
+  <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="dff/pb_type.xml"/>
+  <mode name="LUT">
+    <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="lut2/pb_type.xml"/>
+    <interconn>
+      <direct input="test_pb.a" name="test_pb_a_to_lut2_a" output="lut2.a"/>
+      <direct input="test_pb.b" name="test_pb_b_to_lut2_b" output="lut2.b"/>
+      <direct input="lut2.co" name="lut2_co_to_test_pb_co" output="test_pb.co"/>
+      <direct input="lut2.y" name="lut2_y_to_dff_d" output="dff.d"/>
+    </interconn>
+  </mode>
   <interconnect>
-    <direct input="test_pb.a" name="test_pb_a_to_adder_a" output="adder.a"/>
-    <direct input="test_pb.b" name="test_pb_b_to_adder_b" output="adder.b"/>
-    <direct input="test_pb.ci" name="test_pb_ci_to_adder_ci" output="adder.ci"/>
-    <direct input="adder.co" name="adder_co_to_test_pb_co" output="test_pb.co"/>
     <direct input="test_pb.clk" name="test_pb_clk_to_dff_clk" output="dff.clk"/>
-    <direct input="adder.y" name="adder_y_to_dff_d" output="dff.d"/>
     <direct input="test_pb.rst" name="test_pb_rst_to_dff_rst" output="dff.rst"/>
     <direct input="dff.q" name="dff_q_to_test_pb_q" output="test_pb.q"/>
   </interconnect>
diff --git a/tests/run.sh b/tests/run.sh
index 23c8067..7c49ce6 100755
--- a/tests/run.sh
+++ b/tests/run.sh
@@ -1,5 +1,5 @@
 #!/bin/bash
-INPUT_DIRS="adder dff ."
+INPUT_DIRS="adder dff lut2 ."
 THIS_TOP="test_pb"
 
 for dir in $INPUT_DIRS; do
diff --git a/tests/sim.v b/tests/sim.v
index eebd0ab..ffee6e2 100644
--- a/tests/sim.v
+++ b/tests/sim.v
@@ -1,11 +1,13 @@
 `include "adder/sim.v"
 `include "dff/sim.v"
+`include "lut2/sim.v"
 
 module test_pb(input clk, rst, a, b, ci, output q, co);
 
 wire d;
 
-adder adder_i(.a(a), .b(b), .ci(ci), .y(d), .co(co));
+(* MODE="ADD" *) adder adder_i(.a(a), .b(b), .ci(ci), .y(d), .co(co));
+(* MODE="LUT" *) lut2 lut2_i(.a(a), .b(b), .y(d), .co(co));
 
 dff dff_i(.clk(clk), .rst(rst), .d(d), .q(q));
 
diff --git a/vlog_to_model.py b/vlog_to_model.py
index 6b2f72f..85ae87a 100755
--- a/vlog_to_model.py
+++ b/vlog_to_model.py
@@ -37,7 +37,7 @@
 if "top" in args:
     yj = YosysJson(aig_json, args.top)
 else:
-    yj = YosysJson(aig_json)    
+    yj = YosysJson(aig_json)
 
 top = yj.get_top()
 tmod = yj.get_top_module()
@@ -73,7 +73,7 @@
 outfile = "model.xml"
 if "o" in args and args.o is not None:
     outfile = args.o
-    
+
 f = open(outfile, 'w')
 f.write(ET.tostring(models_xml, pretty_print=True).decode('utf-8'))
 f.close()
diff --git a/vlog_to_pbtype.py b/vlog_to_pbtype.py
index ae9264d..eabc847 100755
--- a/vlog_to_pbtype.py
+++ b/vlog_to_pbtype.py
@@ -4,10 +4,10 @@
 Convert a Verilog simulation model to a VPR `pb_type.xml`
 
 The following are allowed on a top level module:
-    
+
     - (* TYPE="bel|blackbox" *) : specify the type of the module
     (either a Basic ELement or a blackbox named after the pb_type
-    
+
     - (* CLASS="lut|routing|flipflop|mem" *) : specify the class of an given
     instance. Must be specified for BELs
 
@@ -17,12 +17,15 @@
 The following are allowed on nets within modules (TODO: use proper Verilog timing):
     All are NYI at the moment!
     - (* SETUP="clk 10e-12" *) : specify setup time for a given clock
-    
+
     - (* HOLD="clk 10e-12" *) : specify hold time for a given clock
-    
+
     - (* CLK_TO_Q="clk 10e-12" *) : specify clock-to-output time for a given clock
-    
+
     - (* PB_MUX=1 *) : if the signal is driven by a $mux cell, generate a pb_type <mux> element for it
+
+The following are allowed on instances within modules:
+    - (* MODE="mode" *) : specify pb_type is only valid within a given mode
 """
 
 import yosys.run
@@ -74,12 +77,23 @@
         if cname != mod.get_name():
             cname = cname_to_pb_name[cname]
         return ("%s.%s" % (cname, cellpin))
-    
+
+    def make_direct_conn(ic_xml, source, dest):
+        source_pin = get_full_pin_name(source)
+        dest_pin = get_full_pin_name(dest)
+        # TODO: should we use this, or determine a net name from the Verilog?
+        ic_name = source_pin.replace(".","_") + "_to_" + dest_pin.replace(".","_")
+        dir_xml = ET.SubElement(ic_xml, 'direct', {
+            'name': ic_name,
+            'input': source_pin,
+            'output': dest_pin
+        })
+
     attrs = mod.get_module_attrs()
     pb_xml_attrs = dict()
-    
+
     pb_xml_attrs["name"] = mod.get_attr("PB_NAME", mod.get_name())
-    
+
     # Process type and class of module
     mod_type = mod.get_attr("TYPE", "blackbox") #TODO: is blackbox a good default?
     mod_cls = mod.get_attr("CLASS")
@@ -105,18 +119,20 @@
                 assert False
     else:
         assert False
-    
+
     #TODO: might not always be the case? should be use Verilog `generate`s to detect this?
     pb_xml_attrs["num_pb"] = "1"
-    
+
     if xml_parent is None:
         pb_type_xml = ET.Element("pb_type", pb_xml_attrs)
     else:
         pb_type_xml = ET.SubElement(xml_parent, "pb_type", pb_xml_attrs)
-    
-    # List of entries in format ((from_cell, from_pin), (to) 
+
+    # List of entries in format ((from_cell, from_pin), (to_cell, to_pin))
     interconn = []
-    
+    # List of interconnect to ignore, because it was generated inside a <mode>
+    ignore_interconn = []
+
     # Process IOs
     clocks = yosys.run.list_clocks(args.infiles, mod.get_name())
     for name, width, iodir in mod.get_ports():
@@ -129,15 +145,26 @@
             ET.SubElement(pb_type_xml, "output", ioattrs)
         else:
             assert False
-    # Process cells
+    # Process cells. First build the list of cnames.
+    for cname, i_of in mod.get_cells(False):
+        cname_to_pb_name[cname] = mod.get_cell_attr(cname, "PB_NAME", i_of)
+
     for cname, i_of in mod.get_cells(False):
         pb_name = mod.get_cell_attr(cname, "PB_NAME", i_of)
-        pb_type_path = "./%s/pb_type.xml" % pb_name # TODO: might want to override path for complex hierarchies?
-        ET.SubElement(pb_type_xml, "{http://www.w3.org/2001/XInclude}include", {'href': pb_type_path})
-        cname_to_pb_name[cname] = pb_name
+        module_path = os.path.dirname(yj.get_module_file(i_of))
+        pb_type_path = "%s/pb_type.xml" % module_path
+        pb_mode = mod.get_cell_attr(cname, "MODE", "")
+        # If MODE is used, need to wrap cell pb_type and interconnect in "mode"
+        is_modal = (pb_mode != "")
+        if is_modal:
+            mode_xml = ET.SubElement(pb_type_xml, "mode", {'name': pb_mode})
+            ET.SubElement(mode_xml, "{http://www.w3.org/2001/XInclude}include", {'href': pb_type_path})
+            mode_ic = ET.SubElement(mode_xml, "interconn")
+        else:
+            ET.SubElement(pb_type_xml, "{http://www.w3.org/2001/XInclude}include", {'href': pb_type_path})
         # In order to avoid overspecifying interconnect, there are two directions we currently
         # consider. All interconnect going INTO a cell, and interconnect going out of a cell
-        # into a top level output
+        # into a top level output - or all outputs if "mode" is used.
         inp_cons = mod.get_cell_conns(cname, "input")
         for pin, net in inp_cons:
             drvs = mod.get_net_drivers(net)
@@ -146,28 +173,28 @@
             elif len(drvs) > 1:
                 print("WARNING: pin %s.%s has multiple drivers, interconnect will be overspecified" % (pb_name, pin))
             for drv_cell, drv_pin in drvs:
-                interconn.append(((drv_cell, drv_pin), (cname, pin)))
-        
+                 # When mode is used, interconnect goes directly in the <mode>
+                if is_modal:
+                    make_direct_conn(mode_ic, (drv_cell, drv_pin), (cname, pin))
+                    ignore_interconn.append(((drv_cell, drv_pin), (cname, pin)))
+                else:
+                    interconn.append(((drv_cell, drv_pin), (cname, pin)))
+
         out_cons = mod.get_cell_conns(cname, "output")
         for pin, net in out_cons:
             sinks = mod.get_net_sinks(net)
             for sink_cell, sink_pin in sinks:
-                if sink_cell == mod.get_name():
+                if is_modal: # When mode is used, interconnect goes directly in the <mode>. Also, all sinks are considered
+                    make_direct_conn(mode_ic, (cname, pin), (sink_cell, sink_pin))
+                    ignore_interconn.append(((cname, pin), (sink_cell, sink_pin)))
+                elif sink_cell == mod.get_name():
                     interconn.append(((cname, pin), (sink_cell, sink_pin)))
-    
+
     ic_xml = ET.SubElement(pb_type_xml, "interconnect")
     # Process interconnect
     for source, dest in interconn:
-        source_pin = get_full_pin_name(source)
-        dest_pin = get_full_pin_name(dest)
-        # TODO: should we use this, or determine a net name from the Verilog?
-        ic_name = source_pin.replace(".","_") + "_to_" + dest_pin.replace(".","_")
-        dir_xml = ET.SubElement(ic_xml, 'direct', {
-            'name': ic_name,
-            'input': source_pin,
-            'output': dest_pin
-        })
-        
+        if (source, dest) not in ignore_interconn:
+            make_direct_conn(ic_xml, source, dest)
     # TODO: timing
     # TODO: muxes
     return pb_type_xml
@@ -177,7 +204,7 @@
 outfile = "pb_type.xml"
 if "o" in args and args.o is not None:
     outfile = args.o
-    
+
 f = open(outfile, 'w')
 f.write(ET.tostring(pb_type_xml, pretty_print=True).decode('utf-8'))
 f.close()
diff --git a/yosys/json.py b/yosys/json.py
index fd98ca0..c443692 100755
--- a/yosys/json.py
+++ b/yosys/json.py
@@ -1,6 +1,6 @@
 #!/usr/bin/env python3
 """
-This is intended to provide a range of helper functions around the output of 
+This is intended to provide a range of helper functions around the output of
 Yosys' `write_json`. Depending on the tasks, this may need to be flattened
 and/or in AIG format. In any case, at minimum `proc` and usually `prep` should
 be used before outputting the JSON.
@@ -13,17 +13,17 @@
     def __init__(self, name, module_data):
         self.name = name
         self.data = module_data
-    
+
     # Return the name of the module
     def get_name(self):
         return self.name
-    
+
     # Return a list of ports of a module (default: top), as a 3-tuple (name, width, dir)
     def get_ports(self):
         plist = []
         for port, pdata in self.data["ports"].items():
             plist.append((port, len(pdata["bits"]), pdata["direction"]))
-        return plist        
+        return plist
 
     # Return a list of cells of a module, as a 2-tuple (name, type)
     def get_cells(self, include_internal = False):
@@ -36,14 +36,14 @@
     # Return the attributes of a module as a dictionary
     def get_module_attrs(self):
         return self.data["attributes"]
-    
+
     # Return the value of an attribute, or the default value if not set
     def get_attr(self, attr, defval = None):
         if attr in self.get_module_attrs():
             return self.get_module_attrs()[attr]
         else:
             return defval
-            
+
     # Return the attributes of a cell instance as a dictionary
     def get_cell_attrs(self, cell):
         return self.data["cells"][cell]["attributes"]
@@ -53,12 +53,12 @@
         if attr in self.get_cell_attrs(cell):
             return self.get_cell_attrs(cell)[attr]
         else:
-            return defval        
-            
+            return defval
+
     # TODO: the below code is kind of ugly, but because module and cell IO
     # specifications are inconsistent in how they are represented in the JSON,
     # it's hard to make any nicer...
-    
+
     # Return cell connections in a given direction as a 2-tuple (cell pin name, module net number)
     def get_cell_conns(self, cell, direction = "input"):
         cdata = self.data["cells"][cell]
@@ -72,9 +72,9 @@
                     for i in range(N):
                         conns.append(("%s[%d]" % (port, N), condata[i]))
         return conns
-    
+
     # Returns any top level IO matching a direction and connected net number
-    # Result is a list containing entries of the form A or A[15] for single bit 
+    # Result is a list containing entries of the form A or A[15] for single bit
     # or bus ports respectively
     def get_conn_io(self, net, iodir):
         conn_io = []
@@ -86,7 +86,7 @@
                     else:
                         conn_io.append("%s[%d]" % (port, pdata["bits"].index(net)))
         return conn_io
-    
+
     # Returns any cell ports matching a direction and connected net number
     # Result is a list of tuples (cell, port)
     def get_conn_ports(self, net, pdir, include_internal = False):
@@ -103,7 +103,7 @@
                         else:
                             conn_ports.append((cell, "%s[%d]" % (port, condata.index(net))))
         return conn_ports
-    
+
     # Return a list of drivers of a net (usually should only be one...) as a 2-tuple
     # (cell, port). cell is set to the name of the module for top level IOs
     def get_net_drivers(self, net):
@@ -111,7 +111,7 @@
         io_drivers = [(self.name, _) for _ in self.get_conn_io(net, "input")]
         cell_drivers = self.get_conn_ports(net, "output")
         return io_drivers + cell_drivers
-    
+
     # Return a list of sinks of a net, as a 2-tuple as above
     def get_net_sinks(self, net):
         # top level *outputs* and cell inputs are both drivers
@@ -134,20 +134,28 @@
                 self.top = None
         else:
             self.top = top
-    
+
+    # Get the name of the top level module
     def get_top(self):
         if self.top is None:
             print("no top module selected")
             assert(False)
         return self.top
-    
+
+    # Get a given module (by name) as a YosysModule
     def get_module(self, module):
         return YosysModule(module, self.data["modules"][module])
-        
+
+    # Get the top module (by name) as a YosysModule
     def get_top_module(self):
         return self.get_module(self.get_top())
 
     # Return true if a module exists
     def has_module(self, module):
         return module in self.data["modules"]
-    
+
+    # Return the filename in which a given module lives
+    def get_module_file(self, module):
+        src = self.get_module(module).get_attr("src")
+        cpos = src.rfind(":")
+        return src[0:cpos]
diff --git a/yosys/run.py b/yosys/run.py
index fa1ebff..f45a3a6 100755
--- a/yosys/run.py
+++ b/yosys/run.py
@@ -60,7 +60,7 @@
                     pins.append(pin)
     os.remove(outfile)
     return pins
-    
+
 def get_combinational_sinks(infiles, module, innet):
     return do_select(infiles, module, "%s %%coe* o:* %%i %s %%d" % (innet, innet))