Squash everything!

Signed-off-by: Karol Gugala <kgugala@antmicro.com>
diff --git a/tests/carry/carry.sim.v b/tests/carry/carry.sim.v
new file mode 100644
index 0000000..9263abd
--- /dev/null
+++ b/tests/carry/carry.sim.v
@@ -0,0 +1,28 @@
+`default_nettype none
+`include "cblock/cblock.sim.v"
+
+module CARRY (
+	I0,
+	I1,
+	O0,
+	O1,
+	CIN,
+	COUT
+);
+	input wire [3:0] I0;
+	input wire [3:0] I1;
+
+	output wire O0;
+	output wire O1;
+
+	// Implicit carry pins
+	input wire CIN;
+	output wire COUT;
+
+	// Carry between the two blocks
+	wire c;
+
+	CBLOCK cblock0 (.I(I0), .O(O0), .CIN(CIN), .COUT(c));
+	CBLOCK cblock1 (.I(I1), .O(O1), .CIN(c), .COUT(COUT));
+
+endmodule
diff --git a/tests/carry/cblock/cblock.sim.v b/tests/carry/cblock/cblock.sim.v
new file mode 100644
index 0000000..01411d1
--- /dev/null
+++ b/tests/carry/cblock/cblock.sim.v
@@ -0,0 +1,19 @@
+`default_nettype none
+
+(* blackbox *)
+module CBLOCK (
+	I,
+	O,
+	CIN,
+	COUT
+);
+	input wire [3:0] I;
+
+	output wire O;
+
+	(* carry="C" *)
+	input wire CIN;
+	(* carry="C" *)
+	output wire COUT;
+
+endmodule
diff --git a/tests/carry/cblock/golden.model.xml b/tests/carry/cblock/golden.model.xml
new file mode 100644
index 0000000..ddc1c17
--- /dev/null
+++ b/tests/carry/cblock/golden.model.xml
@@ -0,0 +1,12 @@
+<models xmlns:xi="http://www.w3.org/2001/XInclude">
+  <model name="cblock">
+    <input_ports>
+      <port name="CIN"/>
+      <port name="I"/>
+    </input_ports>
+    <output_ports>
+      <port name="COUT"/>
+      <port name="O"/>
+    </output_ports>
+  </model>
+</models>
diff --git a/tests/carry/cblock/golden.pb_type.xml b/tests/carry/cblock/golden.pb_type.xml
new file mode 100644
index 0000000..1acb889
--- /dev/null
+++ b/tests/carry/cblock/golden.pb_type.xml
@@ -0,0 +1,11 @@
+<?xml version='1.0' encoding='utf-8'?>
+<pb_type xmlns:xi="http://www.w3.org/2001/XInclude" blif_model=".subckt cblock" name="CBLOCK" num_pb="1">
+  <input name="CIN" num_pins="1">
+    <pack_pattern name="C" type="carry"/>
+  </input>
+  <input name="I" num_pins="4"/>
+  <output name="COUT" num_pins="1">
+    <pack_pattern name="C" type="carry"/>
+  </output>
+  <output name="O" num_pins="1"/>
+</pb_type>
diff --git a/tests/carry/golden.model.xml b/tests/carry/golden.model.xml
new file mode 100644
index 0000000..9c960ee
--- /dev/null
+++ b/tests/carry/golden.model.xml
@@ -0,0 +1,3 @@
+<models xmlns:xi="http://www.w3.org/2001/XInclude">
+  <xi:include href="cblock/cblock.model.xml" xpointer="xpointer(models/child::node())"/>
+</models>
diff --git a/tests/carry/golden.pb_type.xml b/tests/carry/golden.pb_type.xml
new file mode 100644
index 0000000..b420aa4
--- /dev/null
+++ b/tests/carry/golden.pb_type.xml
@@ -0,0 +1,81 @@
+<?xml version='1.0' encoding='utf-8'?>
+<pb_type xmlns:xi="http://www.w3.org/2001/XInclude" name="CARRY" num_pb="1">
+  <input name="CIN" num_pins="1"/>
+  <input name="I0" num_pins="4"/>
+  <input name="I1" num_pins="4"/>
+  <output name="COUT" num_pins="1"/>
+  <output name="O0" num_pins="1"/>
+  <output name="O1" num_pins="1"/>
+  <pb_type blif_model=".subckt cblock" name="cblock0" num_pb="1">
+    <xi:include href="cblock/cblock.pb_type.xml" xpointer="xpointer(pb_type/child::node())"/>
+  </pb_type>
+  <pb_type blif_model=".subckt cblock" name="cblock1" num_pb="1">
+    <xi:include href="cblock/cblock.pb_type.xml" xpointer="xpointer(pb_type/child::node())"/>
+  </pb_type>
+  <interconnect>
+    <direct>
+      <port name="CIN" type="input"/>
+      <port from="cblock0" name="CIN" type="output"/>
+      <pack_pattern name="C" type="carry">
+        <port name="CIN" type="input"/>
+        <port from="cblock0" name="CIN" type="output"/>
+      </pack_pattern>
+    </direct>
+    <direct>
+      <port name="I0[0]" type="input"/>
+      <port from="cblock0" name="I[0]" type="output"/>
+    </direct>
+    <direct>
+      <port name="I0[1]" type="input"/>
+      <port from="cblock0" name="I[1]" type="output"/>
+    </direct>
+    <direct>
+      <port name="I0[2]" type="input"/>
+      <port from="cblock0" name="I[2]" type="output"/>
+    </direct>
+    <direct>
+      <port name="I0[3]" type="input"/>
+      <port from="cblock0" name="I[3]" type="output"/>
+    </direct>
+    <direct>
+      <port from="cblock0" name="O" type="input"/>
+      <port name="O0" type="output"/>
+    </direct>
+    <direct>
+      <port from="cblock0" name="COUT" type="input"/>
+      <port from="cblock1" name="CIN" type="output"/>
+      <pack_pattern name="C" type="carry">
+        <port from="cblock0" name="COUT" type="input"/>
+        <port from="cblock1" name="CIN" type="output"/>
+      </pack_pattern>
+    </direct>
+    <direct>
+      <port name="I1[0]" type="input"/>
+      <port from="cblock1" name="I[0]" type="output"/>
+    </direct>
+    <direct>
+      <port name="I1[1]" type="input"/>
+      <port from="cblock1" name="I[1]" type="output"/>
+    </direct>
+    <direct>
+      <port name="I1[2]" type="input"/>
+      <port from="cblock1" name="I[2]" type="output"/>
+    </direct>
+    <direct>
+      <port name="I1[3]" type="input"/>
+      <port from="cblock1" name="I[3]" type="output"/>
+    </direct>
+    <direct>
+      <port from="cblock1" name="COUT" type="input"/>
+      <port name="COUT" type="output"/>
+      <pack_pattern name="C" type="carry">
+        <port from="cblock1" name="COUT" type="input"/>
+        <port name="COUT" type="output"/>
+      </pack_pattern>
+    </direct>
+    <direct>
+      <port from="cblock1" name="O" type="input"/>
+      <port name="O1" type="output"/>
+    </direct>
+  </interconnect>
+</pb_type>
diff --git a/tests/fig28-lutff-pair/ff/ff.sim.v b/tests/fig28-lutff-pair/ff/ff.sim.v
new file mode 100644
index 0000000..b979b9a
--- /dev/null
+++ b/tests/fig28-lutff-pair/ff/ff.sim.v
@@ -0,0 +1,16 @@
+(* blackbox *)
+module DFF (CLK, D, Q);
+
+	input wire CLK;
+
+	(* SETUP="CLK 10-12" *)
+	(* HOLD="CLK 10-12" *)
+	(* CLK_TO_Q="CLK 10e-12" *)
+	input wire D;
+
+	output reg Q;
+
+	always @ ( posedge CLK ) begin
+		Q <= D;
+	end
+endmodule
diff --git a/tests/fig28-lutff-pair/ff/golden.model.xml b/tests/fig28-lutff-pair/ff/golden.model.xml
new file mode 100644
index 0000000..3d65c6d
--- /dev/null
+++ b/tests/fig28-lutff-pair/ff/golden.model.xml
@@ -0,0 +1,12 @@
+<models xmlns:xi="http://www.w3.org/2001/XInclude">
+  <!-- https://docs.verilogtorouting.org/en/latest/tutorials/arch/timing_modeling/#sequential-block-no-internal-paths -->
+  <model name="dff">
+    <input_ports>
+      <port name="CLK" is_clock="1"/>
+      <port name="D" clock="CLK"/>
+    </input_ports>
+    <output_ports>
+      <port name="Q" clock="CLK"/>
+    </output_ports>
+  </model>
+</models>
diff --git a/tests/fig28-lutff-pair/ff/golden.pb_type.xml b/tests/fig28-lutff-pair/ff/golden.pb_type.xml
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/tests/fig28-lutff-pair/ff/golden.pb_type.xml
diff --git a/tests/fig28-lutff-pair/golden.model.xml b/tests/fig28-lutff-pair/golden.model.xml
new file mode 100644
index 0000000..c0d91d6
--- /dev/null
+++ b/tests/fig28-lutff-pair/golden.model.xml
@@ -0,0 +1,5 @@
+<models xmlns:xi="http://www.w3.org/2001/XInclude">
+  <xi:include href="ff/ff.model.xml" xpointer="xpointer(models/child::node())"/>
+  <xi:include href="lut/lut.model.xml" xpointer="xpointer(models/child::node())"/>
+  <xi:include href="omux/omux.model.xml" xpointer="xpointer(models/child::node())"/>
+</models>
diff --git a/tests/fig28-lutff-pair/golden.pb_type.xml b/tests/fig28-lutff-pair/golden.pb_type.xml
new file mode 100644
index 0000000..989255b
--- /dev/null
+++ b/tests/fig28-lutff-pair/golden.pb_type.xml
@@ -0,0 +1,59 @@
+<?xml version='1.0' encoding='utf-8'?>
+<pb_type xmlns:xi="http://www.w3.org/2001/XInclude" name="PAIR" num_pb="1">
+  <clock name="CLK" num_pins="1"/>
+  <input name="I" num_pins="4"/>
+  <output name="O" num_pins="1"/>
+  <pb_type blif_model=".subckt dff" name="ff" num_pb="1">
+    <xi:include href="ff/ff.pb_type.xml" xpointer="xpointer(pb_type/child::node())"/>
+  </pb_type>
+  <pb_type blif_model=".subckt lut4" name="lut" num_pb="1">
+    <xi:include href="lut/lut.pb_type.xml" xpointer="xpointer(pb_type/child::node())"/>
+  </pb_type>
+  <interconnect>
+    <direct>
+      <port name="CLK" type="input"/>
+      <port from="ff" name="CLK" type="output"/>
+    </direct>
+    <direct>
+      <port from="lut" name="O" type="input"/>
+      <port from="ff" name="D" type="output"/>
+      <pack_pattern name="LUT2FF" type="pack">
+        <port from="lut" name="O" type="input"/>
+        <port from="ff" name="D" type="output"/>
+      </pack_pattern>
+    </direct>
+    <direct>
+      <port name="I[0]" type="input"/>
+      <port from="lut" name="I[0]" type="output"/>
+    </direct>
+    <direct>
+      <port name="I[1]" type="input"/>
+      <port from="lut" name="I[1]" type="output"/>
+    </direct>
+    <direct>
+      <port name="I[2]" type="input"/>
+      <port from="lut" name="I[2]" type="output"/>
+    </direct>
+    <direct>
+      <port name="I[3]" type="input"/>
+      <port from="lut" name="I[3]" type="output"/>
+    </direct>
+    <mux name="mux">
+      <port from="lut" name="O" type="input">
+        <metadata>
+          <meta name="fasm_mux">L</meta>
+        </metadata>
+      </port>
+      <port from="ff" name="Q" type="input">
+        <metadata>
+          <meta name="fasm_mux">F</meta>
+        </metadata>
+      </port>
+      <port name="O" type="output"/>
+      <metadata>
+        <meta name="type">bel</meta>
+        <meta name="subtype">routing</meta>
+      </metadata>
+    </mux>
+  </interconnect>
+</pb_type>
diff --git a/tests/fig28-lutff-pair/lut/golden.model.xml b/tests/fig28-lutff-pair/lut/golden.model.xml
new file mode 100644
index 0000000..24d9513
--- /dev/null
+++ b/tests/fig28-lutff-pair/lut/golden.model.xml
@@ -0,0 +1,10 @@
+<models xmlns:xi="http://www.w3.org/2001/XInclude">
+  <model name="lut4">
+    <input_ports>
+      <port name="I"/>
+    </input_ports>
+    <output_ports>
+      <port name="O"/>
+    </output_ports>
+  </model>
+</models>
diff --git a/tests/fig28-lutff-pair/lut/golden.pb_type.xml b/tests/fig28-lutff-pair/lut/golden.pb_type.xml
new file mode 100644
index 0000000..a0e38d4
--- /dev/null
+++ b/tests/fig28-lutff-pair/lut/golden.pb_type.xml
@@ -0,0 +1,5 @@
+<?xml version='1.0' encoding='utf-8'?>
+<pb_type xmlns:xi="http://www.w3.org/2001/XInclude" blif_model=".subckt lut4" name="LUT4" num_pb="1">
+  <input name="I" num_pins="4"/>
+  <output name="O" num_pins="1"/>
+</pb_type>
diff --git a/tests/fig28-lutff-pair/lut/lut.sim.v b/tests/fig28-lutff-pair/lut/lut.sim.v
new file mode 100644
index 0000000..91bb0bc
--- /dev/null
+++ b/tests/fig28-lutff-pair/lut/lut.sim.v
@@ -0,0 +1,5 @@
+(* blackbox *)
+module LUT4 (I, O);
+	input wire [3:0] I;
+	output wire O;
+endmodule
diff --git a/tests/fig28-lutff-pair/pair.sim.v b/tests/fig28-lutff-pair/pair.sim.v
new file mode 100644
index 0000000..b5395d1
--- /dev/null
+++ b/tests/fig28-lutff-pair/pair.sim.v
@@ -0,0 +1,26 @@
+`include "lut/lut.sim.v"
+`include "ff/ff.sim.v"
+`include "omux/omux.sim.v"
+
+module PAIR (
+	I,
+	CLK,
+	O
+);
+	input wire [3:0] I;
+	input wire CLK;
+
+	output wire O;
+
+	(* pack="LUT2FF" *)
+	wire lut_out;
+
+	LUT4 lut (.I(I), .O(lut_out));
+
+	wire ff_out;
+	DFF ff (.CLK(CLK), .D(lut_out), .Q(ff_out));
+
+	parameter [0:0] FF_BYPASS = "";
+	OMUX #(.MODE(FF_BYPASS)) mux(.L(lut_out), .F(ff_out), .O(O));
+
+endmodule
diff --git a/tests/fig41-full-adder/adder.sim.v b/tests/fig41-full-adder/adder.sim.v
index fd80b6d..2088a77 100644
--- a/tests/fig41-full-adder/adder.sim.v
+++ b/tests/fig41-full-adder/adder.sim.v
@@ -5,6 +5,7 @@
 );
 	input wire a;
 	input wire b;
