More pb_type.xml generator code (still unfinished)

Signed-off-by: David Shah <davey1576@gmail.com>
diff --git a/.gitignore b/.gitignore
index 1697bbe..1af8baf 100644
--- a/.gitignore
+++ b/.gitignore
@@ -2,3 +2,4 @@
 __pycache__
 *.pyc
 dump.json
+pb_type.xml
diff --git a/tests/test_pb.v b/tests/test_pb.v
new file mode 100644
index 0000000..7b5a92a
--- /dev/null
+++ b/tests/test_pb.v
@@ -0,0 +1,12 @@
+`include "adder.v"
+`include "dff.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));
+
+dff dff_i(.clk(clk), .rst(rst), .d(d), .q(q));
+
+endmodule
diff --git a/vlog_to_pbtype.py b/vlog_to_pbtype.py
index 715affe..d74c08c 100755
--- a/vlog_to_pbtype.py
+++ b/vlog_to_pbtype.py
@@ -15,7 +15,7 @@
     (default: name of module)
 
 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
@@ -57,3 +57,115 @@
 
 vjson = yosys.run.vlog_to_json(args.infiles, False, False)
 yj = YosysJson(vjson)
+
+ET.register_namespace("xi", "http://www.w3.org/2001/XInclude")
+
+if args.top is not None:
+    top = args.top
+else:
+    top = yj.get_top()
+tmod = yj.get_module(top)
+
+def make_pb_type(mod, xml_parent = None):
+    cname_to_pb_name = dict()
+
+    def get_full_pin_name(pin):
+        cname, cellpin = pin
+        if cname != mod.get_name():
+            cname = cname_to_pb_name[cname]
+        return ("%s.%s" % (cname, cellpin))
+    
+    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")
+    if mod_type == "bel":
+        assert mod_cls is not None
+        if mod_cls == "lut":
+            pb_xml_attrs["blif_model"] = ".names"
+            pb_xml_attrs["class"] = "lut"
+        elif mod_cls == "routing":
+            # TODO: pb_xml_attrs["class"] = "routing"
+            pass
+        elif mod_cls == "flipflop":
+            pb_xml_attrs["blif_model"] = ".latch"
+            pb_xml_attrs["class"] = "flipflop"
+        else:
+            assert False
+    elif mod_type == "blackbox":
+        pb_xml_attrs["blif_model"] = ".subckt " + mod.get_name()
+        if mod_cls is not None:
+            if mod_cls == "mem":
+                pb_xml_attrs["class"] = "memory"
+            else:
+                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) 
+    interconn = []
+    
+    # Process cells
+    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
+        # 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
+        inp_cons = mod.get_cell_conns(cname, "input")
+        for pin, net in inp_cons:
+            drvs = mod.get_net_drivers(net)
+            if len(drvs) == 0:
+                print("WARNING: pin %s.%s has no driver, interconnect will be missing" % (pb_name, pin))
+            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)))
+        
+        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():
+                    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
+        })
+        
+    # TODO: timing
+    # TODO: muxes
+    return pb_type_xml
+
+pb_type_xml = make_pb_type(tmod, None)
+
+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 98a7649..fd98ca0 100755
--- a/yosys/json.py
+++ b/yosys/json.py
@@ -13,7 +13,11 @@
     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 = []
@@ -22,25 +26,44 @@
         return plist        
 
     # Return a list of cells of a module, as a 2-tuple (name, type)
-    def get_cells(self, include_hidden = True):
+    def get_cells(self, include_internal = False):
         clist = []
         for cell, cdata in self.data["cells"].items():
-            if include_hidden or not cdata["hide_name"]:
-                clist.append((cell, cdata["type"]))
-        
+            if cell.startswith("$") and not include_internal:
+                continue
+            clist.append((cell, cdata["type"]))
+        return clist
     # 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"]
+
+    # Return the value of an attribute of a cell, or the default value if not set
+    def get_cell_attr(self, cell, attr, defval = None):
+        if attr in self.get_cell_attrs(cell):
+            return self.get_cell_attrs(cell)[attr]
+        else:
+            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]
         conns = []
-        for port, condata in cdata["connections"].iteritems():
+        for port, condata in cdata["connections"].items():
             if cdata["port_directions"][port] == direction:
                 N = len(condata)
                 if N == 1:
@@ -66,17 +89,19 @@
     
     # 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):
+    def get_conn_ports(self, net, pdir, include_internal = False):
         conn_ports = []
         for cell in self.data["cells"]:
+            if cell.startswith("$") and not include_internal:
+                continue
             cdata = self.data["cells"][cell]
-            for port, condata in cdata["connections"].iteritems():
+            for port, condata in cdata["connections"].items():
                 if cdata["port_directions"][port] == pdir:
                     if net in condata:
                         if len(condata) == 1:
-                            conn_ports.append(port)
+                            conn_ports.append((cell, port))
                         else:
-                            conn_ports.append("%s[%d]" % (port, condata.index(net)))
+                            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