artix7: working on muxes.

Signed-off-by: Tim 'mithro' Ansell <mithro@mithis.com>
diff --git a/v2x/mux_gen.py b/v2x/mux_gen.py
index da745d9..0b0f529 100755
--- a/v2x/mux_gen.py
+++ b/v2x/mux_gen.py
@@ -54,6 +54,10 @@
     help="Name of the input values for the mux.")
 
 parser.add_argument(
+    '--name-inputs', type=str, default=None,
+    help="Comma deliminator list for the name of each input to the mux (implies --split-inputs).")
+
+parser.add_argument(
     '--name-output', type=str, default='O',
     help="Name of the output value for the mux.")
 
@@ -62,6 +66,10 @@
     help="Name of the select parameter for the mux.")
 
 parser.add_argument(
+    '--name-selects', type=str, default=None,
+    help="Comma deliminator list for the name of each select to the mux (implies --split-selects).")
+
+parser.add_argument(
     '--order', choices=[''.join(x) for x in itertools.permutations('ios')]+[''.join(x) for x in itertools.permutations('io')],
     default='iso',
     help="""Order of the arguments for the MUX. (i - Inputs, o - Output, s - Select)""")
@@ -83,6 +91,15 @@
     help="""Override the subcircuit name.""")
 
 
+def output_block(name, s):
+    print()
+    print(name, '-'*(75-(len(name)+1)))
+    print(s, end="")
+    if s[-1] != '\n':
+        print()
+    print('-'*75)
+
+
 def clog2(x):
     """Ceiling log 2 of x.
 
@@ -109,49 +126,6 @@
 import doctest
 doctest.testmod()
 
-# Method for implementing the internals of the MUX.
-method = {
-    'impl': """\
-	assign O = I[S];
-""",
-
-    'wrap': {
-        # FIXME: Wrap the LOGIC_MUX_N
-        'logic': """\
-    LOGIC_MUX_N ...
-""",
-        # FIXME: Wrap the ROUTING_MUX_N
-        'routing': """\
-""",
-    },
-
-    'blackbox': "",
-}
-
-
-logic_template = """\
-module {:name}({:args});
-
-    output wire {:name_output};
-    input wire [{:width}:0] {:name_;
-    input wire [{:select}:0] {:name_select};
-
-{:method}
-endmodule
-"""
-
-routing_template = """\
-module {:name}({:args});
-    parameter {:name_select} = 0;
-
-    output wire {:name_output};
-    input wire [{:width}:0] {:name_input};
-
-{:method}
-    assign {:name_output} = {:name_input}[{:name_select}];
-endmodule
-"""
-
 call_args = list(sys.argv)
 
 args = parser.parse_args()
@@ -160,6 +134,7 @@
     args.subckt = args.name_mux
 
 mypath = __file__
+mydir = os.path.dirname(mypath)
 
 print(mypath)
 print(args)
@@ -169,6 +144,8 @@
 else:
     outdir = args.outdir
 
+mux_dir = os.path.relpath(os.path.abspath(os.path.join(mydir, '..', 'vpr', 'muxes')), outdir)
+
 repo_args = []
 skip_next = False
 for i, arg in enumerate(sys.argv):
@@ -210,9 +187,11 @@
     xml_comment += args.comment.replace("--", "~~")
     xml_comment += "\n"
 
+# ------------------------------------------------------------------------
 # Create a makefile to regenerate files.
+# ------------------------------------------------------------------------
 makefile_file = os.path.join(outdir, "Makefile.mux")
-output_files = ['model.xml', 'pb_type.xml', '.gitignore', 'Makefile.mux']
+output_files = ['model.xml', 'pb_type.xml', '.gitignore', 'Makefile.mux', 'sim.v']
 commit_files = ['.gitignore', 'Makefile.mux']
 remove_files = [f for f in output_files if f not in commit_files]
 with open(makefile_file, "w") as f:
@@ -241,72 +220,187 @@
         f.write("%s: .mux_gen.stamp\n\n" % name)
 
 
-print("Makefile.mux", "-"*75)
-print(open(makefile_file).read())
-print("-"*75)
+output_block("Makefile.mux", open(makefile_file).read())
 
-# .gitignore file for the generated file.
+# ------------------------------------------------------------------------
+# Create .gitignore file for the generated files.
+# ------------------------------------------------------------------------
 gitignore_file = os.path.join(outdir, ".gitignore")
 with open(gitignore_file, "w") as f:
     f.write(".mux_gen.stamp\n")
     for name in remove_files:
         f.write(name+'\n')
 
-print(".gitignore", "-"*75)
-print(open(gitignore_file).read())
-print("-"*75)
+output_block(".gitignore", open(gitignore_file).read())
 
-# Work out the port names
+# ------------------------------------------------------------------------
+# Work out the port and their names
+# ------------------------------------------------------------------------
+if args.name_inputs:
+    assert args.name_input == 'I'
+    args.name_input = None
+    args.split_inputs = True
+
+    names = args.name_inputs.split(',')
+    assert len(names) == args.width, "%s input names, but %s needed." % (names, args.width)
+    args.name_inputs = names
+elif args.split_inputs:
+    args.name_inputs = [args.name_input+str(i) for i in range(args.width)]
+
+if args.name_selects:
+    assert args.name_input == 'I'
+    args.name_input = None
+    args.split_selects = True
+
+    names = args.name_selects.split(',')
+    assert len(names) == args.width, "%s select names, but %s needed." % (names, args.width_bits)
+    args.name_selects = names
+elif args.split_selects:
+    args.name_selects = [args.name_select+str(i) for i in range(args.width_bits)]
+
 port_names = []
 for i in args.order:
     if i == 'i':
         if args.split_inputs:
-            port_names.extend(('i', args.name_input+str(i), 1, '[%i]' % i) for i in range(args.width))
+            port_names.extend(('i', args.name_inputs[j], 1, '[%i]' % j) for j in range(args.width))
         else:
             port_names.append(('i', args.name_input, args.width, '[%i:0]' % args.width))
-    elif i == 's' and args.type == 'logic':
+    elif i == 's':
         if args.split_selects and args.width_bits > 1:
-            port_names.extend(('s', args.name_select+str(i), 1, '[%i]' % i) for i in range(args.width_bits))
+            port_names.extend(('s', args.name_selects[j], 1, '[%i]' % j) for j in range(args.width_bits))
         else:
             port_names.append(('s', args.name_select, args.width_bits, '[%i:0]' % args.width_bits))
     elif i == 'o':
         port_names.append(('o', args.name_output, 1, ''))
 
+# ------------------------------------------------------------------------
+# Generate the sim.v Verilog module
+# ------------------------------------------------------------------------
+
+defs = {'i': 'input wire', 's': 'input wire', 'o': 'output wire'}
+
+sim_file = os.path.join(outdir, "sim.v")
+with open(sim_file, "w") as f:
+    module_args = []
+    for type, name, _, _ in port_names:
+        if args.type == 'routing' and type == 's':
+            continue
+        module_args.append(name)
+
+    f.write("/* ")
+    f.write("\n * ".join(generated_with.splitlines()))
+    f.write("\n */\n\n")
+    f.write('`include "%s/sim.mux%i.v"\n' % (mux_dir, args.width))
+    f.write("\n")
+    f.write("module %s(%s);\n" % (args.name_mux, ", ".join(module_args)))
+    previous_type = None
+    for type, name, width, index in port_names:
+        if previous_type != type:
+            f.write("\n")
+            previous_type = type
+        if args.type == 'routing' and type == 's':
+            if width == 1:
+                f.write('\tparameter [0:0] %s = 0;\n' % (name))
+            else:
+                f.write('\tparameter %s %s %s = 0;\n' % (index, name))
+            continue
+
+        if width == 1:
+            f.write('\t%s %s;\n' % (defs[type], name))
+        else:
+            f.write('\t%s %s %s;\n' % (defs[type], index, name))
+
+    f.write("\n")
+    f.write('\tMUX%s mux (\n' % args.width)
+    for i in range(0, args.width):
+        j = 0
+        for type, name, width, index in port_names:
+            if type != 'i':
+                continue
+            if j+width <= i:
+                j += width
+                continue
+            break
+
+        print(i, j, name)
+
+        if width == 1:
+            f.write('\t\t.I%i(%s),\n' % (i, name))
+        else:
+            f.write('\t\t.I%i(%s[%i]),\n' % (i, name, i-j))
+
+    for i in range(0, args.width_bits):
+        j = 0
+        for type, name, width, index in port_names:
+            if type != 's':
+                continue
+            if j+width < i:
+                j += width
+                continue
+            break
+
+        if width == 1:
+            f.write('\t\t.S%i(%s),\n' % (i, name))
+        else:
+            f.write('\t\t.S%i(%s[%i]),\n' % (i, name, i-j))
+
+    for type, name, width, index in port_names:
+        if type != 'o':
+            continue
+        break
+    assert width == 1
+    f.write('\t\t.O(%s)\n\t);\n' % name)
+
+    f.write('endmodule\n')
+
+output_block("sim.v", open(sim_file).read())
+
+# ------------------------------------------------------------------------
 # Generate the Model XML form.
-models_xml = ET.Element('models')
-models_xml.append(ET.Comment(xml_comment))
+# ------------------------------------------------------------------------
+if args.type == 'logic':
+    models_xml = ET.Element('models')
+    models_xml.append(ET.Comment(xml_comment))
 
-model_xml = ET.SubElement(models_xml, 'model', {'name': args.subckt})
+    model_xml = ET.SubElement(models_xml, 'model', {'name': args.subckt})
 
-input_ports = ET.SubElement(model_xml, 'input_ports')
-output_ports = ET.SubElement(model_xml, 'output_ports')
-for type, name, width, index in port_names:
-    if type in ('i', 's'):
-        ET.SubElement(
-            input_ports, 'port', {
-                'name': name,
-                'combinational_sink_ports': ','.join(n for t, n, w, i in port_names if t in ('o',)),
-            })
-    elif type in ('o',):
-        ET.SubElement(output_ports, 'port', {'name': args.name_output})
+    input_ports = ET.SubElement(model_xml, 'input_ports')
+    output_ports = ET.SubElement(model_xml, 'output_ports')
+    for type, name, width, index in port_names:
+        if type in ('i', 's'):
+            ET.SubElement(
+                input_ports, 'port', {
+                    'name': name,
+                    'combinational_sink_ports': ','.join(n for t, n, w, i in port_names if t in ('o',)),
+                })
+        elif type in ('o',):
+            ET.SubElement(output_ports, 'port', {'name': args.name_output})
 
-models_str = ET.tostring(models_xml, pretty_print=True).decode('utf-8')
-print("models.xml", "-"*75)
-print(models_str)
-print("-"*75)
-with open(os.path.join(outdir, "model.xml"), "w") as f:
-    f.write(models_str)
+    models_str = ET.tostring(models_xml, pretty_print=True).decode('utf-8')
+    output_block("model.xml", model_str)
+    with open(os.path.join(outdir, "model.xml"), "w") as f:
+        f.write(models_str)
+else:
+    output_block("models.xml", "No model.xml for routing elements.")
 
+# ------------------------------------------------------------------------
 # Generate the pb_type XML form.
+# ------------------------------------------------------------------------
+
+mn = args.name_mux
 pb_type_xml = ET.Element(
     'pb_type', {
-        'name': args.name_mux,
+        'name': mn,
         'num_pb': str(args.num_pb),
-        'blif_model': '.subckt %s' % args.subckt,
     })
+if args.type == 'logic':
+    pb_type_xml['blif_model'] = '.subckt %s' % args.subckt
+
 pb_type_xml.append(ET.Comment(xml_comment))
 
 for type, name, width, index in port_names:
+    if args.type == 'routing' and type == 's':
+        continue
     ET.SubElement(
         pb_type_xml,
         {'i': 'input',
@@ -332,61 +426,18 @@
                     'out_port': "%s.%s" % (args.name_mux, oname),
                 },
             )
-
-if False:
+else:
     interconnect = ET.SubElement(pb_type_xml, 'interconnect')
-    if args.type == 'routing':
-        ET.SubElement(
-            interconnect,
-            'mux', {
-                'name': 'OUT',
-                'input': ' '.join(n for t, n, w, i in port_names if t in ('i',)),
-                'output': args.name_output,
-            },
-        )
-    else:
-        for type, name, width, index in port_names:
-            if type in ('i', 's'):
-                ET.SubElement(
-                    interconnect,
-                    'direct', {
-                        'name': name,
-                        'input': name,
-                        'output': "MUX.%s%s" % (type.upper(), index),
-                    },
-                )
-            elif type in ('o',):
-                ET.SubElement(
-                    interconnect,
-                    'direct', {
-                        'name': name,
-                        'output': name,
-                        'input': "MUX.%s%s" % (type.upper(), index),
-                    },
-                )
+    ET.SubElement(
+        interconnect,
+        'mux', {
+            'name': '_'+args.name_mux,
+            'input': ' '.join("%s.%s" % (mn,n) for t, n, _, _ in port_names if t in ('i',)),
+            'output': "%s.%s" % (mn,args.name_output),
+        },
+    )
 
 pb_type_str = ET.tostring(pb_type_xml, pretty_print=True).decode('utf-8')
-print("pb_type.xml", "-"*75)
-print(pb_type_str)
-print("-"*75)
+output_block("pb_type.xml", pb_type_str)
 with open(os.path.join(outdir, "pb_type.xml"), "w") as f:
     f.write(pb_type_str)
-
-
-import sys; sys.exit(0)
-
-mux_args = []
-for i in args.order:
-    if i == 'i':
-        if args.split_inputs:
-            for i in range(args.width):
-                mux_args.append(args.name_input+str(i))
-        else:
-            mux_args.append(args.name_input)
-    elif i == 'o':
-        mux_args.append(args.name_output)
-    elif i == 's':
-        mux_args.append(args.name_select)
-    else:
-        assert False, "Unknown input argument."
-