+	(* carry = "ADDER" *)
 	input wire cin;
 
 	(* DELAY_CONST_a   = "300e-12" *)
@@ -12,6 +13,7 @@
 	(* DELAY_CONST_cin = "300e-12" *)
 	output wire sum;
 
+	(* carry = "ADDER" *)
 	(* DELAY_CONST_a   = "300e-12" *)
 	(* DELAY_CONST_b   = "300e-12" *)
 	(* DELAY_CONST_cin =  "10e-12" *)
diff --git a/tests/logicbox/golden.model.xml b/tests/logicbox/golden.model.xml
new file mode 100644
index 0000000..93513b5
--- /dev/null
+++ b/tests/logicbox/golden.model.xml
@@ -0,0 +1,10 @@
+<models xmlns:xi="http://www.w3.org/2001/XInclude">
+  <model name="logicbox">
+    <input_ports>
+      <port name="I"/>
+    </input_ports>
+    <output_ports>
+      <port name="O"/>
+    </output_ports>
+  </model>
+</models>
diff --git a/tests/logicbox/golden.pb_type.xml b/tests/logicbox/golden.pb_type.xml
new file mode 100644
index 0000000..3aaf173
--- /dev/null
+++ b/tests/logicbox/golden.pb_type.xml
@@ -0,0 +1,5 @@
+<?xml version='1.0' encoding='utf-8'?>
+<pb_type xmlns:xi="http://www.w3.org/2001/XInclude" blif_model=".subckt logicbox" name="LOGICBOX" num_pb="1">
+  <input name="I" num_pins="1"/>
+  <output name="O" num_pins="1"/>
+</pb_type>
diff --git a/tests/logicbox/logicbox.sim.v b/tests/logicbox/logicbox.sim.v
new file mode 100644
index 0000000..a6eeeaf
--- /dev/null
+++ b/tests/logicbox/logicbox.sim.v
@@ -0,0 +1,5 @@
+(* blackbox *)
+module LOGICBOX (I, O);
+	input wire I;
+	output wire O;
+endmodule
diff --git a/tests/multiple_instance/golden.pb_type.xml b/tests/multiple_instance/golden.pb_type.xml
index 75334c1..93c5d8d 100644
--- a/tests/multiple_instance/golden.pb_type.xml
+++ b/tests/multiple_instance/golden.pb_type.xml
@@ -10,200 +10,206 @@
   <output name="cout" num_pins="4"/>
   <input  name="d"    num_pins="4"/>
   <output name="sum"  num_pins="8"/>
-  <pb_type blif_model=".subckt ADDER" name="adder" num_pb="8">
+  <pb_type name="comb_apb" num_pb="4">
+    <xi:include href="../fig41-full-adder/adder.pb_type.xml" xpointer="xpointer(pb_type/child::node())"/>
+  </pb_type>
+  <pb_type name="comb_cpd" num_pb="4">
     <xi:include href="../fig41-full-adder/adder.pb_type.xml" xpointer="xpointer(pb_type/child::node())"/>
   </pb_type>
   <interconnect>
 
     <!-- 1st - a+b -> sum -->
     <direct>
-      <port                 name="a[0]"   type="input"  />
-      <port from="adder[2]" name="a"      type="output" />
+      <port                    name="a[0]"   type="input"  />
+      <port from="comb_apb[0]" name="a"      type="output" />
     </direct>
     <direct>
-      <port                 name="b[0]"   type="input"  />
-      <port from="adder[2]" name="b"      type="output" />
+      <port                    name="b[0]"   type="input"  />
+      <port from="comb_apb[0]" name="b"      type="output" />
     </direct>
     <direct>
-      <port from="adder[2]" name="sum"    type="input"  />
-      <port                 name="sum[0]" type="output" />
+      <port from="comb_apb[0]" name="sum"    type="input"  />
+      <port                    name="sum[0]" type="output" />
     </direct>
 
     <!-- 2nd - a+b -> sum -->
     <direct>
-      <port                 name="a[1]"   type="input"  />
-      <port from="adder[4]" name="a"      type="output" />
+      <port                    name="a[1]"   type="input"  />
+      <port from="comb_apb[1]" name="a"      type="output" />
     </direct>
     <direct>
-      <port                 name="b[1]"   type="input"  />
-      <port from="adder[4]" name="b"      type="output" />
+      <port                    name="b[1]"   type="input"  />
+      <port from="comb_apb[1]" name="b"      type="output" />
     </direct>
     <direct>
-      <port from="adder[4]" name="sum"    type="input"  />
-      <port                 name="sum[1]" type="output" />
+      <port from="comb_apb[1]" name="sum"    type="input"  />
+      <port                    name="sum[1]" type="output" />
     </direct>
 
     <!-- 3rd - a+b -> sum -->
     <direct>
-      <port                 name="a[2]"   type="input"/>
-      <port from="adder[6]" name="a"      type="output"/>
+      <port                    name="a[2]"   type="input"/>
+      <port from="comb_apb[2]" name="a"      type="output"/>
     </direct>
     <direct>
-      <port                 name="b[2]"   type="input"/>
-      <port from="adder[6]" name="b"      type="output"/>
+      <port                    name="b[2]"   type="input"/>
+      <port from="comb_apb[2]" name="b"      type="output"/>
     </direct>
     <direct>
-      <port from="adder[6]" name="sum"    type="input"/>
-      <port                 name="sum[2]" type="output"/>
+      <port from="comb_apb[2]" name="sum"    type="input"/>
+      <port                    name="sum[2]" type="output"/>
     </direct>
 
     <!-- 4th - a+b -> sum -->
     <direct>
-      <port                 name="a[3]"   type="input"  />
-      <port from="adder[0]" name="a"      type="output" />
+      <port                    name="a[3]"   type="input"  />
+      <port from="comb_apb[3]" name="a"      type="output" />
     </direct>
     <direct>
-      <port                 name="b[3]"   type="input"  />
-      <port from="adder[0]" name="b"      type="output" />
+      <port                    name="b[3]"   type="input"  />
+      <port from="comb_apb[3]" name="b"      type="output" />
     </direct>
     <direct>
-      <port from="adder[0]" name="sum"    type="input"  />
-      <port                 name="sum[3]" type="output" />
+      <port from="comb_apb[3]" name="sum"    type="input"  />
+      <port                    name="sum[3]" type="output" />
     </direct>
 
     <!-- 1st - c+d -> sum -->
     <direct>
-      <port                 name="c[0]"   type="input"/>
-      <port from="adder[3]" name="a"      type="output"/>
+      <port                    name="c[0]"   type="input"/>
+      <port from="comb_cpd[0]" name="a"      type="output"/>
     </direct>
     <direct>
-      <port                 name="d[0]"   type="input"/>
-      <port from="adder[3]" name="b"      type="output"/>
+      <port                    name="d[0]"   type="input"/>
+      <port from="comb_cpd[0]" name="b"      type="output"/>
     </direct>
     <direct>
-      <port from="adder[3]" name="sum"    type="input"/>
-      <port                 name="sum[4]" type="output"/>
+      <port from="comb_cpd[0]" name="sum"    type="input"/>
+      <port                    name="sum[4]" type="output"/>
     </direct>
 
     <!-- 2nd - c+d -> sum -->
     <direct>
-      <port                 name="c[1]"   type="input"/>
-      <port from="adder[5]" name="a"      type="output"/>
+      <port                    name="c[1]"   type="input"/>
+      <port from="comb_cpd[1]" name="a"      type="output"/>
     </direct>
     <direct>
-      <port                 name="d[1]"   type="input"/>
-      <port from="adder[5]" name="b"      type="output"/>
+      <port                    name="d[1]"   type="input"/>
+      <port from="comb_cpd[1]" name="b"      type="output"/>
     </direct>
     <direct>
-      <port from="adder[5]" name="sum"    type="input"/>
-      <port                 name="sum[5]" type="output"/>
+      <port from="comb_cpd[1]" name="sum"    type="input"/>
+      <port                    name="sum[5]" type="output"/>
     </direct>
 
     <!-- 3rd - c+d -> sum -->
     <direct>
-      <port                 name="c[2]"   type="input"/>
-      <port from="adder[7]" name="a"      type="output"/>
+      <port                    name="c[2]"   type="input"/>
+      <port from="comb_cpd[2]" name="a"      type="output"/>
     </direct>
     <direct>
-      <port                 name="d[2]"   type="input"/>
-      <port from="adder[7]" name="b"      type="output"/>
+      <port                    name="d[2]"   type="input"/>
+      <port from="comb_cpd[2]" name="b"      type="output"/>
     </direct>
     <direct>
-      <port from="adder[7]" name="sum"    type="input"/>
-      <port                 name="sum[6]" type="output"/>
+      <port from="comb_cpd[2]" name="sum"    type="input"/>
+      <port                    name="sum[6]" type="output"/>
     </direct>
 
     <!-- 4th - c+d -> sum -->
     <direct>
-      <port                 name="c[3]"   type="input"/>
-      <port from="adder[1]" name="a"      type="output"/>
+      <port                    name="c[3]"   type="input"/>
+      <port from="comb_cpd[3]" name="a"      type="output"/>
     </direct>
     <direct>
-      <port                 name="d[3]"   type="input"/>
-      <port from="adder[1]" name="b"      type="output"/>
+      <port                    name="d[3]"   type="input"/>
+      <port from="comb_cpd[3]" name="b"      type="output"/>
     </direct>
     <direct>
-      <port from="adder[1]" name="sum"    type="input"/>
-      <port                 name="sum[7]" type="output"/>
+      <port from="comb_cpd[3]" name="sum"    type="input"/>
+      <port                    name="sum[7]" type="output"/>
     </direct>
 
     <!-- Carry chains -->
 
     <!-- FIXME: Hack until carries work -->
     <direct>
-      <port from="adder[2]" name="cout"   type="input"  />
-      <port                 name="a2b[0]" type="output" />
+      <port from="comb_apb[0]" name="cout"   type="input"  />
+      <port                    name="a2b[0]" type="output" />
     </direct>
     <direct>
-      <port from="adder[4]" name="cout"   type="input"  />
-      <port                 name="a2b[1]" type="output" />
+      <port from="comb_apb[1]" name="cout"   type="input"  />
+      <port                    name="a2b[1]" type="output" />
     </direct>
     <direct>
-      <port from="adder[6]" name="cout"   type="input"  />
-      <port                 name="a2b[2]" type="output" />
+      <port from="comb_apb[2]" name="cout"   type="input"  />
+      <port                    name="a2b[2]" type="output" />
     </direct>
     <direct>
-      <port from="adder[0]" name="cout"    type="input"  />
-      <port                 name="a2b[3]"  type="output" />
+      <port from="comb_apb[3]" name="cout"    type="input"  />
+      <port                    name="a2b[3]"  type="output" />
     </direct>
 
 
     <!-- cin -> 1st a+b -> 1st c+d -> cout -->
     <direct>
-      <port                 name="cin[0]"  type="input"  />
-      <port from="adder[2]" name="cin"     type="output" />
+      <port                    name="cin[0]"  type="input"  />
+      <port from="comb_apb[0]" name="cin"     type="output" />
     </direct>
     <direct>
-      <port from="adder[2]" name="cout"    type="input"  />
-      <port from="adder[3]" name="cin"     type="output" />
+      <port from="comb_apb[0]" name="cout"    type="input"  />
+      <port from="comb_cpd[0]" name="cin"     type="output" />
+      <pack_pattern name="carry-ADDER" />
     </direct>
     <direct>
-      <port from="adder[3]" name="cout"    type="input"  />
-      <port                 name="cout[0]" type="output" />
+      <port from="comb_cpd[0]" name="cout"    type="input"  />
+      <port                    name="cout[0]" type="output" />
     </direct>
 
     <!-- cin -> 2nd a+b -> 2nd c+d -> cout -->
     <direct>
-      <port                 name="cin[1]"  type="input"  />
-      <port from="adder[4]" name="cin"     type="output" />
+      <port                    name="cin[1]"  type="input"  />
+      <port from="comb_apb[1]" name="cin"     type="output" />
     </direct>
     <direct>
-      <port from="adder[4]" name="cout"    type="input"  />
-      <port from="adder[5]" name="cin"     type="output" />
+      <port from="comb_apb[1]" name="cout"    type="input"  />
+      <port from="comb_cpd[1]" name="cin"     type="output" />
+      <pack_pattern name="carry-ADDER" />
     </direct>
     <direct>
-      <port from="adder[5]" name="cout"    type="input"  />
-      <port                 name="cout[1]" type="output" />
+      <port from="comb_cpd[1]" name="cout"    type="input"  />
+      <port                    name="cout[1]" type="output" />
     </direct>
 
     <!-- cin -> 3rd a+b -> 3rd c+d -> cout -->
     <direct>
-      <port                 name="cin[2]"  type="input"  />
-      <port from="adder[6]" name="cin"     type="output" />
+      <port                    name="cin[2]"  type="input"  />
+      <port from="comb_apb[2]" name="cin"     type="output" />
     </direct>
     <direct>
-      <port from="adder[6]" name="cout"    type="input"  />
-      <port from="adder[7]" name="cin"     type="output" />
+      <port from="comb_apb[2]" name="cout"    type="input"  />
+      <port from="comb_cpd[2]" name="cin"     type="output" />
+      <pack_pattern name="carry-ADDER" />
     </direct>
     <direct>
-      <port from="adder[7]" name="cout"    type="input"  />
-      <port                 name="cout[2]" type="output" />
+      <port from="comb_cpd[2]" name="cout"    type="input"  />
+      <port                    name="cout[2]" type="output" />
     </direct>
 
     <!-- cin -> 4th a+b -> 4th c+d -> cout -->
     <direct>
-      <port                 name="cin[3]"  type="input"  />
-      <port from="adder[0]" name="cin"     type="output" />
+      <port                    name="cin[3]"  type="input"  />
+      <port from="comb_apb[3]" name="cin"     type="output" />
     </direct>
     <direct>
-      <port from="adder[0]" name="cout"    type="input"  />
-      <port from="adder[1]" name="cin"     type="output" />
+      <port from="comb_apb[3]" name="cout"    type="input"  />
+      <port from="comb_cpd[3]" name="cin"     type="output" />
+      <pack_pattern name="carry-ADDER" />
     </direct>
     <direct>
-      <port from="adder[1]" name="cout"    type="input"  />
-      <port                 name="cout[3]" type="output" />
+      <port from="comb_cpd[3]" name="cout"    type="input"  />
+      <port                    name="cout[3]" type="output" />
     </direct>
 
-
   </interconnect>
 </pb_type>
diff --git a/tests/muxes/golden.model.xml b/tests/muxes/golden.model.xml
new file mode 100644
index 0000000..cfc9bc9
--- /dev/null
+++ b/tests/muxes/golden.model.xml
@@ -0,0 +1,4 @@
+<models xmlns:xi="http://www.w3.org/2001/XInclude">
+  <xi:include href="routing/rmux.model.xml" xpointer="xpointer(models/child::node())"/>
+  <xi:include href="../logicbox/logicbox.model.xml" xpointer="xpointer(models/child::node())"/>
+</models>
diff --git a/tests/muxes/golden.pb_type.xml b/tests/muxes/golden.pb_type.xml
new file mode 100644
index 0000000..c3b9440
--- /dev/null
+++ b/tests/muxes/golden.pb_type.xml
@@ -0,0 +1,65 @@
+<?xml version='1.0' encoding='utf-8'?>
+<pb_type xmlns:xi="http://www.w3.org/2001/XInclude" name="USE_MUX" num_pb="1">
+  <input name="a" num_pins="1"/>
+  <input name="b" num_pins="1"/>
+  <input name="c" num_pins="1"/>
+  <output name="o1" num_pins="1"/>
+  <output name="o2" num_pins="1"/>
+  <pb_type blif_model=".subckt logicbox" name="lboxa" num_pb="1">
+    <xi:include href="../logicbox/logicbox.pb_type.xml" xpointer="xpointer(pb_type/child::node())"/>
+  </pb_type>
+  <pb_type blif_model=".subckt logicbox" name="lboxb" num_pb="1">
+    <xi:include href="../logicbox/logicbox.pb_type.xml" xpointer="xpointer(pb_type/child::node())"/>
+  </pb_type>
+  <pb_type blif_model=".subckt logicbox" name="lboxc" num_pb="1">
+    <xi:include href="../logicbox/logicbox.pb_type.xml" xpointer="xpointer(pb_type/child::node())"/>
+  </pb_type>
+  <interconnect>
+    <direct>
+      <port name="a" type="input"/>
+      <port from="lboxa" name="I" type="output"/>
+    </direct>
+    <direct>
+      <port name="b" type="input"/>
+      <port from="lboxb" name="I" type="output"/>
+    </direct>
+    <direct>
+      <port name="c" type="input"/>
+      <port from="lboxc" name="I" type="output"/>
+    </direct>
+    <mux name="mux1">
+      <port from="lboxa" name="O" type="input">
+        <metadata>
+          <meta name="fasm_mux">I0</meta>
+        </metadata>
+      </port>
+      <port from="lboxb" name="O" type="input">
+        <metadata>
+          <meta name="fasm_mux">I1</meta>
+        </metadata>
+      </port>
+      <port name="o1" type="output"/>
+      <metadata>
+        <meta name="type">bel</meta>
+        <meta name="subtype">routing</meta>
+      </metadata>
+    </mux>
+    <mux name="mux2">
+      <port from="lboxa" name="O" type="input">
+        <metadata>
+          <meta name="fasm_mux">I0</meta>
+        </metadata>
+      </port>
+      <port from="lboxc" name="O" type="input">
+        <metadata>
+          <meta name="fasm_mux">I1</meta>
+        </metadata>
+      </port>
+      <port name="o2" type="output"/>
+      <metadata>
+        <meta name="type">bel</meta>
+        <meta name="subtype">routing</meta>
+      </metadata>
+    </mux>
+  </interconnect>
+</pb_type>
diff --git a/tests/muxes/proper.golden.pb_type.xml b/tests/muxes/proper.golden.pb_type.xml
new file mode 100644
index 0000000..a01c26a
--- /dev/null
+++ b/tests/muxes/proper.golden.pb_type.xml
@@ -0,0 +1,28 @@
+<?xml version='1.0' encoding='utf-8'?>
+<pb_type xmlns:xi="http://www.w3.org/2001/XInclude" name="use_mux" num_pb="1">
+  <input name="a" num_pins="1"/>
+  <input name="b" num_pins="1"/>
+  <input name="cin" num_pins="1"/>
+  <output name="cout" num_pins="1"/>
+  <pb_type name="AMUX" num_pb="1">
+    <xi:include href="routing/amux.pb_type.xml" xpointer="xpointer(pb_type/child::node())"/>
+  </pb_type>
+  <interconnect>
+    <direct>
+      <port name="a" type="input"/>
+      <port from="AMUX" name="A1" type="output"/>
+    </direct>
+    <direct>
+      <port name="b" type="input"/>
+      <port from="AMUX" name="B2" type="output"/>
+    </direct>
+    <direct>
+      <port name="cin" type="input"/>
+      <port from="AMUX" name="C3" type="output"/>
+    </direct>
+    <direct>
+      <port from="AMUX" name="O" type="input"/>
+      <port name="cout" type="output"/>
+    </direct>
+  </interconnect>
+</pb_type>
diff --git a/tests/muxes/use_mux.sim.v b/tests/muxes/use_mux.sim.v
new file mode 100644
index 0000000..9ba59b0
--- /dev/null
+++ b/tests/muxes/use_mux.sim.v
@@ -0,0 +1,22 @@
+`include "routing/rmux.sim.v"
+`include "../logicbox/logicbox.sim.v"
+module USE_MUX (a, b, c, o1, o2);
+	input wire a;
+	input wire b;
+	input wire c;
+	output wire o1;
+	output wire o2;
+
+	wire logic_a;
+	wire logic_b;
+	wire logic_c;
+	LOGICBOX lboxa (.I(a), .O(logic_a));
+	LOGICBOX lboxb (.I(b), .O(logic_b));
+	LOGICBOX lboxc (.I(c), .O(logic_c));
+
+	parameter FASM_MUX1 = "I0";
+	RMUX #(.MODE(FASM_MUX1)) mux1 (.I0(logic_a), .I1(logic_b), .O(o1));
+
+	parameter FASM_MUX2 = "I0";
+	RMUX #(.MODE(FASM_MUX2)) mux2 (.I0(logic_a), .I1(logic_c), .O(o2));
+endmodule
diff --git a/vlog_to_model.py b/vlog_to_model.py
index 72ddfa8..c286048 100755
--- a/vlog_to_model.py
+++ b/vlog_to_model.py
@@ -193,7 +193,9 @@
     modclass = tmod.attr("CLASS", "")
 
     if modclass not in ("lut", "routing", "flipflop"):
-        model_xml = ET.SubElement(models_xml, "model", {'name': topname})
+        model_xml = ET.SubElement(
+            models_xml, "model", {'name': topname}
+        )
         ports = tmod.ports
 
         inports_xml = ET.SubElement(model_xml, "input_ports")
diff --git a/vlog_to_pbtype.py b/vlog_to_pbtype.py
index 401faa8..86120d3 100755
--- a/vlog_to_pbtype.py
+++ b/vlog_to_pbtype.py
@@ -28,8 +28,7 @@
 
     - `(* CLK_TO_Q="clk 10e-12" *)` : specify clock-to-output time for a given clock
 
-    - `(* DELAY_CONST_{input}="30e-12" *)` : specify a constant max delay from an input,
-       applied to the output
+    - `(* DELAY_CONST_{input}="30e-12" *)` : specify a constant max delay from an input (applied to the output)
 
     - `(* DELAY_MATRIX_{input}="30e-12 35e-12; 20e-12 25e-12; ..." *)` : specify a VPR
         delay matrix (semicolons indicate rows). In this format columns specify
@@ -45,23 +44,23 @@
 The Verilog define "PB_TYPE" is set during generation.
 """
 
-import argparse
-import os
-import re
-import sys
+import os, sys
+import argparse, re
+
+from typing import List, Dict, Tuple
+from collections import defaultdict
 
 import lxml.etree as ET
 
 import yosys.run
 from yosys.json import YosysJSON
 
+sys.path.insert(0, "..")
 from lib import xmlinc
 
-INVALID_INSTANCE = -1
-
 
 def is_mod_blackbox(mod):
-    """ Returns true if module is annotated with blackbox (or equivilant).
+    """ Returns true if module is annotated with blackbox (or equivalent).
 
     Yosys supports 3 attributes that denote blackbox behavior:
 
@@ -77,228 +76,541 @@
            (mod.attr("blackbox", 0) == 1)
 
 
-def mod_pb_name(mod):
-    """Convert a Verilog module to a pb_type name in the format documented here:
-    https://github.com/SymbiFlow/symbiflow-arch-defs/#names"""
-
-    modes = mod.attr("MODES", None)
-    has_modes = modes is not None
-    # Process type and class of module
-    mod_cls = mod.CLASS
-    if mod_cls == "routing":
-        return mod.name
-    elif mod_cls == "mux":
-        return mod.name
-    elif mod_cls == "flipflop":
-        return mod.name
-    elif mod_cls == "lut":
-        return mod.name
-    elif is_mod_blackbox(mod) and not has_modes:
-        return mod.name
-    else:
-        # TODO: other types
-        return mod.name
+# $genblock$/vlog/tests/multiple_instance/multiple_instance.sim.v:12$64[57].\comb
+GENBLOCK_REGEX = re.compile(
+    "^\\$genblock\\$.*:[0-9]+\\$[0-9]+\\[(.*)\\]\\.\\\\(.*)"
+)
 
 
-def strip_name(name):
-    if '\\' in name:
-        ts = name.find('\\')
-        tf = name.rfind('\\')
-        return name[ts + 1:tf]
+def strip_name(name: str, include_index=True) -> str:
+    """Convert generate block into normal array form.
+
+    >>> n = r"$genblock$/vlog/tests/multiple_instance/multiple_instance.sim.v:12$64[57].\comb"
+    >>> strip_name(n)
+    'comb[57]'
+    >>> strip_name(n, False)
+    'comb'
+    >>> n = r"$genblock$/vlog/tests/multiple_instance/multiple_instance.sim.v:15$10[3].\\comba"
+    >>> strip_name(n)
+    'comba[3]'
+    """
+    if name.startswith('$genblock$'):
+        index, name = GENBLOCK_REGEX.match(name).groups()
+        if include_index:
+            return "{}[{}]".format(name, index)
+        else:
+            return name
     return name
 
 
-def make_pb_content(outfile, yj, 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>."""
+CellName = str
+CellType = str
+PinName = str
+CellPin = Tuple[CellName, PinName]
 
-    def get_module_name(pin, instance=INVALID_INSTANCE):
-        """Returns the name of the module relative to the pin and a boolean that indicates whether
-        the module is a cell (True) or the top one (False)"""
-        if instance <= INVALID_INSTANCE:
-            instance = ""
-        else:
-            instance = "[" + str(instance) + "]"
-        cname, cellpin = pin
-        if cname.startswith("$"):
-            return mod.cell_type(cname) + instance, True
-        elif cname != mod.name:
-            cname = mod.cell_type(cname)
-            modname = mod_pb_name(yj.module(cname)) + instance
-            return modname, True
-        else:
-            return mod_pname, False
 
-    def get_cellpin(pin):
-        cname, cellpin = pin
-        return cellpin
+def create_port(
+        dir_xml: ET.Element, cell_pin: CellPin, direction: str, metadata=None
+) -> ET.Element:
+    cell_name, pin_name = cell_pin
+    port = dict()
+    port['name'] = pin_name
+    port['type'] = direction
+    if cell_name:
+        port['from'] = cell_name
+    port_xml = ET.SubElement(dir_xml, 'port', port)
 
-    def create_port(pin_name, mod_name, is_cell, direction):
-        """Returns a dictionary containing the port definition. If the module is a cell, the port
-        contains the 'from' attribute."""
-        port = dict()
-        port['name'] = pin_name
-        port['type'] = direction
+    if metadata:
+        meta_root = ET.SubElement(port_xml, "metadata")
+        for name, value in metadata.items():
+            meta_type = ET.SubElement(meta_root, 'meta', {'name': name})
+            meta_type.text = value
 
-        if is_cell:
-            port['from'] = mod_name.lower()
+    return port_xml
 
-        return port
 
-    def make_direct_conn(
-            ic_xml,
-            src,
-            dst,
-            source_instance=INVALID_INSTANCE,
-            dest_instance=INVALID_INSTANCE
-    ):
-        s_cellpin = get_cellpin(src)
-        d_cellpin = get_cellpin(dst)
-        s_cname, s_is_cell = get_module_name(src, source_instance)
-        d_cname, d_is_cell = get_module_name(dst, dest_instance)
+def copy_attrs(dst, srcs):
+    # Find attributes which are on all srcs dictionaries
+    all_have = []
+    for attr in set(sum((list(s.keys()) for s in srcs), [])):
+        if len(srcs) != sum(bool(attr in s) for s in srcs):
+            continue
+        all_have.append(attr)
 
-        s_port = create_port(s_cellpin, s_cname, s_is_cell, "input")
-        d_port = create_port(d_cellpin, d_cname, d_is_cell, "output")
+    for attr in all_have:
+        avalue = srcs[0][attr]
+        avalues = [s[attr] for s in srcs[1:]]
 
-        dir_xml = ET.SubElement(ic_xml, 'direct')
-
-        ET.SubElement(dir_xml, 'port', s_port)
-        ET.SubElement(dir_xml, 'port', d_port)
-
-    # Find out whether or not the module we are generating content for is a blackbox
-    is_blackbox = is_mod_blackbox(mod) or not mod.cells
-
-    # List of entries in format ((from_cell, from_pin), (to_cell, to_pin))
-    interconn = []
-
-    # Determine multiple instances of the same cell:
-    cells = dict()
-    for cname, i_of in mod.cells:
-        if i_of in cells:
-            cells[i_of]['count'] += 1
-            cells[i_of]['is_multi_instance'] = True
-            # assign unique instance number
-            cells[i_of][cname] = cells[i_of]['count']
-        else:
-            cells[i_of] = dict()
-            cells[i_of]['is_multi_instance'] = False
-            cells[i_of]['count'] = 0
-            cells[i_of][cname] = 0
-
-    # Blackbox modules don't have inner cells or interconnect (but do still have timing)
-    if (not is_blackbox) or is_submode:
-        # Process cells. First build the list of cnames.
-        processed_cells = list()
-        for cname, i_of in mod.cells:
-            pb_name = strip_name(i_of).lower()
-            pbtype_already_included = False
-            if i_of in processed_cells:
-                # do not emit xml include for every instance of multi instace cell
-                pbtype_already_included = True
-            else:
-                processed_cells.append(i_of)
-            instance = INVALID_INSTANCE
-
-            # If currently considered cell is a multi instance one, pass it's unique
-            # instance number to connection creator. If not, pass INVALID_INSTANCE
-            # constant
-            if cells[i_of]['is_multi_instance']:
-                instance = cells[i_of][cname]
-            module_file = yj.get_module_file(i_of)
-            module_path = os.path.dirname(module_file)
-            module_basename = os.path.basename(module_file)
-
-            # Heuristic for autogenerated files from w.py
-            if not pbtype_already_included:
-                wm = re.match(r"([A-Za-z0-9_]+)\.sim\.v", module_basename)
-                if wm:
-                    pb_type_path = "{}/{}.pb_type.xml".format(
-                        module_path,
-                        wm.group(1).lower()
-                    )
-                else:
-                    pb_type_path = "{}/pb_type.xml".format(module_path)
-
-                # inlude contents of the included pb_type, but update it's
-                # num_pb value
-                inc_attrib = {}
-                inc_attrib['name'] = pb_name
-                inc_attrib['num_pb'] = str(cells[i_of]['count'] + 1)
-
-                inc_pb_type = ET.SubElement(xml_parent, 'pb_type', inc_attrib)
-                xmlinc.include_xml(
-                    parent=inc_pb_type,
-                    href=pb_type_path,
-                    outfile=outfile,
-                    xptr="xpointer(pb_type/child::node())"
-                )
-
-            # 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 - or all outputs if "mode" is used.
-            inp_cons = mod.cell_conns(cname, "input")
-            for pin, net in inp_cons:
-                drvs = mod.net_drivers(net)
-                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:
-                    print(pin, net, drv_cell, drv_pin)
-                    # check if we're driven by multi instance cell
-                    drive_instance = INVALID_INSTANCE
-                    drv_cell_type = [
-                        c[1] for c in mod.cells if c[0] == drv_cell
-                    ]
-                    if len(drv_cell_type) != 0:
-                        drv_cell_type = drv_cell_type[0]
-                        if cells[drv_cell_type]['is_multi_instance']:
-                            # get drv_cell unique instance number
-                            drive_instance = cells[drv_cell_type][drv_cell]
-                    interconn.append(
-                        (
-                            (drv_cell, drv_pin), (cname, pin), drive_instance,
-                            instance
-                        )
-                    )
-
-            out_cons = mod.cell_conns(cname, "output")
-            for pin, net in out_cons:
-                sinks = mod.net_sinks(net)
-                for sink_cell, sink_pin in sinks:
-                    if sink_cell != mod.name:
-                        continue
-                    # Only consider outputs from cell to top level IO. Inputs to
-                    # other cells will be dealt with in those cells.
-                    interconn.append(
-                        (
-                            (cname, pin), (sink_cell, sink_pin), instance,
-                            INVALID_INSTANCE
-                        )
-                    )
-
-        # Direct pin->pin connections
-        for net in mod.nets:
-            drv = mod.conn_io(net, "input")
-            if not drv:
+        for other_avalue in avalues:
+            if avalue == other_avalue:
                 continue
-            assert len(drv) == 1, (
-                "ERROR: net {} has multiple drivers {}, interconnect will be over specified"
-                .format(net, drv)
+            raise ValueError('{} values: {}'.format(attr, [avalue] + avalues))
+
+        if attr in dst:
+            assert avalue == dst[attr]
+            raise ValueError(
+                '{} on net has value {} but pins have {}'.format(
+                    attr, dst[attr], avalue
+                )
             )
-            for snk in mod.conn_io(net, "output"):
-                conn = ((mod.name, drv[0]), (mod.name, snk))
-                interconn.append(conn)
+        dst[attr] = avalue
 
-        ic_xml = ET.SubElement(xml_parent, "interconnect")
-        # Process interconnect
-        for source, dest, src_instance, dst_instance in interconn:
-            make_direct_conn(ic_xml, source, dest, src_instance, dst_instance)
 
+def net_and_pin_attrs(yj, mod, driver: CellPin, sink: CellPin, netid: int):
+    def filter_src(x):
+        d = {}
+        for k, v in x.items():
+            if k == 'src':
+                continue
+            d[k] = v
+        return d
+
+    potential_attrs = []
+
+    driver_cell, driver_pin = driver
+    driver_type = mod.cell_type(driver_cell)
+    if driver_type != None:
+        dmod = yj.module(driver_type)
+        potential_attrs.append(filter_src(dmod.port_attrs(driver_pin)))
+
+    sink_cell, sink_pin = sink
+    sink_attrs = {}
+    sink_type = mod.cell_type(sink_cell)
+    if sink_type != None:
+        smod = yj.module(sink_type)
+        potential_attrs.append(filter_src(smod.port_attrs(sink_pin)))
+
+    net_attrs = filter_src(mod.net_attrs(mod.net_name(netid)))
+    copy_attrs(net_attrs, potential_attrs)
+    return net_attrs
+
+
+def make_direct_conn(
+        ic_xml: ET.Element, driver: CellPin, sink: CellPin, path_attr: dict
+) -> ET.Element:
+    dir_xml = ET.SubElement(ic_xml, 'direct')
+    create_port(dir_xml, driver, "input")
+    create_port(dir_xml, sink, "output")
+
+    pack_name = path_attr.get('pack', False)
+    if pack_name:
+        pp_xml = ET.SubElement(
+            dir_xml, 'pack_pattern', {
+                'name': pack_name,
+                'type': 'pack'
+            }
+        )
+        create_port(pp_xml, driver, "input")
+        create_port(pp_xml, sink, "output")
+
+    carry_name = path_attr.get('carry', None)
+    if carry_name:
+        pp_xml = ET.SubElement(
+            dir_xml, 'pack_pattern', {
+                'name': carry_name,
+                'type': 'carry'
+            }
+        )
+        create_port(pp_xml, driver, "input")
+        create_port(pp_xml, sink, "output")
+
+    return dir_xml
+
+
+def make_mux_conn(
+        ic_xml: ET.Element, mux_name: str, mux_inputs: Dict[CellPin, CellPin],
+        mux_outputs: Dict[CellPin, List[CellPin]]
+) -> ET.Element:
+
+    ## <mux input="use_mux.a use_mux.b use_mux.cin" name="AMUX" output="use_mux.cout">
+    #mux_xml = ET.SubElement(
+    #    ic_xml,
+    #    "mux",
+    #    {
+    #        "input": " ".join("{}.{}".format(cell_name, cell_pin) for cell_name, cell_pin in mux_inputs.values()),
+    #        "name": mux_name,
+    #        "output": " ".join("{}.{}".format(cell_name, cell_pin) for cell_name, cell_pin in mux_outputs),
+    #    }
+    #)
+    ##  <metadata>
+    #meta_root = ET.SubElement(mux_xml, 'metadata')
+    ##    <meta name="type">bel</meta>
+    #meta_type = ET.SubElement(meta_root, 'meta', {'name': 'type'})
+    #meta_type.text = "bel"
+    ##    <meta name="subtype">routing</meta>
+    #meta_subtype = ET.SubElement(meta_root, 'meta', {'name': 'subtype'})
+    #meta_subtype.text = "routing"
+    ##    <meta name="fasm_mux">
+    ## use_mux.a = AMUX.A1
+    ## use_mux.b = AMUX.B2
+    ## use_mux.cin = AMUX.C3
+    ##    </meta>
+    #meta_fasm = ET.SubElement(meta_root, 'meta', {'name': 'fasm_mux'})
+    #meta_fasm.text = "\n" + "\n".join(
+    #        "{}.{} = {}.{}".format(cell_name, cell_pin, mux_name, mux_pin)
+    #        for mux_pin, (cell_name, cell_pin) in mux_inputs.items()) + "\n"
+
+    # <mux name="AMUX">
+    #   <port name
+    # </mux>
+    mux_xml = ET.SubElement(ic_xml, "mux", {"name": mux_name})
+    for mux_input, driver in mux_inputs.items():
+        mux_port = create_port(
+            mux_xml, driver, "input", metadata={'fasm_mux': mux_input}
+        )
+
+    assert len(mux_outputs) == 1, mux_outputs
+    for mux_pin, sinks in mux_outputs.items():
+        assert len(sinks) == 1, sinks
+        for sink_pin, path_attr in sinks:
+            create_port(mux_xml, sink_pin, "output")
+
+    #  <metadata>
+    meta_root = ET.SubElement(mux_xml, 'metadata')
+    #    <meta name="type">bel</meta>
+    meta_type = ET.SubElement(meta_root, 'meta', {'name': 'type'})
+    meta_type.text = "bel"
+    #    <meta name="subtype">routing</meta>
+    meta_subtype = ET.SubElement(meta_root, 'meta', {'name': 'subtype'})
+    meta_subtype.text = "routing"
+
+    return mux_xml
+
+
+def get_interconnects(yj, mod, mod_pname: str,
+                      valid_names) -> Dict[CellPin, List[CellPin]]:
+    """Get the connectivity of module.
+
+    Returns:
+        A dictionary containing with a list of sink pins for each driver pin.
+    """
+    interconn = defaultdict(list)
+    for cname, ctype in mod.cells:
+        pb_name = strip_name(cname)
+        assert pb_name in valid_names
+        if pb_name == mod_pname:
+            pb_name = None
+
+        # All interconnect going INTO a cell (top level or children).
+        inp_cons = mod.cell_conns(cname, "input")
+        for pin, net in inp_cons:
+            drvs = mod.net_drivers(net)
+            assert len(drvs) > 0, (
+                "ERROR: pin {}.{} has no driver, interconnect will be missing\n{}"
+                .format(cname, pin, mod)
+            )
+            assert len(drvs) < 2, (
+                "ERROR: pin {}.{} has multiple drivers, interconnect will be overspecified"
+                .format(cname, pin)
+            )
+            for drv_cell, drv_pin in drvs:
+                net_attr = net_and_pin_attrs(
+                    yj, mod, (drv_cell, drv_pin), (pb_name, pin), net
+                )
+
+                drv_cell_name = strip_name(drv_cell)
+                assert drv_cell_name in valid_names
+                if drv_cell_name == mod_pname:
+                    drv_cell_name = None
+                interconn[(drv_cell_name,
+                           drv_pin)].append(((pb_name, pin), net_attr))
+
+        # Only consider outputs from cell to top level IO.
+        # Inputs to other cells will be dealt with in those cells.
+        out_cons = mod.cell_conns(cname, "output")
+        for pin, net in out_cons:
+            sinks = mod.net_sinks(net)
+            for sink_cell, sink_pin in sinks:
+                if sink_cell != mod.name:
+                    continue
+                net_attr = net_and_pin_attrs(
+                    yj, mod, (pb_name, pin), (None, sink_pin), net
+                )
+                interconn[(pb_name, pin)].append(((None, sink_pin), net_attr))
+
+    import pprint
+    pprint.pprint(list(interconn.values()))
+
+    def pin_sort(p):
+        pin, attr = p
+        if pin[0] is None:
+            return ('', pin[1])
+        else:
+            return pin
+
+    for l in interconn.values():
+        l.sort(key=pin_sort)
+
+    return interconn
+
+
+def mode_interconnects(mod, mode_name) -> Dict[CellPin, List[CellPin]]:
+    interconn = {}
+    for name, width, bits, iodir in mod.ports:
+        if iodir == "input":
+            interconn[(None, name)] = [
+                (mode_name, name),
+            ]
+        else:
+            interconn[(mode_name, name)] = [
+                (None, name),
+            ]
+    return interconn
+
+
+CellPrefix = str
+ChildrenDict = Dict[CellPrefix, Tuple[CellType, List[CellName]]]
+
+
+def get_children(yj, mod) -> Tuple[ChildrenDict, ChildrenDict]:
+    routing = dict()
+    children = dict()
+    for cname, ctype in mod.cells:
+        # We currently special case routing muxes
+        cell = yj.module(ctype)
+        if cell.CLASS == "routing":
+            d = routing
+        else:
+            d = children
+        cname_prefix = strip_name(cname, False)
+        if cname_prefix not in children:
+            d[cname_prefix] = (ctype, [])
+        assert d[cname_prefix][
+            0
+        ] == ctype, "Type of {} with prefix {} doesn't match existing. Type: {}, existing: {}".format(
+            cname, cname_prefix, ctype, children[cname_prefix]
+        )
+        d[cname_prefix][-1].append(strip_name(cname))
+
+    for d in (routing, children):
+        for _, l in children.values():
+            if len(l) > 1:
+                l.sort()
+                _, _ = get_list_name_and_length(l)
+
+    return routing, children
+
+
+def get_cellname_from_shortname(shortname, mod):
+    for cname, ctype in mod.cells:
+        if shortname != strip_name(cname):
+            continue
+        return cname
+    raise NameError("No cell named {}".format(shortname))
+
+
+def get_list_name_and_length(l: List[str]) -> Tuple[str, int]:
+    """
+    >>> get_list_name_and_length(['i[{}]'.format(i) for i in range(10)])
+    ('i', 10)
+
+    Assertion failure on missing value
+    >>> get_list_name_and_length(['i[0]', 'i[2]'])
+    Traceback (most recent call last):
+        ...
+    AssertionError: index 1 expected: i[1] != actual: i[2]
+    ['i[0]', 'i[2]']
+
+    Assertion failure when not starting at zero
+    >>> get_list_name_and_length(['i[1]', 'i[2]'])
+    Traceback (most recent call last):
+        ...
+    AssertionError: index 0 expected: i[0] != actual: i[1]
+    ['i[1]', 'i[2]']
+
+    Assertion failure when duplicate values
+
+    >>> get_list_name_and_length(['i[0]', 'i[0]'])
+    Traceback (most recent call last):
+        ...
+    AssertionError: index 1 expected: i[1] != actual: i[0]
+    ['i[0]', 'i[0]']
+
+    >>> get_list_name_and_length(['i[0]', 'i[1]', 'i[1]'])
+    Traceback (most recent call last):
+        ...
+    AssertionError: index 2 expected: i[2] != actual: i[1]
+    ['i[0]', 'i[1]', 'i[1]']
+
+    >>> get_list_name_and_length(['i[0]', 'i[1]', 'i[1]', 'i[2]'])
+    Traceback (most recent call last):
+        ...
+    AssertionError: index 2 expected: i[2] != actual: i[1]
+    ['i[0]', 'i[1]', 'i[1]', 'i[2]']
+
+    Assertion failure on incorrect formatting
+    >>> get_list_name_and_length(['i{}'.format(i) for i in range(4)])
+    Traceback (most recent call last):
+        ...
+    AssertionError: No index brackets found in item 0: i0
+    ['i0', 'i1', 'i2', 'i3']
+
+    Allow square brackets in name
+    >>> get_list_name_and_length(['i[1][{}]'.format(i) for i in range(4)])
+    ('i[1]', 4)
+    """
+    if not l:
+        return True
+
+    assert '[' in l[0], "No index brackets found in item 0: {}\n{}".format(
+        l[0], l
+    )
+    list_name = l[0][:l[0].rfind('[')]
+    for i in range(0, len(l)):
+        expected_item = "{}[{}]".format(list_name, i)
+        assert expected_item == l[
+            i], "index {} expected: {} != actual: {}\n{}".format(
+                i, expected_item, l[i], l
+            )
+    return list_name, len(l)
+
+
+def make_ports(clocks, mod, pb_type_xml, only_type=None):
+    for name, width, bits, iodir in mod.ports:
+        ioattrs = {"name": name, "num_pins": str(width)}
+        pclass = mod.net_attr(name, "PORT_CLASS")
+        if pclass is not None:
+            ioattrs["port_class"] = pclass
+        if name in clocks:
+            if only_type and only_type != "clocks":
+                continue
+            port_xml = ET.SubElement(pb_type_xml, "clock", ioattrs)
+        elif iodir == "input":
+            if only_type and only_type != "inputs":
+                continue
+            port_xml = ET.SubElement(pb_type_xml, "input", ioattrs)
+        elif iodir == "output":
+            if only_type and only_type != "outputs":
+                continue
+            port_xml = ET.SubElement(pb_type_xml, "output", ioattrs)
+        else:
+            assert False, "bidirectional ports not supported in VPR pb_types"
+
+        port_attrs = mod.port_attrs(name)
+
+        carry_name = port_attrs.get('carry', None)
+        if carry_name:
+            ET.SubElement(
+                port_xml, 'pack_pattern', {
+                    'name': carry_name,
+                    'type': 'carry'
+                }
+            )
+
+
+def make_container_pb(
+        outfile, yj, mod, mod_pname, pb_type_xml, routing, children
+):
+    # Containers have to include children
+    # ------------------------------------------------------------
+    for child_prefix, (child_type, children_names) in children.items():
+        # Work out were the child pb_type file can be found
+        module_file = yj.get_module_file(child_type)
+        module_path = os.path.dirname(module_file)
+        module_basename = os.path.basename(module_file)
+        module_prefix = re.match(r"([A-Za-z0-9_]+)\.sim\.v",
+                                 module_basename).groups()[0]
+
+        pb_type_path = "{}/{}.pb_type.xml".format(module_path, module_prefix)
+
+        # Read the top level properties of the pb_type
+        with open(pb_type_path, 'r') as inc_xml:
+            xml_inc = ET.fromstring(inc_xml.read().encode('utf-8'))
+            inc_attrib = xml_inc.attrib
+            inc_attrib['name'] = child_prefix
+            inc_attrib['num_pb'] = str(len(children_names))
+
+        inc_pb_type = ET.SubElement(pb_type_xml, 'pb_type', inc_attrib)
+        xmlinc.include_xml(
+            parent=inc_pb_type,
+            href=pb_type_path,
+            outfile=outfile,
+            xptr="xpointer(pb_type/child::node())"
+        )
+
+    # Contains need interconnect to their children
+    # ------------------------------------------------------------
+    # Work out valid names for cells to sanity check the interconnects.
+    valid_names = [mod_pname]
+
+    routing_cells = []
+    for _, routing_names in routing.values():
+        routing_cells.extend(routing_names)
+    valid_names.extend(routing_cells)
+
+    for _, children_names in children.values():
+        valid_names.extend(children_names)
+
+    # Extract the interconnect from the module
+    interconn = get_interconnects(yj, mod, mod_pname, valid_names)
+    import pprint
+    print(mod_pname)
+    print("--")
+    pprint.pprint(interconn)
+    print("--")
+    print(routing_cells)
+    pprint.pprint(routing)
+    print("--")
+
+    # Generate the actual interconnect
+    ic_xml = ET.SubElement(pb_type_xml, "interconnect")
+    for (driver_cell, driver_pin), sinks in interconn.items():
+        if driver_cell in routing_cells:
+            continue
+        for (sink_cell, sink_pin), path_attr in sinks:
+            if sink_cell in routing_cells:
+                continue
+            make_direct_conn(
+                ic_xml, (driver_cell, driver_pin), (sink_cell, sink_pin),
+                path_attr
+            )
+
+    # Generate the mux interconnects
+    for mux_cell in routing_cells:
+        mux_outputs = defaultdict(list)
+        for (driver_cell, driver_pin), sinks in interconn.items():
+            if driver_cell != mux_cell:
+                continue
+            mux_outputs[driver_pin].extend(sinks)
+
+        assert len(mux_outputs) == 1, """\
+Mux {} has multiple outputs ({})!
+Currently muxes can only drive a single output.""".format(
+            mux_cell, ", ".join(mux_outputs.keys())
+        )
+        for mux_output_pin, sinks in mux_outputs.items():
+            assert len(sinks) == 1, """\
+Mux {}.{} has multiple outputs ({})!
+Currently muxes can only drive a single output.""".format(
+                mux_cell, mux_output_pin,
+                ", ".join("{}.{}".format(*pin) for pin, path_attr in sinks)
+            )
+            for (sink_cell, sink_pin), path_attr in sinks:
+                assert sink_cell not in routing_names, """\
+Mux {}.{} is trying to drive mux input pin {}.{}""".format(
+                    mux_cell, mux_output_pin, sink_cell, sink_pin
+                )
+
+        mux_inputs = {}
+        for (driver_cell, driver_pin), sinks in interconn.items():
+            for (sink_cell, mux_pin), path_attr in sinks:
+                if sink_cell != mux_cell:
+                    continue
+                assert driver_cell not in routing_names, "Mux {}.{} is trying to drive mux {}.{}".format(
+                    driver_cell, driver_pin, mux_cell, sink_pin
+                )
+                assert sink_pin not in mux_inputs, """\
+Pin {}.{} is trying to drive mux pin {}.{} (already driving by {}.{})""".format(
+                    driver_cell, driver_pin, mux_cell, mux_pin,
+                    *mux_inputs[sink_pin]
+                )
+                mux_inputs[mux_pin] = (driver_cell, driver_pin)
+
+        make_mux_conn(ic_xml, mux_cell, mux_inputs, mux_outputs)
+
+
+def make_leaf_pb(outfile, yj, mod, mod_pname, pb_type_xml):
+    # As leaf node, need to generate timing information
     def process_clocked_tmg(tmgspec, port, xmltype, xml_parent):
         """Add a suitable timing spec if necessary to the pb_type"""
         if tmgspec is not None:
@@ -315,27 +627,26 @@
                 attrs["value"] = splitspec[1]
             ET.SubElement(xml_parent, xmltype, attrs)
 
-    # Process timing
     for name, width, bits, iodir in mod.ports:
         port = "{}".format(name)
         # Clocked timing
         Tsetup = mod.net_attr(name, "SETUP")
         Thold = mod.net_attr(name, "HOLD")
         Tctoq = mod.net_attr(name, "CLK_TO_Q")
-        process_clocked_tmg(Tsetup, port, "T_setup", xml_parent)
-        process_clocked_tmg(Thold, port, "T_hold", xml_parent)
-        process_clocked_tmg(Tctoq, port, "T_clock_to_Q", xml_parent)
+        process_clocked_tmg(Tsetup, port, "T_setup", pb_type_xml)
+        process_clocked_tmg(Thold, port, "T_hold", pb_type_xml)
+        process_clocked_tmg(Tctoq, port, "T_clock_to_Q", pb_type_xml)
 
         # Combinational delays
         dly_prefix = "DELAY_CONST_"
         dly_mat_prefix = "DELAY_MATRIX_"
-        for attr, atvalue in sorted(mod.net_attrs(name).items()):
+        for attr, atvalue in mod.net_attrs(name).items():
             if attr.startswith(dly_prefix):
                 # Single, constant delays
                 inp = attr[len(dly_prefix):]
                 inport = "{}".format(inp)
                 ET.SubElement(
-                    xml_parent, "delay_constant", {
+                    pb_type_xml, "delay_constant", {
                         "in_port": inport,
                         "out_port": port,
                         "max": str(atvalue)
@@ -347,7 +658,7 @@
                 inport = "{}".format(inp)
                 mat = "\n" + atvalue.replace(";", "\n") + "\n"
                 xml_mat = ET.SubElement(
-                    xml_parent, "delay_matrix", {
+                    pb_type_xml, "delay_matrix", {
                         "in_port": inport,
                         "out_port": port,
                         "type": "max"
@@ -363,7 +674,7 @@
     modes = mod.attr("MODES", None)
     if modes is not None:
         modes = modes.split(";")
-    mod_pname = mod_pb_name(mod)
+    mod_pname = mod.name
     assert mod_pname == mod_pname.upper(
     ), "pb_type name should be all uppercase. {}".format(mod_pname)
 
@@ -414,23 +725,13 @@
     if 'class' in pb_attrs:
         ET.SubElement(pb_type_xml, "pb_class", {}).text = pb_attrs["class"]
 
-    # Process IOs
+    # Create the pins for this pb_type
     clocks = yosys.run.list_clocks(args.infiles, mod.name)
-    for name, width, bits, iodir in mod.ports:
-        ioattrs = {"name": name, "num_pins": str(width)}
-        pclass = mod.net_attr(name, "PORT_CLASS")
-        if pclass is not None:
-            ioattrs["port_class"] = pclass
-        if name in clocks:
-            ET.SubElement(pb_type_xml, "clock", ioattrs)
-        elif iodir == "input":
-            ET.SubElement(pb_type_xml, "input", ioattrs)
-        elif iodir == "output":
-            ET.SubElement(pb_type_xml, "output", ioattrs)
-        else:
-            assert False, "bidirectional ports not supported in VPR pb_types"
+    make_ports(clocks, mod, pb_type_xml, "clocks")
+    make_ports(clocks, mod, pb_type_xml, "inputs")
+    make_ports(clocks, mod, pb_type_xml, "outputs")
 
-    if has_modes:
+    if modes:
         for mode in modes:
             smode = mode.strip()
             mode_xml = ET.SubElement(pb_type_xml, "mode", {"name": smode})
@@ -445,9 +746,27 @@
                 )
             )
             mode_mod = mode_yj.module(mod.name)
-            make_pb_content(outfile, yj, mode_mod, mode_xml, mod_pname, True)
+            make_pb_type(outfile, mode_yj, mode_mod)
+
+            ic_xml = ET.SubElement(pb_type_xml, "interconnect")
+            for (driver_cell,
+                 driver_pin), (sink_cell,
+                               sink_pin) in mode_interconnects(mod, smode):
+                make_direct_conn(
+                    ic_xml, (driver_cell, driver_pin), (sink_cell, sink_pin),
+                    {}
+                )
+
+    routing = children = []
+    if not is_blackbox:
+        routing, children = get_children(yj, mod)
+
+    if routing or children:
+        make_container_pb(
+            outfile, yj, mod, mod_pname, pb_type_xml, routing, children
+        )
     else:
-        make_pb_content(outfile, yj, mod, pb_type_xml, mod_pname)
+        make_leaf_pb(outfile, yj, mod, mod_pname, pb_type_xml)
 
     return pb_type_xml
 
@@ -479,7 +798,7 @@
     type=argparse.FileType('w'),
     default="pb_type.xml",
     help="""\
-Output filename.
+Output filename, default 'model.xml'
 """
 )
 
@@ -492,21 +811,19 @@
     yj = YosysJSON(vjson)
 
     if args.top is not None:
-        top = args.top.upper()
+        top = args.top
     else:
         wm = re.match(r"([A-Za-z0-9_]+)\.sim\.v", iname)
         if wm:
             top = wm.group(1).upper()
         else:
             print(
-                """ERROR file name not of format %.sim.v ({}), cannot detect top level.
-                Manually specify the top level module using --top""".
-                format(iname)
+                "ERROR file name not of format %.sim.v ({}), cannot detect top level. Manually specify the top level module using --top"
+                .format(iname)
             )
             sys.exit(1)
 
-    assert top == top.upper(
-    ), "Top module name should be all uppercase. {}".format(top)
+    top = top.upper()
 
     tmod = yj.module(top)
 
@@ -525,5 +842,7 @@
 
 
 if __name__ == "__main__":
+    import doctest
+    doctest.testmod()
     args = parser.parse_args()
     sys.exit(main(args))
diff --git a/yosys/json.py b/yosys/json.py
index 9a3587c..530d732 100755
--- a/yosys/json.py
+++ b/yosys/json.py
@@ -8,6 +8,7 @@
 
 import json
 import pprint
+import re
 
 
 class YosysModule:
@@ -130,6 +131,15 @@
         else:
             return defval
 
+    PORT_REGEX = re.compile('(.*)(\\[([0-9]+)\\])')
+
+    def port_attrs(self, port_pin):
+        m = self.PORT_REGEX.match(port_pin)
+        if not m:
+            return self.net_attrs(port_pin)
+        port_name, _, port_idx = m.groups()
+        return self.net_attrs(port_name)
+
     # 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...
@@ -241,6 +251,16 @@
                             )
         return conn_ports
 
+    def net_name(self, netid):
+        """Get a net name from a netid."""
+        names = []
+        for n, props in self.data["netnames"].items():
+            if netid in props['bits']:
+                names.append(n)
+        if len(names) != 1:
+            raise KeyError("Net id {} not found".format(netid))
+        return names[0]
+
     def net_drivers(self, net):
         """Returns a list of drivers of a given net, both top level inputs.
         and cell outputs. "cell" is set to the name of the module for top level