diff --git a/chips/yosys/tests/simple/dff_init.v b/chips/yosys/tests/simple/dff_init.v new file mode 100644 index 0000000000000000000000000000000000000000..375ea5c4dc2398e0ae7477ef09b264fa88ff1428 --- /dev/null +++ b/chips/yosys/tests/simple/dff_init.v @@ -0,0 +1,54 @@ +module dff0_test(n1, n1_inv, clk); + input clk; + output n1; + reg n1 = 32'd0; + output n1_inv; + always @(posedge clk) + n1 <= n1_inv; + assign n1_inv = ~n1; +endmodule + +module dff1_test(n1, n1_inv, clk); + input clk; + (* init = 32'd1 *) + output n1; + reg n1 = 32'd1; + output n1_inv; + always @(posedge clk) + n1 <= n1_inv; + assign n1_inv = ~n1; +endmodule + +module dff0a_test(n1, n1_inv, clk); + input clk; + (* init = 32'd0 *) // Must be consistent with reg initialiser below + output n1; + reg n1 = 32'd0; + output n1_inv; + always @(posedge clk) + n1 <= n1_inv; + assign n1_inv = ~n1; +endmodule + +module dff1a_test(n1, n1_inv, clk); + input clk; + (* init = 32'd1 *) // Must be consistent with reg initialiser below + output n1; + reg n1 = 32'd1; + output n1_inv; + always @(posedge clk) + n1 <= n1_inv; + assign n1_inv = ~n1; +endmodule + +module dff_test_997 (y, clk, wire4); +// https://github.com/YosysHQ/yosys/issues/997 + output wire [1:0] y; + input clk; + input signed wire4; + reg [1:0] reg10 = 0; + always @(posedge clk) begin + reg10 <= wire4; + end + assign y = reg10; +endmodule diff --git a/chips/yosys/tests/simple/dynslice.v b/chips/yosys/tests/simple/dynslice.v new file mode 100644 index 0000000000000000000000000000000000000000..7236ac3a59511218cd1dce5e426efebd93ea811e --- /dev/null +++ b/chips/yosys/tests/simple/dynslice.v @@ -0,0 +1,12 @@ +module dynslice ( + input clk , + input [9:0] ctrl , + input [15:0] din , + input [3:0] sel , + output reg [127:0] dout +); +always @(posedge clk) +begin + dout[ctrl*sel+:16] <= din ; +end +endmodule diff --git a/chips/yosys/tests/simple/fiedler-cooley.v b/chips/yosys/tests/simple/fiedler-cooley.v new file mode 100644 index 0000000000000000000000000000000000000000..96861973ab61bc12abe484810a321aa1096f52f4 --- /dev/null +++ b/chips/yosys/tests/simple/fiedler-cooley.v @@ -0,0 +1,33 @@ +// borrowed with some modifications from +// http://www.ee.ed.ac.uk/~gerard/Teach/Verilog/manual/Example/lrgeEx2/cooley.html +module up3down5(clock, data_in, up, down, carry_out, borrow_out, count_out, parity_out); + +input [8:0] data_in; +input clock, up, down; + +output reg [8:0] count_out; +output reg carry_out, borrow_out, parity_out; + +reg [9:0] cnt_up, cnt_dn; +reg [8:0] count_nxt; + +always @(posedge clock) +begin + cnt_dn = count_out - 3'b 101; + cnt_up = count_out + 2'b 11; + + case ({up,down}) + 2'b 00 : count_nxt = data_in; + 2'b 01 : count_nxt = cnt_dn; + 2'b 10 : count_nxt = cnt_up; + 2'b 11 : count_nxt = count_out; + default : count_nxt = 9'bX; + endcase + + parity_out <= ^count_nxt; + carry_out <= up & cnt_up[9]; + borrow_out <= down & cnt_dn[9]; + count_out <= count_nxt; +end + +endmodule diff --git a/chips/yosys/tests/simple/forgen01.v b/chips/yosys/tests/simple/forgen01.v new file mode 100644 index 0000000000000000000000000000000000000000..8b7aa279d3164efde3097ff597ce5630cc1cccc3 --- /dev/null +++ b/chips/yosys/tests/simple/forgen01.v @@ -0,0 +1,23 @@ + +// VERIFIC-SKIP + +module uut_forgen01(a, y); + +input [4:0] a; +output y; + +integer i, j; +reg [31:0] lut; + +initial begin + for (i = 0; i < 32; i = i+1) begin + lut[i] = i > 1; + for (j = 2; j*j <= i; j = j+1) + if (i % j == 0) + lut[i] = 0; + end +end + +assign y = lut[a]; + +endmodule diff --git a/chips/yosys/tests/simple/forgen02.v b/chips/yosys/tests/simple/forgen02.v new file mode 100644 index 0000000000000000000000000000000000000000..14af070c38efafd23a82da4f1d7961802e369173 --- /dev/null +++ b/chips/yosys/tests/simple/forgen02.v @@ -0,0 +1,30 @@ +module uut_forgen02(a, b, cin, y, cout); + +parameter WIDTH = 8; + +input [WIDTH-1:0] a, b; +input cin; + +output [WIDTH-1:0] y; +output cout; + +genvar i; +wire [WIDTH-1:0] carry; + +generate + for (i = 0; i < WIDTH; i=i+1) begin:adder + wire [2:0] D; + assign D[1:0] = { a[i], b[i] }; + if (i == 0) begin:chain + assign D[2] = cin; + end else begin:chain + assign D[2] = carry[i-1]; + end + assign y[i] = ^D; + assign carry[i] = &D[1:0] | (^D[1:0] & D[2]); + end +endgenerate + +assign cout = carry[WIDTH-1]; + +endmodule diff --git a/chips/yosys/tests/simple/forloops.v b/chips/yosys/tests/simple/forloops.v new file mode 100644 index 0000000000000000000000000000000000000000..8665222d827385190ee21ad2c838f8c46625ba7e --- /dev/null +++ b/chips/yosys/tests/simple/forloops.v @@ -0,0 +1,25 @@ +module forloops01 (input clk, a, b, output reg [3:0] p, q, x, y); + integer k; + always @(posedge clk) begin + for (k=0; k<2; k=k+1) + p[2*k +: 2] = {a, b} ^ {2{k}}; + x <= k + {a, b}; + end + always @* begin + for (k=0; k<4; k=k+1) + q[k] = {~a, ~b, a, b} >> k[1:0]; + y = k - {a, b}; + end +endmodule + +module forloops02 (input clk, a, b, output reg [3:0] q, x, output [3:0] y); + integer k; + always @* begin + for (k=0; k<4; k=k+1) + q[k] = {~a, ~b, a, b} >> k[1:0]; + end + always @* begin + x = k + {a, b}; + end + assign y = k - {a, b}; +endmodule diff --git a/chips/yosys/tests/simple/fsm.v b/chips/yosys/tests/simple/fsm.v new file mode 100644 index 0000000000000000000000000000000000000000..26dbd76240432b5be32469b60b5951bf733124a4 --- /dev/null +++ b/chips/yosys/tests/simple/fsm.v @@ -0,0 +1,68 @@ + +// `define ASYNC_RESET + +module fsm_test(clk, reset, button_a, button_b, red_a, green_a, red_b, green_b); + +input clk, reset, button_a, button_b; +output reg red_a, green_a, red_b, green_b; + +(* gentb_constant = 0 *) +wire reset; + +integer state; +reg [3:0] cnt; + +`ifdef ASYNC_RESET +always @(posedge clk, posedge reset) +`else +always @(posedge clk) +`endif +begin + cnt <= 0; + red_a <= 1; + red_b <= 1; + green_a <= 0; + green_b <= 0; + + if (reset) + state <= 100; + else + case (state) + 100: begin + if (button_a && !button_b) + state <= 200; + if (!button_a && button_b) + state <= 300; + end + 200: begin + red_a <= 0; + green_a <= 1; + cnt <= cnt + 1; + if (cnt == 5) + state <= 210; + end + 210: begin + red_a <= 0; + green_a <= cnt[0]; + cnt <= cnt + 1; + if (cnt == 10) + state <= 100; + end + 300: begin + red_b <= 0; + green_b <= 1; + cnt <= cnt + 1; + if (cnt == 5) + state <= 310; + end + 310: begin + red_b <= 0; + green_b <= cnt[0]; + cnt <= cnt + 1; + if (cnt == 10) + state <= 100; + end + endcase +end + +endmodule diff --git a/chips/yosys/tests/simple/func_block.v b/chips/yosys/tests/simple/func_block.v new file mode 100644 index 0000000000000000000000000000000000000000..0ac7ca3bf522ecbf62a57ea7a71f558d869087e9 --- /dev/null +++ b/chips/yosys/tests/simple/func_block.v @@ -0,0 +1,33 @@ +`default_nettype none + +module func_block_top(inp, out1, out2, out3); + input wire [31:0] inp; + + function automatic [31:0] func1; + input [31:0] inp; + reg [31:0] idx; + for (idx = 0; idx < 32; idx = idx + 1) begin : blk + func1[idx] = (idx & 1'b1) ^ inp[idx]; + end + endfunction + + function automatic [31:0] func2; + input [31:0] inp; + reg [31:0] idx; + for (idx = 0; idx < 32; idx = idx + 1) begin : blk + func2[idx] = (idx & 1'b1) ^ inp[idx]; + end + endfunction + + function automatic [31:0] func3; + localparam A = 32 - 1; + parameter B = 1 - 0; + input [31:0] inp; + func3[A:B] = inp[A:B]; + endfunction + + output wire [31:0] out1, out2, out3; + assign out1 = func1(inp); + assign out2 = func2(inp); + assign out3 = func3(inp); +endmodule diff --git a/chips/yosys/tests/simple/func_recurse.v b/chips/yosys/tests/simple/func_recurse.v new file mode 100644 index 0000000000000000000000000000000000000000..02cfbcddf55b3bb4a3ce770e693d2dc3233da8f6 --- /dev/null +++ b/chips/yosys/tests/simple/func_recurse.v @@ -0,0 +1,25 @@ +module func_recurse_top( + input wire [3:0] inp, + output wire [3:0] out1, out2 +); + function automatic [3:0] pow_a; + input [3:0] base, exp; + begin + pow_a = 1; + if (exp > 0) + pow_a = base * pow_a(base, exp - 1); + end + endfunction + + function automatic [3:0] pow_b; + input [3:0] base, exp; + begin + pow_b = 1; + if (exp > 0) + pow_b = base * pow_b(base, exp - 1); + end + endfunction + + assign out1 = pow_a(inp, 3); + assign out2 = pow_b(2, 2); +endmodule diff --git a/chips/yosys/tests/simple/func_width_scope.v b/chips/yosys/tests/simple/func_width_scope.v new file mode 100644 index 0000000000000000000000000000000000000000..2f82988ae1d4d432f0dbb1c969fb785a4139b7cd --- /dev/null +++ b/chips/yosys/tests/simple/func_width_scope.v @@ -0,0 +1,41 @@ +module func_width_scope_top(inp, out1, out2); + input wire signed inp; + + localparam WIDTH_A = 5; + function automatic [WIDTH_A-1:0] func1; + input reg [WIDTH_A-1:0] inp; + func1 = ~inp; + endfunction + wire [func1(0)-1:0] xc; + assign xc = 1'sb1; + wire [WIDTH_A-1:0] xn; + assign xn = func1(inp); + + generate + if (1) begin : blk + localparam WIDTH_A = 6; + function automatic [WIDTH_A-1:0] func2; + input reg [WIDTH_A-1:0] inp; + func2 = ~inp; + endfunction + wire [func2(0)-1:0] yc; + assign yc = 1'sb1; + wire [WIDTH_A-1:0] yn; + assign yn = func2(inp); + + localparam WIDTH_B = 7; + function automatic [WIDTH_B-1:0] func3; + input reg [WIDTH_B-1:0] inp; + func3 = ~inp; + endfunction + wire [func3(0)-1:0] zc; + assign zc = 1'sb1; + wire [WIDTH_B-1:0] zn; + assign zn = func3(inp); + end + endgenerate + + output wire [1023:0] out1, out2; + assign out1 = {xc, 1'b0, blk.yc, 1'b0, blk.zc}; + assign out2 = {xn, 1'b0, blk.yn, 1'b0, blk.zn}; +endmodule diff --git a/chips/yosys/tests/simple/genblk_collide.v b/chips/yosys/tests/simple/genblk_collide.v new file mode 100644 index 0000000000000000000000000000000000000000..118c0b008fb9a65c4a0dd0a58517b12413cce4c9 --- /dev/null +++ b/chips/yosys/tests/simple/genblk_collide.v @@ -0,0 +1,27 @@ +`default_nettype none + +module genblock_collide_top1; + generate + if (1) begin : foo + if (1) begin : bar + wire x; + end + assign bar.x = 1; + wire y; + end + endgenerate +endmodule + +module genblock_collide_top2; + genvar i; + generate + if (1) begin : foo + wire x; + for (i = 0; i < 1; i = i + 1) begin : foo + if (1) begin : foo + assign x = 1; + end + end + end + endgenerate +endmodule diff --git a/chips/yosys/tests/simple/genblk_dive.v b/chips/yosys/tests/simple/genblk_dive.v new file mode 100644 index 0000000000000000000000000000000000000000..ca0c0d4a1d3a1822b97ce51e148955f1adbf1c48 --- /dev/null +++ b/chips/yosys/tests/simple/genblk_dive.v @@ -0,0 +1,21 @@ +`default_nettype none +module genblk_dive_top(output wire x); + generate + if (1) begin : Z + if (1) begin : A + wire x; + if (1) begin : B + wire x; + if (1) begin : C + wire x; + assign B.x = 0; + wire z = A.B.C.x; + end + assign A.x = A.B.C.x; + end + assign B.C.x = B.x; + end + end + endgenerate + assign x = Z.A.x; +endmodule diff --git a/chips/yosys/tests/simple/genblk_order.v b/chips/yosys/tests/simple/genblk_order.v new file mode 100644 index 0000000000000000000000000000000000000000..c80c1ac1ac0121bbaa936191d825b4a3fa0e1c3e --- /dev/null +++ b/chips/yosys/tests/simple/genblk_order.v @@ -0,0 +1,18 @@ +`default_nettype none +module genblk_order_top( + output wire out1, + output wire out2 +); + generate + if (1) begin : outer + if (1) begin : foo + wire x = 0; + if (1) begin : foo + wire x = 1; + assign out1 = foo.x; + end + assign out2 = foo.x; + end + end + endgenerate +endmodule diff --git a/chips/yosys/tests/simple/genblk_port_shadow.v b/chips/yosys/tests/simple/genblk_port_shadow.v new file mode 100644 index 0000000000000000000000000000000000000000..c1348632c2a1003e7895aaafb46f7de35c205c3d --- /dev/null +++ b/chips/yosys/tests/simple/genblk_port_shadow.v @@ -0,0 +1,10 @@ +module genblock_port_shadow_top(x); + generate + if (1) begin : blk + wire x; + assign x = 0; + end + endgenerate + output wire x; + assign x = blk.x; +endmodule diff --git a/chips/yosys/tests/simple/generate.v b/chips/yosys/tests/simple/generate.v new file mode 100644 index 0000000000000000000000000000000000000000..445c88ba89572eb32756689e4fd5d7b59453c3ca --- /dev/null +++ b/chips/yosys/tests/simple/generate.v @@ -0,0 +1,325 @@ + +module gen_test1(clk, a, b, y); + +input clk; +input [7:0] a, b; +output reg [7:0] y; + +genvar i, j; +wire [15:0] tmp1; + +generate + + for (i = 0; i < 8; i = i + 1) begin:gen1 + wire and_wire, or_wire; + assign and_wire = a[i] & b[i]; + assign or_wire = a[i] | b[i]; + if (i % 2 == 0) begin:gen2true + assign tmp1[i] = and_wire; + assign tmp1[i+8] = or_wire; + end else begin:gen2false + assign tmp1[i] = or_wire; + assign tmp1[i+8] = and_wire; + end + end + + for (i = 0; i < 8; i = i + 1) begin:gen3 + wire [4:0] tmp2; + for (j = 0; j <= 4; j = j + 1) begin:gen4 + wire tmpbuf; + assign tmpbuf = tmp1[i+2*j]; + assign tmp2[j] = tmpbuf; + end + always @(posedge clk) + y[i] <= ^tmp2; + end + +endgenerate + +endmodule + +// ------------------------------------------ + +module gen_test2(clk, a, b, y); + +input clk; +input [7:0] a, b; +output reg [8:0] y; + +integer i; +reg [8:0] carry; + +always @(posedge clk) begin + carry[0] = 0; + for (i = 0; i < 8; i = i + 1) begin + casez ({a[i], b[i], carry[i]}) + 3'b?11, 3'b1?1, 3'b11?: + carry[i+1] = 1; + default: + carry[i+1] = 0; + endcase + y[i] = a[i] ^ b[i] ^ carry[i]; + end + y[8] = carry[8]; +end + +endmodule + +// ------------------------------------------ + +module gen_test3(a, b, sel, y, z); + +input [3:0] a, b; +input sel; +output [3:0] y, z; + +genvar i; +generate + for (i=0; i < 2; i=i+1) + assign y[i] = sel ? a[i] : b[i], z[i] = sel ? b[i] : a[i]; + for (i=0; i < 2; i=i+1) begin + if (i == 0) + assign y[2] = sel ? a[2] : b[2]; + else + assign z[2] = sel ? a[2] : b[2]; + case (i) + default: + assign z[3] = sel ? a[3] : b[3]; + 0: + assign y[3] = sel ? a[3] : b[3]; + endcase + end +endgenerate +endmodule + +// ------------------------------------------ + +module gen_test4(a, b); + +input [3:0] a; +output [3:0] b; + +genvar i; +generate + for (i=0; i < 3; i=i+1) begin : foo + localparam PREV = i - 1; + wire temp; + if (i == 0) + assign temp = a[0]; + else + assign temp = foo[PREV].temp & a[i]; + assign b[i] = temp; + end +endgenerate +endmodule + +// ------------------------------------------ + +module gen_test5(input_bits, out); + +parameter WIDTH = 256; +parameter CHUNK = 4; + +input [WIDTH-1:0] input_bits; +output out; + +genvar step, i, j; +generate + for (step = 1; step <= WIDTH; step = step * CHUNK) begin : steps + localparam PREV = step / CHUNK; + localparam DIM = WIDTH / step; + for (i = 0; i < DIM; i = i + 1) begin : outer + localparam LAST_START = i * CHUNK; + for (j = 0; j < CHUNK; j = j + 1) begin : inner + wire temp; + if (step == 1) + assign temp = input_bits[i]; + else if (j == 0) + assign temp = steps[PREV].outer[LAST_START].val; + else + assign temp + = steps[step].outer[i].inner[j-1].temp + & steps[PREV].outer[LAST_START + j].val; + end + wire val; + assign val = steps[step].outer[i].inner[CHUNK - 1].temp; + end + end +endgenerate +assign out = steps[WIDTH].outer[0].val; +endmodule + +// ------------------------------------------ + +module gen_test6(output [3:0] o); +generate + genvar i; + for (i = 3; i >= 0; i = i-1) begin + assign o[i] = 1'b0; + end +endgenerate +endmodule + +// ------------------------------------------ + +module gen_test7; + reg [2:0] out1; + reg [2:0] out2; + wire [2:0] out3; + generate + if (1) begin : cond + reg [2:0] sub_out1; + reg [2:0] sub_out2; + wire [2:0] sub_out3; + initial begin : init + reg signed [31:0] x; + x = 2 ** 2; + out1 = x; + sub_out1 = x; + end + always @* begin : proc + reg signed [31:0] x; + x = 2 ** 1; + out2 = x; + sub_out2 = x; + end + genvar x; + for (x = 0; x < 3; x = x + 1) begin + assign out3[x] = 1; + assign sub_out3[x] = 1; + end + end + endgenerate + +// `define VERIFY +`ifdef VERIFY + assert property (out1 == 4); + assert property (out2 == 2); + assert property (out3 == 7); + assert property (cond.sub_out1 == 4); + assert property (cond.sub_out2 == 2); + assert property (cond.sub_out3 == 7); +`endif +endmodule + +// ------------------------------------------ + +module gen_test8; + +// `define VERIFY +`ifdef VERIFY + `define ASSERT(expr) assert property (expr); +`else + `define ASSERT(expr) +`endif + + wire [1:0] x = 2'b11; + generate + if (1) begin : A + wire [1:0] x; + if (1) begin : B + wire [1:0] x = 2'b00; + `ASSERT(x == 0) + `ASSERT(A.x == 2) + `ASSERT(A.C.x == 1) + `ASSERT(A.B.x == 0) + `ASSERT(gen_test8.x == 3) + `ASSERT(gen_test8.A.x == 2) + `ASSERT(gen_test8.A.C.x == 1) + `ASSERT(gen_test8.A.B.x == 0) + end + if (1) begin : C + wire [1:0] x = 2'b01; + `ASSERT(x == 1) + `ASSERT(A.x == 2) + `ASSERT(A.C.x == 1) + `ASSERT(A.B.x == 0) + `ASSERT(gen_test8.x == 3) + `ASSERT(gen_test8.A.x == 2) + `ASSERT(gen_test8.A.C.x == 1) + `ASSERT(gen_test8.A.B.x == 0) + end + assign x = B.x ^ 2'b11 ^ C.x; + `ASSERT(x == 2) + `ASSERT(A.x == 2) + `ASSERT(A.C.x == 1) + `ASSERT(A.B.x == 0) + `ASSERT(gen_test8.x == 3) + `ASSERT(gen_test8.A.x == 2) + `ASSERT(gen_test8.A.C.x == 1) + `ASSERT(gen_test8.A.B.x == 0) + end + endgenerate + + `ASSERT(x == 3) + `ASSERT(A.x == 2) + `ASSERT(A.C.x == 1) + `ASSERT(A.B.x == 0) + `ASSERT(gen_test8.x == 3) + `ASSERT(gen_test8.A.x == 2) + `ASSERT(gen_test8.A.C.x == 1) + `ASSERT(gen_test8.A.B.x == 0) +endmodule + +// ------------------------------------------ + +module gen_test9; + +// `define VERIFY +`ifdef VERIFY + `define ASSERT(expr) assert property (expr); +`else + `define ASSERT(expr) +`endif + + wire [1:0] w = 2'b11; + generate + begin : A + wire [1:0] x; + begin : B + wire [1:0] y = 2'b00; + `ASSERT(w == 3) + `ASSERT(x == 2) + `ASSERT(y == 0) + `ASSERT(A.x == 2) + `ASSERT(A.C.z == 1) + `ASSERT(A.B.y == 0) + `ASSERT(gen_test9.w == 3) + `ASSERT(gen_test9.A.x == 2) + `ASSERT(gen_test9.A.C.z == 1) + `ASSERT(gen_test9.A.B.y == 0) + end + begin : C + wire [1:0] z = 2'b01; + `ASSERT(w == 3) + `ASSERT(x == 2) + `ASSERT(z == 1) + `ASSERT(A.x == 2) + `ASSERT(A.C.z == 1) + `ASSERT(A.B.y == 0) + `ASSERT(gen_test9.w == 3) + `ASSERT(gen_test9.A.x == 2) + `ASSERT(gen_test9.A.C.z == 1) + `ASSERT(gen_test9.A.B.y == 0) + end + assign x = B.y ^ 2'b11 ^ C.z; + `ASSERT(x == 2) + `ASSERT(A.x == 2) + `ASSERT(A.C.z == 1) + `ASSERT(A.B.y == 0) + `ASSERT(gen_test9.w == 3) + `ASSERT(gen_test9.A.x == 2) + `ASSERT(gen_test9.A.C.z == 1) + `ASSERT(gen_test9.A.B.y == 0) + end + endgenerate + + `ASSERT(w == 3) + `ASSERT(A.x == 2) + `ASSERT(A.C.z == 1) + `ASSERT(A.B.y == 0) + `ASSERT(gen_test9.w == 3) + `ASSERT(gen_test9.A.x == 2) + `ASSERT(gen_test9.A.C.z == 1) + `ASSERT(gen_test9.A.B.y == 0) +endmodule diff --git a/chips/yosys/tests/simple/generate_mk.py b/chips/yosys/tests/simple/generate_mk.py new file mode 100644 index 0000000000000000000000000000000000000000..f8e79bcafaa49885b6c58a969213b26978075764 --- /dev/null +++ b/chips/yosys/tests/simple/generate_mk.py @@ -0,0 +1,17 @@ +#!/usr/bin/env python3 + +import sys +sys.path.append("..") + +import shutil + +# ---------------------- +# Check if iverilog is installed +# ---------------------- +if shutil.which("iverilog") is None: + print("Error: Icarus Verilog 'iverilog' not found.", file=sys.stderr) + sys.exit(1) + +import gen_tests_makefile + +gen_tests_makefile.generate_autotest("*.*v", "") diff --git a/chips/yosys/tests/simple/graphtest.v b/chips/yosys/tests/simple/graphtest.v new file mode 100644 index 0000000000000000000000000000000000000000..9b16b61ca62eb6a54dece7b026e21cb6cf556e6f --- /dev/null +++ b/chips/yosys/tests/simple/graphtest.v @@ -0,0 +1,34 @@ +module graphtest (A,B,X,Y,Z); + +input [3:0] A; +input [3:0] B; +output reg [3:0] X; +output [9:0] Y; +output [7:0] Z; + +wire [4:0] t; + +assign t[4] = 1'b0; // Constant connects to wire +assign t[2:0] = A[2:0] & { 2'b10, B[3]}; // Concatenation of intermediate wire +assign t[3] = A[2] ^ B[3]; // Bitwise-XOR + +// assign Y[2:0] = 3'b111; +// assign Y[6:3] = A; +// assign Y[9:7] = t[0:2]; +assign Y = {3'b111, A, t[2:0]}; // Direct assignment of concatenation + +assign Z[0] = 1'b0; // Constant connects to PO +assign Z[1] = t[3]; // Intermediate sig connects to PO +assign Z[3:2] = A[2:1]; // PI connects to PO +assign Z[7:4] = {1'b0, B[2:0]}; // Concat of CV and PI connect to PO + +always @* begin + if (A == 4'b1111) begin // All-Const at port (eq) + X = B; + end + else begin + X = 4'b0000; // All-Const at port (mux) + end +end + +endmodule diff --git a/chips/yosys/tests/simple/hierarchy.v b/chips/yosys/tests/simple/hierarchy.v new file mode 100644 index 0000000000000000000000000000000000000000..b765433725a1c7ca807b02c2c678ea2d21623be9 --- /dev/null +++ b/chips/yosys/tests/simple/hierarchy.v @@ -0,0 +1,26 @@ + +(* top *) +module hierarchy_top(a, b, y1, y2, y3, y4); +input [3:0] a; +input signed [3:0] b; +output [7:0] y1, y2, y3, y4; + +// this version triggers a bug in Icarus Verilog +// submod #(-3'sd1, 3'b111 + 3'b001) foo (a, b, y1, y2, y3, y4); + +// this version is handled correctly by Icarus Verilog +submod #(-3'sd1, -3'sd1) foo (a, b, y1, y2, y3, y4); + +endmodule + +(* gentb_skip *) +module submod(a, b, y1, y2, y3, y4); +parameter c = 0; +parameter [7:0] d = 0; +input [3:0] a, b; +output [7:0] y1, y2, y3, y4; +assign y1 = a; +assign y2 = b; +assign y3 = c; +assign y4 = d; +endmodule diff --git a/chips/yosys/tests/simple/hierdefparam.v b/chips/yosys/tests/simple/hierdefparam.v new file mode 100644 index 0000000000000000000000000000000000000000..a6e0ac1b73d2384ec43b1748f79c867c06b6bd3b --- /dev/null +++ b/chips/yosys/tests/simple/hierdefparam.v @@ -0,0 +1,25 @@ +`default_nettype none + +module hierdefparam_top(input wire [7:0] A, output wire [7:0] Y); + generate begin:foo + hierdefparam_a mod_a(.A(A), .Y(Y)); + end endgenerate + defparam foo.mod_a.bar[0].mod_b.addvalue = 42; + defparam foo.mod_a.bar[1].mod_b.addvalue = 43; +endmodule + +module hierdefparam_a(input wire [7:0] A, output wire [7:0] Y); + genvar i; + generate + for (i = 0; i < 2; i=i+1) begin:bar + wire [7:0] a, y; + hierdefparam_b mod_b(.A(a), .Y(y)); + end + endgenerate + assign bar[0].a = A, bar[1].a = bar[0].y, Y = bar[1].y; +endmodule + +module hierdefparam_b(input wire [7:0] A, output wire [7:0] Y); + parameter [7:0] addvalue = 44; + assign Y = A + addvalue; +endmodule diff --git a/chips/yosys/tests/simple/i2c_master_tests.v b/chips/yosys/tests/simple/i2c_master_tests.v new file mode 100644 index 0000000000000000000000000000000000000000..958c5b0e9c734400a87e9b4f3ab067d690b21fac --- /dev/null +++ b/chips/yosys/tests/simple/i2c_master_tests.v @@ -0,0 +1,61 @@ +// one of my early test cases was the OpenCores I2C master +// This is a collection of stripped down code snippets from +// this core that triggered bugs in early versions of yosys. + +// from i2c_master_bit_ctrl +module i2c_test01(clk, rst, nReset, al); + + input clk, rst, nReset; + output reg al; + + reg cmd_stop; + always @(posedge clk or negedge nReset) + if (~nReset) + cmd_stop <= #1 1'b0; + else if (rst) + cmd_stop <= #1 1'b0; + + always @(posedge clk or negedge nReset) + if (~nReset) + al <= #1 1'b0; + else if (rst) + al <= #1 1'b0; + else + al <= #1 ~cmd_stop; + +endmodule + +// from i2c_master_bit_ctrl +module i2c_test02(clk, slave_wait, clk_cnt, cmd, cmd_stop, cnt); + + input clk, slave_wait, clk_cnt; + input cmd; + + output reg cmd_stop; + + reg clk_en; + output reg [15:0] cnt; + + always @(posedge clk) + if (~|cnt) + if (~slave_wait) + begin + cnt <= #1 clk_cnt; + clk_en <= #1 1'b1; + end + else + begin + cnt <= #1 cnt; + clk_en <= #1 1'b0; + end + else + begin + cnt <= #1 cnt - 16'h1; + clk_en <= #1 1'b0; + end + + always @(posedge clk) + if (clk_en) + cmd_stop <= #1 cmd; + +endmodule diff --git a/chips/yosys/tests/simple/ifdef_1.v b/chips/yosys/tests/simple/ifdef_1.v new file mode 100644 index 0000000000000000000000000000000000000000..f1358185c498b411357e1a065074fed2ae4f659c --- /dev/null +++ b/chips/yosys/tests/simple/ifdef_1.v @@ -0,0 +1,88 @@ +module ifdef_1_top(o1, o2, o3, o4); + +`define FAIL input wire not_a_port; + +`ifdef COND_1 + `FAIL +`elsif COND_2 + `FAIL +`elsif COND_3 + `FAIL +`elsif COND_4 + `FAIL +`else + + `define COND_4 + output wire o4; + + `ifdef COND_1 + `FAIL + `elsif COND_2 + `FAIL + `elsif COND_3 + `FAIL + `elsif COND_4 + + `define COND_3 + output wire o3; + + `ifdef COND_1 + `FAIL + `elsif COND_2 + `FAIL + `elsif COND_3 + + `define COND_2 + output wire o2; + + `ifdef COND_1 + `FAIL + `elsif COND_2 + + `define COND_1 + output wire o1; + + `ifdef COND_1 + + `ifdef COND_1 + `elsif COND_2 + `FAIL + `elsif COND_3 + `FAIL + `elsif COND_4 + `FAIL + `else + `FAIL + `endif + + `elsif COND_2 + `FAIL + `elsif COND_3 + `FAIL + `elsif COND_4 + `FAIL + `else + `FAIL + `endif + + `elsif COND_3 + `FAIL + `elsif COND_4 + `FAIL + `else + `FAIL + `endif + + `elsif COND_4 + `FAIL + `else + `FAIL + `endif + + `else + `FAIL + `endif + +`endif + +endmodule diff --git a/chips/yosys/tests/simple/ifdef_2.v b/chips/yosys/tests/simple/ifdef_2.v new file mode 100644 index 0000000000000000000000000000000000000000..9fae7570d3497418294207f315a1ec4fdcfdeb5e --- /dev/null +++ b/chips/yosys/tests/simple/ifdef_2.v @@ -0,0 +1,21 @@ +module ifdef_2_top(o1, o2, o3); + +output wire o1; + +`define COND_1 +`define COND_2 +`define COND_3 + +`ifdef COND_1 + output wire o2; +`elsif COND_2 + input wire dne1; +`elsif COND_3 + input wire dne2; +`else + input wire dne3; +`endif + +output wire o3; + +endmodule diff --git a/chips/yosys/tests/simple/implicit_ports.sv b/chips/yosys/tests/simple/implicit_ports.sv new file mode 100644 index 0000000000000000000000000000000000000000..8b0a6f38639a01c0bc9ea23885607078821f07b4 --- /dev/null +++ b/chips/yosys/tests/simple/implicit_ports.sv @@ -0,0 +1,16 @@ +// Test implicit port connections +module alu (input [2:0] a, input [2:0] b, input cin, output cout, output [2:0] result); + assign cout = cin; + assign result = a + b; +endmodule + +module named_ports(input [2:0] a, b, output [2:0] alu_result, output cout); + wire cin = 1; + alu alu ( + .a(a), + .b, // Implicit connection is equivalent to .b(b) + .cin(), // Explicitely unconnected + .cout(cout), + .result(alu_result) + ); +endmodule diff --git a/chips/yosys/tests/simple/lesser_size_cast.sv b/chips/yosys/tests/simple/lesser_size_cast.sv new file mode 100644 index 0000000000000000000000000000000000000000..8c0bc98144227992135224010084e6db8aa80a0f --- /dev/null +++ b/chips/yosys/tests/simple/lesser_size_cast.sv @@ -0,0 +1,7 @@ +module top ( + input signed [1:0] a, + input signed [2:0] b, + output signed [4:0] c +); + assign c = 2'(a) * b; +endmodule diff --git a/chips/yosys/tests/simple/local_loop_var.sv b/chips/yosys/tests/simple/local_loop_var.sv new file mode 100644 index 0000000000000000000000000000000000000000..42860e21856990f0a88d2b39aaf87e4f0b1a5a22 --- /dev/null +++ b/chips/yosys/tests/simple/local_loop_var.sv @@ -0,0 +1,11 @@ +module local_loop_top(out); + output integer out; + initial begin + integer i; + for (i = 0; i < 5; i = i + 1) + if (i == 0) + out = 1; + else + out += 2 ** i; + end +endmodule diff --git a/chips/yosys/tests/simple/localparam_attr.v b/chips/yosys/tests/simple/localparam_attr.v new file mode 100644 index 0000000000000000000000000000000000000000..2ef76c71c6582615416fa352eb6d79855cd5f8ed --- /dev/null +++ b/chips/yosys/tests/simple/localparam_attr.v @@ -0,0 +1,11 @@ +module uut_localparam_attr (I, O); + +(* LOCALPARAM_ATTRIBUTE = "attribute_content" *) +localparam WIDTH = 1; + +input wire [WIDTH-1:0] I; +output wire [WIDTH-1:0] O; + +assign O = I; + +endmodule diff --git a/chips/yosys/tests/simple/loop_prefix_case.v b/chips/yosys/tests/simple/loop_prefix_case.v new file mode 100644 index 0000000000000000000000000000000000000000..0cfa005477cf0fb50331d1f02791c746ded73e6e --- /dev/null +++ b/chips/yosys/tests/simple/loop_prefix_case.v @@ -0,0 +1,18 @@ +module loop_prefix_case_top( + input wire x, + output reg y +); + localparam I = 1; + genvar i; + generate + for (i = 0; i < 1; i = i + 1) begin : blk + wire [i:i] z = x; + end + endgenerate + always @* begin + case (blk[I - 1].z) + 1: y = 0; + 0: y = 1; + endcase + end +endmodule diff --git a/chips/yosys/tests/simple/loop_var_shadow.v b/chips/yosys/tests/simple/loop_var_shadow.v new file mode 100644 index 0000000000000000000000000000000000000000..b75a15ab06c4dd2f85c4b93dc28f6bcb8046d788 --- /dev/null +++ b/chips/yosys/tests/simple/loop_var_shadow.v @@ -0,0 +1,15 @@ +module loop_var_shadow_top(out); + genvar i; + generate + for (i = 0; i < 2; i = i + 1) begin : loop + localparam j = i + 1; + if (1) begin : blk + localparam i = j + 1; + wire [i:0] x; + assign x = 1'sb1; + end + end + endgenerate + output wire [63:0] out; + assign out = {loop[0].blk.x, loop[1].blk.x}; +endmodule diff --git a/chips/yosys/tests/simple/loops.v b/chips/yosys/tests/simple/loops.v new file mode 100644 index 0000000000000000000000000000000000000000..ffd6245b23bdd610e4784fb2c067676379e390a7 --- /dev/null +++ b/chips/yosys/tests/simple/loops.v @@ -0,0 +1,78 @@ + +// a simple test case extracted from systemcaes (as included in iwls2005) +// this design has latches (or logic loops) for the two temp variables. +// this latches (or logic loops) must be removed in the final synthesis results + +module aes( + // inputs + input [3:0] addroundkey_data_i, + input [3:0] addroundkey_data_reg, + input [3:0] addroundkey_round, + input [3:0] key_i, + input [3:0] keysched_new_key_o, + input [3:0] round, + input addroundkey_start_i, + input keysched_ready_o, + + // outputs + output reg [3:0] keysched_last_key_i, + output reg [3:0] keysched_round_i, + output reg [3:0] next_addroundkey_data_reg, + output reg [3:0] next_addroundkey_round, + output reg [3:0] round_data_var, + output reg keysched_start_i, + output reg next_addroundkey_ready_o +); + +// temp variables +reg [3:0] data_var; +reg [3:0] round_key_var; + +always @* +begin + keysched_start_i = 0; + keysched_round_i = addroundkey_round; + round_data_var = addroundkey_data_reg; + next_addroundkey_data_reg = addroundkey_data_reg; + next_addroundkey_ready_o = 0; + next_addroundkey_round = addroundkey_round; + + if (addroundkey_round == 1 || addroundkey_round == 0) + keysched_last_key_i = key_i; + else + keysched_last_key_i = keysched_new_key_o; + + if (round == 0 && addroundkey_start_i) + begin + data_var = addroundkey_data_i; + round_key_var = key_i; + round_data_var = round_key_var ^ data_var; + next_addroundkey_data_reg = round_data_var; + next_addroundkey_ready_o = 1; + end + else if (addroundkey_start_i && round != 0) + begin + keysched_last_key_i = key_i; + keysched_start_i = 1; + keysched_round_i = 1; + next_addroundkey_round = 1; + end + else if (addroundkey_round != round && keysched_ready_o) + begin + next_addroundkey_round = addroundkey_round + 1; + keysched_last_key_i = keysched_new_key_o; + keysched_start_i = 1; + keysched_round_i = addroundkey_round + 1; + end + else if (addroundkey_round == round && keysched_ready_o) + begin + data_var = addroundkey_data_i; + round_key_var = keysched_new_key_o; + round_data_var = round_key_var ^ data_var; + next_addroundkey_data_reg = round_data_var; + next_addroundkey_ready_o = 1; + next_addroundkey_round = 0; + end +end + +endmodule diff --git a/chips/yosys/tests/simple/macro_arg_spaces.sv b/chips/yosys/tests/simple/macro_arg_spaces.sv new file mode 100644 index 0000000000000000000000000000000000000000..5fc9e288189e31ff064528a415702fcb30154101 --- /dev/null +++ b/chips/yosys/tests/simple/macro_arg_spaces.sv @@ -0,0 +1,28 @@ +module macro_arg_spaces_top( + input wire [31:0] i, + output wire [31:0] x, y, z +); + +`define BAR(a) a +`define FOO(a = function automatic [31:0] f) a + +`BAR(function automatic [31:0] a); + input [31:0] i; + a = i * 2; +endfunction + +`FOO(); + input [31:0] i; + f = i * 3; +endfunction + +`FOO(function automatic [31:0] b); + input [31:0] i; + b = i * 5; +endfunction + +assign x = a(i); +assign y = f(i); +assign z = b(i); + +endmodule diff --git a/chips/yosys/tests/simple/macro_arg_surrounding_spaces.v b/chips/yosys/tests/simple/macro_arg_surrounding_spaces.v new file mode 100644 index 0000000000000000000000000000000000000000..e0239c08bd48c1c954aabfa017090c8907e1f682 --- /dev/null +++ b/chips/yosys/tests/simple/macro_arg_surrounding_spaces.v @@ -0,0 +1,20 @@ +module macr_arg_surrounding_spaces_top( + IDENT_V_, + IDENT_W_, + IDENT_X_, + IDENT_Y_, + IDENT_Z_, + IDENT_A_, + IDENT_B_, + IDENT_C_ +); + `define MACRO(dummy, x) IDENT_``x``_ + output wire IDENT_V_; + output wire `MACRO(_,W); + output wire `MACRO(_, X); + output wire `MACRO(_,Y ); + output wire `MACRO(_, Z ); + output wire `MACRO(_, A); + output wire `MACRO(_,B ); + output wire `MACRO(_, C ); +endmodule diff --git a/chips/yosys/tests/simple/macros.v b/chips/yosys/tests/simple/macros.v new file mode 100644 index 0000000000000000000000000000000000000000..7b4d616eae8cd787e7e02cb977d832e5b709e7d6 --- /dev/null +++ b/chips/yosys/tests/simple/macros.v @@ -0,0 +1,244 @@ + +module test_def(a, y); + +`define MSB_LSB_SEP : +`define get_msb(off, len) ((off)+(len)-1) +`define get_lsb(off, len) (off) +`define sel_bits(offset, len) `get_msb(offset, len) `MSB_LSB_SEP `get_lsb(offset, len) + +input [31:0] a; +output [7:0] y; + +assign y = a[`sel_bits(16, 8)]; + +endmodule + +// --------------------------------------------------- + +module test_ifdef(a, y); + +input [2:0] a; +output reg [31:0] y; + +always @* begin + y = 0; + + `undef X + `ifdef X + y = y + 42; + `else + `undef A + `undef B + `ifdef A + y = (y << 1) | a[0]; + `elsif B + y = (y << 1) | a[1]; + `else + y = (y << 1) | a[2]; + `endif + `undef A + `define B + `ifdef A + y = (y << 1) | a[0]; + `elsif B + y = (y << 1) | a[1]; + `else + y = (y << 1) | a[2]; + `endif + `define A + `undef B + `ifdef A + y = (y << 1) | a[0]; + `elsif B + y = (y << 1) | a[1]; + `else + y = (y << 1) | a[2]; + `endif + `define A + `define B + `ifdef A + y = (y << 1) | a[0]; + `elsif B + y = (y << 1) | a[1]; + `else + y = (y << 1) | a[2]; + `endif + // ------------------------------------ + `undef A + `undef B + `ifndef A + y = (y << 1) | a[0]; + `elsif B + y = (y << 1) | a[1]; + `else + y = (y << 1) | a[2]; + `endif + `undef A + `define B + `ifndef A + y = (y << 1) | a[0]; + `elsif B + y = (y << 1) | a[1]; + `else + y = (y << 1) | a[2]; + `endif + `define A + `undef B + `ifndef A + y = (y << 1) | a[0]; + `elsif B + y = (y << 1) | a[1]; + `else + y = (y << 1) | a[2]; + `endif + `define A + `define B + `ifndef A + y = (y << 1) | a[0]; + `elsif B + y = (y << 1) | a[1]; + `else + y = (y << 1) | a[2]; + `endif + // ------------------------------------ + `undef A + `ifdef A + y = (y << 1) | a[0]; + `else + y = (y << 1) | a[2]; + `endif + `define A + `ifdef A + y = (y << 1) | a[0]; + `else + y = (y << 1) | a[2]; + `endif + // ------------------------------------ + `undef A + `ifndef A + y = (y << 1) | a[0]; + `else + y = (y << 1) | a[2]; + `endif + `define A + `ifndef A + y = (y << 1) | a[0]; + `else + y = (y << 1) | a[2]; + `endif + `endif + + `define X + `ifdef X + `undef A + `undef B + `ifdef A + y = (y << 1) | a[0]; + `elsif B + y = (y << 1) | a[1]; + `else + y = (y << 1) | a[2]; + `endif + `undef A + `define B + `ifdef A + y = (y << 1) | a[0]; + `elsif B + y = (y << 1) | a[1]; + `else + y = (y << 1) | a[2]; + `endif + `define A + `undef B + `ifdef A + y = (y << 1) | a[0]; + `elsif B + y = (y << 1) | a[1]; + `else + y = (y << 1) | a[2]; + `endif + `define A + `define B + `ifdef A + y = (y << 1) | a[0]; + `elsif B + y = (y << 1) | a[1]; + `else + y = (y << 1) | a[2]; + `endif + // ------------------------------------ + `undef A + `undef B + `ifndef A + y = (y << 1) | a[0]; + `elsif B + y = (y << 1) | a[1]; + `else + y = (y << 1) | a[2]; + `endif + `undef A + `define B + `ifndef A + y = (y << 1) | a[0]; + `elsif B + y = (y << 1) | a[1]; + `else + y = (y << 1) | a[2]; + `endif + `define A + `undef B + `ifndef A + y = (y << 1) | a[0]; + `elsif B + y = (y << 1) | a[1]; + `else + y = (y << 1) | a[2]; + `endif + `define A + `define B + `ifndef A + y = (y << 1) | a[0]; + `elsif B + y = (y << 1) | a[1]; + `else + y = (y << 1) | a[2]; + `endif + // ------------------------------------ + `undef A + `ifdef A + y = (y << 1) | a[0]; + `else + y = (y << 1) | a[2]; + `endif + `define A + `ifdef A + y = (y << 1) | a[0]; + `else + y = (y << 1) | a[2]; + `endif + // ------------------------------------ + `undef A + `ifndef A + y = (y << 1) | a[0]; + `else + y = (y << 1) | a[2]; + `endif + `define A + `ifndef A + y = (y << 1) | a[0]; + `else + y = (y << 1) | a[2]; + `endif + `else + y = y + 42; + `endif +end + +endmodule + +`define SIZE 4 // comment supported in this part +module test_comment_in_macro ( din_a, dout_a ); +input [`SIZE-1:0] din_a; +output [`SIZE-1:0] dout_a; +assign dout_a = din_a | `SIZE'ha; +endmodule diff --git a/chips/yosys/tests/simple/matching_end_labels.sv b/chips/yosys/tests/simple/matching_end_labels.sv new file mode 100644 index 0000000000000000000000000000000000000000..2d42e7e10d614b0f9e544c57845f8dd5061317b7 --- /dev/null +++ b/chips/yosys/tests/simple/matching_end_labels.sv @@ -0,0 +1,29 @@ +module matching_end_labels_top( + output reg [7:0] + out1, out2, out3, out4 +); + initial begin + begin : blk1 + reg x; + x = 1; + end + out1 = blk1.x; + begin : blk2 + reg x; + x = 2; + end : blk2 + out2 = blk2.x; + end + if (1) begin + if (1) begin : blk3 + reg x; + assign x = 3; + end + assign out3 = blk3.x; + if (1) begin : blk4 + reg x; + assign x = 4; + end : blk4 + assign out4 = blk4.x; + end +endmodule diff --git a/chips/yosys/tests/simple/mem2reg.v b/chips/yosys/tests/simple/mem2reg.v new file mode 100644 index 0000000000000000000000000000000000000000..100426785174df953a0ce3ec676d8d062c223cf0 --- /dev/null +++ b/chips/yosys/tests/simple/mem2reg.v @@ -0,0 +1,116 @@ + +module mem2reg_test1(in_addr, in_data, out_addr, out_data); + +input [1:0] in_addr, out_addr; +input [3:0] in_data; +output reg [3:0] out_data; + +reg [3:0] array [2:0]; + +always @* begin + array[0] = 0; + array[1] = 23; + array[2] = 42; + array[in_addr] = in_data; + out_data = array[out_addr]; +end + +endmodule + +// ------------------------------------------------------ + +module mem2reg_test2(clk, reset, mode, addr, data); + +input clk, reset, mode; +input [2:0] addr; +output [3:0] data; + +(* mem2reg *) +reg [3:0] mem [0:7]; + +assign data = mem[addr]; + +integer i; + +always @(posedge clk) begin + if (reset) begin + for (i=0; i<8; i=i+1) + mem[i] <= i; + end else + if (mode) begin + for (i=0; i<8; i=i+1) + mem[i] <= mem[i]+1; + end else begin + mem[addr] <= 0; + end +end + +endmodule + +// ------------------------------------------------------ + +// http://www.reddit.com/r/yosys/comments/28d9lx/problem_with_concatenation_of_two_dimensional/ +module mem2reg_test3( input clk, input [8:0] din_a, output reg [7:0] dout_a, output [7:0] dout_b); +reg [7:0] dint_c [0:7]; +always @(posedge clk) + begin + {dout_a[0], dint_c[3]} <= din_a; + end +assign dout_b = dint_c[3]; +endmodule + +// ------------------------------------------------------ + +module mem2reg_test4(result1, result2, result3); + output signed [9:0] result1; + output signed [9:0] result2; + output signed [9:0] result3; + + wire signed [9:0] intermediate [0:3]; + + function integer depth2Index; + input integer depth; + depth2Index = depth; + endfunction + + assign intermediate[depth2Index(1)] = 1; + assign intermediate[depth2Index(2)] = 2; + assign intermediate[3] = 3; + assign result1 = intermediate[1]; + assign result2 = intermediate[depth2Index(2)]; + assign result3 = intermediate[depth2Index(3)]; +endmodule + +// ------------------------------------------------------ + +module mem2reg_test5(input ctrl, output out); + wire [0:0] foo[0:0]; + wire [0:0] bar[0:1]; + + assign foo[0] = ctrl; + assign bar[0] = 0, bar[1] = 1; + assign out = bar[foo[0]]; +endmodule + +// ------------------------------------------------------ + +module mem2reg_test6 (din, dout); + input wire [3:0] din; + output reg [3:0] dout; + + reg [1:0] din_array [1:0]; + reg [1:0] dout_array [1:0]; + + always @* begin + din_array[0] = din[0 +: 2]; + din_array[1] = din[2 +: 2]; + + dout_array[0] = din_array[0]; + dout_array[1] = din_array[1]; + + {dout_array[0][1], dout_array[0][0]} = dout_array[0][0] + dout_array[1][0]; + + dout[0 +: 2] = dout_array[0]; + dout[2 +: 2] = dout_array[1]; + end +endmodule diff --git a/chips/yosys/tests/simple/mem2reg_bounds_tern.v b/chips/yosys/tests/simple/mem2reg_bounds_tern.v new file mode 100644 index 0000000000000000000000000000000000000000..0e6852fe764a1f8af94a82d128338191dce27b0d --- /dev/null +++ b/chips/yosys/tests/simple/mem2reg_bounds_tern.v @@ -0,0 +1,19 @@ +module mem2reg_bounds_term_top( + input clk, + input wire [1:0] sel, + input wire [7:0] base, + output reg [7:0] line +); + reg [0:7] mem [0:2]; + + generate + genvar i; + for (i = 0; i < 4; i = i + 1) begin : gen + always @(posedge clk) + mem[i] <= i == 0 ? base : mem[i - 1] + 1; + end + endgenerate + + always @(posedge clk) + line = mem[sel]; +endmodule diff --git a/chips/yosys/tests/simple/mem_arst.v b/chips/yosys/tests/simple/mem_arst.v new file mode 100644 index 0000000000000000000000000000000000000000..11ba2701528691b6b5231f9ac09cc13920ac81e4 --- /dev/null +++ b/chips/yosys/tests/simple/mem_arst.v @@ -0,0 +1,40 @@ + +module MyMem #( + parameter AddrWidth = 4, + parameter DataWidth = 4) ( + (* gentb_constant = 1 *) + input Reset_n_i, + input Clk_i, + input [AddrWidth-1:0] Addr_i, + input [DataWidth-1:0] Data_i, + output reg [DataWidth-1:0] Data_o, + input WR_i); + + localparam Size = 2**AddrWidth; + + (* mem2reg *) + reg [DataWidth-1:0] Mem[Size-1:0]; + + integer i; + + always @(negedge Reset_n_i or posedge Clk_i) + begin + if (!Reset_n_i) + begin + Data_o <= 'bx; + for (i=0; i> u2; + 5: y <= u1 >> s2; + 6: y <= s1 >> u2; + 7: y <= s1 >> s2; + + 8: y <= u1 <<< u2; + 9: y <= u1 <<< s2; + 10: y <= s1 <<< u2; + 11: y <= s1 <<< s2; + + 12: y <= u1 >>> u2; + 13: y <= u1 >>> s2; + 14: y <= s1 >>> u2; + 15: y <= s1 >>> s2; + + 16: y <= u1 < u2; + 17: y <= u1 < s2; + 18: y <= s1 < u2; + 19: y <= s1 < s2; + + 20: y <= u1 <= u2; + 21: y <= u1 <= s2; + 22: y <= s1 <= u2; + 23: y <= s1 <= s2; + + 24: y <= u1 == u2; + 25: y <= u1 == s2; + 26: y <= s1 == u2; + 27: y <= s1 == s2; + + 28: y <= u1 != u2; + 29: y <= u1 != s2; + 30: y <= s1 != u2; + 31: y <= s1 != s2; + + 32: y <= u1 >= u2; + 33: y <= u1 >= s2; + 34: y <= s1 >= u2; + 35: y <= s1 >= s2; + + 36: y <= u1 > u2; + 37: y <= u1 > s2; + 38: y <= s1 > u2; + 39: y <= s1 > s2; + + 40: y <= u1 + u2; + 41: y <= u1 + s2; + 42: y <= s1 + u2; + 43: y <= s1 + s2; + + 44: y <= u1 - u2; + 45: y <= u1 - s2; + 46: y <= s1 - u2; + 47: y <= s1 - s2; + + 48: y <= u1 * u2; + 49: y <= u1 * s2; + 50: y <= s1 * u2; + 51: y <= s1 * s2; + + 52: y <= u1 / u2; + 53: y <= u1 / s2; + 54: y <= s1 / u2; + 55: y <= s1 / s2; + + 56: y <= u1 % u2; + 57: y <= u1 % s2; + 58: y <= s1 % u2; + 59: y <= s1 % s2; + + 60: y <= 4'd2 ** u1; + 61: y <= 4'd2 ** s1; + 62: y <= 4'sd2 ** u1; + 63: y <= 4'sd2 ** s1; + + 64: y <= +u1; + 65: y <= -u1; + 66: y <= ~u1; + 67: y <= !u1; + + 68: y <= +s1; + 69: y <= -s1; + 70: y <= ~s1; + 71: y <= !s1; + + 72: y <= { &u1, ~&u1, |u1, ~|u1, ^u1, ~^u1, ^~u1 }; + 73: y <= { &s1, ~&s1, |s1, ~|s1, ^s1, ~^s1, ^~s1 }; + 74: y <= { &u1[1:0], ~&u1[1:0], |u1[1:0], ~|u1[1:0], ^u1[1:0], ~^u1[1:0], ^~u1[1:0] }; + 75: y <= { &s1[1:0], ~&s1[1:0], |s1[1:0], ~|s1[1:0], ^s1[1:0], ~^s1[1:0], ^~s1[1:0] }; + + 76: y <= { u1[1:0] && u2[1:0], u1[1:0] && u2[1:0], !u1[1:0] }; + 77: y <= {4{u1[1:0]}}; + 78: y <= {u1, u2} ^ {s1, s2}; + 79: y <= {u1, u2} & {s1, s2}; + + 80: y <= u1[0] ? u1 : u2; + 81: y <= u1[0] ? u1 : s2; + 82: y <= u1[0] ? s1 : u2; + 83: y <= u1[0] ? s1 : s2; + endcase +end + +endmodule diff --git a/chips/yosys/tests/simple/param_attr.v b/chips/yosys/tests/simple/param_attr.v new file mode 100644 index 0000000000000000000000000000000000000000..34d63a34e01910d702cbc0b72c11d1e24b34185f --- /dev/null +++ b/chips/yosys/tests/simple/param_attr.v @@ -0,0 +1,11 @@ +module uut_param_attr (I, O); + +(* PARAMETER_ATTRIBUTE = "attribute_content" *) +parameter WIDTH = 1; + +input wire [WIDTH-1:0] I; +output wire [WIDTH-1:0] O; + +assign O = I; + +endmodule diff --git a/chips/yosys/tests/simple/paramods.v b/chips/yosys/tests/simple/paramods.v new file mode 100644 index 0000000000000000000000000000000000000000..a404c07dabdd44ff572bcb665bf970190adc8e08 --- /dev/null +++ b/chips/yosys/tests/simple/paramods.v @@ -0,0 +1,52 @@ + +module pm_test1(a, b, x, y); + +input [7:0] a, b; +output [7:0] x, y; + +inc #(.step(3)) inc_a (.in(a), .out(x)); +inc #(.width(4), .step(7)) inc_b (b, y); + +endmodule + +// ----------------------------------- + +module pm_test2(a, b, x, y); + +input [7:0] a, b; +output [7:0] x, y; + +inc #(5) inc_a (.in(a), .out(x)); +inc #(4, 7) inc_b (b, y); + +endmodule + +// ----------------------------------- + +module pm_test3(a, b, x, y); + +input [7:0] a, b; +output [7:0] x, y; + +inc inc_a (.in(a), .out(x)); +inc inc_b (b, y); + +defparam inc_a.step = 3; +defparam inc_b.step = 7; +defparam inc_b.width = 4; + +endmodule + +// ----------------------------------- + +module inc(in, out); + +parameter width = 8; +parameter step = 1; + +input [width-1:0] in; +output [width-1:0] out; + +assign out = in + step; + +endmodule diff --git a/chips/yosys/tests/simple/partsel.v b/chips/yosys/tests/simple/partsel.v new file mode 100644 index 0000000000000000000000000000000000000000..722ed7b1bd9ab463e49878e5475f21f06a6648f2 --- /dev/null +++ b/chips/yosys/tests/simple/partsel.v @@ -0,0 +1,151 @@ +module partsel_test001(input [2:0] idx, input [31:0] data, output [3:0] slice_up, slice_down); +wire [5:0] offset = idx << 2; +assign slice_up = data[offset +: 4]; +assign slice_down = data[offset + 3 -: 4]; +endmodule + +module partsel_test002 ( + input clk, rst, + input [7:0] a, + input [0:7] b, + input [1:0] s, + output [7:0] x1, x2, x3, + output [0:7] x4, x5, x6, + output [7:0] y1, y2, y3, + output [0:7] y4, y5, y6, + output [7:0] z1, z2, z3, + output [0:7] z4, z5, z6, + output [7:0] w1, w2, w3, + output [0:7] w4, w5, w6, + output [7:0] p1, p2, p3, p4, p5, p6, + output [0:7] q1, q2, q3, q4, q5, q6, + output reg [7:0] r1, + output reg [0:7] r2 +); + +assign x1 = a, x2 = a + b, x3 = b; +assign x4 = a, x5 = a + b, x6 = b; +assign y1 = a[4 +: 3], y2 = a[4 +: 3] + b[4 +: 3], y3 = b[4 +: 3]; +assign y4 = a[4 +: 3], y5 = a[4 +: 3] + b[4 +: 3], y6 = b[4 +: 3]; +assign z1 = a[4 -: 3], z2 = a[4 -: 3] + b[4 -: 3], z3 = b[4 -: 3]; +assign z4 = a[4 -: 3], z5 = a[4 -: 3] + b[4 -: 3], z6 = b[4 -: 3]; +assign w1 = a[6:3], w2 = a[6:3] + b[3:6], w3 = b[3:6]; +assign w4 = a[6:3], w5 = a[6:3] + b[3:6], w6 = b[3:6]; +assign p1 = a[s], p2 = b[s], p3 = a[s+2 +: 2], p4 = b[s+2 +: 2], p5 = a[s+2 -: 2], p6 = b[s+2 -: 2]; +assign q1 = a[s], q2 = b[s], q3 = a[s+2 +: 2], q4 = b[s+2 +: 2], q5 = a[s+2 -: 2], q6 = b[s+2 -: 2]; + +always @(posedge clk) begin + if (rst) begin + { r1, r2 } = 16'h1337 ^ {a, b}; + end else begin + case (s) + 0: begin + r1[3:0] <= r2[0:3] ^ x1; + r2[4:7] <= r1[7:4] ^ x4; + end + 1: begin + r1[2 +: 3] <= r2[5 -: 3] + x1; + r2[3 +: 3] <= r1[6 -: 3] + x4; + end + 2: begin + r1[6 -: 3] <= r2[3 +: 3] - x1; + r2[7 -: 3] <= r1[4 +: 3] - x4; + end + 3: begin + r1 <= r2; + r2 <= r1; + end + endcase + end +end + +endmodule + +module partsel_test003(input [2:0] a, b, input [31:0] din, output [3:0] dout); +assign dout = din[a*b +: 2]; +endmodule + +module partsel_test004 ( + input [31:0] din, + input signed [4:0] n, + output reg [31:0] dout +); + always @(*) begin + dout = 0; + dout[n+1 +: 2] = din[n +: 2]; + end +endmodule + + +module partsel_test005 ( + input [31:0] din, + input signed [4:0] n, + output reg [31:0] dout +); + always @(*) begin + dout = 0; + dout[n+1] = din[n]; + end +endmodule + +module partsel_test006 ( + input [31:-32] din, + input signed [4:0] n, + output reg [31:-32] dout +); + always @(*) begin + dout = 0; + dout[n+1 +: 2] = din[n +: 2]; + end +endmodule + + +module partsel_test007 ( + input [31:-32] din, + input signed [4:0] n, + output reg [31:-32] dout +); + always @(*) begin + dout = 0; + dout[n+1] = din[n]; + end +endmodule + + +module partsel_test008 ( + input [127:0] din, + input [3:0] idx, + input [4:0] uoffset, + input signed [4:0] soffset, + output [ 7:0] dout0, + output [ 7:0] dout1, + output [ 7:0] dout2, + output [ 7:0] dout3, + output [ 3:0] dout4, + output [ 3:0] dout5, + output [ 3:0] dout6, + output [ 3:0] dout7, + output [ 3:0] dout8, + output [11:0] dout9, + output [11:0] dout10, + output [11:0] dout11 +); + +// common: block-select with offsets +assign dout0 = din[idx*8 +uoffset +:8]; +assign dout1 = din[idx*8 -uoffset +:8]; +assign dout2 = din[idx*8 +soffset +:8]; +assign dout3 = din[idx*8 -soffset +:8]; + +// only partial block used +assign dout4 = din[idx*8 +uoffset +:4]; +assign dout5 = din[idx*8 -uoffset +:4]; +assign dout6 = din[idx*8 +soffset +:4]; +assign dout7 = din[idx*8 -soffset +:4]; + +// uncommon: more than one block used +assign dout8 = din[idx*8 +uoffset +:12]; +assign dout9 = din[idx*8 -uoffset +:12]; +assign dout10 = din[idx*8 +soffset +:12]; +assign dout11 = din[idx*8 -soffset +:12]; +endmodule diff --git a/chips/yosys/tests/simple/process.v b/chips/yosys/tests/simple/process.v new file mode 100644 index 0000000000000000000000000000000000000000..3be002bbb4fbd3863d13d117c9b08f7884a1d8a0 --- /dev/null +++ b/chips/yosys/tests/simple/process.v @@ -0,0 +1,83 @@ + +module blocking_cond (in, out); + +input in; +output reg out; +reg tmp; + +always @* begin + tmp = 1; + out = 1'b0; + case (1'b1) + tmp: out = in; + endcase + tmp = 0; +end + +endmodule + +// ------------------------------------------------------------- + +module uut(clk, arst, a, b, c, d, e, f, out1); + +input clk, arst, a, b, c, d, e, f; +output reg [3:0] out1; + +always @(posedge clk, posedge arst) begin + if (arst) + out1 = 0; + else begin + if (a) begin + case ({b, c}) + 2'b00: + out1 = out1 + 9; + 2'b01, 2'b10: + out1 = out1 + 13; + endcase + if (d) begin + out1 = out1 + 2; + out1 = out1 + 1; + end + case ({e, f}) + 2'b11: + out1 = out1 + 8; + 2'b00: + ; + default: + out1 = out1 + 10; + endcase + out1 = out1 ^ 7; + end + out1 = out1 + 14; + end +end + +endmodule + +// ------------------------------------------------------------- + +// extracted from ../asicworld/code_hdl_models_uart.v +// (triggered a bug in the proc_mux pass) +module uart (reset, txclk, ld_tx_data, tx_empty, tx_cnt); + +input reset; +input txclk; +input ld_tx_data; + +output reg tx_empty; +output reg [3:0] tx_cnt; + +always @ (posedge txclk) +if (reset) begin + tx_empty <= 1; + tx_cnt <= 0; +end else begin + if (ld_tx_data) begin + tx_empty <= 0; + end + if (!tx_empty) begin + tx_cnt <= tx_cnt + 1; + end +end + +endmodule diff --git a/chips/yosys/tests/simple/real_cond.v b/chips/yosys/tests/simple/real_cond.v new file mode 100644 index 0000000000000000000000000000000000000000..16d0f5385d29ebb8b7298ca3fd821ca6befaa462 --- /dev/null +++ b/chips/yosys/tests/simple/real_cond.v @@ -0,0 +1,8 @@ +module real_cond(input i, output a, b, c); + localparam real Q = 0.25, N = -0.0; + assign a = Q ? 1 : 0; + assign b = N ? 1 : 0; + reg r; + always @* if (Q) r = i; else r = ~i; + assign c = r; +endmodule diff --git a/chips/yosys/tests/simple/real_rtoi.v b/chips/yosys/tests/simple/real_rtoi.v new file mode 100644 index 0000000000000000000000000000000000000000..1b896f51df26adede86f963ca178dfde231fc5b9 --- /dev/null +++ b/chips/yosys/tests/simple/real_rtoi.v @@ -0,0 +1,3 @@ +module real_rtoi(output [31:0] a); + assign a = $rtoi(1.0e20); +endmodule diff --git a/chips/yosys/tests/simple/realexpr.v b/chips/yosys/tests/simple/realexpr.v new file mode 100644 index 0000000000000000000000000000000000000000..74ed8faa56ca26561043ab7f0c402c448be29f61 --- /dev/null +++ b/chips/yosys/tests/simple/realexpr.v @@ -0,0 +1,33 @@ +module demo_001(y1, y2, y3, y4); + output [7:0] y1, y2, y3, y4; + + localparam [7:0] p1 = 123.45; + localparam real p2 = 123.45; + localparam real p3 = 123; + localparam p4 = 123.45; + + assign y1 = p1 + 0.2; + assign y2 = p2 + 0.2; + assign y3 = p3 + 0.2; + assign y4 = p4 + 0.2; +endmodule + +module demo_002(y0, y1, y2, y3); + output [63:0] y0, y1, y2, y3; + + assign y0 = 1'bx >= (-1 * -1.17); + assign y1 = 1 ? 1 ? -1 : 'd0 : 0.0; + assign y2 = 1 ? -1 : 1 ? 'd0 : 0.0; + assign y3 = 1 ? -1 : 'd0; +endmodule + +module demo_003(output A, B); + parameter real p = 0; + assign A = (p==1.0); + assign B = (p!="1.000000"); +endmodule + +module demo_004(output A, B, C, D); + demo_003 #(1.0) demo_real (A, B); + demo_003 #(1) demo_int (C, D); +endmodule diff --git a/chips/yosys/tests/simple/repwhile.v b/chips/yosys/tests/simple/repwhile.v new file mode 100644 index 0000000000000000000000000000000000000000..5d0c75fa60e6f7fcbf91f14847e68a1b85e8aa5b --- /dev/null +++ b/chips/yosys/tests/simple/repwhile.v @@ -0,0 +1,36 @@ +module repwhile_test001(input [5:0] a, output [7:0] y, output [31:0] x); + + function [7:0] mylog2; + input [31:0] value; + begin + mylog2 = 0; + while (value > 0) begin + value = value >> 1; + mylog2 = mylog2 + 1; + end + end + endfunction + + function [31:0] myexp2; + input [7:0] value; + begin + myexp2 = 1; + repeat (value) + myexp2 = myexp2 << 1; + end + endfunction + + reg [7:0] y_table [63:0]; + reg [31:0] x_table [63:0]; + + integer i; + initial begin + for (i = 0; i < 64; i = i+1) begin + y_table[i] <= mylog2(i); + x_table[i] <= myexp2(i); + end + end + + assign y = y_table[a]; + assign x = x_table[a]; +endmodule diff --git a/chips/yosys/tests/simple/retime.v b/chips/yosys/tests/simple/retime.v new file mode 100644 index 0000000000000000000000000000000000000000..30b6087dc865dd4ad67be21441b7ff39030d305b --- /dev/null +++ b/chips/yosys/tests/simple/retime.v @@ -0,0 +1,6 @@ +module retime_test(input clk, input [7:0] a, output z); + reg [7:0] ff = 8'hF5; + always @(posedge clk) + ff <= {ff[6:0], ^a}; + assign z = ff[7]; +endmodule diff --git a/chips/yosys/tests/simple/rotate.v b/chips/yosys/tests/simple/rotate.v new file mode 100644 index 0000000000000000000000000000000000000000..e1fd2e4086367f77749f974e8fbbda2bc1ab8162 --- /dev/null +++ b/chips/yosys/tests/simple/rotate.v @@ -0,0 +1,47 @@ + +// test case taken from amber23 Verilog code +module a23_barrel_shift_fpga_rotate(i_in, direction, shift_amount, rot_prod); + +input [31:0] i_in; +input direction; +input [4:0] shift_amount; +output [31:0] rot_prod; + +// Generic rotate. Theoretical cost: 32x5 4-to-1 LUTs. +// Practically a bit higher due to high fanout of "direction". +generate +genvar i, j; + for (i = 0; i < 5; i = i + 1) + begin : netgen + wire [31:0] in; + reg [31:0] out; + for (j = 0; j < 32; j = j + 1) + begin : net + always @* + out[j] = in[j] & (~shift_amount[i] ^ direction) | + in[wrap(j, i)] & (shift_amount[i] ^ direction); + end + end + + // Order is reverted with respect to volatile shift_amount[0] + assign netgen[4].in = i_in; + for (i = 1; i < 5; i = i + 1) + begin : router + assign netgen[i-1].in = netgen[i].out; + end +endgenerate + +// Aliasing +assign rot_prod = netgen[0].out; + +function [4:0] wrap; +input integer pos; +input integer level; +integer out; +begin + out = pos - (1 << level); + wrap = out[4:0]; +end +endfunction + +endmodule diff --git a/chips/yosys/tests/simple/scopes.v b/chips/yosys/tests/simple/scopes.v new file mode 100644 index 0000000000000000000000000000000000000000..eecc1a0b2f87a0482baaa057e3c8d250227cc484 --- /dev/null +++ b/chips/yosys/tests/simple/scopes.v @@ -0,0 +1,63 @@ +module scopes_test_01(input [3:0] k, output reg [15:0] x, y); + function [15:0] func_01; + input [15:0] x, y; + begin + func_01 = x + y; + begin:blk + reg [15:0] x; + x = y; + func_01 = func_01 ^ x; + end + func_01 = func_01 ^ x; + end + endfunction + + function [15:0] func_02; + input [15:0] x, y; + begin + func_02 = x - y; + begin:blk + reg [15:0] func_02; + func_02 = 0; + end + end + endfunction + + task task_01; + input [3:0] a; + reg [15:0] y; + begin + y = a * 23; + x = x + y; + end + endtask + + task task_02; + input [3:0] a; + begin:foo + reg [15:0] x, z; + x = y; + begin:bar + reg [15:0] x; + x = 77 + a; + z = -x; + end + y = x ^ z; + end + endtask + + always @* begin + x = func_01(11, 22); + y = func_02(33, 44); + task_01(k); + task_02(k); + begin:foo + reg [15:0] y; + y = x; + y = y + k; + x = y; + end + x = func_01(y, x); + y = func_02(y, x); + end +endmodule diff --git a/chips/yosys/tests/simple/sign_part_assign.v b/chips/yosys/tests/simple/sign_part_assign.v new file mode 100644 index 0000000000000000000000000000000000000000..5f65ac284021c55d04d5ba7ac10bc62a10484b78 --- /dev/null +++ b/chips/yosys/tests/simple/sign_part_assign.v @@ -0,0 +1,20 @@ +module test ( + offset_i, + data_o, + data_ref_o +); +input wire [ 2:0] offset_i; +output reg [15:0] data_o; +output reg [15:0] data_ref_o; + +always @(*) begin + // defaults + data_o = '0; + data_ref_o = '0; + + // partial assigns + data_ref_o[offset_i+:4] = 4'b1111; // unsigned + data_o[offset_i+:4] = 1'sb1; // sign extension to 4'b1111 +end + +endmodule diff --git a/chips/yosys/tests/simple/signed_full_slice.v b/chips/yosys/tests/simple/signed_full_slice.v new file mode 100644 index 0000000000000000000000000000000000000000..f8a3315788529028ce5172fb962d17abbe568909 --- /dev/null +++ b/chips/yosys/tests/simple/signed_full_slice.v @@ -0,0 +1,29 @@ +module pass_through_a( + input wire [31:0] inp, + output wire [31:0] out +); + assign out[31:0] = inp[31:0]; +endmodule + +module top_a( + input wire signed [31:0] inp, + output wire signed [31:0] out +); + pass_through_a pt(inp[31:0], out[31:0]); +endmodule + +// tests both module declaration orderings + +module top_b( + input wire signed [31:0] inp, + output wire signed [31:0] out +); + pass_through_b pt(inp[31:0], out[31:0]); +endmodule + +module pass_through_b( + input wire [31:0] inp, + output wire [31:0] out +); + assign out[31:0] = inp[31:0]; +endmodule diff --git a/chips/yosys/tests/simple/signedexpr.v b/chips/yosys/tests/simple/signedexpr.v new file mode 100644 index 0000000000000000000000000000000000000000..8bba4a4b16b39d28dbd99a9085d547f25da4f3f0 --- /dev/null +++ b/chips/yosys/tests/simple/signedexpr.v @@ -0,0 +1,18 @@ +module signed_test01(a, b, xu, xs, yu, ys, zu, zs); + +input signed [1:0] a; +input signed [2:0] b; +output [3:0] xu, xs; +output [3:0] yu, ys; +output zu, zs; + +assign xu = (a + b) + 3'd0; +assign xs = (a + b) + 3'sd0; + +assign yu = {a + b} + 3'd0; +assign ys = {a + b} + 3'sd0; + +assign zu = a + b != 3'd0; +assign zs = a + b != 3'sd0; + +endmodule diff --git a/chips/yosys/tests/simple/sincos.v b/chips/yosys/tests/simple/sincos.v new file mode 100644 index 0000000000000000000000000000000000000000..b3124337daeee8d2f9ed541afc7f2b73d75c1ce2 --- /dev/null +++ b/chips/yosys/tests/simple/sincos.v @@ -0,0 +1,124 @@ +// File: design.v +// Generated by MyHDL 0.8 +// Date: Tue Dec 3 04:33:14 2013 + + +module d ( + cos_z0, + sin_z0, + done, + z0, + start, + clock, + reset +); +// Sine and cosine computer. +// +// This module computes the sine and cosine of an input angle. The +// floating point numbers are represented as integers by scaling them +// up with a factor corresponding to the number of bits after the point. +// +// Ports: +// ----- +// cos_z0: cosine of the input angle +// sin_z0: sine of the input angle +// done: output flag indicated completion of the computation +// z0: input angle +// start: input that starts the computation on a posedge +// clock: clock input +// reset: reset input + +output signed [19:0] cos_z0; +reg signed [19:0] cos_z0; +output signed [19:0] sin_z0; +reg signed [19:0] sin_z0; +output done; +reg done; +input signed [19:0] z0; +input start; +input clock; +input reset; + +(* gentb_constant = 1'b0 *) +wire reset; + +always @(posedge clock, posedge reset) begin: DESIGN_PROCESSOR + reg [5-1:0] i; + reg [1-1:0] state; + reg signed [20-1:0] dz; + reg signed [20-1:0] dx; + reg signed [20-1:0] dy; + reg signed [20-1:0] y; + reg signed [20-1:0] x; + reg signed [20-1:0] z; + if (reset) begin + state = 1'b0; + cos_z0 <= 1; + sin_z0 <= 0; + done <= 1'b0; + x = 0; + y = 0; + z = 0; + i = 0; + end + else begin + case (state) + 1'b0: begin + if (start) begin + x = 159188; + y = 0; + z = z0; + i = 0; + done <= 1'b0; + state = 1'b1; + end + end + 1'b1: begin + dx = $signed(y >>> $signed({1'b0, i})); + dy = $signed(x >>> $signed({1'b0, i})); + case (i) + 0: dz = 205887; + 1: dz = 121542; + 2: dz = 64220; + 3: dz = 32599; + 4: dz = 16363; + 5: dz = 8189; + 6: dz = 4096; + 7: dz = 2048; + 8: dz = 1024; + 9: dz = 512; + 10: dz = 256; + 11: dz = 128; + 12: dz = 64; + 13: dz = 32; + 14: dz = 16; + 15: dz = 8; + 16: dz = 4; + 17: dz = 2; + default: dz = 1; + endcase + if ((z >= 0)) begin + x = x - dx; + y = y + dy; + z = z - dz; + end + else begin + x = x + dx; + y = y - dy; + z = z + dz; + end + if ((i == (19 - 1))) begin + cos_z0 <= x; + sin_z0 <= y; + state = 1'b0; + done <= 1'b1; + end + else begin + i = i + 1; + end + end + endcase + end +end + +endmodule diff --git a/chips/yosys/tests/simple/specify.v b/chips/yosys/tests/simple/specify.v new file mode 100644 index 0000000000000000000000000000000000000000..a8b87f53ba696006a8e3c75bf0f4ed77a5c82906 --- /dev/null +++ b/chips/yosys/tests/simple/specify.v @@ -0,0 +1,30 @@ +module test_specify(input A, output B); + +specparam a=1; + +specify +endspecify + +specify +(A => B) = ( 1 ) ; +(A- => B) = ( 1,2 ) ; +(A+ => B) = ( 1,2,3 ) ; +(A => B) = ( + 1.1, 2, 3, + 4, 5.5, 6.6 +) ; +(A => B) = ( + 1.1, 2, 3, + 4, 5.5, 6.6 , + 7.7, 8.8, 9, + 10.1, 11, 12 +) ; +specparam b=1; +specparam [1:2] asasa=1; +endspecify + +specify +specparam c=1:2:3; +endspecify + +endmodule diff --git a/chips/yosys/tests/simple/string_format.v b/chips/yosys/tests/simple/string_format.v new file mode 100644 index 0000000000000000000000000000000000000000..cb7b419ac279457d492880b8c405c410fad9552b --- /dev/null +++ b/chips/yosys/tests/simple/string_format.v @@ -0,0 +1,7 @@ +module string_format_top; + parameter STR = "something interesting"; + initial begin + $display("A: %s", STR); + $display("B: %0s", STR); + end +endmodule diff --git a/chips/yosys/tests/simple/subbytes.v b/chips/yosys/tests/simple/subbytes.v new file mode 100644 index 0000000000000000000000000000000000000000..04269a99f0948e1e0c48fe73937eb70106635ad3 --- /dev/null +++ b/chips/yosys/tests/simple/subbytes.v @@ -0,0 +1,82 @@ + +// test taken from systemcaes from iwls2005 + +module subbytes_00(clk, reset, start_i, decrypt_i, data_i, ready_o, data_o, sbox_data_o, sbox_data_i, sbox_decrypt_o); + +input clk; +input reset; +input start_i; +input decrypt_i; +input [31:0] data_i; +output ready_o; +output [31:0] data_o; +output [7:0] sbox_data_o; +input [7:0] sbox_data_i; +output sbox_decrypt_o; + +reg ready_o; +reg [31:0] data_o; +reg [7:0] sbox_data_o; +reg sbox_decrypt_o; + +reg [1:0] state; +reg [1:0] next_state; +reg [31:0] data_reg; +reg [31:0] next_data_reg; +reg next_ready_o; + +always @(posedge clk or negedge reset) +begin + if (!reset) begin + data_reg = 0; + state = 0; + ready_o = 0; + end else begin + data_reg = next_data_reg; + state = next_state; + ready_o = next_ready_o; + end +end + +reg [31:0] data_i_var, data_reg_128; +reg [7:0] data_array [3:0]; +reg [7:0] data_reg_var [3:0]; + +always @(decrypt_i or start_i or state or data_i or sbox_data_i or data_reg) +begin + data_i_var = data_i; + + data_array[0] = data_i_var[ 31: 24]; + data_array[1] = data_i_var[ 23: 16]; + data_array[2] = data_i_var[ 15: 8]; + data_array[3] = data_i_var[ 7: 0]; + + data_reg_var[0] = data_reg[ 31: 24]; + data_reg_var[1] = data_reg[ 23: 16]; + data_reg_var[2] = data_reg[ 15: 8]; + data_reg_var[3] = data_reg[ 7: 0]; + + sbox_decrypt_o = decrypt_i; + sbox_data_o = data_array[state]; + next_state = state; + next_data_reg = data_reg; + + next_ready_o = 0; + data_o = data_reg; + + if (state) begin + if (start_i) begin + next_state = 1; + end + end else begin + data_reg_var[state] = sbox_data_i; + data_reg_128[ 31: 24] = data_reg_var[0]; + data_reg_128[ 23: 16] = data_reg_var[1]; + data_reg_128[ 15: 8] = data_reg_var[2]; + data_reg_128[ 7: 0] = data_reg_var[3]; + next_data_reg = data_reg_128; + next_state = state + 1; + end +end + +endmodule diff --git a/chips/yosys/tests/simple/task_func.v b/chips/yosys/tests/simple/task_func.v new file mode 100644 index 0000000000000000000000000000000000000000..f6e902f630ce72e588de674455527445a417c022 --- /dev/null +++ b/chips/yosys/tests/simple/task_func.v @@ -0,0 +1,141 @@ + +module task_func_test01(clk, a, b, c, x, y, z, w); + +input clk; +input [7:0] a, b, c; +output reg [7:0] x, y, z, w; + +function [7:0] sum_shift; +input [3:0] s1, s2, s3; +sum_shift = s1 + (s2 << 2) + (s3 << 4); +endfunction + +task reset_w; +w = 0; +endtask + +task add_to; +output [7:0] out; +input [7:0] in; +out = out + in; +endtask + +always @(posedge clk) begin + x = sum_shift(a, b, c); + y = sum_shift(a[7:4], b[5:2], c[3:0]); + z = sum_shift(a[0], b[5:4], c >> 5) ^ sum_shift(1, 2, 3); + + reset_w; + add_to(w, x); + add_to(w, y); + add_to(w, z); +end + +endmodule + +// ------------------------------------------------------------------- + +module task_func_test02(clk, a, b, c, x, y, z, w); + +input clk; +input [7:0] a, b, c; +output reg [7:0] x, y, z, w; + +function [7:0] sum_shift(input [3:0] s1, s2, s3); +sum_shift = s1 + (s2 << 2) + (s3 << 4); +endfunction + +task reset_w; +w = 0; +endtask + +task add_to(output [7:0] out, input [7:0] in); +out = out + in; +endtask + +always @(posedge clk) begin + x = sum_shift(a, b, c); + y = sum_shift(a[7:4], b[5:2], c[3:0]); + z = sum_shift(a[0], b[5:4], c >> 5) ^ sum_shift(1, 2, 3); + + reset_w; + add_to(w, x); + add_to(w, y); + add_to(w, z); +end + +endmodule + +// ------------------------------------------------------------------- + +module task_func_test03(input [7:0] din_a, input [7:0] din_b, output [7:0] dout_a); + assign dout_a = test(din_a,din_b); + function [7:0] test; + input [7:0] a; + input [7:0] b; + begin : TEST + integer i; + for (i = 0; i <= 7; i = i + 1) + test[i] = a[i] & b[i]; + end + endfunction +endmodule + +// ------------------------------------------------------------------- + +module task_func_test04(input [7:0] in, output [7:0] out1, out2, out3, out4); + parameter p = 23; + parameter px = 42; + function [7:0] test1; + input [7:0] i; + parameter p = 42; + begin + test1 = i + p; + end + endfunction + function [7:0] test2; + input [7:0] i; + parameter p2 = p+42; + begin + test2 = i + p2; + end + endfunction + function [7:0] test3; + input [7:0] i; + begin + test3 = i + p; + end + endfunction + function [7:0] test4; + input [7:0] i; + parameter px = p + 13; + parameter p3 = px - 37; + parameter p4 = p3 ^ px; + begin + test4 = i + p4; + end + endfunction + assign out1 = test1(in); + assign out2 = test2(in); + assign out3 = test3(in); + assign out4 = test4(in); +endmodule + +// ------------------------------------------------------------------- + +// https://github.com/YosysHQ/yosys/issues/857 +module task_func_test05(data_in,data_out,clk); + output reg data_out; + input data_in; + input clk; + + task myTask; + output out; + input in; + out = in; + endtask + + always @(posedge clk) begin + myTask(data_out,data_in); + end +endmodule diff --git a/chips/yosys/tests/simple/undef_eqx_nex.v b/chips/yosys/tests/simple/undef_eqx_nex.v new file mode 100644 index 0000000000000000000000000000000000000000..b0178677bc0fa37664ec2f57b4bcf8181a6e07b0 --- /dev/null +++ b/chips/yosys/tests/simple/undef_eqx_nex.v @@ -0,0 +1,11 @@ +module undef_eqx_nex(y); +output [7:0] y; +assign y[0] = 0/0; +assign y[1] = 0/1; +assign y[2] = 0/0 == 32'bx; +assign y[3] = 0/0 != 32'bx; +assign y[4] = 0/0 === 32'bx; +assign y[5] = 0/0 !== 32'bx; +assign y[6] = 0/1 === 32'bx; +assign y[7] = 0/1 !== 32'bx; +endmodule diff --git a/chips/yosys/tests/simple/unnamed_block_decl.sv b/chips/yosys/tests/simple/unnamed_block_decl.sv new file mode 100644 index 0000000000000000000000000000000000000000..e78c577daae374eb64e38de85b72c249481cdd83 --- /dev/null +++ b/chips/yosys/tests/simple/unnamed_block_decl.sv @@ -0,0 +1,17 @@ +module unnamed_block_decl(z); + output integer z; + initial begin + integer x; + x = 1; + begin + integer y; + y = x + 1; + begin + integer z; + z = y + 1; + y = z + 1; + end + z = y + 1; + end + end +endmodule diff --git a/chips/yosys/tests/simple/usb_phy_tests.v b/chips/yosys/tests/simple/usb_phy_tests.v new file mode 100644 index 0000000000000000000000000000000000000000..dcc5ace4fd1bc7ff862a3fae6d352a346e73e7e0 --- /dev/null +++ b/chips/yosys/tests/simple/usb_phy_tests.v @@ -0,0 +1,35 @@ + +// from usb_rx_phy +module usb_phy_test01(clk, rst, rx_en, fs_ce); + +input clk, rst; +input rx_en; +output reg fs_ce; +reg [1:0] dpll_next_state; +reg [1:0] dpll_state; + +always @(posedge clk) + dpll_state <= rst ? 0 : dpll_next_state; + +always @* + begin + fs_ce = 1'b0; + case(dpll_state) + 2'h0: + if(rx_en) dpll_next_state = 2'h0; + else dpll_next_state = 2'h1; + 2'h1:begin + fs_ce = 1'b1; + if(rx_en) dpll_next_state = 2'h3; + else dpll_next_state = 2'h2; + end + 2'h2: + if(rx_en) dpll_next_state = 2'h0; + else dpll_next_state = 2'h3; + 2'h3: + if(rx_en) dpll_next_state = 2'h0; + else dpll_next_state = 2'h0; + endcase + end + +endmodule diff --git a/chips/yosys/tests/simple/values.v b/chips/yosys/tests/simple/values.v new file mode 100644 index 0000000000000000000000000000000000000000..c69b57176b455582ef734812fb45d31e935de627 --- /dev/null +++ b/chips/yosys/tests/simple/values.v @@ -0,0 +1,43 @@ + +module test_signed(a, b, c, d, y); + +input [3:0] a, b, c; +input signed [3:0] d; +output reg [7:0] y; + +always @* begin + if (a && b) + y = c; + else + y = d; +end + +endmodule + +module test_const(a, y); + +input [3:0] a; +output reg [28:0] y; + +always @* + case (a) + 4'b0000: y = 0; + 4'b0001: y = 11; + 4'b0010: y = 222; + 4'b0011: y = 3456; + 4'b0100: y = 'b10010010; + 4'b0101: y = 'h123abc; + 4'b0110: y = 'o1234567; + 4'b0111: y = 'd3456789; + 4'b1000: y = 16'b10010010; + 4'b1001: y = 16'h123abc; + 4'b1010: y = 16'o1234567; + 4'b1011: y = 16'd3456789; + 4'b1100: y = { "foo", "bar" }; + 4'b1101: y = "foobarfoobarfoobar"; + 4'b1110: y = 16'h1; + 4'b1111: y = a; + default: y = 'bx; + endcase + +endmodule diff --git a/chips/yosys/tests/simple/verilog_primitives.v b/chips/yosys/tests/simple/verilog_primitives.v new file mode 100644 index 0000000000000000000000000000000000000000..0ee07393bc81c6480829bd55824a99360518e7b3 --- /dev/null +++ b/chips/yosys/tests/simple/verilog_primitives.v @@ -0,0 +1,15 @@ +module verilog_primitives ( + input wire in1, in2, in3, + output wire out_buf0, out_buf1, out_buf2, out_buf3, out_buf4, + output wire out_not0, out_not1, out_not2, + output wire out_xnor +); + +buf u_buf0 (out_buf0, in1); +buf u_buf1 (out_buf1, out_buf2, out_buf3, out_buf4, in2); + +not u_not0 (out_not0, out_not1, out_not2, in1); + +xnor u_xnor0 (out_xnor, in1, in2, in3); + +endmodule diff --git a/chips/yosys/tests/simple/vloghammer.v b/chips/yosys/tests/simple/vloghammer.v new file mode 100644 index 0000000000000000000000000000000000000000..e36c971f7262fa7da15cb2af59aecc1d4613eff0 --- /dev/null +++ b/chips/yosys/tests/simple/vloghammer.v @@ -0,0 +1,81 @@ + +// test cases found using vloghammer +// https://github.com/YosysHQ/VlogHammer + +module test01(a, y); + input [7:0] a; + output [3:0] y; + assign y = ~a >> 4; +endmodule + +module test02(a, y); + input signed [3:0] a; + output signed [4:0] y; + assign y = (~a) >> 1; +endmodule + +module test03(a, b, y); + input [2:0] a; + input signed [1:0] b; + output y; + assign y = ~(a >>> 1) == b; +endmodule + +module test04(a, y); + input a; + output [1:0] y; + assign y = ~(a - 1'b0); +endmodule + +// .. this test triggers a bug in Xilinx ISIM. +// module test05(a, y); +// input a; +// output y; +// assign y = 12345 >> {a, 32'd0}; +// endmodule + +// .. this test triggers a bug in Icarus Verilog. +// module test06(a, b, c, y); +// input signed [3:0] a; +// input signed [1:0] b; +// input signed [1:0] c; +// output [5:0] y; +// assign y = (a >> b) >>> c; +// endmodule + +module test07(a, b, y); + input signed [1:0] a; + input signed [2:0] b; + output y; + assign y = 2'b11 != a+b; +endmodule + +module test08(a, b, y); + input [1:0] a; + input [1:0] b; + output y; + assign y = a == ($signed(b) >>> 1); +endmodule + +module test09(a, b, c, y); + input a; + input signed [1:0] b; + input signed [2:0] c; + output [3:0] y; + assign y = a ? b : c; +endmodule + +module test10(a, b, c, y); + input a; + input signed [1:0] b; + input signed [2:0] c; + output y; + assign y = ^(a ? b : c); +endmodule + +// module test11(a, b, y); +// input signed [3:0] a; +// input signed [3:0] b; +// output signed [5:0] y; +// assign y = -(5'd27); +// endmodule diff --git a/chips/yosys/tests/simple/wandwor.v b/chips/yosys/tests/simple/wandwor.v new file mode 100644 index 0000000000000000000000000000000000000000..40502acfc017b65382848c355120d6cbfa7c2c09 --- /dev/null +++ b/chips/yosys/tests/simple/wandwor.v @@ -0,0 +1,36 @@ +module wandwor_test0 (A, B, C, D, X, Y, Z); + input A, B, C, D; + output wor X; + output wand Y; + output Z; + + assign X = A, X = B, Y = C, Y = D; + wandwor_foo foo_0 (C, D, X); + wandwor_foo foo_1 (A, B, Y); + wandwor_foo foo_2 (X, Y, Z); +endmodule + +module wandwor_test1 (A, B, C, D, X, Y, Z); + input [3:0] A, B, C, D; + output wor [3:0] X; + output wand [3:0] Y; + output Z; + + wandwor_bar bar_inst ( + .I0({A, B}), + .I1({B, A}), + .O({X, Y}) + ); + + assign X = C, X = D; + assign Y = C, Y = D; + assign Z = ^{X,Y}; +endmodule + +module wandwor_foo(input I0, I1, output O); + assign O = I0 ^ I1; +endmodule + +module wandwor_bar(input [7:0] I0, I1, output [7:0] O); + assign O = I0 + I1; +endmodule diff --git a/chips/yosys/tests/simple/wreduce.v b/chips/yosys/tests/simple/wreduce.v new file mode 100644 index 0000000000000000000000000000000000000000..ba54843858fcff005609bf5ecd50a26998a2b71f --- /dev/null +++ b/chips/yosys/tests/simple/wreduce.v @@ -0,0 +1,9 @@ +module wreduce_test0(input [7:0] a, b, output [15:0] x, y, z); + assign x = -$signed({1'b0, a}); + assign y = $signed({1'b0, a}) + $signed({1'b0, b}); + assign z = x ^ y; +endmodule + +module wreduce_test1(input [31:0] a, b, output [7:0] x, y, z, w); + assign x = a - b, y = a * b, z = a >> b, w = a << b; +endmodule diff --git a/chips/yosys/tests/simple/xfirrtl b/chips/yosys/tests/simple/xfirrtl new file mode 100644 index 0000000000000000000000000000000000000000..10063d2c2e9aaa5ac7be93f2a4896ca40a27ee5d --- /dev/null +++ b/chips/yosys/tests/simple/xfirrtl @@ -0,0 +1,29 @@ +# This file contains the names of verilog files to exclude from verilog to FIRRTL regression tests due to known failures. +arraycells.v inst id[0] of +defvalue.sv Initial value not supported +dff_different_styles.v +dff_init.v Initial value not supported +generate.v combinational loop +hierdefparam.v inst id[0] of +i2c_master_tests.v $adff +implicit_ports.v not fully initialized +macros.v drops modules +mem2reg.v drops modules +mem_arst.v $adff +memory.v $adff +multiplier.v inst id[0] of +muxtree.v drops modules +omsp_dbg_uart.v $adff +partsel.v drops modules +process.v drops modules +realexpr.v drops modules +retime.v Initial value (11110101) for (retime_test.ff) not supported +scopes.v original verilog issues ( -x where x isn't declared signed) +sincos.v $adff +specify.v no code (empty module generates error +subbytes.v $adff +task_func.v drops modules +values.v combinational loop +wandwor.v Invalid connect to an expression that is not a reference or a WritePort. +vloghammer.v combinational loop +wreduce.v original verilog issues ( -x where x isn't declared signed) diff --git a/chips/yosys/tests/simple_abc9/.gitignore b/chips/yosys/tests/simple_abc9/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..e31b7dc7f7fed1ef71e9cd75155b38d06b3b51a9 --- /dev/null +++ b/chips/yosys/tests/simple_abc9/.gitignore @@ -0,0 +1,3 @@ +*.v +*.sv +*.bak diff --git a/chips/yosys/tests/simple_abc9/abc9.v b/chips/yosys/tests/simple_abc9/abc9.v new file mode 100644 index 0000000000000000000000000000000000000000..fba089b1f8bbbf009288588f1adaeaeddf821327 --- /dev/null +++ b/chips/yosys/tests/simple_abc9/abc9.v @@ -0,0 +1,328 @@ +module abc9_test001(input a, output o); +assign o = a; +endmodule + +module abc9_test002(input [1:0] a, output o); +assign o = a[1]; +endmodule + +module abc9_test003(input [1:0] a, output [1:0] o); +assign o = a; +endmodule + +module abc9_test004(input [1:0] a, output o); +assign o = ^a; +endmodule + +module abc9_test005(input [1:0] a, output o, output p); +assign o = ^a; +assign p = ~o; +endmodule + +module abc9_test006(input [1:0] a, output [2:0] o); +assign o[0] = ^a; +assign o[1] = ~o[0]; +assign o[2] = o[1]; +endmodule + +module abc9_test007(input a, output o); +wire b, c; +assign c = ~a; +assign b = c; +abc9_test007_sub s(b, o); +endmodule + +module abc9_test007_sub(input a, output b); +assign b = a; +endmodule + +module abc9_test008(input a, output o); +wire b, c; +assign b = ~a; +assign c = b; +abc9_test008_sub s(b, o); +endmodule + +module abc9_test008_sub(input a, output b); +assign b = ~a; +endmodule + +module abc9_test009(inout io, input oe); +reg latch; +always @(io or oe) + if (!oe) + latch <= io; +assign io = oe ? ~latch : 1'bz; +endmodule + +module abc9_test010(inout [7:0] io, input oe); +reg [7:0] latch; +always @(io or oe) + if (!oe) + latch <= io; +assign io = oe ? ~latch : 8'bz; +endmodule + +module abc9_test011(inout io, input oe); +reg latch; +always @(io or oe) + if (!oe) + latch <= io; +//assign io = oe ? ~latch : 8'bz; +endmodule + +module abc9_test012(inout io, input oe); +reg latch; +//always @(io or oe) +// if (!oe) +// latch <= io; +assign io = oe ? ~latch : 8'bz; +endmodule + +module abc9_test013(inout [3:0] io, input oe); +reg [3:0] latch; +always @(io or oe) + if (!oe) + latch[3:0] <= io[3:0]; + else + latch[7:4] <= io; +assign io[3:0] = oe ? ~latch[3:0] : 4'bz; +assign io[7:4] = !oe ? {latch[4], latch[7:3]} : 4'bz; +endmodule + +module abc9_test014(inout [7:0] io, input oe); +abc9_test012_sub sub(io, oe); +endmodule + +module abc9_test012_sub(inout [7:0] io, input oe); +reg [7:0] latch; +always @(io or oe) + if (!oe) + latch[3:0] <= io; + else + latch[7:4] <= io; +assign io[3:0] = oe ? ~latch[3:0] : 4'bz; +assign io[7:4] = !oe ? {latch[4], latch[7:3]} : 4'bz; +endmodule + +module abc9_test015(input a, output b, input c); +assign b = ~a; +(* keep *) wire d; +assign d = ~c; +endmodule + +module abc9_test016(input a, output b); +assign b = ~a; +(* keep *) reg c; +always @* c <= ~a; +endmodule + +module abc9_test017(input a, output b); +assign b = ~a; +(* keep *) reg c; +always @* c = b; +endmodule + +module abc9_test018(input a, output b, output c); +assign b = ~a; +(* keep *) wire [1:0] d; +assign c = &d; +endmodule + +module abc9_test019(input a, output b); +assign b = ~a; +(* keep *) reg [1:0] c; +reg d; +always @* d <= &c; +endmodule + +module abc9_test020(input a, output b); +assign b = ~a; +(* keep *) reg [1:0] c; +(* keep *) reg d; +always @* d <= &c; +endmodule + +// Citation: https://github.com/alexforencich/verilog-ethernet +module abc9_test021(clk, rst, s_eth_hdr_valid, s_eth_hdr_ready, s_eth_dest_mac, s_eth_src_mac, s_eth_type, s_eth_payload_axis_tdata, s_eth_payload_axis_tkeep, s_eth_payload_axis_tvalid, s_eth_payload_axis_tready, s_eth_payload_axis_tlast, s_eth_payload_axis_tid, s_eth_payload_axis_tdest, s_eth_payload_axis_tuser, m_eth_hdr_valid, m_eth_hdr_ready, m_eth_dest_mac, m_eth_src_mac, m_eth_type, m_eth_payload_axis_tdata, m_eth_payload_axis_tkeep, m_eth_payload_axis_tvalid, m_eth_payload_axis_tready, m_eth_payload_axis_tlast, m_eth_payload_axis_tid, m_eth_payload_axis_tdest, m_eth_payload_axis_tuser); + input clk; + output [47:0] m_eth_dest_mac; + input m_eth_hdr_ready; + output m_eth_hdr_valid; + output [7:0] m_eth_payload_axis_tdata; + output [7:0] m_eth_payload_axis_tdest; + output [7:0] m_eth_payload_axis_tid; + output m_eth_payload_axis_tkeep; + output m_eth_payload_axis_tlast; + input m_eth_payload_axis_tready; + output m_eth_payload_axis_tuser; + output m_eth_payload_axis_tvalid; + output [47:0] m_eth_src_mac; + output [15:0] m_eth_type; + input rst; + input [191:0] s_eth_dest_mac; + output [3:0] s_eth_hdr_ready; + input [3:0] s_eth_hdr_valid; + input [31:0] s_eth_payload_axis_tdata; + input [31:0] s_eth_payload_axis_tdest; + input [31:0] s_eth_payload_axis_tid; + input [3:0] s_eth_payload_axis_tkeep; + input [3:0] s_eth_payload_axis_tlast; + output [3:0] s_eth_payload_axis_tready; + input [3:0] s_eth_payload_axis_tuser; + input [3:0] s_eth_payload_axis_tvalid; + input [191:0] s_eth_src_mac; + input [63:0] s_eth_type; + (* keep *) + wire [0:0] grant, request; + wire a; + not u0 ( + a, + grant[0] + ); + and u1 ( + request[0], + s_eth_hdr_valid[0], + a + ); + (* keep *) + MUXF8 u2 ( + .I0(1'bx), + .I1(1'bx), + .O(o), + .S(1'bx) + ); + arbiter arb_inst ( + .acknowledge(acknowledge), + .clk(clk), + .grant(grant), + .grant_encoded(grant_encoded), + .grant_valid(grant_valid), + .request(request), + .rst(rst) + ); +endmodule + +module arbiter (clk, rst, request, acknowledge, grant, grant_valid, grant_encoded); + input [3:0] acknowledge; + input clk; + output [3:0] grant; + output [1:0] grant_encoded; + output grant_valid; + input [3:0] request; + input rst; +endmodule + +(* abc9_box, blackbox *) +module MUXF8(input I0, I1, S, output O); +specify + (I0 => O) = 0; + (I1 => O) = 0; + (S => O) = 0; +endspecify +endmodule + +// Citation: https://github.com/alexforencich/verilog-ethernet +module abc9_test022 +( + input wire clk, + input wire i, + output wire [7:0] m_eth_payload_axis_tkeep +); + reg [7:0] m_eth_payload_axis_tkeep_reg = 8'd0; + assign m_eth_payload_axis_tkeep = m_eth_payload_axis_tkeep_reg; + always @(posedge clk) + m_eth_payload_axis_tkeep_reg <= i ? 8'hff : 8'h0f; +endmodule + +// Citation: https://github.com/riscv/riscv-bitmanip +module abc9_test023 #( + parameter integer N = 2, + parameter integer M = 2 +) ( + input [7:0] din, + output [M-1:0] dout +); + wire [2*M-1:0] mask = {M{1'b1}}; + assign dout = (mask << din[N-1:0]) >> M; +endmodule + +module abc9_test024(input [3:0] i, output [3:0] o); +abc9_test024_sub a(i[1:0], o[1:0]); +endmodule + +module abc9_test024_sub(input [1:0] i, output [1:0] o); +assign o = i; +endmodule + +module abc9_test025(input [3:0] i, output [3:0] o); +abc9_test024_sub a(i[2:1], o[2:1]); +endmodule + +module abc9_test026(output [3:0] o, p); +assign o = { 1'b1, 1'bx }; +assign p = { 1'b1, 1'bx, 1'b0 }; +endmodule + +module abc9_test030(input [3:0] d, input en, output reg [3:0] q); +always @* + if (en) + q <= d; +endmodule + +module abc9_test031(input clk1, clk2, d, output reg q1, q2); +always @(posedge clk1) q1 <= d; +always @(negedge clk2) q2 <= q1; +endmodule + +module abc9_test032(input clk, d, r, output reg q); +always @(posedge clk or posedge r) + if (r) q <= 1'b0; + else q <= d; +endmodule + +module abc9_test033(input clk, d, r, output reg q); +always @(negedge clk or posedge r) + if (r) q <= 1'b1; + else q <= d; +endmodule + +module abc9_test034(input clk, d, output reg q1, q2); +always @(posedge clk) q1 <= d; +always @(posedge clk) q2 <= q1; +endmodule + +module abc9_test035(input clk, d, output reg [1:0] q); +always @(posedge clk) q[0] <= d; +always @(negedge clk) q[1] <= q[0]; +endmodule + +module abc9_test036(input A, B, S, output [1:0] O); + (* keep *) + MUXF8 m ( + .I0(A), + .I1(B), + .O(O[0]), + .S(S) + ); + MUXF8 m2 ( + .I0(A), + .I1(B), + .O(O[1]), + .S(S) + ); +endmodule + +(* abc9_box, whitebox *) +module MUXF7(input I0, I1, S, output O); +assign O = S ? I1 : I0; +specify + (I0 => O) = 0; + (I1 => O) = 0; + (S => O) = 0; +endspecify +endmodule + +module abc9_test037(output o); +MUXF7 m(.I0(1'b1), .I1(1'b0), .S(o), .O(o)); +endmodule diff --git a/chips/yosys/tests/simple_abc9/generate_mk.py b/chips/yosys/tests/simple_abc9/generate_mk.py new file mode 100644 index 0000000000000000000000000000000000000000..44dd7e2b4117dde8dd662c4a37333adff68b1698 --- /dev/null +++ b/chips/yosys/tests/simple_abc9/generate_mk.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python3 + +import sys +sys.path.append("..") + +import shutil +import os +from pathlib import Path + +# ---------------------- +# Check if iverilog is installed +# ---------------------- +if shutil.which("iverilog") is None: + print("Error: Icarus Verilog 'iverilog' not found.", file=sys.stderr) + sys.exit(1) + +src_dir = Path("../simple") +# ---------------------- +# Copy all files from ../simple to current directory +# ---------------------- +for file in src_dir.glob("*.v"): + shutil.copy(file, os.path.join(".", file.name)) + +for file in src_dir.glob("*.sv"): + shutil.copy(file, os.path.join(".", file.name)) + +# bug 2675 +bug_file = os.path.join(".", "specify.v") +if os.path.exists(bug_file): + os.remove(bug_file) + +import gen_tests_makefile + +gen_tests_makefile.generate_autotest("*.*v", "-f \"verilog -noblackbox -specify\" -n 300 -p '\ + read_verilog -icells -lib +/abc9_model.v; \ + hierarchy; \ + synth -run coarse; \ + opt -full; \ + techmap; \ + abc9 -lut 4; \ + clean; \ + check -assert * abc9_test037 %d; \ + select -assert-none t:?_NOT_ t:?_AND_ %%; \ + setattr -mod -unset blackbox -unset whitebox =*'") diff --git a/chips/yosys/tests/smv/.gitignore b/chips/yosys/tests/smv/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..9c595a6fb7692405a5c4a10e1caf93d7a5bd9c37 --- /dev/null +++ b/chips/yosys/tests/smv/.gitignore @@ -0,0 +1 @@ +temp diff --git a/chips/yosys/tests/smv/run-single.sh b/chips/yosys/tests/smv/run-single.sh new file mode 100644 index 0000000000000000000000000000000000000000..452187425024658481dbe4b9a128fc59f2840843 --- /dev/null +++ b/chips/yosys/tests/smv/run-single.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash + +cat > $1.tpl < $1.ys <> $1.log +grep "^-- invariant .* is true" $1.log diff --git a/chips/yosys/tests/smv/run-test.sh b/chips/yosys/tests/smv/run-test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7df3b65f11445f72e1f7cd67dd98c13c1775ddfc --- /dev/null +++ b/chips/yosys/tests/smv/run-test.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash + +set -ex + +rm -rf temp +mkdir -p temp + +../../yosys -p 'test_cell -muxdiv -w temp/test all' +rm -f temp/test_{alu,fa,lcu,lut,macc,shiftx}_* + +cat > temp/makefile << "EOT" +all: $(addsuffix .ok,$(basename $(wildcard temp/test_*.il))) +%.ok: %.il + bash run-single.sh $(basename $<) + touch $@ +EOT + +${MAKE:-make} -f temp/makefile diff --git a/chips/yosys/tests/sva/.gitignore b/chips/yosys/tests/sva/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..b1965c97d3a70e06df64f2ead01673b4f273f862 --- /dev/null +++ b/chips/yosys/tests/sva/.gitignore @@ -0,0 +1,8 @@ +/*_pass.sby +/*_fail.sby +/*_pass +/*_fail +/*.ok +/*.fst +/vhdlpsl[0-9][0-9] +/vhdlpsl[0-9][0-9].sby diff --git a/chips/yosys/tests/sva/Makefile b/chips/yosys/tests/sva/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..a562012dbdcfbd36d51471285b9d462d3ec126f3 --- /dev/null +++ b/chips/yosys/tests/sva/Makefile @@ -0,0 +1,15 @@ +OVERRIDE_MAIN=1 +include ../common.mk + +TESTS = $(sort $(basename $(wildcard *.sv)) $(basename $(wildcard *.vhd))) + +all: $(addsuffix .ok,$(TESTS)) + +%.ok: + bash runtest.sh $@ + +clean: + rm -rf $(addsuffix .ok,$(TESTS)) $(addsuffix .sby,$(TESTS)) $(TESTS) + rm -rf $(addsuffix _pass.sby,$(TESTS)) $(addsuffix _pass,$(TESTS)) + rm -rf $(addsuffix _fail.sby,$(TESTS)) $(addsuffix _fail,$(TESTS)) + rm -rf $(addsuffix .fst,$(TESTS)) diff --git a/chips/yosys/tests/sva/basic00.sv b/chips/yosys/tests/sva/basic00.sv new file mode 100644 index 0000000000000000000000000000000000000000..30c37f5f1af5333894eb9468a1c729ab42529ac3 --- /dev/null +++ b/chips/yosys/tests/sva/basic00.sv @@ -0,0 +1,12 @@ +module top (input clk, reset, antecedent, output reg consequent); + always @(posedge clk) + consequent <= reset ? 0 : antecedent; + +`ifdef FAIL + test_assert: assert property ( @(posedge clk) disable iff (reset) antecedent |-> consequent ) + else $error("Failed with consequent = ", $sampled(consequent)); +`else + test_assert: assert property ( @(posedge clk) disable iff (reset) antecedent |=> consequent ) + else $error("Failed with consequent = ", $sampled(consequent)); +`endif +endmodule diff --git a/chips/yosys/tests/sva/basic01.sv b/chips/yosys/tests/sva/basic01.sv new file mode 100644 index 0000000000000000000000000000000000000000..d5ad497dd0a78ce13a642b8f2a27d4f5cb4fc5db --- /dev/null +++ b/chips/yosys/tests/sva/basic01.sv @@ -0,0 +1,16 @@ +module top (input logic clock, ctrl); + logic read = 0, write = 0, ready = 0; + + always @(posedge clock) begin + read <= !ctrl; + write <= ctrl; + ready <= write; + end + + a_rw: assert property ( @(posedge clock) !(read && write) ); +`ifdef FAIL + a_wr: assert property ( @(posedge clock) write |-> ready ); +`else + a_wr: assert property ( @(posedge clock) write |=> ready ); +`endif +endmodule diff --git a/chips/yosys/tests/sva/basic02.sv b/chips/yosys/tests/sva/basic02.sv new file mode 100644 index 0000000000000000000000000000000000000000..b34f3aff3138b3a526bf494ca8edfad02387fd73 --- /dev/null +++ b/chips/yosys/tests/sva/basic02.sv @@ -0,0 +1,20 @@ +module top (input logic clock, ctrl); + logic read = 0, write = 0, ready = 0; + + always @(posedge clock) begin + read <= !ctrl; + write <= ctrl; + ready <= write; + end +endmodule + +module top_properties (input logic clock, read, write, ready); + a_rw: assert property ( @(posedge clock) !(read && write) ); +`ifdef FAIL + a_wr: assert property ( @(posedge clock) write |-> ready ); +`else + a_wr: assert property ( @(posedge clock) write |=> ready ); +`endif +endmodule + +bind top top_properties properties_inst (.*); diff --git a/chips/yosys/tests/sva/basic03.sv b/chips/yosys/tests/sva/basic03.sv new file mode 100644 index 0000000000000000000000000000000000000000..8018de4ca9410ca890522ed1c8f6683b610e515e --- /dev/null +++ b/chips/yosys/tests/sva/basic03.sv @@ -0,0 +1,12 @@ +module top (input logic clk, input logic selA, selB, QA, QB, output logic Q); + always @(posedge clk) begin + if (selA) Q <= QA; + if (selB) Q <= QB; + end + + check_selA: assert property ( @(posedge clk) selA |=> Q == $past(QA) ); + check_selB: assert property ( @(posedge clk) selB |=> Q == $past(QB) ); +`ifndef FAIL + assume_not_11: assume property ( @(posedge clk) !(selA & selB) ); +`endif +endmodule diff --git a/chips/yosys/tests/sva/basic04.sv b/chips/yosys/tests/sva/basic04.sv new file mode 100644 index 0000000000000000000000000000000000000000..bc46be9f689e3c1902beb1eb78413bde4379bdf1 --- /dev/null +++ b/chips/yosys/tests/sva/basic04.sv @@ -0,0 +1,10 @@ +module top_properties (input logic clock, read, write, ready); + a_rw: assert property ( @(posedge clock) !(read && write) ); +`ifdef FAIL + a_wr: assert property ( @(posedge clock) write |-> ready ); +`else + a_wr: assert property ( @(posedge clock) write |=> ready ); +`endif +endmodule + +bind top top_properties properties_inst (.*); diff --git a/chips/yosys/tests/sva/basic04.vhd b/chips/yosys/tests/sva/basic04.vhd new file mode 100644 index 0000000000000000000000000000000000000000..f2ec305ecdbef76bd194e870f649346d8d8834a2 --- /dev/null +++ b/chips/yosys/tests/sva/basic04.vhd @@ -0,0 +1,26 @@ +library ieee; +use ieee.std_logic_1164.all; + +entity top is + port ( + clock : in std_logic; + ctrl : in std_logic; + x : out std_logic + ); +end entity; + +architecture rtl of top is + signal read : std_logic := '0'; + signal write : std_logic := '0'; + signal ready : std_logic := '0'; +begin + process (clock) begin + if (rising_edge(clock)) then + read <= not ctrl; + write <= ctrl; + ready <= write; + end if; + end process; + + x <= read xor write xor ready; +end architecture; diff --git a/chips/yosys/tests/sva/basic05.sv b/chips/yosys/tests/sva/basic05.sv new file mode 100644 index 0000000000000000000000000000000000000000..816ee1da700b4cbc926ae42822c0cc208286261a --- /dev/null +++ b/chips/yosys/tests/sva/basic05.sv @@ -0,0 +1,19 @@ +module top (input logic clock, ctrl); + logic read, write, ready; + + demo uut ( + .clock(clock), + .ctrl(ctrl) + ); + + assign read = uut.read; + assign write = uut.write; + assign ready = uut.ready; + + a_rw: assert property ( @(posedge clock) !(read && write) ); +`ifdef FAIL + a_wr: assert property ( @(posedge clock) write |-> ready ); +`else + a_wr: assert property ( @(posedge clock) write |=> ready ); +`endif +endmodule diff --git a/chips/yosys/tests/sva/basic05.vhd b/chips/yosys/tests/sva/basic05.vhd new file mode 100644 index 0000000000000000000000000000000000000000..8d42f71e849b1b322952916480f3692b51388ea1 --- /dev/null +++ b/chips/yosys/tests/sva/basic05.vhd @@ -0,0 +1,26 @@ +library ieee; +use ieee.std_logic_1164.all; + +entity demo is + port ( + clock : in std_logic; + ctrl : in std_logic; + x : out std_logic + ); +end entity; + +architecture rtl of demo is + signal read : std_logic := '0'; + signal write : std_logic := '0'; + signal ready : std_logic := '0'; +begin + process (clock) begin + if (rising_edge(clock)) then + read <= not ctrl; + write <= ctrl; + ready <= write; + end if; + end process; + + x <= read xor write xor ready; +end architecture; diff --git a/chips/yosys/tests/sva/counter.sv b/chips/yosys/tests/sva/counter.sv new file mode 100644 index 0000000000000000000000000000000000000000..4f949115ef53d6f3c38114e359ab4a30fda30454 --- /dev/null +++ b/chips/yosys/tests/sva/counter.sv @@ -0,0 +1,30 @@ +module top (input clk, reset, up, down, output reg [7:0] cnt); + always @(posedge clk) begin + if (reset) + cnt <= 0; + else if (up) + cnt <= cnt + 1; + else if (down) + cnt <= cnt - 1; + end + + default clocking @(posedge clk); endclocking + default disable iff (reset); + + assert property (up |=> cnt == $past(cnt) + 8'd 1); + assert property (up [*2] |=> cnt == $past(cnt, 2) + 8'd 2); + assert property (up ##1 up |=> cnt == $past(cnt, 2) + 8'd 2); + +`ifndef FAIL + assume property (down |-> !up); +`endif + assert property (up ##1 down |=> cnt == $past(cnt, 2)); + assert property (down |=> cnt == $past(cnt) - 8'd 1); + + property down_n(n); + down [*n] |=> cnt == $past(cnt, n) - n; + endproperty + + assert property (down_n(8'd 3)); + assert property (down_n(8'd 5)); +endmodule diff --git a/chips/yosys/tests/sva/extnets.sv b/chips/yosys/tests/sva/extnets.sv new file mode 100644 index 0000000000000000000000000000000000000000..47312de7aec6a2e5a97ed7b9c7df602fbbacdf8f --- /dev/null +++ b/chips/yosys/tests/sva/extnets.sv @@ -0,0 +1,22 @@ +module top(input i, output o); + A A(); + B B(); + assign A.i = i; + assign o = B.o; + always @* assert(o == i); +endmodule + +module A; + wire i, y; +`ifdef FAIL + assign B.x = i; +`else + assign B.x = !i; +`endif + assign y = !B.y; +endmodule + +module B; + wire x, y, o; + assign y = x, o = A.y; +endmodule diff --git a/chips/yosys/tests/sva/nested_clk_else.sv b/chips/yosys/tests/sva/nested_clk_else.sv new file mode 100644 index 0000000000000000000000000000000000000000..4421cb36ab5bb516f28c4ab524dcbbf755311b17 --- /dev/null +++ b/chips/yosys/tests/sva/nested_clk_else.sv @@ -0,0 +1,11 @@ +module top (input clk, a, b); + always @(posedge clk) begin + if (a); + else assume property (@(posedge clk) b); + end + +`ifndef FAIL + assume property (@(posedge clk) !a); +`endif + assert property (@(posedge clk) b); +endmodule diff --git a/chips/yosys/tests/sva/runtest.sh b/chips/yosys/tests/sva/runtest.sh new file mode 100644 index 0000000000000000000000000000000000000000..ee97e2d47d42ac9cccc57fd90f8b3cf80b2a02bc --- /dev/null +++ b/chips/yosys/tests/sva/runtest.sh @@ -0,0 +1,89 @@ +#!/usr/bin/env bash + +set -e + +prefix=${1%.ok} +prefix=${prefix%.sv} +prefix=${prefix%.vhd} +test -f $prefix.sv -o -f $prefix.vhd + +generate_sby() { + cat <<- EOT + [options] + mode bmc + depth 10 + expect $1 + + [engines] + smtbmc yices + + [script] + EOT + + if [ -f $prefix.sv ]; then + if [ "$1" = "fail" ]; then + echo "read -sv ${prefix}_fail.sv" + else + echo "read -sv $prefix.sv" + fi + fi + + if [ -f $prefix.vhd ]; then + echo "read -vhdl $prefix.vhd" + fi + + cat <<- EOT + prep -top top + chformal -early -assume + + [files] + EOT + + if [ -f $prefix.sv ]; then + echo "$prefix.sv" + fi + + if [ -f $prefix.vhd ]; then + echo "$prefix.vhd" + fi + + if [ "$1" = "fail" ]; then + cat <<- EOT + + [file ${prefix}_fail.sv] + \`define FAIL + \`include "$prefix.sv" + EOT + fi +} + +if [ -f $prefix.ys ]; then + set -x + ${YOSYS} -q -e "Assert .* failed." -s $prefix.ys +elif [ -f $prefix.sv ]; then + generate_sby pass > ${prefix}_pass.sby + generate_sby fail > ${prefix}_fail.sby + + # Check that SBY is up to date enough for this yosys version + if ${SBY} --help | grep -q -e '--status'; then + set -x + ${SBY} --yosys ${YOSYS} -f ${prefix}_pass.sby + ${SBY} --yosys ${YOSYS} -f ${prefix}_fail.sby + else + echo "sva test '${prefix}' requires an up to date SBY, skipping" + fi +else + generate_sby pass > ${prefix}.sby + + # Check that SBY is up to date enough for this yosys version + if ${SBY} --help | grep -q -e '--status'; then + set -x + ${SBY} --yosys ${YOSYS} -f ${prefix}.sby + else + echo "sva test '${prefix}' requires an up to date SBY, skipping" + fi +fi + +{ set +x; } &>/dev/null + +touch $prefix.ok diff --git a/chips/yosys/tests/sva/sva_not.sv b/chips/yosys/tests/sva/sva_not.sv new file mode 100644 index 0000000000000000000000000000000000000000..d81a48653aabeca34103f38693523364a0cac786 --- /dev/null +++ b/chips/yosys/tests/sva/sva_not.sv @@ -0,0 +1,34 @@ +module top ( + input clk, + input reset, + input ping, + input [1:0] cfg, + output reg pong +); + reg [2:0] cnt; + localparam integer maxdelay = 8; + + always @(posedge clk) begin + if (reset) begin + cnt <= 0; + pong <= 0; + end else begin + cnt <= cnt - |cnt; + pong <= cnt == 1; + if (ping) cnt <= 4 + cfg; + end + end + + assert property ( + @(posedge clk) + disable iff (reset) + not (ping ##1 !pong [*maxdelay]) + ); + +`ifndef FAIL + assume property ( + @(posedge clk) + not (cnt && ping) + ); +`endif +endmodule diff --git a/chips/yosys/tests/sva/sva_range.sv b/chips/yosys/tests/sva/sva_range.sv new file mode 100644 index 0000000000000000000000000000000000000000..d1569fc830619aee07cc65ab0d12315a9a383858 --- /dev/null +++ b/chips/yosys/tests/sva/sva_range.sv @@ -0,0 +1,19 @@ +module top ( + input clk, + input a, b, c, d +); + default clocking @(posedge clk); endclocking + + assert property ( + a ##[*] b |=> c until d + ); + +`ifndef FAIL + assume property ( + b |=> ##5 d + ); + assume property ( + b || (c && !d) |=> c + ); +`endif +endmodule diff --git a/chips/yosys/tests/sva/sva_throughout.sv b/chips/yosys/tests/sva/sva_throughout.sv new file mode 100644 index 0000000000000000000000000000000000000000..7e036a0669dd411ab4efbba2d5939884a3a0d0de --- /dev/null +++ b/chips/yosys/tests/sva/sva_throughout.sv @@ -0,0 +1,19 @@ +module top ( + input clk, + input a, b, c, d +); + default clocking @(posedge clk); endclocking + + assert property ( + a |=> b throughout (c ##1 d) + ); + +`ifndef FAIL + assume property ( + a |=> b && c + ); + assume property ( + b && c |=> b && d + ); +`endif +endmodule diff --git a/chips/yosys/tests/sva/sva_value_change_changed.sv b/chips/yosys/tests/sva/sva_value_change_changed.sv new file mode 100644 index 0000000000000000000000000000000000000000..3ce2078500c5e4254b5efa12ecfd4e9274ff4122 --- /dev/null +++ b/chips/yosys/tests/sva/sva_value_change_changed.sv @@ -0,0 +1,19 @@ +module top ( + input clk, + input a, b +); + default clocking @(posedge clk); endclocking + + assert property ( + $changed(b) + ); + + wire x = 'x; + +`ifndef FAIL + assume property ( + b !== x ##1 $changed(b) + ); +`endif + +endmodule diff --git a/chips/yosys/tests/sva/sva_value_change_changed_wide.sv b/chips/yosys/tests/sva/sva_value_change_changed_wide.sv new file mode 100644 index 0000000000000000000000000000000000000000..c9147c4f3595397fc0d32cf473cce69cadab21a8 --- /dev/null +++ b/chips/yosys/tests/sva/sva_value_change_changed_wide.sv @@ -0,0 +1,22 @@ +module top ( + input clk, + input [2:0] a, + input [2:0] b +); + default clocking @(posedge clk); endclocking + + assert property ( + $changed(a) + ); + + assert property ( + $changed(b) == ($changed(b[0]) || $changed(b[1]) || $changed(b[2])) + ); + +`ifndef FAIL + assume property ( + a !== 'x ##1 $changed(a) + ); +`endif + +endmodule diff --git a/chips/yosys/tests/sva/sva_value_change_rose.sv b/chips/yosys/tests/sva/sva_value_change_rose.sv new file mode 100644 index 0000000000000000000000000000000000000000..d1c5290f1a8257ab0446f5aa978397f5695bc7d2 --- /dev/null +++ b/chips/yosys/tests/sva/sva_value_change_rose.sv @@ -0,0 +1,20 @@ +module top ( + input clk, + input a, b +); + default clocking @(posedge clk); endclocking + + wire a_copy; + assign a_copy = a; + + assert property ( + $rose(a) |-> b + ); + +`ifndef FAIL + assume property ( + $rose(a_copy) |-> b + ); +`endif + +endmodule diff --git a/chips/yosys/tests/sva/sva_value_change_sim.sv b/chips/yosys/tests/sva/sva_value_change_sim.sv new file mode 100644 index 0000000000000000000000000000000000000000..92fe30b239a383d8cae5101b01f09b1679d7463a --- /dev/null +++ b/chips/yosys/tests/sva/sva_value_change_sim.sv @@ -0,0 +1,70 @@ +module top ( + input clk +); + +reg [7:0] counter = 0; + +reg a = 0; +reg b = 1; +reg c; +reg [2:0] wide_a = 3'b10x; +reg [2:0] wide_b = 'x; + +wire a_fell; assign a_fell = $fell(a, @(posedge clk)); +wire a_rose; assign a_rose = $rose(a, @(posedge clk)); +wire a_stable; assign a_stable = $stable(a, @(posedge clk)); + +wire b_fell; assign b_fell = $fell(b, @(posedge clk)); +wire b_rose; assign b_rose = $rose(b, @(posedge clk)); +wire b_stable; assign b_stable = $stable(b, @(posedge clk)); + +wire c_fell; assign c_fell = $fell(c, @(posedge clk)); +wire c_rose; assign c_rose = $rose(c, @(posedge clk)); +wire c_stable; assign c_stable = $stable(c, @(posedge clk)); + +wire wide_a_stable; assign wide_a_stable = $stable(wide_a, @(posedge clk)); +wire wide_b_stable; assign wide_b_stable = $stable(wide_b, @(posedge clk)); + +always @(posedge clk) begin + counter <= counter + 1; + + case (counter) + 0: begin + assert property ( $fell(a) && !$rose(a) && !$stable(a)); + assert property (!$fell(b) && $rose(b) && !$stable(b)); + assert property (!$fell(c) && !$rose(c) && $stable(c)); + assert property (!$stable(wide_a)); + assert property ($stable(wide_b)); + a <= 1; b <= 1; c <= 1; + end + 1: begin + a <= 0; b <= 1; c <= 'x; + wide_a <= 3'b101; wide_b <= 3'bxx0; + end + 2: begin + assert property ( $fell(a) && !$rose(a) && !$stable(a)); + assert property (!$fell(b) && !$rose(b) && $stable(b)); + assert property (!$fell(c) && !$rose(c) && !$stable(c)); + assert property (!$stable(wide_a)); + assert property (!$stable(wide_b)); + a <= 0; b <= 0; c <= 0; + end + 3: begin a <= 0; b <= 1; c <= 'x; end + 4: begin + assert property (!$fell(a) && !$rose(a) && $stable(a)); + assert property (!$fell(b) && $rose(b) && !$stable(b)); + assert property (!$fell(c) && !$rose(c) && !$stable(c)); + assert property ($stable(wide_a)); + assert property ($stable(wide_b)); + a <= 'x; b <= 'x; c <= 'x; + wide_a <= 'x; wide_b <= 'x; + end + 5: begin + a <= 0; b <= 1; c <= 'x; + wide_a <= 3'b10x; wide_b <= 'x; + counter <= 0; + end + endcase; +end + +endmodule diff --git a/chips/yosys/tests/sva/sva_value_change_sim.ys b/chips/yosys/tests/sva/sva_value_change_sim.ys new file mode 100644 index 0000000000000000000000000000000000000000..e004520ce07f4386595e4395cfc4fa732e752abe --- /dev/null +++ b/chips/yosys/tests/sva/sva_value_change_sim.ys @@ -0,0 +1,3 @@ +read -sv sva_value_change_sim.sv +hierarchy -top top +sim -clock clk -fst sva_value_change_sim.fst diff --git a/chips/yosys/tests/svinterfaces/.gitignore b/chips/yosys/tests/svinterfaces/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..a5b7927d18695819381faee4ba905ed0a54115ba --- /dev/null +++ b/chips/yosys/tests/svinterfaces/.gitignore @@ -0,0 +1,8 @@ +/a.out +/dut_result.txt +/reference_result.txt +/*.diff +/*.log_stderr +/*.log_stdout +/*_ref_syn.v +/*_syn.v diff --git a/chips/yosys/tests/svinterfaces/generate_mk.py b/chips/yosys/tests/svinterfaces/generate_mk.py new file mode 100644 index 0000000000000000000000000000000000000000..4703e9c9e81632dc5abbfe797444d6508584f8cf --- /dev/null +++ b/chips/yosys/tests/svinterfaces/generate_mk.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 + +from pathlib import Path +import glob +import sys +sys.path.append("..") + +import gen_tests_makefile + +runone_tests = [ + "svinterface1", + #"svinterface_at_top" +] + +def run_one(): + for testname in runone_tests: + cmd_lines = [ + f'$(YOSYS) -p "read_verilog -sv {testname}.sv ; hierarchy -check -top TopModule ; synth ; write_verilog {testname}_syn.v" >> {testname}.log_stdout 2>> {testname}.log_stderr', + f'$(YOSYS) -p "read_verilog -sv {testname}_ref.v ; hierarchy -check -top TopModule ; synth ; write_verilog {testname}_ref_syn.v" >> {testname}.log_stdout 2>> {testname}.log_stderr', + f'rm -f a.out reference_result.txt dut_result.txt', + f'iverilog -g2012 {testname}_syn.v', + f'iverilog -g2012 {testname}_ref_syn.v', + f'iverilog -g2012 {testname}_tb.v {testname}_ref_syn.v', + f'./a.out', + f'mv output.txt reference_result.txt', + f'iverilog -g2012 {testname}_tb_wrapper.v {testname}_syn.v' if testname=="svinterface_at_top" else + f'iverilog -g2012 {testname}_tb.v {testname}_syn.v', + f'./a.out', + f'mv output.txt dut_result.txt', + f'diff reference_result.txt dut_result.txt > {testname}.diff', + ] + gen_tests_makefile.generate_cmd_test(testname, cmd_lines) + +def run_simple(): + for f in sorted(glob.glob("*.ys")): + gen_tests_makefile.generate_ys_test(f) + +def main(): + def callback(): + run_one() + run_simple() + + gen_tests_makefile.generate_custom(callback) + +if __name__ == "__main__": + main() diff --git a/chips/yosys/tests/svinterfaces/load_and_derive.sv b/chips/yosys/tests/svinterfaces/load_and_derive.sv new file mode 100644 index 0000000000000000000000000000000000000000..0de0de3b34623fc3374b4707dab1edef1be5bb75 --- /dev/null +++ b/chips/yosys/tests/svinterfaces/load_and_derive.sv @@ -0,0 +1,20 @@ +// This test checks that we correctly elaborate interfaces in modules, even if they are loaded on +// demand. The "ondemand" module is defined in ondemand.sv in this directory and will be read as +// part of the hierarchy pass. + +interface iface; + logic [7:0] x; + logic [7:0] y; +endinterface + +module dut (input logic [7:0] x, output logic [7:0] y); + iface intf(); + assign intf.x = x; + assign y = intf.y; + + ondemand u(.intf); +endmodule + +module ref (input logic [7:0] x, output logic [7:0] y); + assign y = ~x; +endmodule diff --git a/chips/yosys/tests/svinterfaces/load_and_derive.ys b/chips/yosys/tests/svinterfaces/load_and_derive.ys new file mode 100644 index 0000000000000000000000000000000000000000..067235ec2ab6369d86b1feadbe549e4f45c7b81a --- /dev/null +++ b/chips/yosys/tests/svinterfaces/load_and_derive.ys @@ -0,0 +1,6 @@ +read_verilog -sv load_and_derive.sv +hierarchy -libdir . -check +flatten +equiv_make ref dut equiv +equiv_simple +equiv_status -assert diff --git a/chips/yosys/tests/svinterfaces/ondemand.sv b/chips/yosys/tests/svinterfaces/ondemand.sv new file mode 100644 index 0000000000000000000000000000000000000000..70d6048f8c3fe395908c49953b1d582011a1cbce --- /dev/null +++ b/chips/yosys/tests/svinterfaces/ondemand.sv @@ -0,0 +1,5 @@ +// This is used by the load_and_derive test. + +module ondemand (iface intf); + assign intf.y = ~intf.x; +endmodule diff --git a/chips/yosys/tests/svinterfaces/positional_args.ys b/chips/yosys/tests/svinterfaces/positional_args.ys new file mode 100644 index 0000000000000000000000000000000000000000..6017a1c25c404c0d0bbb0a9c49fd2ed13c257b22 --- /dev/null +++ b/chips/yosys/tests/svinterfaces/positional_args.ys @@ -0,0 +1,33 @@ +read_verilog -sv << EOF +interface simple_if; + logic receiver; + logic driver; +endinterface + +module driver_mod(simple_if intf, input in); + assign intf.driver = in; +endmodule + +module receiver_mod(simple_if intf); + assign intf.receiver = intf.driver; +endmodule + +module top( + input logic [1:0] inputs, + output logic [1:0] outputs +); + simple_if intf0(); + simple_if intf1(); + + driver_mod d0(intf0, inputs[0]); + driver_mod d1(intf1, inputs[1]); + + receiver_mod r0(intf0); + receiver_mod r1(intf1); + + assign outputs = {intf0.receiver, intf1.receiver}; +endmodule +EOF + +logger -expect error "Unable to connect.* with positional interface" 1 +hierarchy -top top diff --git a/chips/yosys/tests/svinterfaces/resolve_types.sv b/chips/yosys/tests/svinterfaces/resolve_types.sv new file mode 100644 index 0000000000000000000000000000000000000000..3c6644e334d4676b22df12eb44337cd1af3978ea --- /dev/null +++ b/chips/yosys/tests/svinterfaces/resolve_types.sv @@ -0,0 +1,24 @@ +// This test checks that types, including package types, are resolved from within an interface. + +typedef logic [7:0] x_t; + +package pkg; + typedef logic [7:0] y_t; +endpackage + +interface iface; + x_t x; + pkg::y_t y; +endinterface + +module dut (input logic [7:0] x, output logic [7:0] y); + iface intf(); + assign intf.x = x; + assign y = intf.y; + + ondemand u(.intf); +endmodule + +module ref (input logic [7:0] x, output logic [7:0] y); + assign y = ~x; +endmodule diff --git a/chips/yosys/tests/svinterfaces/resolve_types.ys b/chips/yosys/tests/svinterfaces/resolve_types.ys new file mode 100644 index 0000000000000000000000000000000000000000..a25791f3785c890bb87739c0a1f61dea51b528a3 --- /dev/null +++ b/chips/yosys/tests/svinterfaces/resolve_types.ys @@ -0,0 +1,6 @@ +read_verilog -sv resolve_types.sv +hierarchy -libdir . -check +flatten +equiv_make ref dut equiv +equiv_simple +equiv_status -assert diff --git a/chips/yosys/tests/svinterfaces/svinterface1.sv b/chips/yosys/tests/svinterfaces/svinterface1.sv new file mode 100644 index 0000000000000000000000000000000000000000..6d60b4880a21daf023dfc08124589ad4959c294c --- /dev/null +++ b/chips/yosys/tests/svinterfaces/svinterface1.sv @@ -0,0 +1,117 @@ + + +module TopModule( + input logic clk, + input logic rst, + output logic [21:0] outOther, + input logic [1:0] sig, + input logic flip, + output logic [1:0] sig_out, + output logic [15:0] passThrough); + + MyInterface #(.WIDTH(4)) MyInterfaceInstance(); + + SubModule1 u_SubModule1 ( + .clk(clk), + .rst(rst), + .u_MyInterface(MyInterfaceInstance), + .outOther(outOther), + .sig (sig) + ); + + assign sig_out = MyInterfaceInstance.mysig_out; + + + assign MyInterfaceInstance.setting = flip; + + assign passThrough = MyInterfaceInstance.passThrough; + +endmodule + +interface MyInterface #( + parameter WIDTH = 3)( + ); + + logic setting; + logic [WIDTH-1:0] other_setting; + + logic [1:0] mysig_out; + + logic [15:0] passThrough; + + modport submodule1 ( + input setting, + output other_setting, + output mysig_out, + output passThrough + ); + + modport submodule2 ( + input setting, + output other_setting, + input mysig_out, + output passThrough + ); + +endinterface + + +module SubModule1( + input logic clk, + input logic rst, + MyInterface.submodule1 u_MyInterface, + input logic [1:0] sig, + output logic [21:0] outOther + + ); + + always_ff @(posedge clk or posedge rst) + if(rst) + u_MyInterface.mysig_out <= 0; + else begin + if(u_MyInterface.setting) + u_MyInterface.mysig_out <= sig; + else + u_MyInterface.mysig_out <= ~sig; + end + + MyInterface #(.WIDTH(22)) MyInterfaceInstanceInSub(); + + SubModule2 u_SubModule2 ( + .clk(clk), + .rst(rst), + .u_MyInterfaceInSub2(u_MyInterface), + .u_MyInterfaceInSub3(MyInterfaceInstanceInSub) + ); + + assign outOther = MyInterfaceInstanceInSub.other_setting; + + assign MyInterfaceInstanceInSub.setting = 0; + assign MyInterfaceInstanceInSub.mysig_out = sig; + +endmodule + +module SubModule2( + + input logic clk, + input logic rst, + MyInterface.submodule2 u_MyInterfaceInSub2, + MyInterface.submodule2 u_MyInterfaceInSub3 + + ); + + always_comb begin + if (u_MyInterfaceInSub3.mysig_out == 2'b00) + u_MyInterfaceInSub3.other_setting[21:0] = 1000; + else if (u_MyInterfaceInSub3.mysig_out == 2'b01) + u_MyInterfaceInSub3.other_setting[21:0] = 2000; + else if (u_MyInterfaceInSub3.mysig_out == 2'b10) + u_MyInterfaceInSub3.other_setting[21:0] = 3000; + else + u_MyInterfaceInSub3.other_setting[21:0] = 4000; + end + + assign u_MyInterfaceInSub2.passThrough[7:0] = 124; + assign u_MyInterfaceInSub2.passThrough[15:8] = 200; + +endmodule diff --git a/chips/yosys/tests/svinterfaces/svinterface1_ref.v b/chips/yosys/tests/svinterfaces/svinterface1_ref.v new file mode 100644 index 0000000000000000000000000000000000000000..b119f40376e3a75c53ae83671143dd893ea17ea0 --- /dev/null +++ b/chips/yosys/tests/svinterfaces/svinterface1_ref.v @@ -0,0 +1,107 @@ + +module TopModule( + input logic clk, + input logic rst, + input logic [1:0] sig, + input logic flip, + output logic [15:0] passThrough, + output logic [21:0] outOther, + output logic [1:0] sig_out); + + + logic MyInterfaceInstance_setting; + logic [3:0] MyInterfaceInstance_other_setting; + logic [1:0] MyInterfaceInstance_mysig_out; + + SubModule1 u_SubModule1 ( + .clk(clk), + .rst(rst), + .u_MyInterface_setting(MyInterfaceInstance_setting), + .u_MyInterface_mysig_out(MyInterfaceInstance_mysig_out), + .u_MyInterface_other_setting(MyInterfaceInstance_other_setting), + .outOther(outOther), + .passThrough (passThrough), + .sig (sig) + ); + + assign sig_out = MyInterfaceInstance_mysig_out; + + + assign MyInterfaceInstance_setting = flip; + +endmodule + + +module SubModule1( + input logic clk, + input logic rst, + input logic u_MyInterface_setting, + output logic [3:0] u_MyInterface_other_setting, + output logic [1:0] u_MyInterface_mysig_out, + output logic [21:0] outOther, + input logic [1:0] sig, + output logic [15:0] passThrough + ); + + always @(posedge clk or posedge rst) + if(rst) + u_MyInterface_mysig_out <= 0; + else begin + if(u_MyInterface_setting) + u_MyInterface_mysig_out <= sig; + else + u_MyInterface_mysig_out <= ~sig; + end + + logic MyInterfaceInstanceInSub_setting; + logic [21:0] MyInterfaceInstanceInSub_other_setting; + logic [1:0] MyInterfaceInstanceInSub_mysig_out; + + + SubModule2 u_SubModule2 ( + .clk(clk), + .rst(rst), + .u_MyInterfaceInSub2_setting(u_MyInterface_setting), + .u_MyInterfaceInSub2_mysig_out(u_MyInterface_mysig_out), + .u_MyInterfaceInSub2_other_setting(u_MyInterface_other_setting), + .u_MyInterfaceInSub3_setting(MyInterfaceInstanceInSub_setting), + .u_MyInterfaceInSub3_mysig_out(MyInterfaceInstanceInSub_mysig_out), + .u_MyInterfaceInSub3_other_setting(MyInterfaceInstanceInSub_other_setting), + .passThrough (passThrough) + ); + assign outOther = MyInterfaceInstanceInSub_other_setting; + + assign MyInterfaceInstanceInSub_setting = 0; + assign MyInterfaceInstanceInSub_mysig_out = sig; + +endmodule + +module SubModule2( + + input logic clk, + input logic rst, + input logic u_MyInterfaceInSub2_setting, + output logic [3:0] u_MyInterfaceInSub2_other_setting, + input logic [1:0] u_MyInterfaceInSub2_mysig_out, + input logic u_MyInterfaceInSub3_setting, + output logic [21:0] u_MyInterfaceInSub3_other_setting, + input logic [1:0] u_MyInterfaceInSub3_mysig_out, + output logic [15:0] passThrough + + ); + + always @(u_MyInterfaceInSub3_mysig_out) begin + if (u_MyInterfaceInSub3_mysig_out == 2'b00) + u_MyInterfaceInSub3_other_setting[21:0] = 1000; + else if (u_MyInterfaceInSub3_mysig_out == 2'b01) + u_MyInterfaceInSub3_other_setting[21:0] = 2000; + else if (u_MyInterfaceInSub3_mysig_out == 2'b10) + u_MyInterfaceInSub3_other_setting[21:0] = 3000; + else + u_MyInterfaceInSub3_other_setting[21:0] = 4000; + end + + assign passThrough[7:0] = 124; + assign passThrough[15:8] = 200; + +endmodule diff --git a/chips/yosys/tests/svinterfaces/svinterface1_tb.v b/chips/yosys/tests/svinterfaces/svinterface1_tb.v new file mode 100644 index 0000000000000000000000000000000000000000..44c3b5f681eb8c396efda577e355a150a112d021 --- /dev/null +++ b/chips/yosys/tests/svinterfaces/svinterface1_tb.v @@ -0,0 +1,57 @@ +`timescale 1ns/10ps + +module svinterface1_tb; + + + logic clk; + logic rst; + logic [21:0] outOther; + logic [1:0] sig; + logic [1:0] sig_out; + logic flip; + logic [15:0] passThrough; + integer outfile; + + TopModule u_dut ( + .clk(clk), + .rst(rst), + .outOther(outOther), + .sig(sig), + .flip(flip), + .passThrough(passThrough), + .sig_out(sig_out) + ); + + initial begin + clk = 0; + while(1) begin + clk = ~clk; + #50; + end + end + + initial begin + outfile = $fopen("output.txt"); + rst = 1; + sig = 0; + flip = 0; + @(posedge clk); + #(2); + rst = 0; + @(posedge clk); + for(int j=0;j<2;j++) begin + for(int i=0;i<20;i++) begin + #(2); + flip = j; + sig = i; + @(posedge clk); + end + end + $finish; + end + + always @(negedge clk) begin + $fdisplay(outfile, "%d %d %d", outOther, sig_out, passThrough); + end + +endmodule diff --git a/chips/yosys/tests/svinterfaces/svinterface_at_top.sv b/chips/yosys/tests/svinterfaces/svinterface_at_top.sv new file mode 100644 index 0000000000000000000000000000000000000000..b5aa8c8f5f0cbc8665eebba5c77fae198f0c171e --- /dev/null +++ b/chips/yosys/tests/svinterfaces/svinterface_at_top.sv @@ -0,0 +1,125 @@ + + +module TopModule( + input logic clk, + input logic rst, + output logic [21:0] outOther, + input logic [1:0] sig, + input logic flip, + output logic [1:0] sig_out, + MyInterface.submodule1 interfaceInstanceAtTop, + output logic [15:0] passThrough); + + MyInterface #(.WIDTH(4)) MyInterfaceInstance(); + + SubModule1 u_SubModule1 ( + .clk(clk), + .rst(rst), + .u_MyInterface(MyInterfaceInstance), + .u_MyInterfaceFromTop(interfaceInstanceAtTop), + .outOther(outOther), + .sig (sig) + ); + + assign sig_out = MyInterfaceInstance.mysig_out; + + + assign MyInterfaceInstance.setting = flip; + + assign passThrough = MyInterfaceInstance.passThrough; + +endmodule + +interface MyInterface #( + parameter WIDTH = 3)( + ); + + logic setting; + logic [WIDTH-1:0] other_setting; + + logic [1:0] mysig_out; + + logic [15:0] passThrough; + + modport submodule1 ( + input setting, + output other_setting, + output mysig_out, + output passThrough + ); + + modport submodule2 ( + input setting, + output other_setting, + input mysig_out, + output passThrough + ); + +endinterface + + +module SubModule1( + input logic clk, + input logic rst, + MyInterface.submodule1 u_MyInterface, + MyInterface.submodule1 u_MyInterfaceFromTop, + input logic [1:0] sig, + output logic [21:0] outOther + + ); + + + always_ff @(posedge clk or posedge rst) + if(rst) + u_MyInterface.mysig_out <= 0; + else begin + if(u_MyInterface.setting) + u_MyInterface.mysig_out <= sig; + else + u_MyInterface.mysig_out <= ~sig; + end + + MyInterface #(.WIDTH(22)) MyInterfaceInstanceInSub(); + + SubModule2 u_SubModule2 ( + .clk(clk), + .rst(rst), + .u_MyInterfaceFromTopDown(u_MyInterfaceFromTop), + .u_MyInterfaceInSub2(u_MyInterface), + .u_MyInterfaceInSub3(MyInterfaceInstanceInSub) + ); + + assign outOther = MyInterfaceInstanceInSub.other_setting; + + assign MyInterfaceInstanceInSub.setting = 0; + assign MyInterfaceInstanceInSub.mysig_out = sig; + +endmodule + +module SubModule2( + + input logic clk, + input logic rst, + MyInterface.submodule2 u_MyInterfaceInSub2, + MyInterface.submodule1 u_MyInterfaceFromTopDown, + MyInterface.submodule2 u_MyInterfaceInSub3 + + ); + + assign u_MyInterfaceFromTopDown.mysig_out = u_MyInterfaceFromTop.setting ? 10 : 20; + + always_comb begin + if (u_MyInterfaceInSub3.mysig_out == 2'b00) + u_MyInterfaceInSub3.other_setting[21:0] = 1000; + else if (u_MyInterfaceInSub3.mysig_out == 2'b01) + u_MyInterfaceInSub3.other_setting[21:0] = 2000; + else if (u_MyInterfaceInSub3.mysig_out == 2'b10) + u_MyInterfaceInSub3.other_setting[21:0] = 3000; + else + u_MyInterfaceInSub3.other_setting[21:0] = 4000; + end + + assign u_MyInterfaceInSub2.passThrough[7:0] = 124; + assign u_MyInterfaceInSub2.passThrough[15:8] = 200; + +endmodule diff --git a/chips/yosys/tests/svinterfaces/svinterface_at_top_ref.v b/chips/yosys/tests/svinterfaces/svinterface_at_top_ref.v new file mode 100644 index 0000000000000000000000000000000000000000..7b54a26d6d30e4b1da7b6b7cce89a05be2f2e757 --- /dev/null +++ b/chips/yosys/tests/svinterfaces/svinterface_at_top_ref.v @@ -0,0 +1,120 @@ + +module TopModule( + input logic clk, + input logic rst, + input logic [1:0] sig, + input logic flip, + output logic [15:0] passThrough, + output logic [21:0] outOther, + input logic interfaceInstanceAtTop_setting, + output logic [2:0] interfaceInstanceAtTop_other_setting, + output logic [1:0] interfaceInstanceAtTop_mysig_out, + output logic [15:0] interfaceInstanceAtTop_passThrough, + output logic [1:0] sig_out); + + + logic MyInterfaceInstance_setting; + logic [3:0] MyInterfaceInstance_other_setting; + logic [1:0] MyInterfaceInstance_mysig_out; + + SubModule1 u_SubModule1 ( + .clk(clk), + .rst(rst), + .u_MyInterface_setting(MyInterfaceInstance_setting), + .u_MyInterface_mysig_out(MyInterfaceInstance_mysig_out), + .u_MyInterface_other_setting(MyInterfaceInstance_other_setting), + .u_MyInterfaceFromTop_setting(interfaceInstanceAtTop_setting), + .u_MyInterfaceFromTop_other_setting(interfaceInstanceAtTop_other_setting), + .u_MyInterfaceFromTop_mysig_out(interfaceInstanceAtTop_mysig_out), + .u_MyInterfaceFromTop_passThrough(interfaceInstanceAtTop_passThrough), + .outOther(outOther), + .passThrough (passThrough), + .sig (sig) + ); + + assign sig_out = MyInterfaceInstance_mysig_out; + + + assign MyInterfaceInstance_setting = flip; + +endmodule + + +module SubModule1( + input logic clk, + input logic rst, + input logic u_MyInterface_setting, + output logic [3:0] u_MyInterface_other_setting, + output logic [1:0] u_MyInterface_mysig_out, + output logic [21:0] outOther, + input logic [1:0] sig, + input logic u_MyInterfaceFromTop_setting, + output logic [2:0] u_MyInterfaceFromTop_other_setting, + output logic [1:0] u_MyInterfaceFromTop_mysig_out, + output logic [14:0] u_MyInterfaceFromTop_passThrough, + output logic [15:0] passThrough + ); + + always @(posedge clk or posedge rst) + if(rst) + u_MyInterface_mysig_out <= 0; + else begin + if(u_MyInterface_setting) + u_MyInterface_mysig_out <= sig; + else + u_MyInterface_mysig_out <= ~sig; + end + + logic MyInterfaceInstanceInSub_setting; + logic [21:0] MyInterfaceInstanceInSub_other_setting; + logic [1:0] MyInterfaceInstanceInSub_mysig_out; + + assign u_MyInterfaceFromTop_mysig_out = u_MyInterfaceFromTop_setting ? 10 : 20; + + SubModule2 u_SubModule2 ( + .clk(clk), + .rst(rst), + .u_MyInterfaceInSub2_setting(u_MyInterface_setting), + .u_MyInterfaceInSub2_mysig_out(u_MyInterface_mysig_out), + .u_MyInterfaceInSub2_other_setting(u_MyInterface_other_setting), + .u_MyInterfaceInSub3_setting(MyInterfaceInstanceInSub_setting), + .u_MyInterfaceInSub3_mysig_out(MyInterfaceInstanceInSub_mysig_out), + .u_MyInterfaceInSub3_other_setting(MyInterfaceInstanceInSub_other_setting), + .passThrough (passThrough) + ); + assign outOther = MyInterfaceInstanceInSub_other_setting; + + assign MyInterfaceInstanceInSub_setting = 0; + assign MyInterfaceInstanceInSub_mysig_out = sig; + +endmodule + +module SubModule2( + + input logic clk, + input logic rst, + input logic u_MyInterfaceInSub2_setting, + output logic [3:0] u_MyInterfaceInSub2_other_setting, + input logic [1:0] u_MyInterfaceInSub2_mysig_out, + input logic u_MyInterfaceInSub3_setting, + output logic [21:0] u_MyInterfaceInSub3_other_setting, + input logic [1:0] u_MyInterfaceInSub3_mysig_out, + output logic [15:0] passThrough + + ); + + always @(u_MyInterfaceInSub3_mysig_out) begin + if (u_MyInterfaceInSub3_mysig_out == 2'b00) + u_MyInterfaceInSub3_other_setting[21:0] = 1000; + else if (u_MyInterfaceInSub3_mysig_out == 2'b01) + u_MyInterfaceInSub3_other_setting[21:0] = 2000; + else if (u_MyInterfaceInSub3_mysig_out == 2'b10) + u_MyInterfaceInSub3_other_setting[21:0] = 3000; + else + u_MyInterfaceInSub3_other_setting[21:0] = 4000; + end + + assign passThrough[7:0] = 124; + assign passThrough[15:8] = 200; + +endmodule diff --git a/chips/yosys/tests/svinterfaces/svinterface_at_top_tb.v b/chips/yosys/tests/svinterfaces/svinterface_at_top_tb.v new file mode 100644 index 0000000000000000000000000000000000000000..bf37a148d077007a7b6271787916f39e644dd561 --- /dev/null +++ b/chips/yosys/tests/svinterfaces/svinterface_at_top_tb.v @@ -0,0 +1,68 @@ +`timescale 1ns/10ps + +module svinterface_at_top_tb; + + + logic clk; + logic rst; + logic [21:0] outOther; + logic [1:0] sig; + logic [1:0] sig_out; + logic flip; + logic [15:0] passThrough; + integer outfile; + + logic interfaceInstanceAtTop_setting; + logic [2:0] interfaceInstanceAtTop_other_setting; + logic [1:0] interfaceInstanceAtTop_mysig_out; + logic [15:0] interfaceInstanceAtTop_passThrough; + + + TopModule u_dut ( + .clk(clk), + .rst(rst), + .outOther(outOther), + .sig(sig), + .flip(flip), + .passThrough(passThrough), + .interfaceInstanceAtTop_setting(interfaceInstanceAtTop_setting), + .interfaceInstanceAtTop_other_setting(interfaceInstanceAtTop_other_setting), + .interfaceInstanceAtTop_mysig_out(interfaceInstanceAtTop_mysig_out), + .interfaceInstanceAtTop_passThrough(interfaceInstanceAtTop_passThrough), + .sig_out(sig_out) + ); + + initial begin + clk = 0; + while(1) begin + clk = ~clk; + #50; + end + end + + initial begin + outfile = $fopen("output.txt"); + rst = 1; + interfaceInstanceAtTop_setting = 0; + sig = 0; + flip = 0; + @(posedge clk); + #(2); + rst = 0; + @(posedge clk); + for(int j=0;j<2;j++) begin + for(int i=0;i<20;i++) begin + #(2); + flip = j; + sig = i; + @(posedge clk); + end + end + $finish; + end + + always @(negedge clk) begin + $fdisplay(outfile, "%d %d %d %d", outOther, sig_out, passThrough, interfaceInstanceAtTop_mysig_out); + end + +endmodule diff --git a/chips/yosys/tests/svinterfaces/svinterface_at_top_tb_wrapper.v b/chips/yosys/tests/svinterfaces/svinterface_at_top_tb_wrapper.v new file mode 100644 index 0000000000000000000000000000000000000000..b344a7b88a8dc50757d0b256fa43981157002636 --- /dev/null +++ b/chips/yosys/tests/svinterfaces/svinterface_at_top_tb_wrapper.v @@ -0,0 +1,68 @@ +`timescale 1ns/10ps + +module svinterface_at_top_tb_wrapper; + + + logic clk; + logic rst; + logic [21:0] outOther; + logic [1:0] sig; + logic [1:0] sig_out; + logic flip; + logic [15:0] passThrough; + integer outfile; + + logic interfaceInstanceAtTop_setting; + logic [2:0] interfaceInstanceAtTop_other_setting; + logic [1:0] interfaceInstanceAtTop_mysig_out; + logic [15:0] interfaceInstanceAtTop_passThrough; + + + TopModule u_dut ( + .clk(clk), + .rst(rst), + .outOther(outOther), + .sig(sig), + .flip(flip), + .passThrough(passThrough), + .\interfaceInstanceAtTop.setting (interfaceInstanceAtTop_setting), + .\interfaceInstanceAtTop.other_setting (interfaceInstanceAtTop_other_setting), + .\interfaceInstanceAtTop.mysig_out (interfaceInstanceAtTop_mysig_out), + .\interfaceInstanceAtTop.passThrough (interfaceInstanceAtTop_passThrough), + .sig_out(sig_out) + ); + + initial begin + clk = 0; + while(1) begin + clk = ~clk; + #50; + end + end + + initial begin + outfile = $fopen("output.txt"); + rst = 1; + sig = 0; + interfaceInstanceAtTop_setting = 0; + flip = 0; + @(posedge clk); + #(2); + rst = 0; + @(posedge clk); + for(int j=0;j<2;j++) begin + for(int i=0;i<20;i++) begin + #(2); + flip = j; + sig = i; + @(posedge clk); + end + end + $finish; + end + + always @(negedge clk) begin + $fdisplay(outfile, "%d %d %d %d", outOther, sig_out, passThrough, interfaceInstanceAtTop_mysig_out); + end + +endmodule diff --git a/chips/yosys/tests/svinterfaces/svinterface_at_top_wrapper.v b/chips/yosys/tests/svinterfaces/svinterface_at_top_wrapper.v new file mode 100644 index 0000000000000000000000000000000000000000..64f906c07a0b4ea8ba4cee10a619fcba8087de20 --- /dev/null +++ b/chips/yosys/tests/svinterfaces/svinterface_at_top_wrapper.v @@ -0,0 +1,33 @@ +`timescale 1ns/10ps + +module svinterface_at_top_wrapper( + input logic clk, + input logic rst, + output logic [21:0] outOther, + input logic [1:0] sig, + output logic [1:0] sig_out, + input logic flip, + output logic [15:0] passThrough, + + input logic interfaceInstanceAtTop_setting, + output logic [2:0] interfaceInstanceAtTop_other_setting, + output logic [1:0] interfaceInstanceAtTop_mysig_out, + output logic [15:0] interfaceInstanceAtTop_passThrough, + ); + + + TopModule u_dut ( + .clk(clk), + .rst(rst), + .outOther(outOther), + .sig(sig), + .flip(flip), + .passThrough(passThrough), + .\interfaceInstanceAtTop.setting(interfaceInstanceAtTop_setting), + .\interfaceInstanceAtTop.other_setting(interfaceInstanceAtTop_other_setting), + .\interfaceInstanceAtTop.mysig_out(interfaceInstanceAtTop_mysig_out), + .\interfaceInstanceAtTop.passThrough(interfaceInstanceAtTop_passThrough), + .sig_out(sig_out) + ); + +endmodule diff --git a/chips/yosys/tests/svtypes/array_assign.sv b/chips/yosys/tests/svtypes/array_assign.sv new file mode 100644 index 0000000000000000000000000000000000000000..f23a08d279cd88a9887e223b5208327de3ba7278 --- /dev/null +++ b/chips/yosys/tests/svtypes/array_assign.sv @@ -0,0 +1,168 @@ +// Test for array-to-array assignment and ternary expressions + +`define STRINGIFY(x) `"x`" +`define STATIC_ASSERT(x) if(!(x)) $error({"assert failed: ", `STRINGIFY(x)}) + +module top; + // Test 1: Basic array ternary with continuous assignment + reg [7:0] a1[4]; + reg [7:0] b1[4]; + wire [7:0] out1[4]; + wire sel1; + assign out1 = sel1 ? a1 : b1; + `STATIC_ASSERT($bits(out1) == 32); + + // Test 2: Non-zero base index + reg [7:0] a2[3:6]; + reg [7:0] b2[3:6]; + wire [7:0] out2[3:6]; + wire sel2; + assign out2 = sel2 ? a2 : b2; + `STATIC_ASSERT($bits(out2) == 32); + + // Test 3: Single-bit elements + reg a3[8]; + reg b3[8]; + wire out3[8]; + wire sel3; + assign out3 = sel3 ? a3 : b3; + `STATIC_ASSERT($bits(out3) == 8); + + // Test 4: Multi-dimensional array ternary + reg [7:0] a4[2][3]; + reg [7:0] b4[2][3]; + wire [7:0] out4[2][3]; + wire sel4; + assign out4 = sel4 ? a4 : b4; + `STATIC_ASSERT($bits(out4) == 48); + + // Test 5: Direct array assignment (continuous) + reg [7:0] a5[4]; + wire [7:0] b5[4]; + assign b5 = a5; + `STATIC_ASSERT($bits(b5) == 32); + + // Test 6: Multi-dimensional direct assignment (continuous) + reg [7:0] a6[2][3]; + wire [7:0] b6[2][3]; + assign b6 = a6; + `STATIC_ASSERT($bits(b6) == 48); + + // Test 7: Procedural direct assignment with different unpacked index ranges + // Covers the AST_BLOCK expansion path for AST_ASSIGN_EQ. + logic pa [1:0][1:0]; + logic pb [1:0][0:1]; + always_comb begin + pa[0][0] = 1'b0; + pa[0][1] = 1'b1; + pa[1][0] = 1'b1; + pa[1][1] = 1'b1; + + pb = pa; + + assert(pb[0][1] == 1'b0); + assert(pb[0][0] == 1'b1); + assert(pb[1][1] == 1'b1); + assert(pb[1][0] == 1'b1); + end + + // Test 8: Procedural ternary assignment on arrays + // Covers the AST_BLOCK expansion path for ternary RHS. + logic pt_a [1:0]; + logic pt_b [1:0]; + logic pt_o [1:0]; + logic pt_sel; + always_comb begin + pt_a[0] = 1'b0; + pt_a[1] = 1'b1; + pt_b[0] = 1'b1; + pt_b[1] = 1'b0; + pt_sel = 1'b1; + + pt_o = pt_sel ? pt_a : pt_b; + + assert(pt_o[0] == 1'b0); + assert(pt_o[1] == 1'b1); + end + + // Test 9: Positional assignment pattern on a whole unpacked array + // Covers the parser and continuous assignment expansion path for `'{...}. + wire ap_table [1]; + wire ap_i = 1'b0; + wire ap_out; + assign ap_table = '{1'h1}; + assign ap_out = ap_table[ap_i > 1'h0 ? 1'h0 : ap_i]; + always_comb begin + assert(ap_out == 1'b1); + end + + // Test 10: Positional assignment pattern preserves left-to-right element order. + wire ap_order [2]; + assign ap_order = '{1'b0, 1'b1}; + always_comb begin + assert(ap_order[0] == 1'b0); + assert(ap_order[1] == 1'b1); + end + + function automatic logic ap_identity(input logic value); + ap_identity = value; + endfunction + + // Test 11: The first assignment pattern element is a runtime expression. + wire ap_runtime_in = 1'b1; + wire ap_runtime [2]; + assign ap_runtime = '{ap_identity(ap_runtime_in), 1'b0}; + always_comb begin + assert(ap_runtime[0] == 1'b1); + assert(ap_runtime[1] == 1'b0); + end + + // Test 12: Nested positional assignment pattern on a multidimensional array. + wire ap_nested [2][2]; + assign ap_nested = '{'{1'b1, 1'b0}, '{1'b0, 1'b1}}; + always_comb begin + assert(ap_nested[0][0] == 1'b1); + assert(ap_nested[0][1] == 1'b0); + assert(ap_nested[1][0] == 1'b0); + assert(ap_nested[1][1] == 1'b1); + end + + // Test 13: Multidimensional assignment pattern with row expressions. + wire ap_row0 [2]; + wire ap_row1 [2]; + wire ap_rows [2][2]; + assign ap_row0 = '{1'b1, 1'b0}; + assign ap_row1 = '{1'b0, 1'b1}; + assign ap_rows = '{ap_row0, ap_row1}; + always_comb begin + assert(ap_rows[0][0] == 1'b1); + assert(ap_rows[0][1] == 1'b0); + assert(ap_rows[1][0] == 1'b0); + assert(ap_rows[1][1] == 1'b1); + end + + // Test 14: Procedural blocking assignment pattern preserves RHS values. + logic ap_swap [2]; + always_comb begin + ap_swap[0] = 1'b0; + ap_swap[1] = 1'b1; + ap_swap = '{ap_swap[1], ap_swap[0]}; + + assert(ap_swap[0] == 1'b1); + assert(ap_swap[1] == 1'b0); + end + + // Test 15: Assignment pattern elements use the target element width context. + logic [4:0] ap_width_ctx [1]; + assign ap_width_ctx = '{4'hf + 4'h1}; + always_comb begin + assert(ap_width_ctx[0] == 5'h10); + end + + // Test 16: Nested assignment pattern elements also use the target element width context. + logic [4:0] ap_nested_width_ctx [1][1]; + assign ap_nested_width_ctx = '{'{4'hf + 4'h1}}; + always_comb begin + assert(ap_nested_width_ctx[0][0] == 5'h10); + end +endmodule diff --git a/chips/yosys/tests/svtypes/array_assign_const_pattern_init.ys b/chips/yosys/tests/svtypes/array_assign_const_pattern_init.ys new file mode 100644 index 0000000000000000000000000000000000000000..0c9902b8a9d7cc4eedc0504888ded1f1d5388a0f --- /dev/null +++ b/chips/yosys/tests/svtypes/array_assign_const_pattern_init.ys @@ -0,0 +1,43 @@ +read_verilog -sv <>> 1}; + assign o0 = a[0]; + assign o1 = a[1]; +endmodule +EOT +proc +sat -verify -prove o0 16'hffff -prove o1 16'hfffc diff --git a/chips/yosys/tests/svtypes/enum_simple.sv b/chips/yosys/tests/svtypes/enum_simple.sv new file mode 100644 index 0000000000000000000000000000000000000000..4e4d5871c5c26e1eef24f33a573e440ad93d1637 --- /dev/null +++ b/chips/yosys/tests/svtypes/enum_simple.sv @@ -0,0 +1,48 @@ + +module enum_simple(input clk, input rst); + + enum {s0, s1, s2, s3} test_enum; + typedef enum logic [1:0] { + ts0, ts1, ts2, ts3 + } states_t; + states_t state; + (states_t) state1; + states_t enum_const = ts1; + + always @(posedge clk) begin + if (rst) begin + test_enum <= s3; + state <= ts0; + end else begin + //test_enum + if (test_enum == s0) + test_enum <= s1; + else if (test_enum == s1) + test_enum <= s2; + else if (test_enum == s2) + test_enum <= s3; + else if (test_enum == s3) + test_enum <= s0; + else + assert(1'b0); //should be unreachable + + //state + if (state == ts0) + state <= ts1; + else if (state == ts1) + state <= ts2; + else if (state == ts2) + state <= ts0; + else + assert(1'b0); //should be unreachable + end + end + + always @(*) begin + assert(state != 2'h3); + assert(s0 == '0); + assert(ts0 == '0); + assert(enum_const == ts1); + end + +endmodule diff --git a/chips/yosys/tests/svtypes/enum_simple.ys b/chips/yosys/tests/svtypes/enum_simple.ys new file mode 100644 index 0000000000000000000000000000000000000000..26a39943b5a660fc9d3959f2fdb314eb26366095 --- /dev/null +++ b/chips/yosys/tests/svtypes/enum_simple.ys @@ -0,0 +1,4 @@ + +read_verilog -sv enum_simple.sv +hierarchy; proc; opt; async2sync +sat -verify -seq 1 -set-at 1 rst 1 -tempinduct -prove-asserts -show-all diff --git a/chips/yosys/tests/svtypes/generate_mk.py b/chips/yosys/tests/svtypes/generate_mk.py new file mode 100644 index 0000000000000000000000000000000000000000..618163ccafb1ff774a5e85835bed4db8418d13e7 --- /dev/null +++ b/chips/yosys/tests/svtypes/generate_mk.py @@ -0,0 +1,8 @@ +#!/usr/bin/env python3 + +import sys +sys.path.append("..") + +import gen_tests_makefile + +gen_tests_makefile.generate(["--yosys-scripts", "--prove-sv"]) diff --git a/chips/yosys/tests/svtypes/logic_rom.sv b/chips/yosys/tests/svtypes/logic_rom.sv new file mode 100644 index 0000000000000000000000000000000000000000..45fe0a4cae14a24b84e08657dd356ee51d5002ae --- /dev/null +++ b/chips/yosys/tests/svtypes/logic_rom.sv @@ -0,0 +1,6 @@ +module top(input [3:0] addr, output [7:0] data); + logic [7:0] mem[0:15]; + assign data = mem[addr]; + integer i; + initial for(i = 0; i < 16; i = i + 1) mem[i] = i; +endmodule diff --git a/chips/yosys/tests/svtypes/logic_rom.ys b/chips/yosys/tests/svtypes/logic_rom.ys new file mode 100644 index 0000000000000000000000000000000000000000..776d2e985088553ae0a39237f1dac205b6442f83 --- /dev/null +++ b/chips/yosys/tests/svtypes/logic_rom.ys @@ -0,0 +1,3 @@ +read_verilog -sv logic_rom.sv +prep -top top +select -assert-count 1 t:$mem_v2 r:SIZE=16 %i r:WIDTH=8 %i diff --git a/chips/yosys/tests/svtypes/multirange_array.sv b/chips/yosys/tests/svtypes/multirange_array.sv new file mode 100644 index 0000000000000000000000000000000000000000..29e4559abaeaafc36881ae4699680caa5813d909 --- /dev/null +++ b/chips/yosys/tests/svtypes/multirange_array.sv @@ -0,0 +1,28 @@ +// test for multirange arrays + +`define STRINGIFY(x) `"x`" +`define STATIC_ASSERT(x) if(!(x)) $error({"assert failed: ", `STRINGIFY(x)}) + +module top; + + logic a [3]; + logic b [3][5]; + logic c [3][5][7]; + logic [2:0] d; + logic [2:0][4:0] e; + logic [2:0][4:0][6:0] f; + logic [2:0] g [3]; + logic [2:0][4:0] h [3][5]; + logic [2:0][4:0][6:0] i [3][5][7]; + + `STATIC_ASSERT($bits(a) == 3); + `STATIC_ASSERT($bits(b) == 15); + `STATIC_ASSERT($bits(c) == 105); + `STATIC_ASSERT($bits(d) == 3); + `STATIC_ASSERT($bits(e) == 15); + `STATIC_ASSERT($bits(f) == 105); + `STATIC_ASSERT($bits(g) == 9); + `STATIC_ASSERT($bits(h) == 225); + `STATIC_ASSERT($bits(i) == 11025); + +endmodule diff --git a/chips/yosys/tests/svtypes/multirange_subarray_access.ys b/chips/yosys/tests/svtypes/multirange_subarray_access.ys new file mode 100644 index 0000000000000000000000000000000000000000..de57d142315d59e3e43ce39425a1d8f8a7929bef --- /dev/null +++ b/chips/yosys/tests/svtypes/multirange_subarray_access.ys @@ -0,0 +1,12 @@ +logger -expect error "Insufficient number of array indices for a." 1 +read_verilog -sv < 8'h00 && !a_special; + wire a_subnorm = a_exp == 8'h00 && a_sig != '0; + wire a_finite = a_norm || a_subnorm; + + wire signed [8:0] a_sexp = $signed({1'b0, a_exp}) - 8'h7f; + wire signed [8:0] half_a_sexp = a_sexp >>> 1; + + wire b_sign = b[31]; + wire [30:0] b_unsigned = b[30:0]; + wire [7:0] b_exp = b[30:23]; + wire [22:0] b_sig = b[22:0]; + wire b_zero = b_unsigned == '0; + wire b_special = b_exp == 8'hff; + wire b_inf = b_special && b_sig == '0; + wire b_nan = b_special && b_sig != '0; + wire b_qnan = b_nan && b_sig[22]; + wire b_snan = b_nan && !b_sig[22]; + wire b_norm = b_exp > 8'h00 && !b_special; + wire b_subnorm = b_exp == 8'h00 && b_sig != '0; + wire b_finite = b_norm || b_subnorm; + + wire c_sign = c[31]; + wire [30:0] c_unsigned = c[30:0]; + wire [7:0] c_exp = c[30:23]; + wire [22:0] c_sig = c[22:0]; + wire c_zero = c_unsigned == '0; + wire c_special = c_exp == 8'hff; + wire c_inf = c_special && c_sig == '0; + wire c_nan = c_special && c_sig != '0; + wire c_qnan = c_nan && c_sig[22]; + wire c_snan = c_nan && !c_sig[22]; + wire c_norm = c_exp > 8'h00 && !c_special; + wire c_subnorm = c_exp == 8'h00 && c_sig != '0; + wire c_finite = c_norm || c_subnorm; + + wire o_sign = o[31]; + wire [30:0] o_unsigned = o[30:0]; + wire [7:0] o_exp = o[30:23]; + wire [22:0] o_sig = o[22:0]; + wire o_zero = o_unsigned == '0; + wire o_special = o_exp == 8'hff; + wire o_inf = o_special && o_sig == '0; + wire o_nan = o_special && o_sig != '0; + wire o_qnan = o_nan && o_sig[22]; + wire o_snan = o_nan && !o_sig[22]; + wire o_norm = o_exp > 8'h00 && !o_special; + wire o_subnorm = o_exp == 8'h00 && o_sig != '0; + wire o_finite = o_norm || o_subnorm; + wire o_clamped = o_unsigned == 31'h7f7fffff; + wire o_unclamped = o_finite && !o_clamped; + wire o_ebmin = o_exp == 8'h01 && o_sig == '0; + + wire signed [8:0] o_sexp = $signed({1'b0, o_exp}) - 8'h7f; + + (* keep *) wire [25:0] a_faux = {2'b10, !a_subnorm, a_sig}; + (* keep *) wire [25:0] b_faux = {2'b00, !b_subnorm, b_sig}; + (* keep *) wire [25:0] o_faux = (a_faux - b_faux); + +`ifdef MULADD + wire muladd_zero = c_zero; + wire a_is_1 = a == 32'h3f800000; + wire b_is_1 = b == 32'h3f800000; + wire use_lhs = a_is_1 || b_is_1; + wire lhs_sign = b_is_1 ? a_sign : b_sign; + wire [30:0] lhs_unsigned = b_is_1 ? a_unsigned : b_unsigned; + wire [7:0] lhs_exp = b_is_1 ? a_exp : b_exp; + wire [22:0] lhs_sig = b_is_1 ? a_sig : b_sig; + wire lhs_zero = b_is_1 ? a_zero : b_zero; + wire lhs_inf = b_is_1 ? a_inf : b_inf; + wire lhs_nan = b_is_1 ? a_nan : b_nan; + wire lhs_qnan = b_is_1 ? a_qnan : b_qnan; + wire lhs_snan = b_is_1 ? a_snan : b_snan; + wire lhs_norm = b_is_1 ? a_norm : b_norm; + wire lhs_subnorm = b_is_1 ? a_subnorm : b_subnorm; + wire lhs_finite = b_is_1 ? a_finite : b_finite; + + wire rhs_sign = c_sign; + wire [30:0] rhs_unsigned = c_unsigned; + wire [7:0] rhs_exp = c_exp; + wire [22:0] rhs_sig = c_sig; + wire rhs_zero = c_zero; + wire rhs_inf = c_inf; + wire rhs_nan = c_nan; + wire rhs_qnan = c_qnan; + wire rhs_snan = c_snan; + wire rhs_norm = c_norm; + wire rhs_subnorm = c_subnorm; + wire rhs_finite = c_finite; +`else + wire muladd_zero = 1; + wire use_lhs = 1; + wire lhs_sign = a_sign; + wire [30:0] lhs_unsigned = a_unsigned; + wire [7:0] lhs_exp = a_exp; + wire [22:0] lhs_sig = a_sig; + wire lhs_zero = a_zero; + wire lhs_inf = a_inf; + wire lhs_nan = a_nan; + wire lhs_qnan = a_qnan; + wire lhs_snan = a_snan; + wire lhs_norm = a_norm; + wire lhs_subnorm = a_subnorm; + wire lhs_finite = a_finite; + + wire rhs_sign = b_sign; + wire [30:0] rhs_unsigned = b_unsigned; + wire [7:0] rhs_exp = b_exp; + wire [22:0] rhs_sig = b_sig; + wire rhs_zero = b_zero; + wire rhs_inf = b_inf; + wire rhs_nan = b_nan; + wire rhs_qnan = b_qnan; + wire rhs_snan = b_snan; + wire rhs_norm = b_norm; + wire rhs_subnorm = b_subnorm; + wire rhs_finite = b_finite; +`endif + +`ifdef SUB + wire is_sub = lhs_sign == rhs_sign; +`else + wire is_sub = lhs_sign != rhs_sign; +`endif + wire lhs_dominates = lhs_exp > rhs_exp; + wire [7:0] exp_diff = lhs_dominates ? lhs_exp - rhs_exp : rhs_exp - lhs_exp; + + wire round_p_001, round_p_011, round_n_001, round_n_011; + wire [30:0] rounded_100, rounded_010, rounded_000; + +`ifdef MUL + assign round_p_001 = 0; + assign round_p_011 = a == 32'h40400000 && b == 32'h40000001; + assign round_n_001 = 0; + assign round_n_011 = a == 32'hc0400000 && b == 32'h40000001; + + assign rounded_100 = 31'h40C00002; + assign rounded_010 = 31'h40C00001; + assign rounded_000 = 31'h40C00000; +`elsif ADD + assign round_p_001 = a == 32'h4c000000 && b == 32'h40000000; + assign round_p_011 = a == 32'h4c000001 && b == 32'h40000000; + assign round_n_001 = a == 32'hcc000000 && b == 32'hc0000000; + assign round_n_011 = a == 32'hcc000001 && b == 32'hc0000000; + + assign rounded_100 = 31'h4C000002; + assign rounded_010 = 31'h4C000001; + assign rounded_000 = 31'h4C000000; +`else + assign round_p_001 = 0; + assign round_p_011 = 0; + assign round_n_001 = 0; + assign round_n_011 = 0; + + assign rounded_100 = '0; + assign rounded_010 = '0; + assign rounded_000 = '0; +`endif + +`ifdef MAX + wire choose_max = 1; +`else + wire choose_max = 0; +`endif + + wire rm_RNE = rm[0] == 1'b1; + wire rm_RNA = rm[1:0] == 2'b10; + wire rm_RTP = rm[2:0] == 3'b100; + wire rm_RTN = rm[3:0] == 4'b1000; + wire rm_RTZ = rm[4:0] == 5'b10000; + + wire c_muladd_turning = rm_RNE || rm_RNA ? c_sig <= 23'h200000 : + rm_RTP ? c_sig == '0 : + rm_RTN ? c_sig < 23'h400000 : + c_sig == '0; + + always @* begin + // all classes of input are possible (for all inputs) + cover (a_sign); + cover (!a_sign); + cover (a_zero); + cover (a_norm); + cover (a_subnorm); + cover (a_inf); + cover (a_qnan); + cover (a_snan); + +`ifndef SQRTS +// sqrt has no b input + cover (b_sign); + cover (!b_sign); + cover (b_zero); + cover (b_norm); + cover (b_subnorm); + cover (b_inf); + cover (b_qnan); + cover (b_snan); +`endif + +`ifdef MULADD +// only muladd has c input + cover (c_sign); + cover (!c_sign); + cover (c_zero); + cover (c_norm); + cover (c_subnorm); + cover (c_inf); + cover (c_qnan); + cover (c_snan); +`endif + + // all flags are possible + cover (NV); +`ifndef COMPARES + `ifdef DIVS + // only div can div/zero + cover (DZ); + `endif + `ifndef SQRTS + // sqrt can't overflow or underflow + cover (OF); + `ifndef ADDSUB + // add/sub can't underflow + cover (UF); + `endif + `endif + cover (NX); +`endif + cover (!NV); + cover (!DZ); + cover (!OF); + cover (!UF); + cover (!NX); + + // all classes of output are possible + cover (o_sign); + cover (!o_sign); + cover (o_zero); + cover (o_norm); + cover (o_inf); + cover (o_nan); +`ifndef SQRTS +// subnormal outputs not possible for 8/24 sqrt + cover (o_subnorm); + cover (o_ebmin); +`endif + +`ifndef COMPARES +`ifndef SQRTS + if (OF) begin + cover (o_inf); + cover (o_clamped); + end else begin + cover (o_inf); + cover (o_clamped); + end + + if (UF) begin + `ifndef ADDSUB + cover (o_zero); + cover (o_ebmin); + cover (o_subnorm); + `endif + end else begin + cover (o_zero); + cover (o_ebmin); + cover (o_subnorm); + end + + if (NX) begin + cover (o_norm); + cover (o_inf); + `ifndef ADDSUB + cover (o_subnorm); + cover (o_zero); + `endif + end +`endif + + if (a_nan || b_nan || c_nan) begin + // input NaN = output NaN + assert (o_nan); + + // NaN inputs give NaN outputs, do not raise exceptions (unless signaling NV) + assert (!DZ); + assert (!OF); + assert (!UF); + assert (!NX); + end + + if (NV) + // output = qNaN + assert (o_qnan); +`endif // !COMPARES + + if (a_snan || b_snan) + // signalling NaN raises invalid exception + assert (NV); + + if (a_qnan && b_qnan && c_qnan) + // quiet NaN inputs do not raise invalid exception + assert (!NV); + + if (DZ) + // output = +-inf + assert (o_inf); + + if (OF) + // overflow is always inexact + assert (NX); + + if (UF) + // underflow is always inexact + assert (NX); + + if (UF) + // output = subnormal or zero or +-e^bmin + assert (o_subnorm || o_zero || o_ebmin); + + if (o_inf && !OF) + // a non-overflowing infinity is exact + assert (!NX); + + if (o_subnorm && !UF) + // a non-underflowing subnormal is exact + assert (!NX); + +`ifdef COMPARES + assume (c_zero); + assert (!OF); + assert (!UF); + assert (!NX); + assert (!DZ); + + if (!a_nan && b_nan) + assert (o == a); + else if (a_nan && !b_nan) + assert (o == b); + else if (a_nan && b_nan) + assert (o_nan); + else begin + assert (o == a || o == b); + + if (a_inf) begin + if (a_sign == choose_max) + assert (o == b); + else + assert (o == a); + end + + if (b_inf) begin + if (b_sign == choose_max) + assert (o == a); + else + assert (o == b); + end + end + + if (!a_special && !b_special) begin + if (a_sign != b_sign) + if (a_sign == choose_max) + assert (o == b); + else + assert (o == a); + // a_sign == b_sign + else if (a_exp != b_exp) + if ((a_exp > b_exp) ^ a_sign ^ choose_max) + assert (o == b); + else + assert (o == a); + // a_exp == b_exp + else if ((a_sig > b_sig) ^ a_sign ^ choose_max) + assert (o == b); + else + assert (o == a); + end +`endif + +`ifdef DIVS + assume (c_zero); + // div/zero only when a is finite + assert (DZ ^~ (a_finite && b_zero)); + // 0/0 or inf/inf + if ((a_zero && b_zero) || (a_inf && b_inf)) + assert (NV); + // dividing by a very small number will overflow + if (a_norm && a_exp > 8'h80 && b == 32'h00000001) + assert (OF); + // dividing by a much smaller number will overflow + if (a_norm && b_finite && lhs_dominates && exp_diff > 8'h80) + assert (OF); + // dividing by a much larger number will hit 0 bias + if (a_finite && b_norm && !lhs_dominates && exp_diff > 8'h7f) begin + assert (o_exp == '0); + // if the divisor is large enough, underflow (or zero) is guaranteed + if (exp_diff > 8'h95) begin + assert (NX); + assert (UF || o_zero); + end + end + // an unrounded result between +-e^bmin is still an underflow when rounded to ebmin + if (a_unsigned == 31'h0031b7be && b_unsigned == 31'h3ec6def9) + assert (UF); + `ifdef ALTDIV + if (!NV && !NX && !a_special && b_finite && o_norm) + // if o is subnorm then it can be shifted arbitrarily depending on exponent difference + assert (o_sig == (o_faux[25] ? o_faux[24:2] : o_faux[23:1])); + `endif +`endif + +`ifdef MUL + assume (c_zero); + // an unrounded result between +-e^bmin is still an underflow when rounded to ebmin + if (a_unsigned == 31'h0ffffffd && b_unsigned == 31'h30000001) begin + assert (UF); + // but it's only ebmin when rounded towards the nearest infinity + assert (o_ebmin ^~ (o_sign ? rm_RTN : rm_RTP)); + end +`endif + +`ifdef MULS + if (a_unsigned == 31'h0ffffffd && b_unsigned == 31'h30000001 && c_subnorm) + if (!c_sign ^ b_sign ^ a_sign) + assert (!UF); + else + assert (UF); + // 0/inf or inf/0 + if ((a_inf && b_zero) || (a_zero && b_inf)) + assert (NV); + // very large multiplications overflow + if (a_unsigned == 31'h7f400000 && b_unsigned == a_unsigned && !c_special) + assert (OF); + // multiplying a small number by an even smaller number will underflow + if (a_norm && a_exp < 8'h68 && b_subnorm && !c_special) begin + assert (NX); + `ifdef MULADD + // within rounding + assert (UF || (c_zero ? o_zero : (o == c || o == c+1 || o == c-1))); + `else + assert (UF || o_zero); + if (o_zero) + assert (o_sign == a_sign ^ b_sign); + `endif + end +`endif + +`ifdef ADDSUB + assume (c_zero); + // adder can't underflow, subnormals are always exact + assert (!UF); +`endif + +`ifdef RNE + assume (rm_RNE); +`elsif RNA + assume (rm_RNA); +`elsif RTP + assume (rm_RTP); +`elsif RTN + assume (rm_RTN); +`elsif RTZ + assume (rm_RTZ); +`else + assume ($onehot(rm)); +`endif + + if (OF) + // rounding mode determines if overflow value is inf or max + casez (rm) + 5'bzzzz1 /* RNE */: assert (o_inf); + 5'bzzz10 /* RNA */: assert (o_inf); + 5'bzz100 /* RTP */: assert (o == pos_inf || o == neg_max); + 5'bz1000 /* RTN */: assert (o == pos_max || o == neg_inf); + 5'b10000 /* RTZ */: assert (o == pos_max || o == neg_max); + endcase + + // RTx modes cannot underflow to the opposite ebmin (or either for RTZ) + if (UF && o_ebmin) + if (o_sign) + assert (rm_RNE || rm_RNA || rm_RTN); + else + assert (rm_RNE || rm_RNA || rm_RTP); + + // and the same for overflowing to infinities + if (OF && o_inf) + if (o_sign) + assert (rm_RNE || rm_RNA || rm_RTN); + else + assert (rm_RNE || rm_RNA || rm_RTP); + + // test rounding + if (round_p_001) + casez (rm) + 5'bzzzz1 /* RNE */: assert (o_unsigned == rounded_000); + 5'bzzz10 /* RNA */: assert (o_unsigned == rounded_010); + 5'bzz100 /* RTP */: assert (o_unsigned == rounded_010); + 5'bz1000 /* RTN */: assert (o_unsigned == rounded_000); + 5'b10000 /* RTZ */: assert (o_unsigned == rounded_000); + endcase + if (round_p_011) + casez (rm) + 5'bzzzz1 /* RNE */: assert (o_unsigned == rounded_100); + 5'bzzz10 /* RNA */: assert (o_unsigned == rounded_100); + 5'bzz100 /* RTP */: assert (o_unsigned == rounded_100); + 5'bz1000 /* RTN */: assert (o_unsigned == rounded_010); + 5'b10000 /* RTZ */: assert (o_unsigned == rounded_010); + endcase + if (round_n_001) + casez (rm) + 5'bzzzz1 /* RNE */: assert (o_unsigned == rounded_000); + 5'bzzz10 /* RNA */: assert (o_unsigned == rounded_010); + 5'bzz100 /* RTP */: assert (o_unsigned == rounded_000); + 5'bz1000 /* RTN */: assert (o_unsigned == rounded_010); + 5'b10000 /* RTZ */: assert (o_unsigned == rounded_000); + endcase + if (round_n_011) + casez (rm) + 5'bzzzz1 /* RNE */: assert (o_unsigned == rounded_100); + 5'bzzz10 /* RNA */: assert (o_unsigned == rounded_100); + 5'bzz100 /* RTP */: assert (o_unsigned == rounded_010); + 5'bz1000 /* RTN */: assert (o_unsigned == rounded_100); + 5'b10000 /* RTZ */: assert (o_unsigned == rounded_010); + endcase + +`ifdef ADDS + if (use_lhs) begin + // inf - inf + if (lhs_inf && rhs_inf && is_sub) + assert (NV); + // very large additions overflow + if (lhs_unsigned == 31'h7f400000 && rhs_unsigned == lhs_unsigned && !is_sub) + assert (OF); + // if the difference in exponent is more than the width of the mantissa, + // the result cannot be exact + if (lhs_finite && rhs_finite && exp_diff > 8'd24) + assert (NX || OF); + if (!UF) begin + // for a small difference in exponent with zero LSB, the result must be + // exact + if (o_unclamped && lhs_dominates && exp_diff < 8'd08 && rhs_sig[7:0] == 0 && lhs_sig[7:0] == 0) + assert (!NX); + if (exp_diff == 0 && !OF && lhs_sig[7:0] == 0 && rhs_sig[7:0] == 0) + assert (!NX); + end + // there's probably a better general case for this, but a moderate + // difference in exponent with non zero LSB must be inexact + if (o_finite && lhs_dominates && exp_diff > 8'd09 && rhs_sig[7:0] != 0 && lhs_sig[7:0] == 0) + assert (NX); + end +`endif + +`ifdef MULADD + // not sure how to check this in the generic case since we don't have the partial mul + if ((a_inf || b_inf) && !(a_nan || b_nan) && c_inf && (a_sign ^ b_sign ^ c_sign)) + assert (NV); + // normal multiplication, overflow addition + if (a == 31'h5f400000 && b == a && c == 32'h7f400000) begin + assert (OF); + end + // if multiplication overflows, addition can bring it back in range + if (a == 32'hc3800001 && b == 32'h7b800000 && !c_special) begin + if (c_sign) + // result is negative, so a negative addend can't + assert (OF); + else if (c_exp <= 8'he7) + // addend can't be too small + assert (OF); + else if (c_exp == 8'he8 && c_muladd_turning) + // this is just the turning point for this particular value + assert (OF); + else + // a large enough positive addend will never overflow (but is + // still likely to be inexact) + assert (!OF); + end +`endif + +`ifdef SQRTS + assume (b_zero); + assume (c_zero); + assert (!UF); + assert (!OF); + // complex roots are invalid + if (a_sign) begin + if (a_norm || a_subnorm) + assert (NV); + end else begin + // root exponents for normal numbers are trivial + if (a_norm) begin + // root of a normal is always normal + assert (o_norm); + if (rm_RTZ) + assert (o_sexp == half_a_sexp); + else + assert (o_sexp == half_a_sexp || o_sexp == (half_a_sexp + 1)); + `ifdef ALTSQRT + if (o_sexp == half_a_sexp) begin + if (NX) begin + assert (a_sig[0] == 1'b1); + if (rm_RTZ || rm_RTN) begin + assert (o_sig[22] == 1'b1); + assert (o_sig[21:0] == a_sig >> 1); + end else begin + assert (o_sig[22] != &a_sig); + if (rm_RNE && a_sig[1] == 1'b0) begin + assert (o_sig[21:0] == a_sig >> 1); + end else begin + assert (o_sig[21:0] == (a_sig[22:1]+1'b1)); + end + end + end else begin + assert (a_sig[0] == 1'b0); + assert (o_sig[22] == a_sig[0]); + assert (o_sig[21:0] == a_sig >> 1); + end + end + `endif + end else if (a_subnorm) begin + // root of a subnormal is either normal or an exact subnormal + assert (o_norm || !NX); + end + end +`endif + end + +`ifdef EDGE_EVENTS + reg skip = 1; + always @(posedge clk) begin + if (skip) begin + skip <= 0; + end else begin + // same input, different rounding mode + if ($stable(a) && $stable(b) && $stable(c)) begin + // general rounding + cover (NX && rm_RNE && o_sig[1:0] == 2'b00); + cover (NX && rm_RNE && o_sig[1:0] == 2'b10); + if (NX && $fell(rm_RNE)) begin + if ($past(o_sig[1:0]) == 2'b00) begin // should be rounding from 001 + if (o_sign) begin +`ifndef SQRTS + cover ($rose(rm_RNA) && o_sig[1:0] == 2'b01); + cover ($rose(rm_RTP) && o_sig[1:0] == 2'b00); + cover ($rose(rm_RTN) && o_sig[1:0] == 2'b01); + cover ($rose(rm_RTZ) && o_sig[1:0] == 2'b00); +`endif + end else begin + cover ($rose(rm_RNA) && o_sig[1:0] == 2'b01); + cover ($rose(rm_RTP) && o_sig[1:0] == 2'b01); + cover ($rose(rm_RTN) && o_sig[1:0] == 2'b00); + cover ($rose(rm_RTZ) && o_sig[1:0] == 2'b00); + end + end else if ($past(o_sig[1:0]) == 2'b10) begin // should be rounding from 011 + if (o_sign) begin +`ifndef SQRTS + cover ($rose(rm_RNA) && o_sig[1:0] == 2'b10); + cover ($rose(rm_RTP) && o_sig[1:0] == 2'b01); + cover ($rose(rm_RTN) && o_sig[1:0] == 2'b10); + cover ($rose(rm_RTZ) && o_sig[1:0] == 2'b01); +`endif + end else begin + cover ($rose(rm_RNA) && o_sig[1:0] == 2'b10); + cover ($rose(rm_RTP) && o_sig[1:0] == 2'b10); + cover ($rose(rm_RTN) && o_sig[1:0] == 2'b01); + cover ($rose(rm_RTZ) && o_sig[1:0] == 2'b01); + end + end + end + +`ifndef SQRTS +// none of these are applicable for sqrt since we can't underflow or overflow + // inf edge cases + cover ($rose(o_inf)); + if ($rose(o_inf)) begin + cover ($rose(rm_RNE)); + cover ($rose(rm_RNA)); + cover ($rose(rm_RTN)); + cover ($rose(rm_RTP)); + // rm_RTZ can never round to inf + end + + `ifndef ADDSUB + // these aren't applicable to addsub since we they rely on underflow + // ebmin edge cases + cover ($rose(o_ebmin)); + if ($rose(o_ebmin)) begin + cover ($rose(rm_RNE)); + cover ($rose(rm_RNA)); + cover ($rose(rm_RTN)); + cover ($rose(rm_RTP)); + cover ($rose(rm_RTZ)); + end + + // zero edge cases + cover ($rose(o_zero)); + if ($rose(o_zero)) begin + cover ($rose(rm_RNE)); + cover ($rose(rm_RNA)); + cover ($rose(rm_RTN)); + cover ($rose(rm_RTP)); + cover ($rose(rm_RTZ)); + end + `endif + + `ifndef DIV + cover ($rose(OF)); + `endif + `ifdef TININESS_AFTER + cover ($rose(UF)); + `endif +`endif +`ifdef MULADD + // same multiplier output, different addend + end else if ($stable(a) && $stable(b) && $stable(rm)) begin + // we can get boundary cases + cover ($rose(o_inf)); + cover ($rose(o_ebmin)); + cover ($rose(o_zero)); + + // multiplication with an exception can be recovered by addend + if ($fell(c_zero)) begin + cover ($fell(OF)); + cover ($fell(UF)); + cover ($fell(NX)); + // unless it was an invalid multiplication + if ($past(NV)) + assert (NV); + end + + // flags are always determined after addition + cover ($rose(OF)); + cover ($rose(UF)); + cover ($rose(NV)); + cover ($rose(NX)); +`endif + end + end + end +`endif +endmodule diff --git a/chips/yosys/tests/symfpu/generate_mk.py b/chips/yosys/tests/symfpu/generate_mk.py new file mode 100644 index 0000000000000000000000000000000000000000..c55e513abdb698a51179b2219d9d19c8bfa1bd53 --- /dev/null +++ b/chips/yosys/tests/symfpu/generate_mk.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python3 + +import sys +sys.path.append("..") +import gen_tests_makefile + +from textwrap import dedent + +gen_tests_makefile.remove_generated("*_edges.*") + +for op, defs in { + # standard ops + "sqrt": "-DSQRT -DSQRTS", + "add": "-DADD -DADDSUB -DADDS", + "sub": "-DSUB -DADDSUB -DADDS", + "mul": "-DMUL -DMULS", + "div": "-DDIV -DDIVS", + "muladd": "-DMULADD -DMULS -DADDS", + # altops + "altdiv": "-DALTDIV -DDIVS", + "altsqrt": "-DALTSQRT -DSQRTS", + # unrounded + "min": "-DMIN -DCOMPARES", + "max": "-DMAX -DCOMPARES", +}.items(): + rms = ["DYN"] + dyn_only = op in ["min", "max"] + if not dyn_only: + rms.extend(["RNE", "RNA", "RTP", "RTN", "RTZ"]) + for rm in rms: + with open(f"{op}_{rm}_edges.ys", "w") as ys: + print(f"symfpu -op {op} -rm {rm}", file=ys) + if rm != "DYN" or dyn_only: + print("sat -prove-asserts -verify", file=ys) + print( + dedent(f"""\ + chformal -remove + opt + + read_verilog -sv -formal {defs} -D{rm} edges.sv + chformal -remove -cover + chformal -lower + prep -top edges -flatten + sat -set-assumes -prove-asserts -verify""" + ), file=ys) + +gen_tests_makefile.generate(["--yosys-scripts"]) diff --git a/chips/yosys/tests/techmap/abc9-nonbox-loop-with-box.ys b/chips/yosys/tests/techmap/abc9-nonbox-loop-with-box.ys new file mode 100644 index 0000000000000000000000000000000000000000..2b7a551bc51124f1fc0478a440e09f27cfcd1841 --- /dev/null +++ b/chips/yosys/tests/techmap/abc9-nonbox-loop-with-box.ys @@ -0,0 +1,19 @@ +read_verilog -icells -specify < o) = 1; +endspecify +endmodule + +module top(input i, output o); + wire a, b, c, z; + $_AND_ a0(.A(b), .B(i), .Y(a)); + $_AND_ b0(.A(a), .B(c), .Y(b)); + $_AND_ c0(.A(b), .B(i), .Y(c)); + box1 u_box(.i(i), .o(z)); + assign o = c ^ z; +endmodule +EOT + +abc9 -lut 4 diff --git a/chips/yosys/tests/techmap/abc9.ys b/chips/yosys/tests/techmap/abc9.ys new file mode 100644 index 0000000000000000000000000000000000000000..bb201385c691ebc961b9d8c14ea9103ee12ddc55 --- /dev/null +++ b/chips/yosys/tests/techmap/abc9.ys @@ -0,0 +1,81 @@ +read_verilog <, 3, 3, 1) +`BIOP(ge, >=, 3, 3, 1) +`UNOP(pos, +, 3) +`UNOP(not, ~, 3) +`UNOP_REDUCE(logic_not, !, 3) +`UNOP_REDUCE(reduce_and, &, 3) +`UNOP_REDUCE(reduce_or, |, 3) +`UNOP_REDUCE(reduce_xor, ^, 3) +`UNOP_REDUCE(reduce_xnor, ~^, 3) + +wire [3:0] mux_a, mux_b, mux_s, mux_y; +assign mux_y = mux_s ? mux_b : mux_a; +endmodule +EOF + +expose -input c:* %ci* w:* %i +expose c:* %co* w:* %i +copy test gold +aigmap test +select -assert-none test/t:$_AND_ test/t:$_NOT_ %% test/c:* %D +miter -equiv -flatten gold test miter +sat -verify -prove trigger 0 miter + + +design -reset +read_verilog <> t; + +endmodule +EOT + +wreduce +equiv_opt -assert peepopt diff --git a/chips/yosys/tests/techmap/bug2759.ys b/chips/yosys/tests/techmap/bug2759.ys new file mode 100644 index 0000000000000000000000000000000000000000..05699bef813f3a97713a4ea41ff8cd3f04db9774 --- /dev/null +++ b/chips/yosys/tests/techmap/bug2759.ys @@ -0,0 +1,14 @@ +read_verilog -specify < o) = 1; +endspecify +assign o = ^i; +endmodule + +module top(input [1:0] i, output o); +box i1(i, o); +endmodule +EOT +abc9 -lut 4 diff --git a/chips/yosys/tests/techmap/bug2972.ys b/chips/yosys/tests/techmap/bug2972.ys new file mode 100644 index 0000000000000000000000000000000000000000..8ae895f56b537bd69af7fb35d695be97e5975b24 --- /dev/null +++ b/chips/yosys/tests/techmap/bug2972.ys @@ -0,0 +1,20 @@ +read_verilog -specify < (q : d)) = 1; + (d => do) = 1; +endspecify +endmodule + +module top(input clk, d, output q); +box i1(clk, d, q); +endmodule +EOT +hierarchy +abc9 -lut 4 +abc9 -lut 4 diff --git a/chips/yosys/tests/techmap/bug4349.ys b/chips/yosys/tests/techmap/bug4349.ys new file mode 100644 index 0000000000000000000000000000000000000000..dad1bd10d67de3e3abe4947e57109fb57f62aa7a --- /dev/null +++ b/chips/yosys/tests/techmap/bug4349.ys @@ -0,0 +1,64 @@ +read_rtlil < Q) = 100; + endspecify +endmodule +module top(input clk, d, output q); + PRIM p(.C(clk), .D(d), .Q(q)); +endmodule +EOT +setattr -mod -set whitebox 1 PRIM +hierarchy -top top +abc9 -lut 4 +delete -port =PRIM/E +hierarchy -check diff --git a/chips/yosys/tests/techmap/cellmatch.ys b/chips/yosys/tests/techmap/cellmatch.ys new file mode 100644 index 0000000000000000000000000000000000000000..05368fb3b355ccbb2d425229dbac7ec7094c4e0b --- /dev/null +++ b/chips/yosys/tests/techmap/cellmatch.ys @@ -0,0 +1,87 @@ +read_verilog < b; +assign gts = $signed(a) > $signed(b); +assign ltu = a < b; +assign lts = $signed(a) < $signed(b); +assign geu = a >= b; +assign ges = $signed(a) >= $signed(b); +assign leu = a <= b; +assign les = $signed(a) <= $signed(b); +endmodule +EOT + +equiv_opt -assert techmap -map +/cmp2lcu.v -D LUT_WIDTH=6 +design -load postopt +select -assert-count 8 t:$lcu r:WIDTH=5 %i +select -assert-none t:$gt t:$ge t:$lt t:$le + +design -load preopt +equiv_opt -assert techmap -map +/cmp2lcu.v -D LUT_WIDTH=4 +design -load postopt +select -assert-count 8 t:$lcu r:WIDTH=7 %i +select -assert-none t:$gt t:$ge t:$lt t:$le + + +design -reset +read_verilog < d; +assign gts = $signed(c) > $signed(d); +assign ltu = c < d; +assign lts = $signed(c) < $signed(d); +assign geu = c >= d; +assign ges = $signed(c) >= $signed(d); +assign leu = c <= d; +assign les = $signed(c) <= $signed(d); +endmodule +EOT +design -save gold + +equiv_opt -assert techmap -map +/cmp2lcu.v -D LUT_WIDTH=5 +design -load postopt +select -assert-count 8 t:$lcu r:WIDTH=2 %i +select -assert-none t:$gt t:$ge t:$lt t:$le + +design -load preopt +equiv_opt -assert techmap -map +/cmp2lcu.v -D LUT_WIDTH=3 +design -load postopt +select -assert-count 8 t:$lcu r:WIDTH=4 %i +select -assert-none t:$gt t:$ge t:$lt t:$le diff --git a/chips/yosys/tests/techmap/constmap.ys b/chips/yosys/tests/techmap/constmap.ys new file mode 100644 index 0000000000000000000000000000000000000000..6945cf514351a36abf68a2845e647ebac9f39875 --- /dev/null +++ b/chips/yosys/tests/techmap/constmap.ys @@ -0,0 +1,43 @@ +read_verilog << EOT + +module test(); + wire [31:0] in; + wire [31:0] out; + assign out = in + 16; +endmodule + +EOT + +constmap -cell const_cell O value +select -assert-count 1 t:const_cell r:value=16 %i + +design -reset + +read_verilog -lib << EOT +module const_cell(O); +parameter value=0; +output O; +endmodule +EOT + +read_verilog << EOT + +module test(); + wire [31:0] in; + wire [31:0] out1; + wire [31:0] out2; + assign out1 = in + 16; + assign out2 = in + 32; +endmodule + +EOT + +constmap -cell const_cell O value + +select -assert-count 2 t:const_cell +select -assert-count 1 r:value=16 +select -assert-count 1 r:value=32 +select -assert-count 1 test/out1 %ci* r:value=16 %i +select -assert-count 1 test/out2 %ci* r:value=32 %i +select -assert-count 1 t:const_cell r:value=16 %i +select -assert-count 1 t:const_cell r:value=32 %i diff --git a/chips/yosys/tests/techmap/dff2ff.ys b/chips/yosys/tests/techmap/dff2ff.ys new file mode 100644 index 0000000000000000000000000000000000000000..6e7e6082bbea8ab72beecd5f933f38191ac8afec --- /dev/null +++ b/chips/yosys/tests/techmap/dff2ff.ys @@ -0,0 +1,16 @@ +read_verilog -icells << EOT +module top(...); + +input [1:0] D; +input C; +output [1:0] Q; + +always @(posedge C) + Q <= D; + +endmodule +EOT + +proc + +equiv_opt -assert techmap -map +/dff2ff.v diff --git a/chips/yosys/tests/techmap/dffinit.ys b/chips/yosys/tests/techmap/dffinit.ys new file mode 100644 index 0000000000000000000000000000000000000000..218d411f8b91e422e5b1e4c5e6a00a54593ebf1e --- /dev/null +++ b/chips/yosys/tests/techmap/dffinit.ys @@ -0,0 +1,25 @@ +read_verilog < gate-level $_MUX_ +design -save gold +lut2mux +rename \top \gate +select -assert-count 3 gate/t:$_MUX_ +select -assert-count 0 gate/t:$mux +select -assert-count 0 gate/t:$lut + +# -word mode -> word-level $mux +design -copy-from gold -as top \top +select -none +select top +lut2mux -word +select -clear +rename \top \word +select -assert-count 3 word/t:$mux +select -assert-count 0 word/t:$_MUX_ +select -assert-count 0 gate/t:$lut + +# equivalence +equiv_make \gate \word equiv +hierarchy -top equiv +equiv_simple +equiv_induct +equiv_status -assert diff --git a/chips/yosys/tests/techmap/mcm.ys b/chips/yosys/tests/techmap/mcm.ys new file mode 100644 index 0000000000000000000000000000000000000000..25336ee77051acde0fceacb2e335d01f6d6d1ecd --- /dev/null +++ b/chips/yosys/tests/techmap/mcm.ys @@ -0,0 +1,170 @@ +# tests for mcm pass +log -header "MCM normalized A-operation width" +read_verilog < \d+ adder\(s\), depth (\d+),", re.MULTILINE) +ACM_COST_RE = re.compile(r"^// Cost: (\d+) adds/subtracts (\d+) shifts (\d+) negations$", re.MULTILINE) +ACM_DEPTH_RE = re.compile(r"^// Depth: (\d+)$", re.MULTILINE) + +@dataclass +class ProfileResult: + seconds: float + adds_subs: int + negations: int + depth: int | None + shifts: int | None = None + mul: int = 0 + + def time(self) -> str: + return f"{self.seconds:.3f}s" + + def stats(self) -> str: + depth = self.depth if self.depth is not None else "unknown" + return f"add+sub={self.adds_subs}, mul={self.mul}, depth={depth}" + +def parse_yosys(stdout: str, seconds: float) -> ProfileResult: + if not re.search(r"^=== .+ ===$", stdout, re.MULTILINE): + raise ValueError("Missing Yosys statistics") + cells: dict[str, int] = {} + for count, cell in STAT_RE.findall(stdout): + cells[cell] = cells.get(cell, 0) + int(count) + depths = [int(depth) for depth in DEPTH_RE.findall(stdout)] + return ProfileResult(seconds, cells.get("add", 0) + cells.get("sub", 0), cells.get("neg", 0), max(depths, default=None), mul=cells.get("mul", 0)) + +def parse_acm(stdout: str, seconds: float) -> ProfileResult: + cost = ACM_COST_RE.search(stdout) + depth = ACM_DEPTH_RE.search(stdout) + if cost is None or depth is None: + raise ValueError("Missing ACM cost or depth") + adds_subs, shifts, negations = map(int, cost.groups()) + mul = len(re.findall(r"^\s*t\d+\s*=\s*cmul\(", stdout, re.MULTILINE)) + return ProfileResult(seconds, adds_subs, negations, int(depth.group(1)), shifts, mul) + +def run_profile(args: list[str], log_path: Path) -> tuple[str, float]: + log_path.parent.mkdir(parents=True, exist_ok=True) + start = time.perf_counter() + res = subprocess.run(args, capture_output=True, text=True) + seconds = time.perf_counter() - start + log_path.write_text(res.stdout) + res.check_returncode() + return res.stdout, seconds + + +class Coeff: + def __init__(self, number: int, bit_width: int): + self.number = number + self.bit_width = bit_width + + def __str__(self): + return f"{self.number}" + +class Test: + def __init__(self, input_width: int, coeffs: list[Coeff], idx: int, output_dir: Path): + self.coeffs = coeffs + self.input_width = input_width + self.results_dir = output_dir / f"test_{idx}" + self.verilog_file = self.results_dir / f"unoptimized.v" + + self.generate_v_file() + + def generate_v_file(self) -> None: + self.results_dir.mkdir(parents=True, exist_ok=True) + + + file = "\n".join([ + "module unoptimized(", + f" input wire signed [{self.input_width - 1}:0] x,", + ",\n".join( + f" output wire signed [{c.bit_width+self.input_width-1}:0] y{i}" + for i, c in enumerate(self.coeffs) + ), + ");", + "\n".join( + f" assign y{i} = x * ({'-' if c.number < 0 else ''}{self.input_width-1}'sd{abs(c.number)});" + for i, c in enumerate(self.coeffs) + ), + "endmodule", + "", + ]) + + with open(self.verilog_file, "w") as f: + f.write(file) + + def profile_yosys(self, yosys_path: Path) -> ProfileResult: + verilog_path = self.results_dir / "yosys.v" + stdout, seconds = run_profile( + [str(yosys_path), "-p", f'read_verilog "{self.verilog_file}"; mcm -depth 16 -search_budget 200000000; stat; write_verilog "{verilog_path}"'], + self.results_dir / "yosys.log", + ) + return parse_yosys(stdout, seconds) + + def profile_acm(self, acm_path: Path) -> ProfileResult: + coeffs = [str(coeff) for coeff in self.coeffs] + args = [str(acm_path), "-b", "30", *coeffs, "-gc", "-seed", "1"] + stdout, seconds = run_profile(args, self.results_dir / "acm.log") + return parse_acm(stdout, seconds) + + def profile_synth(self, yosys_path: Path, liberty_path: Path, use_mcm: bool) -> float: + name = "synth_mcm" if use_mcm else "synth" + script_path = self.results_dir / f"{name}.ys" + stats_path = self.results_dir / f"{name}.stat" + mcm = "mcm -depth 16 -search_budget 200000000\n" if use_mcm else "" + script_path.write_text( + f'read_verilog "{self.verilog_file}"\n' + "hierarchy -top unoptimized\n" + + mcm + dedent(f"""\ + synth -top unoptimized -noabc + abc -liberty "{liberty_path}" + tee -o "{stats_path}" stat -liberty "{liberty_path}" + """) + ) + run_profile([str(yosys_path), "-s", str(script_path)], self.results_dir / f"{name}.log") + area = AREA_RE.search(stats_path.read_text()) + if area is None: + raise ValueError(f"Missing chip area in {stats_path}") + return float(area.group(1)) + + def profile(self, yosys_path: Path, acm_path: Path, liberty_path: Path, idx: int): + yosys = self.profile_yosys(yosys_path) + acm = self.profile_acm(acm_path) + synth_area = self.profile_synth(yosys_path, liberty_path, use_mcm=False) + mcm_area = self.profile_synth(yosys_path, liberty_path, use_mcm=True) + relative_area = f"{mcm_area / synth_area:.2%}" if synth_area else "n/a" + coeffs = [str(coeff) for coeff in self.coeffs] + ratio = yosys.seconds / acm.seconds + items = [ + ("yosys runtime", yosys.time()), + ("hcub_paper runtime", acm.time()), + ("yosys stats", yosys.stats()), + ("hcub_paper stats", acm.stats()), + ("synth area", f"{synth_area:.3f}"), + ("synth with MCM area", f"{mcm_area:.3f}"), + ("MCM / baseline area", relative_area), + ("runtime ratio", f"{ratio:.2f}"), + ("coeffs", ", ".join(coeffs)), + ] + print_table(f"Test {idx}", items) + return yosys, acm, synth_area, mcm_area + +def print_table(title: str, items: list[tuple[str, str]]) -> None: + print(title) + longest_name = 0 + for name, value in items: + longest_name = max(longest_name, len(name)) + for name, value in items: + num_spaces = longest_name - len(name) + value = str(value).replace("\n", "\n\t" + " " * (longest_name + 2)) + print(f"\t{name}:{' ' * num_spaces} {value}") + print() + +class Cmp(Enum): + Better = 1 + Same = 2 + Worse = 3 + +def cmp(yosys: ProfileResult, acm: ProfileResult) -> Cmp: + if yosys.mul > acm.mul: + return Cmp.Worse + elif yosys.mul < acm.mul: + return Cmp.Better + + if yosys.adds_subs > acm.adds_subs: + return Cmp.Worse + elif yosys.adds_subs < acm.adds_subs: + return Cmp.Better + + return Cmp.Same + +def bit_width(val: int): + return len(bin(val)) - 2 + +def generate_coeffs(rng: random.Random, number_tests: int, length_range: tuple[int, int], value_range: tuple[int, int], seed=42) -> list[list[Coeff]]: + rng.seed(seed) + coeffs = [sample_coeff(rng, length_range, value_range) for idx in range(number_tests)] + return coeffs + +# smaller a means proportially more larger values and fewer smaller values +# larger scale shifts all values upwards +# the distrition is the following +# p(x) ~ 1 - x^(-a) +def sample_coeff( + rng: random.Random, + length_range: tuple[int, int], + value_range: tuple[int, int], + a: float = 1.3, + scale: float = 1024, +) -> list[Coeff]: + if a <= 1 or scale <= 0: + raise ValueError("Require a > 1 and scale > 0") + + length = rng.randint(*length_range) + low, high = value_range + coeffs = [] + + while len(coeffs) < length: + magnitude = int(scale * (rng.paretovariate(a - 1) - 1)) + val = rng.choice((-1, 1)) * magnitude + if low <= val <= high: + coeffs.append(Coeff(val, bit_width(val))) + + return coeffs + +def main(): + if not "YOSYS" in os.environ: + raise Exception("Set YOSYS environment variable to absolute path of yosys binary") + + yosys_bin = Path(os.environ["YOSYS"]) + root_dir = Path(sys.argv[0]).parent + acm_path = root_dir / "synth" / "acm" + liberty_path = root_dir / "NangateOpenCellLibrary_typical.lib" + output_dir = root_dir / "results" + + number_tests = 40 + seed = 42 + rng = random.Random() + + input_bit_width = 32 + length_range = (1, 6) + value_range = (-2_147_483_648, 2_147_483_647) + + coeffs = generate_coeffs(rng, number_tests, length_range, value_range, seed) + results = [] + area_results = [] + + for idx, coeff in enumerate(coeffs): + test_file = Test(input_bit_width, coeff, idx, output_dir) + yosys_res, acm_res, synth_area, mcm_area = test_file.profile(yosys_bin, acm_path, liberty_path, idx) + results.append((yosys_res, acm_res)) + area_results.append((synth_area, mcm_area)) + + # 1000ms = 1s + timescale = 1000 + + avg_yosys_runtime = sum(res.seconds * timescale for res, _ in results) / len(results) + avg_acm_runtime = sum(res.seconds * timescale for _, res in results) / len(results) + stdev_yosys_runtime = statistics.stdev([res.seconds * timescale for res, _ in results]) + stdev_acm_runtime = statistics.stdev([res.seconds * timescale for _, res in results]) + + avg_runtime_ratio = avg_yosys_runtime / avg_acm_runtime + + compared_results = [cmp(yosys_res, acm_res) for (yosys_res, acm_res) in results] + + num_better = len([i for i in compared_results if i == Cmp.Better]) + num_same = len([i for i in compared_results if i == Cmp.Same]) + num_worse = len([i for i in compared_results if i == Cmp.Worse]) + num_mcm_better_or_same = sum(mcm_area <= synth_area for synth_area, mcm_area in area_results) + num_mcm_larger = len(area_results) - num_mcm_better_or_same + area_savings = [100 * (1 - mcm_area / synth_area) for synth_area, mcm_area in area_results if synth_area] + avg_area_savings = f"{statistics.mean(area_savings):.2f}%" if area_savings else "n/a" + + items = [ + ("Avg Yosys runtime (ms)", f"{avg_yosys_runtime:.2f}"), + ("Avg hcub_paper runtime (ms)", f"{avg_acm_runtime:.2f}"), + ("Stdev Yosys runtime (ms)", f"{stdev_yosys_runtime:.2f}"), + ("Stdev hcub_paper runtime (ms)", f"{stdev_acm_runtime:.2f}"), + ("Average hcub_paper Speed Up", f"{avg_runtime_ratio:.2f}"), + ("Number of Times Yosys Results Smaller v.s. HCUB Paper", str(num_better)), + ("Number of Times Yosys Results Same v.s. HCUB Paper", str(num_same)), + ("Number of Times Yosys Results Larger v.s. HCUB Paper", str(num_worse)), + ("Number of Times MCM Area Smaller or Same v.s. Without MCM", str(num_mcm_better_or_same)), + ("Number of Times MCM Area Larger v.s. Without MCM", str(num_mcm_larger)), + ("Avg MCM area savings", avg_area_savings), + ] + print_table("Results", items) + +if __name__ == "__main__": + main() diff --git a/chips/yosys/tests/techmap/mcm/synth.patch b/chips/yosys/tests/techmap/mcm/synth.patch new file mode 100644 index 0000000000000000000000000000000000000000..7f59f927ebc3fc855de4ae862dc6db17dd816ea6 --- /dev/null +++ b/chips/yosys/tests/techmap/mcm/synth.patch @@ -0,0 +1,39 @@ +--- a/synth.cpp ++++ b/synth.cpp +@@ -1,5 +1,6 @@ + #include "synth.h" + #include "ac1.h" ++#include + #include + #include + #include +@@ -102,8 +103,8 @@ + void synthesize(coeff_t c, adder ad); + adder *get_adder(coeff_t c); + void ac1_decompose_cheapest(); +-void print_set(char *nam, full_addmap_t &s, int max_nprint = MAX_NPRINT, ostream &ostr = cerr); +-void print_set(char *nam, cfset_t &s, int max_nprint = MAX_NPRINT, ostream &ostr = cerr); ++void print_set(const char *nam, full_addmap_t &s, int max_nprint = MAX_NPRINT, ostream &ostr = cerr); ++void print_set(const char *nam, cfset_t &s, int max_nprint = MAX_NPRINT, ostream &ostr = cerr); + + int MAX_TARGET_DEPTH(coeff_t t) { + if(DEPTH_LIMITS.find(t)==DEPTH_LIMITS.end()) return MAX_DEPTH; +--- a/bhm.cpp ++++ b/bhm.cpp +@@ -1,6 +1,6 @@ + + /****************************************************************************/ +-void print_set(char *nam, cfset_t &s, int max_nprint, ostream &ostr) { ++void print_set(const char *nam, cfset_t &s, int max_nprint, ostream &ostr) { + int nprinted = 0; + ostr << nam << " "; + FORALL(s, i) { +@@ -10,7 +10,7 @@ + } + } + +-void print_set(char *nam, full_addmap_t &s, int max_nprint, ostream &ostr) { ++void print_set(const char *nam, full_addmap_t &s, int max_nprint, ostream &ostr) { + int nprinted = 0; + ostr << nam << " "; + FORALL_FAM(s, i) { diff --git a/chips/yosys/tests/techmap/mem_simple_4x1_cells.v b/chips/yosys/tests/techmap/mem_simple_4x1_cells.v new file mode 100644 index 0000000000000000000000000000000000000000..7ecdd2dee0923bf95dda302a7eed965a2c3906c4 --- /dev/null +++ b/chips/yosys/tests/techmap/mem_simple_4x1_cells.v @@ -0,0 +1,13 @@ +module MEM4X1 (CLK, RD_ADDR, RD_DATA, WR_ADDR, WR_DATA, WR_EN); + input CLK, WR_DATA, WR_EN; + input [3:0] RD_ADDR, WR_ADDR; + output reg RD_DATA; + + reg [15:0] memory; + + always @(posedge CLK) begin + if (WR_EN) + memory[WR_ADDR] <= WR_DATA; + RD_DATA <= memory[RD_ADDR]; + end +endmodule diff --git a/chips/yosys/tests/techmap/mem_simple_4x1_map.v b/chips/yosys/tests/techmap/mem_simple_4x1_map.v new file mode 100644 index 0000000000000000000000000000000000000000..4cf706a977599b60c3ed1d1787b56f4d534ece1a --- /dev/null +++ b/chips/yosys/tests/techmap/mem_simple_4x1_map.v @@ -0,0 +1,151 @@ + +module \$mem (RD_CLK, RD_EN, RD_ADDR, RD_DATA, WR_CLK, WR_EN, WR_ADDR, WR_DATA); + parameter MEMID = ""; + parameter SIZE = 256; + parameter OFFSET = 0; + parameter ABITS = 8; + parameter WIDTH = 8; + parameter signed INIT = 1'bx; + + parameter RD_PORTS = 1; + parameter RD_CLK_ENABLE = 1'b1; + parameter RD_CLK_POLARITY = 1'b1; + parameter RD_TRANSPARENT = 1'b1; + + parameter WR_PORTS = 1; + parameter WR_CLK_ENABLE = 1'b1; + parameter WR_CLK_POLARITY = 1'b1; + + input [RD_PORTS-1:0] RD_CLK; + input [RD_PORTS-1:0] RD_EN; + input [RD_PORTS*ABITS-1:0] RD_ADDR; + output reg [RD_PORTS*WIDTH-1:0] RD_DATA; + + input [WR_PORTS-1:0] WR_CLK; + input [WR_PORTS*WIDTH-1:0] WR_EN; + input [WR_PORTS*ABITS-1:0] WR_ADDR; + input [WR_PORTS*WIDTH-1:0] WR_DATA; + + wire [1023:0] _TECHMAP_DO_ = "proc; clean"; + + parameter _TECHMAP_CONNMAP_RD_CLK_ = 0; + parameter _TECHMAP_CONNMAP_WR_CLK_ = 0; + + parameter _TECHMAP_CONSTVAL_RD_EN_ = 0; + + parameter _TECHMAP_BITS_CONNMAP_ = 0; + parameter _TECHMAP_CONNMAP_WR_EN_ = 0; + + reg _TECHMAP_FAIL_; + integer k; + initial begin + _TECHMAP_FAIL_ <= 0; + + // no initialized memories + if (INIT !== 1'bx) + _TECHMAP_FAIL_ <= 1; + + // only map cells with only one read and one write port + if (RD_PORTS > 1 || WR_PORTS > 1) + _TECHMAP_FAIL_ <= 1; + + // read enable must be constant high + if (_TECHMAP_CONSTVAL_RD_EN_[0] !== 1'b1) + _TECHMAP_FAIL_ <= 1; + + // we expect positive read clock and non-transparent reads + if (RD_TRANSPARENT || !RD_CLK_ENABLE || !RD_CLK_POLARITY) + _TECHMAP_FAIL_ <= 1; + + // we expect positive write clock + if (!WR_CLK_ENABLE || !WR_CLK_POLARITY) + _TECHMAP_FAIL_ <= 1; + + // only one global write enable bit is supported + for (k = 1; k < WR_PORTS*WIDTH; k = k+1) + if (_TECHMAP_CONNMAP_WR_EN_[0 +: _TECHMAP_BITS_CONNMAP_] != + _TECHMAP_CONNMAP_WR_EN_[k*_TECHMAP_BITS_CONNMAP_ +: _TECHMAP_BITS_CONNMAP_]) + _TECHMAP_FAIL_ <= 1; + + // read and write must be in same clock domain + if (_TECHMAP_CONNMAP_RD_CLK_ != _TECHMAP_CONNMAP_WR_CLK_) + _TECHMAP_FAIL_ <= 1; + + // we don't do small memories or memories with offsets + if (OFFSET != 0 || ABITS < 4 || SIZE < 16) + _TECHMAP_FAIL_ <= 1; + end + + genvar i; + generate + for (i = 0; i < WIDTH; i=i+1) begin:slice + \$__mem_4x1_generator #( + .ABITS(ABITS), + .SIZE(SIZE) + ) bit_slice ( + .CLK(RD_CLK), + .RD_ADDR(RD_ADDR), + .RD_DATA(RD_DATA[i]), + .WR_ADDR(WR_ADDR), + .WR_DATA(WR_DATA[i]), + .WR_EN(WR_EN[0]) + ); + end + endgenerate +endmodule + +module \$__mem_4x1_generator (CLK, RD_ADDR, RD_DATA, WR_ADDR, WR_DATA, WR_EN); + parameter ABITS = 4; + parameter SIZE = 16; + + input CLK, WR_DATA, WR_EN; + input [ABITS-1:0] RD_ADDR, WR_ADDR; + output RD_DATA; + + wire [1023:0] _TECHMAP_DO_ = "proc; clean"; + + generate + if (ABITS > 4) begin + wire high_rd_data, low_rd_data; + if (SIZE > 2**(ABITS-1)) begin + \$__mem_4x1_generator #( + .ABITS(ABITS-1), + .SIZE(SIZE - 2**(ABITS-1)) + ) part_high ( + .CLK(CLK), + .RD_ADDR(RD_ADDR[ABITS-2:0]), + .RD_DATA(high_rd_data), + .WR_ADDR(WR_ADDR[ABITS-2:0]), + .WR_DATA(WR_DATA), + .WR_EN(WR_EN && WR_ADDR[ABITS-1]) + ); + end else begin + assign high_rd_data = 1'bx; + end + \$__mem_4x1_generator #( + .ABITS(ABITS-1), + .SIZE(SIZE > 2**(ABITS-1) ? 2**(ABITS-1) : SIZE) + ) part_low ( + .CLK(CLK), + .RD_ADDR(RD_ADDR[ABITS-2:0]), + .RD_DATA(low_rd_data), + .WR_ADDR(WR_ADDR[ABITS-2:0]), + .WR_DATA(WR_DATA), + .WR_EN(WR_EN && !WR_ADDR[ABITS-1]) + ); + reg delayed_abit; + always @(posedge CLK) + delayed_abit <= RD_ADDR[ABITS-1]; + assign RD_DATA = delayed_abit ? high_rd_data : low_rd_data; + end else begin + MEM4X1 _TECHMAP_REPLACE_ ( + .CLK(CLK), + .RD_ADDR(RD_ADDR), + .RD_DATA(RD_DATA), + .WR_ADDR(WR_ADDR), + .WR_DATA(WR_DATA), + .WR_EN(WR_EN) + ); + end + endgenerate +endmodule diff --git a/chips/yosys/tests/techmap/mem_simple_4x1_runtest.sh b/chips/yosys/tests/techmap/mem_simple_4x1_runtest.sh new file mode 100644 index 0000000000000000000000000000000000000000..4d8494a6e07998946f5d88386e7297fe4f72e15e --- /dev/null +++ b/chips/yosys/tests/techmap/mem_simple_4x1_runtest.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash + +exec ../tools/autotest.sh -G -Y ${YOSYS} -j $@ -p 'proc; opt; memory -nomap; techmap -map ../mem_simple_4x1_map.v;; techmap; opt; abc;; stat' mem_simple_4x1_uut.v diff --git a/chips/yosys/tests/techmap/mem_simple_4x1_tb.v b/chips/yosys/tests/techmap/mem_simple_4x1_tb.v new file mode 100644 index 0000000000000000000000000000000000000000..5326269605cc998c5bc824ec4b2de5901c6054c9 --- /dev/null +++ b/chips/yosys/tests/techmap/mem_simple_4x1_tb.v @@ -0,0 +1,29 @@ +module tb; + +reg clk, rst; +wire [7:0] out; +wire [4:0] counter; + +uut uut (clk, rst, out, counter); + +initial begin + #5 clk <= 0; + repeat (100) #5 clk <= ~clk; + #5 $finish; +end + +initial begin + rst <= 1; + repeat (2) @(posedge clk); + rst <= 0; +end + +always @(posedge clk) + $display("%d %d %d", rst, out, counter); + +initial begin + $dumpfile("mem_simple_4x1_tb.vcd"); + $dumpvars(0, uut); +end + +endmodule diff --git a/chips/yosys/tests/techmap/mem_simple_4x1_uut.v b/chips/yosys/tests/techmap/mem_simple_4x1_uut.v new file mode 100644 index 0000000000000000000000000000000000000000..8d4614595ce9cca2f3a7399f59785fe2431d1e33 --- /dev/null +++ b/chips/yosys/tests/techmap/mem_simple_4x1_uut.v @@ -0,0 +1,15 @@ +module uut (clk, rst, out, counter); + +input clk, rst; +output reg [7:0] out; +output reg [4:0] counter; + +reg [7:0] memory [0:19]; + +always @(posedge clk) begin + counter <= rst || counter == 19 ? 0 : counter+1; + memory[counter] <= counter; + out <= memory[counter]; +end + +endmodule diff --git a/chips/yosys/tests/techmap/module_not_derived.ys b/chips/yosys/tests/techmap/module_not_derived.ys new file mode 100644 index 0000000000000000000000000000000000000000..299e4b75bc013f6927043d74bf32cfed0a4f74fd --- /dev/null +++ b/chips/yosys/tests/techmap/module_not_derived.ys @@ -0,0 +1,31 @@ +# Test 1: internal cells from alumacc/techmap must not keep module_not_derived. +read_verilog < Y) = 453; + (D1 => Y) = 449; + (D2 => Y) = 488; + (D3 => Y) = 484; + (S0 => Y) = 422; + (S1 => Y) = 385; + endspecify + + assign Y = S1 ? (S0 ? D3 : D2) : + (S0 ? D1 : D0); + +endmodule + +EOF + +abc_new -liberty ../../tests/liberty/normal.lib -liberty ../../tests/liberty/dff.lib + +# the mapped box must replace the original one, not be added next to it +select -assert-count 1 t:CC_MX4 +check -assert diff --git a/chips/yosys/tests/techmap/xaiger2-keep-box.ys b/chips/yosys/tests/techmap/xaiger2-keep-box.ys new file mode 100644 index 0000000000000000000000000000000000000000..a3ba0fc27cde8b8b4df9acee0fdc7ecdc8bf39dd --- /dev/null +++ b/chips/yosys/tests/techmap/xaiger2-keep-box.ys @@ -0,0 +1,19 @@ +# abc9_box driving only a keep wire +read_verilog -specify < o) = 10; + endspecify +endmodule + +module top(input d, output y); + (* keep *) wire a; + box b (.i(d), .o(a)); + assign y = ~d; +endmodule +EOT +abc9 -lut 4 +opt_clean +select -assert-count 1 top/t:box +select -assert-count 1 top/w:a %ci1 top/t:box %i diff --git a/chips/yosys/tests/techmap/zinit.ys b/chips/yosys/tests/techmap/zinit.ys new file mode 100644 index 0000000000000000000000000000000000000000..562db07769ccecde0de74f3b707ef1d0160ade02 --- /dev/null +++ b/chips/yosys/tests/techmap/zinit.ys @@ -0,0 +1,154 @@ +read_verilog -icells <&2 +if [ ! -f "$toolsdir/cmp_tbdata" -o "$toolsdir/cmp_tbdata.c" -nt "$toolsdir/cmp_tbdata" ]; then + ( set -ex; ${CXX:-g++} -Wall ${CPPFLAGS} ${CXXFLAGS:-} -o "$toolsdir/cmp_tbdata" "$toolsdir/cmp_tbdata.c"; ) || exit 1 +fi +flock -u "$lock"; exec {lock}>&- + +while getopts xmGl:wkjvref:s:p:n:S:I:A:Y:-: opt; do + case "$opt" in + x) + use_xsim=true ;; + m) + use_modelsim=true ;; + G) + warn_iverilog_git=true ;; + l) + libs+=("$(cd "$(dirname "$OPTARG")"; pwd)/$(basename "$OPTARG")");; + w) + genvcd=true ;; + k) + keeprunning=true ;; + j) + makejmode=true ;; + v) + verbose=true ;; + r) + backend_opts="$backend_opts -norename" ;; + e) + backend_opts="$( echo " $backend_opts " | sed 's, -noexpr , ,; s,^ ,,; s, $,,;'; )" ;; + f) + frontend="$OPTARG" ;; + s) + [[ "$OPTARG" == /* ]] || OPTARG="$PWD/$OPTARG" + scriptfiles="$scriptfiles $OPTARG" ;; + p) + scriptopt="$OPTARG" ;; + n) + autotb_opts="$autotb_opts -n $OPTARG" ;; + S) + autotb_opts="$autotb_opts -seed $OPTARG" ;; + I) + include_opts="$include_opts -I $OPTARG" + xinclude_opts="$xinclude_opts -i $OPTARG" + minclude_opts="$minclude_opts +incdir+$OPTARG" ;; + A) + abcprog="$OPTARG" ;; + Y) + yosysprog="$OPTARG" ;; + -) + case "${OPTARG}" in + xfirrtl) + xfirrtl="${!OPTIND}" + OPTIND=$(( $OPTIND + 1 )) + ;; + firrtl2verilog) + firrtl2verilog="${!OPTIND}" + OPTIND=$(( $OPTIND + 1 )) + ;; + *) + if [ "$OPTERR" == 1 ] && [ "${optspec:0:1}" != ":" ]; then + echo "Unknown option --${OPTARG}" >&2 + fi + ;; + esac;; + *) + echo "Usage: $0 [-x|-m] [-G] [-w] [-k] [-j] [-v] [-r] [-e] [-l libs] [-f frontend] [-s script] [-p cmdstring] [-n iters] [-S seed] [-I incdir] [--xfirrtl FIRRTL test exclude file] [--firrtl2verilog command to generate verilog from firrtl] verilog-files\n" >&2 + exit 1 + esac +done + +compile_and_run() { + exe="$1"; output="$2"; shift 2 + if [ "${2##*.}" == "sv" ]; then + language_gen="-g2012" + else + language_gen="-g2005" + fi + + if $use_modelsim; then + altver=$( ls -v /opt/altera/ | grep '^[0-9]' | tail -n1; ) + /opt/altera/$altver/modelsim_ase/bin/vlib work + /opt/altera/$altver/modelsim_ase/bin/vlog $minclude_opts +define+outfile=\"$output\" "$@" + /opt/altera/$altver/modelsim_ase/bin/vsim -c -do 'run -all; exit;' testbench + elif $use_xsim; then + xilver=$( ls -v /opt/Xilinx/Vivado/ | grep '^[0-9]' | tail -n1; ) + /opt/Xilinx/Vivado/$xilver/bin/xvlog $xinclude_opts -d outfile=\"$output\" "$@" + /opt/Xilinx/Vivado/$xilver/bin/xelab -R work.testbench + else + iverilog $language_gen $include_opts -Doutfile=\"$output\" -s testbench -o "$exe" "$@" + vvp -n "$exe" + fi +} + +shift $((OPTIND - 1)) + +for fn +do + bn=${fn%.*} + ext=${fn##*.} + if [[ "$ext" != "v" ]] && [[ "$ext" != "sv" ]] && [[ "$ext" != "aag" ]] && [[ "$ext" != "aig" ]]; then + echo "Invalid argument: $fn" >&2 + exit 1 + fi + [[ "$bn" == *_tb ]] && continue + + if $makejmode; then + status_prefix="Test: $bn " + else + status_prefix="" + echo -n "Test: $bn " + fi + + if [ "$ext" == sv ]; then + frontend="$frontend -sv" + fi + + rm -f ${bn}.{err,log,skip} + mkdir -p ${bn}.out + rm -rf ${bn}.out/* + + body() { + cd ${bn}.out + fn=$(basename $fn) + bn=$(basename $bn) + refext=v + + rm -f ${bn}_ref.fir + if [[ "$ext" == "v" ]]; then + grep -Ev '^\s*`timescale' ../$fn > ${bn}_ref.${ext} + elif [[ "$ext" == "aig" ]] || [[ "$ext" == "aag" ]]; then + $abcprog -c "read_aiger ../${fn}; write ${bn}_ref.${refext}" + else + refext=$ext + cp ../${fn} ${bn}_ref.${refext} + fi + + if [ ! -f ../${bn}_tb.v ]; then + $yosysprog -f "$frontend $include_opts -D_AUTOTB" -b "test_autotb $autotb_opts" -o ${bn}_tb.v ${bn}_ref.${refext} + else + cp ../${bn}_tb.v ${bn}_tb.v + fi + if $genvcd; then sed -i 's,// \$dump,$dump,g' ${bn}_tb.v; fi + touch ${bn}.iverilog + compile_and_run ${bn}_tb_ref ${bn}_out_ref ${bn}_tb.v ${bn}_ref.${refext} "${libs[@]}" \ + "$toolsdir"/../../techlibs/common/simlib.v \ + "$toolsdir"/../../techlibs/common/simcells.v + rm ${bn}.iverilog + if $genvcd; then mv testbench.vcd ${bn}_ref.vcd; fi + + test_count=0 + test_passes() { + $yosysprog -b "verilog $backend_opts" -o ${bn}_syn${test_count}.v "$@" + touch ${bn}.iverilog + compile_and_run ${bn}_tb_syn${test_count} ${bn}_out_syn${test_count} \ + ${bn}_tb.v ${bn}_syn${test_count}.v "${libs[@]}" \ + "$toolsdir"/../../techlibs/common/simlib.v \ + "$toolsdir"/../../techlibs/common/simcells.v + if $genvcd; then mv testbench.vcd ${bn}_syn${test_count}.vcd; fi + "$toolsdir/cmp_tbdata" ${bn}_out_ref ${bn}_out_syn${test_count} + rm ${bn}.iverilog + test_count=$(( test_count + 1 )) + } + + if [ "$frontend" = "verific" -o "$frontend" = "verific_gates" ] && grep -q VERIFIC-SKIP ${bn}_ref.${refext}; then + touch ../${bn}.skip + return + fi + + if [ -n "$scriptfiles" ]; then + test_passes -f "$frontend $include_opts" ${bn}_ref.${refext} $scriptfiles + elif [ -n "$scriptopt" ]; then + test_passes -f "$frontend $include_opts" -p "$scriptopt" ${bn}_ref.${refext} + elif [ "$frontend" = "verific" ]; then + test_passes -p "verific -vlog2k ${bn}_ref.${refext}; verific -import -all; opt; memory;;" + elif [ "$frontend" = "verific_gates" ]; then + test_passes -p "verific -vlog2k ${bn}_ref.${refext}; verific -import -gates -all; opt; memory;;" + else + test_passes -f "$frontend $include_opts" -p "hierarchy; proc; opt -nodffe -nosdff; fsm; opt; memory; opt -full -fine" ${bn}_ref.${refext} + test_passes -f "$frontend $include_opts" -p "hierarchy; synth -run coarse; techmap; opt; abc -dff" ${bn}_ref.${refext} + if [ -n "$firrtl2verilog" ]; then + if test -z "$xfirrtl" || ! grep "$fn" "$xfirrtl" ; then + $yosysprog -b "firrtl" -o ${bn}_ref.fir -f "$frontend $include_opts" -p "prep; proc; opt -nodffe -nosdff; fsm; opt; memory; opt -full -fine; pmuxtree" ${bn}_ref.${refext} + $firrtl2verilog -i ${bn}_ref.fir -o ${bn}_ref.fir.v + test_passes -f "$frontend $include_opts" -p "hierarchy; proc; opt -nodffe -nosdff; fsm; opt; memory; opt -full -fine" ${bn}_ref.fir.v + fi + fi + fi + touch ../${bn}.log + } + + if $verbose; then + echo ".." + echo "Output written to console." > ${bn}.err + ( set -ex; body; ) + else + ( set -ex; body; ) > ${bn}.err 2>&1 + fi + + did_firrtl="" + if [ -f ${bn}.out/${bn}_ref.fir ]; then + did_firrtl="+FIRRTL " + fi + if [ -f ${bn}.log ]; then + mv ${bn}.err ${bn}.log + echo "${status_prefix}${did_firrtl}-> ok" + elif [ -f ${bn}.skip ]; then + mv ${bn}.err ${bn}.skip + echo "${status_prefix}-> skip" + else + echo "${status_prefix}${did_firrtl}-> ERROR!" + if $warn_iverilog_git; then + if [ -f ${bn}.out/${bn}.iverilog ]; then + echo "Note: Make sure that 'iverilog' is an up-to-date git checkout of Icarus Verilog." + fi + fi + sed -e "s,^,${bn}: ," ${bn}.err + $keeprunning || exit 1 + fi +done + +exit 0 diff --git a/chips/yosys/tests/tools/cmp_tbdata.c b/chips/yosys/tests/tools/cmp_tbdata.c new file mode 100644 index 0000000000000000000000000000000000000000..a6bc9dae7cc51fce8235b3ae3571458490973e5c --- /dev/null +++ b/chips/yosys/tests/tools/cmp_tbdata.c @@ -0,0 +1,68 @@ +#include +#include +#include +#include + +int line = 0; +char buffer1[8192]; +char buffer2[8192]; + +void check(bool ok) +{ + if (ok) + return; + fprintf(stderr, "Error in testbench output compare (line=%d):\n-%s\n+%s\n", line, buffer1, buffer2); + exit(1); +} + +int main(int argc, char **argv) +{ + FILE *f1, *f2; + bool eof1, eof2; + int i; + + check(argc == 3); + + f1 = fopen(argv[1], "r"); + f2 = fopen(argv[2], "r"); + + check(f1 && f2); + + while (!feof(f1) && !feof(f2)) + { + line++; + buffer1[0] = 0; + buffer2[0] = 0; + + eof1 = fgets(buffer1, 1024, f1) == NULL; + eof2 = fgets(buffer2, 1024, f2) == NULL; + + if (*buffer1 && buffer1[strlen(buffer1)-1] == '\n') + buffer1[strlen(buffer1)-1] = 0; + + if (*buffer2 && buffer2[strlen(buffer2)-1] == '\n') + buffer2[strlen(buffer2)-1] = 0; + + check(eof1 == eof2); + + for (i = 0; buffer1[i] || buffer2[i]; i++) + { + check(buffer1[i] != 0 && buffer2[i] != 0); + + // first argument is the reference. An 'z' or 'x' + // here means we don't care about the result. + if (buffer1[i] == 'z' || buffer1[i] == 'x') + continue; + if (buffer1[i] == 'Z' || buffer1[i] == 'X') + continue; + + check(buffer1[i] == buffer2[i]); + } + } + + check(feof(f1) && feof(f2)); + + fclose(f1); + fclose(f2); + return 0; +} diff --git a/chips/yosys/tests/tools/profiler.pl b/chips/yosys/tests/tools/profiler.pl new file mode 100644 index 0000000000000000000000000000000000000000..99155eec7f8de863498739c01122bd1111e40b7c --- /dev/null +++ b/chips/yosys/tests/tools/profiler.pl @@ -0,0 +1,54 @@ +#!/usr/bin/perl +# parse 'yosys -t' logfile and find slow passes + +my $max_depth = 0; +my %last_line_by_depth; +my %last_time_by_depth; + +my @lines_text; +my @lines_depth; +my @lines_time; + +while (<>) +{ + chomp; + next unless /^\[([0-9.]+)\] (([0-9]+\.)+)/; + my ($this_time, $this_id, $this_header) = ($1, $2, $4); + + push @lines_text, $_; + push @lines_depth, 0; + push @lines_time, 0; + + my $depth = $this_id; + $depth =~ s/[^.]//g; + $depth = length $depth; + $max_depth = $depth if $depth > $max_depth; + + for (my $i = $depth; $i <= $max_depth; $i++) { + next unless exists $last_time_by_depth{$i}; + $lines_time[$last_line_by_depth{$i}] = $this_time-$last_time_by_depth{$i}; + delete $last_time_by_depth{$i}; + delete $last_header_by_depth{$i}; + } + + $last_time_by_depth{$depth} = $this_time; + $last_line_by_depth{$depth} = $#lines_text; + $lines_depth[$#lines_text] = $depth; +} + +for (my $depth = 1; $depth <= $max_depth; $depth++) { + printf "\nSlow passes on recursion depth %d:\n", $depth; + my @lines; + for (my $i = 0; $i <= $#lines_text; $i++) { + next if $lines_depth[$i] != $depth or $lines_time[$i] < 1.0; + push @lines, sprintf("%3d %08.2f %s\n", $lines_depth[$i], $lines_time[$i], $lines_text[$i]); + } + for my $line (sort {$b cmp $a} @lines) { + print $line; + } +} + +printf "\nFull journal of headers:\n"; +for (my $i = 0; $i <= $#lines_text; $i++) { + printf "%3d %08.2f %s\n", $lines_depth[$i], $lines_time[$i], $lines_text[$i]; +} diff --git a/chips/yosys/tests/tools/rtlil-fuzz-grammar.json b/chips/yosys/tests/tools/rtlil-fuzz-grammar.json new file mode 100644 index 0000000000000000000000000000000000000000..96af9bde3f3b233213c68d6cdfc9d334739efb3c --- /dev/null +++ b/chips/yosys/tests/tools/rtlil-fuzz-grammar.json @@ -0,0 +1,106 @@ +{ + "": [ + [ + "module \\test\n", + "", "", + "", + "", + "end\n" + ] + ], + "": [ [ "", " wire width ", "", " ", "", " ", "", "\n" ] ], + "": [ [ "1" ], [ "2" ], [ "3" ], [ "4" ], [ "32" ], [ "128" ] ], + "": [ [ "input ", "" ], [ "output ", "" ], [ "inout ", "" ], [] ], + "": [ + [ + " cell $not ", "", "\n", + " parameter \\A_SIGNED 0\n", + " parameter \\A_WIDTH 0\n", + " parameter \\Y_WIDTH 0\n", + " connect \\A ", "", "\n", + " connect \\Y ", "", "\n", + " end\n" + ], + [ + " cell $and ", "", "\n", + " parameter \\A_SIGNED 0\n", + " parameter \\B_SIGNED 0\n", + " parameter \\A_WIDTH 0\n", + " parameter \\B_WIDTH 0\n", + " parameter \\Y_WIDTH 0\n", + " connect \\A ", "", "\n", + " connect \\B ", "", "\n", + " connect \\Y ", "", "\n", + " end\n" + ], + [ + " cell $or ", "", "\n", + " parameter \\A_SIGNED 0\n", + " parameter \\B_SIGNED 0\n", + " parameter \\A_WIDTH 0\n", + " parameter \\B_WIDTH 0\n", + " parameter \\Y_WIDTH 0\n", + " connect \\A ", "", "\n", + " connect \\B ", "", "\n", + " connect \\Y ", "", "\n", + " end\n" + ], + [ + " cell $xor ", "", "\n", + " parameter \\A_SIGNED 0\n", + " parameter \\B_SIGNED 0\n", + " parameter \\A_WIDTH 0\n", + " parameter \\B_WIDTH 0\n", + " parameter \\Y_WIDTH 0\n", + " connect \\A ", "", "\n", + " connect \\B ", "", "\n", + " connect \\Y ", "", "\n", + " end\n" + ], + [ + " cell ", "", " ", "", "\n", + " connect \\A ", "", "\n", + " connect \\Y ", "", "\n", + " end\n" + ], + [ + " cell ", "", " ", "", "\n", + " connect \\A ", "", "\n", + " connect \\B ", "", "\n", + " connect \\Y ", "", "\n", + " end\n" + ] + ], + "": [ [ " attribute \\init ", "", "\n" ] ], + "": [ [ "\\wire_a" ], [ "\\wire_b" ], [ "\\wire_c" ], [ "\\wire_d" ], [ "\\wire_e" ], [ "\\wire_f" ], [ "\\wire_g" ], [ "\\wire_h" ], [ "\\wire_i" ], [ "\\wire_j" ] ], + "": [ [ "\\cell_a" ], [ "\\cell_b" ], [ "\\cell_c" ], [ "\\cell_d" ], [ "\\cell_e" ], [ "\\cell_f" ], [ "\\cell_g" ], [ "\\cell_h" ], [ "\\cell_i" ], [ "\\cell_j" ] ], + "": [ [ "\\bb1" ], [ "\\bb2" ] ], + "": [ + [ "", " " ], + [ "{", "", " ", "", "}" ], + [ "" ], + [ "", "[", "", "]" ], + [ "", "[", "", ":", "", "]" ] + ], + "": [ + [ "0'", "" ], + [ "1'", "" ], + [ "2'", "" ], + [ "3'", "" ], + [ "4'", "" ], + [ "31'", "" ], + [ "32'", "" ], + [ "128'", "" ] + ], + "": [ [ "0" ], [ "1" ], [ "x" ], [ "z" ], [ "-" ], [ "m" ] ], + "": [ "0", "1", "2", "3", "31", "32" ], + "": [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" ], + "": [ [ " connect ", "", " ", "", "\n" ] ], + + "": [ [ ], [ "", "" ] ], + "": [ [ ], [ "", "" ] ], + "": [ [ ], [ "", "" ] ], + "": [ [ ], [ "", "" ] ], + "": [ [ ], [ "", "" ] ], + "": [ [ ], [ "", " ", "" ] ] +} diff --git a/chips/yosys/tests/tools/txt2tikztiming.py b/chips/yosys/tests/tools/txt2tikztiming.py new file mode 100644 index 0000000000000000000000000000000000000000..e608ece998fcd8cbf69837a5450574794ef77777 --- /dev/null +++ b/chips/yosys/tests/tools/txt2tikztiming.py @@ -0,0 +1,105 @@ +#!/usr/bin/env python3 + +import argparse +import fileinput +import sys + +parser = argparse.ArgumentParser(description='Convert vcd2txt output to tikz-timing line.') +parser.add_argument('filename', metavar='FILE', help='input txt file') +parser.add_argument('signame', metavar='SIG', help='Signal name') +parser.add_argument('-s', metavar='scale', default=1.0, type=float, help='Scale all time spans with this factor') +parser.add_argument('-l', action='store_true', help='Logic signal (high/low)') +parser.add_argument('-b', action='store_true', help='Display binary value') +parser.add_argument('-x', action='store_true', help='Display hex value') +parser.add_argument('-d', action='store_true', help='Display decimal value') +args = parser.parse_args() + +start_time = None +stop_time = None +time_val = { } + +def value_to_logic(value): + found_x = False + for char in value: + if char == '1': + return "H" + if char == 'x': + found_x = True + return "U" if found_x else "L" + +def value_to_binary(value): + return "D{%s}" % value + +def value_to_hex(value): + hex_string = "" + found_def = False + while len(value) % 4 != 0: + value = "0" + value + while len(value) != 0: + bin_digits = value[0:4] + hex_digit = 0 + value = value[4:] + for b in bin_digits: + if b == '0': + hex_digit = hex_digit * 2 + elif b == '1': + hex_digit = hex_digit * 2 + 1 + else: + hex_digit += 100 + if hex_digit > 15: + hex_string += "x" + else: + found_def = True + hex_string += "0123456789abcdef"[hex_digit] + if not found_def: + return "U"; + return "D{%s}" % hex_string + +def value_to_decimal(value): + val = 0 + found_def = False + found_undef = False + for digit in value: + if digit == 'x': + found_undef = True + else: + val = val*2 + int(digit) + found_def = True + if found_def: + if found_undef: + return "D{X}" + else: + return "D{%d}" % val + return "U" + +for line in fileinput.input(args.filename): + (node, time, name, value) = line.strip().split('\t') + time = int(time) + if start_time is None or start_time > time: + start_time = time + if stop_time is None or stop_time < time: + stop_time = time + if name == args.signame: + if args.l: + time_val[+time] = value_to_logic(value) + elif args.b: + time_val[+time] = value_to_binary(value) + elif args.x: + time_val[+time] = value_to_hex(value) + elif args.d: + time_val[+time] = value_to_decimal(value) + else: + time_val[+time] = value + +if start_time not in time_val: + time_val[start_time] = "S" + +last_time = None +last_value = None +for t in sorted(time_val.keys()): + if last_time is not None: + print("%f%s" % ((t - last_time)*args.s, last_value), end='') + (last_time, last_value) = (t, time_val[t]) +if last_time < stop_time: + print("%f%s" % ((stop_time - last_time)*args.s, last_value), end='') +print('') diff --git a/chips/yosys/tests/tools/vcd2txt.pl b/chips/yosys/tests/tools/vcd2txt.pl new file mode 100644 index 0000000000000000000000000000000000000000..34758f2904fd0d8f0e6bc682e2e135987b67b8dd --- /dev/null +++ b/chips/yosys/tests/tools/vcd2txt.pl @@ -0,0 +1,60 @@ +#!/usr/bin/perl -w +# +# Note: You might need to install the Verilog::VCD package using CPAN.. + +use strict; +use Data::Dumper; +use Verilog::VCD qw(parse_vcd list_sigs); + +$| = 1; + +my $from_time = -1; +my $to_time = -1; + +while (1) +{ + if ($ARGV[0] eq '-f') { + $from_time = +$ARGV[1]; + shift @ARGV; + shift @ARGV; + next; + } + if ($ARGV[0] eq '-t') { + $to_time = +$ARGV[1]; + shift @ARGV; + shift @ARGV; + next; + } + last; +} + +if ($#ARGV < 0) { + print STDERR "\n"; + print STDERR "VCD2TXT - Convert VCD to tab-separated text file\n"; + print STDERR "\n"; + print STDERR "Usage: $0 [-f from_time] [-t to_time] input.vcd [ ...]\n"; + print STDERR "\n"; + exit 1; +} + +my $vcd = parse_vcd($ARGV[0]); + +for my $node (keys $vcd) { + for my $net (@{$vcd->{$node}->{'nets'}}) { + my $dump_this = $#ARGV == 0; + for (my $i = 1; $i <= $#ARGV; $i++) { + my $regex = $ARGV[$i]; + $dump_this = 1 if ($net->{"hier"} . "." . $net->{"name"}) =~ /$regex/; + } + next unless $dump_this; + my $cached_value = ""; + for my $tv (@{$vcd->{$node}->{'tv'}}) { + $cached_value = $tv->[1], next if $from_time >= 0 and +$tv->[0] < $from_time; + next if $to_time >= 0 and +$tv->[0] > $to_time; + printf "%s\t%s\t%s\t%s\n", $node, $from_time, $net->{"hier"} . "." . $net->{"name"}, $cached_value + if $cached_value ne "" and $from_time >= 0 and +$tv->[0] > $from_time; + printf "%s\t%s\t%s\t%s\n", $node, $tv->[0], $net->{"hier"} . "." . $net->{"name"}, $tv->[1]; + $cached_value = ""; + } + } +} diff --git a/chips/yosys/tests/tools/vcdcd.pl b/chips/yosys/tests/tools/vcdcd.pl new file mode 100644 index 0000000000000000000000000000000000000000..0f33371fb8b6315892ac4b03ef67d4e97d19a668 --- /dev/null +++ b/chips/yosys/tests/tools/vcdcd.pl @@ -0,0 +1,287 @@ +#!/usr/bin/perl -w +# +# Note: You might need to install the Verilog::VCD package using CPAN.. + +use strict; +use Data::Dumper; +use Verilog::VCD qw(parse_vcd list_sigs); + +$| = 1; + +my $opt_width = 0; +my $opt_delay = 0; + +while ($#ARGV >= 0) +{ + if ($ARGV[0] eq '-w') { + $opt_width = +$ARGV[1]; + shift @ARGV; + shift @ARGV; + next; + } + if ($ARGV[0] eq '-d') { + $opt_delay = +$ARGV[1]; + shift @ARGV; + shift @ARGV; + next; + } + last; +} + +if ($#ARGV != 1) { + print STDERR "\n"; + print STDERR "VCDCD - Value Change Dump Change Dumper\n"; + print STDERR "\n"; + print STDERR "Usage: $0 [-w N] [-d N] gold.vcd gate.vcd\n"; + print STDERR "\n"; + print STDERR " -w N\n"; + print STDERR " reserve N characters for bitmap in text output (default: auto)\n"; + print STDERR "\n"; + print STDERR " -d N\n"; + print STDERR " allow for N timesteps delay between gate and gold (default: 0)\n"; + print STDERR "\n"; + print STDERR "Compare a known-good (gold) vcd file with a second (gate) vcd file.\n"; + print STDERR "This is not very efficient -- so use with care on large vcd files.\n"; + print STDERR "\n"; + exit 1; +} + +my $fn_gold = $ARGV[0]; +my $fn_gate = $ARGV[1]; + +print "Finding common signals..\n"; +my @gold_signals = list_sigs($fn_gold); +my @gate_signals = list_sigs($fn_gate); + +my %gold_signals_hash; +my %gate_signals_hash; + +for (@gold_signals) { + my $fullname = $_; + s/(\[([0-9]+|[0-9]+:[0-9]+)\])$//; + $gold_signals_hash{$_}->{$fullname} = 1 unless /(^|\.)_[0-9]+_/; +} + +for (@gate_signals) { + my $fullname = $_; + s/(\[([0-9]+|[0-9]+:[0-9]+)\])$//; + $gate_signals_hash{$_}->{$fullname} = 1 unless /(^|\.)_[0-9]+_/; +} + +my @signals; +for my $net (sort keys %gold_signals_hash) { + next unless exists $gate_signals_hash{$net}; + # next unless $net eq "tst_bench_top.i2c_top.byte_controller.bit_controller.cnt"; + my %orig_net_names; + print "common signal: $net"; + for my $fullname (keys %{$gold_signals_hash{$net}}) { + $orig_net_names{$fullname} = 1; + } + for my $fullname (keys %{$gate_signals_hash{$net}}) { + $orig_net_names{$fullname} = 1; + } + for my $net (sort keys %orig_net_names) { + push @signals, $net; + print " $1" if /(\[([0-9]+|[0-9]+:[0-9]+)\])$/; + } + print "\n"; +} + +print "Loading gold vcd data..\n"; +my $vcd_gold = parse_vcd($fn_gold, {siglist => \@signals}); + +print "Loading gate vcd data..\n"; +my $vcd_gate = parse_vcd($fn_gate, {siglist => \@signals}); + +# print Dumper($vcd_gold); +# print Dumper($vcd_gate); + +my %times; +my $signal_maxlen = 8; +my $data_gold = { }; +my $data_gate = { }; + +sub checklen($$) +{ + my ($net, $val) = @_; + my $thislen = length $val; + $thislen += $1 if $net =~ /\[([0-9]+)\]$/; + $thislen += $1 if $net =~ /\[([0-9]+):[0-9]+\]$/; + $signal_maxlen = $thislen if $signal_maxlen < $thislen; +} + +print "Processing gold vcd data..\n"; +for my $key (keys %$vcd_gold) { + for my $net (@{$vcd_gold->{$key}->{'nets'}}) { + my $netname = $net->{'hier'} . "." . $net->{'name'}; + for my $tv (@{$vcd_gold->{$key}->{'tv'}}) { + my $time = int($tv->[0]); + my $value = $tv->[1]; + checklen($netname, $value); + $data_gold->{$time}->{$netname} = $value; + $times{$time} = 1; + } + } +} + +print "Processing gate vcd data..\n"; +for my $key (keys %$vcd_gate) { + for my $net (@{$vcd_gate->{$key}->{'nets'}}) { + my $netname = $net->{'hier'} . "." . $net->{'name'}; + for my $tv (@{$vcd_gate->{$key}->{'tv'}}) { + my $time = int($tv->[0]); + my $value = $tv->[1]; + checklen($netname, $value); + $data_gate->{$time}->{$netname} = $value; + $times{$time} = 1; + } + } +} + +$signal_maxlen = $opt_width if $opt_width > 0; + +my $diffcount = 0; +my %state_gold; +my %state_gate; +my %signal_sync; +my %touched_nets; + +sub set_state_bit($$$$) +{ + my ($state, $net, $bit, $value) = @_; + my @data; + @data = split //, $state->{$net} if exists $state->{$net}; + unshift @data, "-" while $#data < $bit; + $data[$#data - $bit] = $value; + $state->{$net} = join "", @data; + $signal_sync{$net} = 1 unless exists $signal_sync{$net}; + $touched_nets{$net} = 1; +} + +sub set_state($$$) +{ + my ($state, $net, $value) = @_; + + if ($net =~ /(.*)\[([0-9]+)\]$/) { + set_state_bit($state, $1, $2, $value); + return; + } + + if ($net =~ /(.*)\[([0-9]+):([0-9]+)\]$/) { + my ($n, $u, $d) = ($1, $2, $3); + my @bits = split //, $value; + my $extbit = $bits[0] eq "1" ? "0" : $bits[0]; + unshift @bits, $extbit while $#bits < $u - $d; + set_state_bit($state, $n, $u--, shift @bits) while $u >= $d; + return; + } + + $state->{$net} = $value; + $signal_sync{$net} = 1 unless exists $signal_sync{$net}; + $touched_nets{$net} = 1; +} + +sub cmp_signal($$) +{ + my ($a, $b) = @_; + return 1 if $a eq $b; + + my @a = split //, $a; + my @b = split //, $b; + + my $trail_a = $#a < 0 ? '-' : $a[0] eq '1' ? '0' : $a[0]; + my $trail_b = $#b < 0 ? '-' : $b[0] eq '1' ? '0' : $b[0]; + + unshift @a, $trail_a while $#a < $#b; + unshift @b, $trail_b while $#b < $#a; + + for (my $i = 0; $i <= $#a; $i++) { + next if $a[$i] eq "-" || $b[$i] eq "-"; + return 0 if $a[$i] ne "x" && $a[$i] ne $b[$i]; + } + + return 1; +} + +# Message objects: .text, .time, .signal, .sync +my @messages; + +print "Comparing vcd data..\n"; +for my $time (sort { $a <=> $b } keys %times) +{ + %touched_nets = (); + for my $net (keys %{$data_gold->{$time}}) { + set_state(\%state_gold, $net, $data_gold->{$time}->{$net}); + } + for my $net (keys %{$data_gate->{$time}}) { + set_state(\%state_gate, $net, $data_gate->{$time}->{$net}); + } + for my $net (sort keys %touched_nets) { + my ($stgo, $stga) = ('-', '-'); + $stgo = $state_gold{$net} if exists $state_gold{$net}; + $stga = $state_gate{$net} if exists $state_gate{$net}; + if (cmp_signal($stgo, $stga)) { + next if $signal_sync{$net}; + my $message = { }; + $message->{text} = sprintf "%-10s %-20d %-*s %-*s %s\n", "", $time, $signal_maxlen, $stgo, $signal_maxlen, $stga, $net; + $message->{time} = $time; + $message->{signal} = $net; + $message->{sync} = 1; + push @messages, $message; + $signal_sync{$net} = 1; + } else { + my $message = { }; + $message->{text} = sprintf "%-10d %-20d %-*s %-*s %s\n", $diffcount, $time, $signal_maxlen, $stgo, $signal_maxlen, $stga, $net; + $message->{time} = $time; + $message->{signal} = $net; + $message->{sync} = 0; + push @messages, $message; + $signal_sync{$net} = 0; + $diffcount++; + } + } +} + +print "Found $diffcount differences.\n"; + +if ($opt_delay > 0) { + my %per_net_history; + my $removed_diff_count = 0; + for (my $i = 0; $i <= $#messages; $i++) { + my $message = $messages[$i]; + $message->{deleted} = 0; + $per_net_history{$message->{signal}} = [ ] unless exists $per_net_history{$message->{signal}}; + if ($message->{sync}) { + my $deleted_all = 1; + for my $j (@{$per_net_history{$message->{signal}}}) { + my $m = $messages[$j]; + if ($m->{time} + $opt_delay >= $message->{time}) { + $m->{deleted} = 1; + $removed_diff_count++; + } else { + $deleted_all = 0; + } + } + $message->{deleted} = 1 if $deleted_all; + $per_net_history{$message->{signal}} = [ ]; + } else { + push @{$per_net_history{$message->{signal}}}, $i; + } + } + my @new_messages; + for my $message (@messages) { + push @new_messages, $message unless $message->{deleted}; + } + @messages = @new_messages; + printf "Removed %d differences using delay filtering.\n", $removed_diff_count; + $diffcount = $diffcount - $removed_diff_count; +} + +if ($#messages >= 0) { + printf "\n%-10s %-20s %-*s %-*s %s\n", "count", "time", $signal_maxlen, "gold", $signal_maxlen, "gate", "net" if $diffcount++ == 0; + for (my $i = 0; $i <= $#messages; $i++) { + printf "%s", $messages[$i]->{text}; + } +} + +exit ($diffcount > 0 ? 1 : 0); diff --git a/chips/yosys/tests/unit/CMakeLists.txt b/chips/yosys/tests/unit/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..f94982f1452c5649dc1c765d047bc2fd9bcc06d0 --- /dev/null +++ b/chips/yosys/tests/unit/CMakeLists.txt @@ -0,0 +1,36 @@ +include(CTest) +include(GoogleTest) + +function(yosys_gtest arg_TARGET) + cmake_parse_arguments(PARSE_ARGV 1 arg "" "" "COMPONENTS") + set(arg_SOURCES ${arg_UNPARSED_ARGUMENTS}) + + set(target "gtest-${arg_TARGET}") + add_executable(${target} ${arg_SOURCES} ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/yosysSetupEnv.cc) + target_link_libraries(${target} PRIVATE + GTest::gmock_main + yosys_common + $<${YOSYS_ENABLE_PYTHON}:Python3::Python> + ) + yosys_expand_components(test_components essentials ${arg_COMPONENTS}) + yosys_link_components(${target} PRIVATE ${test_components}) + add_dependencies(yosys-gtest-all ${target}) + + if(NOT CMAKE_CROSSCOMPILING) + gtest_discover_tests(${target}) + endif() +endfunction() + +if (GTest_FOUND) + add_custom_target(yosys-gtest-all) + + add_subdirectory(cmds) + add_subdirectory(kernel) + add_subdirectory(opt) + add_subdirectory(techmap) + if (YOSYS_ENABLE_VERIFIC) + add_subdirectory(verific) + endif() + + enable_testing() +endif() diff --git a/chips/yosys/tests/unit/cmds/CMakeLists.txt b/chips/yosys/tests/unit/cmds/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..50c4fa46e1cb25783f6991f0c5b56a2065195105 --- /dev/null +++ b/chips/yosys/tests/unit/cmds/CMakeLists.txt @@ -0,0 +1,5 @@ +yosys_gtest(cmds + shuffleTest.cc + COMPONENTS + shuffle +) diff --git a/chips/yosys/tests/unit/cmds/shuffleTest.cc b/chips/yosys/tests/unit/cmds/shuffleTest.cc new file mode 100644 index 0000000000000000000000000000000000000000..d49e111bd433a06890058fc47b3885804ac79b81 --- /dev/null +++ b/chips/yosys/tests/unit/cmds/shuffleTest.cc @@ -0,0 +1,71 @@ +#include + +#include "kernel/rtlil.h" +#include "kernel/yosys.h" + +YOSYS_NAMESPACE_BEGIN + +namespace { + +RTLIL::Module *build_module(RTLIL::Design *design) +{ + RTLIL::Module *module = design->addModule("\\top"); + for (int i = 0; i < 8; i++) { + RTLIL::Wire *a = module->addWire(stringf("\\a%d", i)); + RTLIL::Wire *y = module->addWire(stringf("\\y%d", i)); + module->addNot(stringf("\\not%d", i), a, y); + module->connect(module->addWire(stringf("\\z%d", i)), y); + module->addMemory(stringf("\\mem%d", i)); + module->addProcess(stringf("\\proc%d", i)); + } + return module; +} + +std::vector> snapshot(const RTLIL::Module *module) +{ + std::vector> result(5); + for (const auto &it : module->wires_) result[0].push_back(std::string(module->twines().str(it.first))); + for (const auto &it : module->cells_) result[1].push_back(std::string(module->twines().str(it.first))); + for (const auto &it : module->memories) result[2].push_back(std::string(module->twines().str(it.first))); + for (const auto &it : module->processes) result[3].push_back(std::string(module->twines().str(it.first))); + for (const auto &it : module->connections_) result[4].push_back(log_signal(it.first) + "=" + log_signal(it.second)); + return result; +} + +TEST(ShuffleTest, ReordersAndPreservesContents) +{ + RTLIL::Design design; + RTLIL::Module *module = build_module(&design); + auto before = snapshot(module); + Pass::call(&design, "shuffle -seed 3"); + auto after = snapshot(module); + + for (size_t i = 0; i < before.size(); i++) { + EXPECT_NE(before[i], after[i]); + std::sort(before[i].begin(), before[i].end()); + std::sort(after[i].begin(), after[i].end()); + EXPECT_EQ(before[i], after[i]); + } + for (const auto &it : module->wires_) + EXPECT_EQ(module->wire(it.first), it.second); + for (const auto &it : module->cells_) + EXPECT_EQ(module->cell(it.first), it.second); +} + +TEST(ShuffleTest, SeedIsDeterministic) +{ + RTLIL::Design design_a, design_b; + RTLIL::Module *a = build_module(&design_a); + RTLIL::Module *b = build_module(&design_b); + + Pass::call(&design_a, "shuffle -seed 7"); + Pass::call(&design_b, "shuffle -seed 7"); + EXPECT_EQ(snapshot(a), snapshot(b)); + + Pass::call(&design_b, "shuffle -seed 8"); + EXPECT_NE(snapshot(a), snapshot(b)); +} + +} + +YOSYS_NAMESPACE_END diff --git a/chips/yosys/tests/unit/kernel/CMakeLists.txt b/chips/yosys/tests/unit/kernel/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..0b1c999224a7c7109d0e55f6e72305d6040a2b58 --- /dev/null +++ b/chips/yosys/tests/unit/kernel/CMakeLists.txt @@ -0,0 +1,25 @@ +yosys_gtest(kernel + bitpatternTest.cc + cellTypesTest.cc + designStateTest.cc + flattenPerfTest.cc + hashTest.cc + ioTest.cc + logTest.cc + modindexTest.cc + ownedIdTest.cc + perfHelpers.h + pooledNameTest.cc + rtlilHelpers.h + rtlilStringTest.cc + rtlilTest.cc + sigbitPerfTest.cc + sigspecExtractTest.cc + sigspecRemove2Test.cc + threadingTest.cc + twineHashTest.cc + twineSortTest.cc + twinePublicityTest.cc + COMPONENTS + flatten +) diff --git a/chips/yosys/tests/unit/kernel/bitpatternTest.cc b/chips/yosys/tests/unit/kernel/bitpatternTest.cc new file mode 100644 index 0000000000000000000000000000000000000000..a8d7bae714d7597cea5aef5aa40e551c55549bdc --- /dev/null +++ b/chips/yosys/tests/unit/kernel/bitpatternTest.cc @@ -0,0 +1,137 @@ +#include + +#include + +#include "kernel/bitpattern.h" +#include "kernel/rtlil.h" + +YOSYS_NAMESPACE_BEGIN + +TEST(BitpatternTest, has) +{ + SigSpec _aaa = {RTLIL::Sa, RTLIL::Sa, RTLIL::Sa}; + SigSpec _01a = {RTLIL::S0, RTLIL::S1, RTLIL::Sa}; + SigSpec _011 = {RTLIL::S0, RTLIL::S1, RTLIL::S1}; + SigSpec _111 = {RTLIL::S1, RTLIL::S1, RTLIL::S1}; + SigSpec _01x = {RTLIL::S0, RTLIL::S1, RTLIL::Sx}; + SigSpec _01z = {RTLIL::S0, RTLIL::S1, RTLIL::Sz}; + + EXPECT_TRUE(BitPatternPool(_aaa).has_any(_01a)); + EXPECT_TRUE(BitPatternPool(_01a).has_any(_01a)); + // 011 overlaps with 01a + EXPECT_TRUE(BitPatternPool(_011).has_any(_01a)); + // overlap is symmetric + EXPECT_TRUE(BitPatternPool(_01a).has_any(_011)); + EXPECT_FALSE(BitPatternPool(_111).has_any(_01a)); + // overlaps nothing + EXPECT_FALSE(BitPatternPool(_011).has_any(_01x)); + EXPECT_FALSE(BitPatternPool(_011).has_any(_01z)); + EXPECT_FALSE(BitPatternPool(_aaa).has_any(_01x)); + + EXPECT_TRUE(BitPatternPool(_aaa).has_all(_01a)); + EXPECT_TRUE(BitPatternPool(_01a).has_all(_01a)); + // 011 is covered by 01a + EXPECT_TRUE(BitPatternPool(_01a).has_all(_011)); + // 01a is not covered by 011 + EXPECT_FALSE(BitPatternPool(_011).has_all(_01a)); + EXPECT_FALSE(BitPatternPool(_111).has_all(_01a)); + // trivially covered by any pool + EXPECT_TRUE(BitPatternPool(_011).has_all(_01x)); + EXPECT_TRUE(BitPatternPool(_011).has_all(_01z)); + EXPECT_TRUE(BitPatternPool(_111).has_all(_01x)); +} + +namespace detail +{ + +// casez items 0, 0..01, 0..01?, ..., 1?..?. +std::vector priority_items(int width) +{ + std::vector items = {SigSpec(RTLIL::S0, width)}; + for (int one = 0; one < width; one++) { + SigSpec item(RTLIL::Sa, width); + for (int i = one; i < width; i++) + item[i] = i == one ? RTLIL::S1 : RTLIL::S0; + items.push_back(item); + } + return items; +} + +// item x = (sel == x && data[x]), sel low or high +std::vector mux_items(bool sel_low) +{ + int sel_lsb = sel_low ? 0 : 16; + int data_lsb = sel_low ? 4 : 0; + std::vector items; + for (int x = 0; x < 16; x++) { + SigSpec item(RTLIL::Sa, 20); + for (int i = 0; i < 4; i++) + item[sel_lsb + i] = (x >> i) & 1 ? RTLIL::S1 : RTLIL::S0; + item[data_lsb + x] = RTLIL::S1; + items.push_back(item); + } + return items; +} + +void expect_exact_mux(bool sel_low, int max_nodes) +{ + std::vector items = mux_items(sel_low); + BitPatternPool pool(20); + pool.max_nodes = max_nodes; + for (auto &item : items) + EXPECT_TRUE(pool.take(item)); + EXPECT_FALSE(pool.gave_up); + EXPECT_FALSE(pool.take(items[0])); + EXPECT_FALSE(pool.has_any(items[0])); + EXPECT_TRUE(pool.has_all(SigSpec(RTLIL::S0, 20))); + EXPECT_FALSE(pool.empty()); +} + +} // namespace detail + +TEST(BitpatternTest, priority_encoder) +{ + std::vector items = detail::priority_items(64); + for (int pass = 0; pass < 2; pass++) { + BitPatternPool pool(64); + for (auto &item : items) { + EXPECT_FALSE(pool.empty()); + EXPECT_TRUE(pool.has_all(item)); + EXPECT_TRUE(pool.take(item)); + EXPECT_FALSE(pool.has_any(item)); + EXPECT_FALSE(pool.take(item)); + } + EXPECT_TRUE(pool.empty()); + std::reverse(items.begin(), items.end()); + } +} + +TEST(BitpatternTest, flips_bit_order) +{ + detail::expect_exact_mux(true, 128); +} + +TEST(BitpatternTest, retries_msb_first) +{ + detail::expect_exact_mux(false, 128); +} + +TEST(BitpatternTest, gives_up_conservatively) +{ + std::vector items = detail::priority_items(4); + BitPatternPool pool(4); + pool.max_nodes = 4; + EXPECT_TRUE(pool.take(items[0])); + EXPECT_TRUE(pool.gave_up); + EXPECT_TRUE(pool.take(items[0])); + EXPECT_TRUE(pool.has_any(items[0])); + EXPECT_FALSE(pool.has_all(items[1])); + for (auto &item : items) + pool.take(item); + EXPECT_FALSE(pool.empty()); + EXPECT_TRUE(pool.take_all()); + EXPECT_TRUE(pool.empty()); + EXPECT_FALSE(pool.take(items[1])); +} + +YOSYS_NAMESPACE_END diff --git a/chips/yosys/tests/unit/kernel/cellTypesTest.cc b/chips/yosys/tests/unit/kernel/cellTypesTest.cc new file mode 100644 index 0000000000000000000000000000000000000000..56e7f1ee3d2aa6dde75aa54cb5afdfaadc00553c --- /dev/null +++ b/chips/yosys/tests/unit/kernel/cellTypesTest.cc @@ -0,0 +1,86 @@ +#include +#include "kernel/yosys.h" +#include "kernel/yosys_common.h" +#include "kernel/celltypes.h" +#include "kernel/newcelltypes.h" + +#include + +YOSYS_NAMESPACE_BEGIN + +TEST(CellTypesTest, basic) +{ + CellTypes older; + NewCellTypes newer; + older.setup(nullptr); + newer.setup(nullptr); + RTLIL::Design design; + IdString bleh = design.twines().add("\\bleh"); + IdString aaaaa = design.twines().add("\\aaaaa"); + older.setup_type(bleh, {ID::G}, {ID::H, ID::I}, false, true); + newer.setup_type(bleh, {ID::G}, {ID::H, ID::I}, false, true); + EXPECT_EQ(older.cell_known(aaaaa), newer.cell_known(aaaaa)); + EXPECT_EQ(older.cell_known(ID($and)), newer.cell_known(ID($and))); + auto check_port = [&](auto type, auto port) { + EXPECT_EQ(older.cell_port_dir(type, port), newer.cell_port_dir(type, port)); + EXPECT_EQ(older.cell_input(type, port), newer.cell_input(type, port)); + EXPECT_EQ(older.cell_output(type, port), newer.cell_output(type, port)); + }; + + // ground truth + const pool expected_ff_types = { + ID($sr), ID($ff), ID($dff), ID($dffe), ID($dffsr), ID($dffsre), + ID($adff), ID($adffe), ID($aldff), ID($aldffe), + ID($sdff), ID($sdffe), ID($sdffce), + ID($dlatch), ID($adlatch), ID($dlatchsr), + ID($_DFFE_NN_), ID($_DFFE_NP_), ID($_DFFE_PN_), ID($_DFFE_PP_), + ID($_DFFSR_NNN_), ID($_DFFSR_NNP_), ID($_DFFSR_NPN_), ID($_DFFSR_NPP_), + ID($_DFFSR_PNN_), ID($_DFFSR_PNP_), ID($_DFFSR_PPN_), ID($_DFFSR_PPP_), + ID($_DFFSRE_NNNN_), ID($_DFFSRE_NNNP_), ID($_DFFSRE_NNPN_), ID($_DFFSRE_NNPP_), + ID($_DFFSRE_NPNN_), ID($_DFFSRE_NPNP_), ID($_DFFSRE_NPPN_), ID($_DFFSRE_NPPP_), + ID($_DFFSRE_PNNN_), ID($_DFFSRE_PNNP_), ID($_DFFSRE_PNPN_), ID($_DFFSRE_PNPP_), + ID($_DFFSRE_PPNN_), ID($_DFFSRE_PPNP_), ID($_DFFSRE_PPPN_), ID($_DFFSRE_PPPP_), + ID($_DFF_N_), ID($_DFF_P_), + ID($_DFF_NN0_), ID($_DFF_NN1_), ID($_DFF_NP0_), ID($_DFF_NP1_), + ID($_DFF_PN0_), ID($_DFF_PN1_), ID($_DFF_PP0_), ID($_DFF_PP1_), + ID($_DFFE_NN0N_), ID($_DFFE_NN0P_), ID($_DFFE_NN1N_), ID($_DFFE_NN1P_), + ID($_DFFE_NP0N_), ID($_DFFE_NP0P_), ID($_DFFE_NP1N_), ID($_DFFE_NP1P_), + ID($_DFFE_PN0N_), ID($_DFFE_PN0P_), ID($_DFFE_PN1N_), ID($_DFFE_PN1P_), + ID($_DFFE_PP0N_), ID($_DFFE_PP0P_), ID($_DFFE_PP1N_), ID($_DFFE_PP1P_), + ID($_ALDFF_NN_), ID($_ALDFF_NP_), ID($_ALDFF_PN_), ID($_ALDFF_PP_), + ID($_ALDFFE_NNN_), ID($_ALDFFE_NNP_), ID($_ALDFFE_NPN_), ID($_ALDFFE_NPP_), + ID($_ALDFFE_PNN_), ID($_ALDFFE_PNP_), ID($_ALDFFE_PPN_), ID($_ALDFFE_PPP_), + ID($_SDFF_NN0_), ID($_SDFF_NN1_), ID($_SDFF_NP0_), ID($_SDFF_NP1_), + ID($_SDFF_PN0_), ID($_SDFF_PN1_), ID($_SDFF_PP0_), ID($_SDFF_PP1_), + ID($_SDFFE_NN0N_), ID($_SDFFE_NN0P_), ID($_SDFFE_NN1N_), ID($_SDFFE_NN1P_), + ID($_SDFFE_NP0N_), ID($_SDFFE_NP0P_), ID($_SDFFE_NP1N_), ID($_SDFFE_NP1P_), + ID($_SDFFE_PN0N_), ID($_SDFFE_PN0P_), ID($_SDFFE_PN1N_), ID($_SDFFE_PN1P_), + ID($_SDFFE_PP0N_), ID($_SDFFE_PP0P_), ID($_SDFFE_PP1N_), ID($_SDFFE_PP1P_), + ID($_SDFFCE_NN0N_), ID($_SDFFCE_NN0P_), ID($_SDFFCE_NN1N_), ID($_SDFFCE_NN1P_), + ID($_SDFFCE_NP0N_), ID($_SDFFCE_NP0P_), ID($_SDFFCE_NP1N_), ID($_SDFFCE_NP1P_), + ID($_SDFFCE_PN0N_), ID($_SDFFCE_PN0P_), ID($_SDFFCE_PN1N_), ID($_SDFFCE_PN1P_), + ID($_SDFFCE_PP0N_), ID($_SDFFCE_PP0P_), ID($_SDFFCE_PP1N_), ID($_SDFFCE_PP1P_), + ID($_SR_NN_), ID($_SR_NP_), ID($_SR_PN_), ID($_SR_PP_), + ID($_DLATCH_N_), ID($_DLATCH_P_), + ID($_DLATCH_NN0_), ID($_DLATCH_NN1_), ID($_DLATCH_NP0_), ID($_DLATCH_NP1_), + ID($_DLATCH_PN0_), ID($_DLATCH_PN1_), ID($_DLATCH_PP0_), ID($_DLATCH_PP1_), + ID($_DLATCHSR_NNN_), ID($_DLATCHSR_NNP_), ID($_DLATCHSR_NPN_), ID($_DLATCHSR_NPP_), + ID($_DLATCHSR_PNN_), ID($_DLATCHSR_PNP_), ID($_DLATCHSR_PPN_), ID($_DLATCHSR_PPP_), + ID($_FF_), + }; + + for (size_t i = 0; i < static_cast(STATIC_TWINE_END); i++) { + IdString type(i); + EXPECT_EQ(older.cell_known(type), newer.cell_known(type)); + if (older.cell_evaluable(type) != newer.cell_evaluable(type)) + std::cout << ID::unescaped_str(type) << "\n"; + EXPECT_EQ(older.cell_evaluable(type), newer.cell_evaluable(type)); + for (auto port : StaticCellTypes::builder.cells.data()->inputs.ports) + check_port(type, port); + for (auto port : StaticCellTypes::builder.cells.data()->outputs.ports) + check_port(type, port); + EXPECT_EQ(expected_ff_types.count(type) > 0, StaticCellTypes::categories.is_ff(type)); + } +} + +YOSYS_NAMESPACE_END diff --git a/chips/yosys/tests/unit/kernel/designStateTest.cc b/chips/yosys/tests/unit/kernel/designStateTest.cc new file mode 100644 index 0000000000000000000000000000000000000000..ede48190d6b9015a52639b389c5438ae357dfcbe --- /dev/null +++ b/chips/yosys/tests/unit/kernel/designStateTest.cc @@ -0,0 +1,46 @@ +#include + +#include "kernel/rtlil.h" +#include "kernel/yosys.h" + +YOSYS_NAMESPACE_BEGIN + +namespace { + +TEST(DesignStateTest, AutoidxInTwinePool) +{ + TwinePool a, b; + int start = a.autoidx(); + EXPECT_EQ(b.autoidx(), start); + + IdString first = a.add(NEW_ID); + EXPECT_EQ(a.autoidx(), start + 1); + EXPECT_EQ(b.autoidx(), start); + + IdString second = b.add(NEW_ID_SUFFIX("tail")); + EXPECT_EQ(b.autoidx(), start + 1); + + EXPECT_TRUE(a.str(first).ends_with(std::to_string(start))); + EXPECT_TRUE(b.str(second).ends_with("tail$" + std::to_string(start))); +} + +TEST(DesignStateTest, HashidxPerDesign) +{ + RTLIL::Design old_d; + RTLIL::Module *old_mod = old_d.addModule(std::string("\\m")); + RTLIL::Wire *old_wire = old_mod->addWire(NEW_ID, 1); + + RTLIL::Design new_d; + RTLIL::Module *new_mod = new_d.addModule(std::string("\\m")); + RTLIL::Wire *new_wire = new_mod->addWire(NEW_ID, 1); + + EXPECT_EQ(run_hash(old_d), run_hash(LARGE_HASHIDX_COLLIDER)); + EXPECT_EQ(run_hash(new_d), run_hash(LARGE_HASHIDX_COLLIDER)); + + EXPECT_EQ(run_hash(old_mod), run_hash(new_mod)); + EXPECT_EQ(run_hash(old_wire), run_hash(new_wire)); +} + +} // namespace + +YOSYS_NAMESPACE_END diff --git a/chips/yosys/tests/unit/kernel/flattenPerfTest.cc b/chips/yosys/tests/unit/kernel/flattenPerfTest.cc new file mode 100644 index 0000000000000000000000000000000000000000..45872f8f03d374be11bd18026c67b19b770bd8ff --- /dev/null +++ b/chips/yosys/tests/unit/kernel/flattenPerfTest.cc @@ -0,0 +1,147 @@ +#include + +#include + +#include "kernel/rtlil.h" +#include "kernel/yosys.h" +#include "perfHelpers.h" + +YOSYS_NAMESPACE_BEGIN + +namespace { + +std::string name_padding; +bool attach_src = false; +int src_counter = 0; + +void set_src(RTLIL::AttrObject *object) +{ + if (!attach_src) + return; + src_counter++; + object->set_src_attribute(stringf("flatten_perf_source_file.v:%d.1-%d.20", src_counter, src_counter)); +} + +std::string pad(std::string name) +{ + name += name_padding; + return name; +} + +RTLIL::Module *build_leaf(RTLIL::Design *design, int chain_length) +{ + RTLIL::Module *m = design->addModule(pad("\\flatten_perf_leaf_module")); + + RTLIL::Wire *in = m->addWire(pad("\\leaf_module_data_input_port")); + in->port_input = true; + set_src(in); + RTLIL::Wire *out = m->addWire(pad("\\leaf_module_data_output_port")); + out->port_output = true; + set_src(out); + m->fixup_ports(); + + RTLIL::SigBit prev = in; + for (int i = 0; i < chain_length; i++) { + RTLIL::SigBit next = i + 1 == chain_length + ? RTLIL::SigBit(out) + : RTLIL::SigBit(m->addWire(pad(stringf("\\leaf_intermediate_signal_wire_number_%d", i)))); + if (next.wire != nullptr) + set_src(next.wire); + set_src(m->addNotGate(pad(stringf("$leaf_inverter_cell_instance_number_%d", i)), prev, next)); + prev = next; + } + return m; +} + +RTLIL::Module *build_level(RTLIL::Design *design, RTLIL::Module *child, int level, int branch) +{ + RTLIL::Module *m = design->addModule(pad(stringf("\\flatten_perf_hierarchy_level_%d_module", level))); + + RTLIL::Wire *in = m->addWire(pad(stringf("\\level_%d_module_data_input_port", level))); + in->port_input = true; + set_src(in); + RTLIL::Wire *out = m->addWire(pad(stringf("\\level_%d_module_data_output_port", level))); + out->port_output = true; + set_src(out); + m->fixup_ports(); + + RTLIL::Wire *child_in = child->wire(child->ports.at(0)); + RTLIL::Wire *child_out = child->wire(child->ports.at(1)); + + RTLIL::SigBit prev = in; + for (int k = 0; k < branch; k++) { + RTLIL::SigBit next = k + 1 == branch + ? RTLIL::SigBit(out) + : RTLIL::SigBit(m->addWire(pad(stringf("\\level_%d_interconnect_signal_wire_number_%d", level, k)))); + RTLIL::Cell *cell = m->addCell( + pad(stringf("\\hierarchical_child_instance_at_level_%d_branch_%d", level, k)), child->name); + set_src(cell); + cell->setPort(child_in->name, prev); + cell->setPort(child_out->name, next); + prev = next; + } + return m; +} + +RTLIL::Module *build_design(RTLIL::Design *design, int depth, int branch, int chain_length) +{ + RTLIL::Module *m = build_leaf(design, chain_length); + for (int level = depth - 1; level >= 0; level--) + m = build_level(design, m, level, branch); + m->set_bool_attribute(ID::top); + return m; +} + +} // namespace + +TEST(FlattenPerf, deep_hierarchy_stress) +{ + int depth = env_int("YOSYS_FLATTEN_PERF_DEPTH", 8); + int branch = env_int("YOSYS_FLATTEN_PERF_BRANCH", 2); + int chain_length = env_int("YOSYS_FLATTEN_PERF_CHAIN", 48); + int extra_name_chars = env_int("YOSYS_FLATTEN_PERF_NAMEPAD", 32); + const char *flatten_args = getenv("YOSYS_FLATTEN_PERF_ARGS"); + + ASSERT_GE(depth, 1); + ASSERT_GE(branch, 2); + ASSERT_GE(chain_length, 1); + ASSERT_GE(extra_name_chars, 0); + + name_padding = std::string(extra_name_chars, 'n'); + attach_src = env_int("YOSYS_FLATTEN_PERF_SRC", 0) != 0; + + RTLIL::Design *design = new RTLIL::Design; + + auto build_start = std::chrono::steady_clock::now(); + RTLIL::Module *top = build_design(design, depth, branch, chain_length); + auto build_end = std::chrono::steady_clock::now(); + + size_t rss_before = rss_bytes(); + + auto flatten_start = std::chrono::steady_clock::now(); + Pass::call(design, flatten_args != nullptr ? std::string("flatten ") + flatten_args : std::string("flatten")); + auto flatten_end = std::chrono::steady_clock::now(); + + size_t rss_after = rss_bytes(); + + size_t leaves = 1; + for (int level = 0; level < depth; level++) + leaves *= (size_t)branch; + + EXPECT_EQ(design->modules().size(), 1u); + EXPECT_EQ(design->top_module(), top); + EXPECT_GE(top->cells().size(), leaves * (size_t)chain_length); + + printf("[ PERF ] depth=%d branch=%d chain=%d namepad=%d src=%d args=%s leaves=%zu\n", depth, branch, chain_length, + extra_name_chars, (int)attach_src, flatten_args != nullptr ? flatten_args : "", leaves); + printf("[ PERF ] cells=%zu wires=%zu\n", top->cells().size(), top->wires().size()); + printf("[ PERF ] build_ms=%.1f flatten_ms=%.1f\n", ms(build_end - build_start), ms(flatten_end - flatten_start)); + printf("[ PERF ] rss_before_mb=%.1f rss_after_mb=%.1f flatten_rss_mb=%.1f peak_rss_mb=%.1f\n", + mb(rss_before), mb(rss_after), + mb(rss_after - rss_before), mb(peak_rss_bytes())); + fflush(stdout); + + delete design; +} + +YOSYS_NAMESPACE_END diff --git a/chips/yosys/tests/unit/kernel/hashTest.cc b/chips/yosys/tests/unit/kernel/hashTest.cc new file mode 100644 index 0000000000000000000000000000000000000000..319d064a7c17234693d8a77bbe796f5e60efbbfb --- /dev/null +++ b/chips/yosys/tests/unit/kernel/hashTest.cc @@ -0,0 +1,67 @@ +#include +#include "kernel/yosys_common.h" + +#include + +YOSYS_NAMESPACE_BEGIN + +static Hasher hash(int x) +{ + Hasher h; + h.eat(x); + return h; +} + +TEST(CommutativeTest, basic) +{ + hashlib::commutative_hash comm1; + comm1.eat(hash(1)); + comm1.eat(hash(2)); + hashlib::commutative_hash comm2; + comm2.eat(hash(2)); + comm2.eat(hash(1)); + EXPECT_EQ(comm1.hash_into(Hasher()).yield(), comm2.hash_into(Hasher()).yield()); +} + +TEST(PoolHashTest, collisions) +{ + uint64_t collisions = 0; + std::unordered_set hashes; + for (int i = 0; i < 1000; ++i) { + for (int j = i + 1; j < 1000; ++j) { + pool p1; + p1.insert(i); + p1.insert(j); + auto h = p1.hash_into(Hasher()).yield(); + if (!hashes.insert(h).second) { + ++collisions; + } + } + } + std::cout << "pool collisions: " << collisions << std::endl; + EXPECT_LT(collisions, 10'000); +} + +TEST(PoolHashTest, subset_collisions) +{ + uint64_t collisions = 0; + std::unordered_set hashes; + for (int i = 0; i < 1000 * 1000; ++i) { + + pool p1; + for (int b = 0; i >> b; ++b) { + if ((i >> b) & 1) { + p1.insert(b); + } + } + auto h = p1.hash_into(Hasher()).yield(); + if (!hashes.insert(h).second) { + ++collisions; + } + + } + std::cout << "pool subset collisions: " << collisions << std::endl; + EXPECT_LT(collisions, 100); +} + +YOSYS_NAMESPACE_END diff --git a/chips/yosys/tests/unit/kernel/ioTest.cc b/chips/yosys/tests/unit/kernel/ioTest.cc new file mode 100644 index 0000000000000000000000000000000000000000..e75f2d801540106a11b819569422872318823d38 --- /dev/null +++ b/chips/yosys/tests/unit/kernel/ioTest.cc @@ -0,0 +1,83 @@ +#include + +#include "kernel/io.h" +#include "kernel/rtlil.h" + +YOSYS_NAMESPACE_BEGIN + +TEST(KernelStringfTest, integerTruncation) +{ + EXPECT_EQ(stringf("%d", 1LL << 32), "0"); + EXPECT_EQ(stringf("%u", 1LL << 32), "0"); + EXPECT_EQ(stringf("%x", 0xff12345678LL), "12345678"); + EXPECT_EQ(stringf("%hu", 0xff12345678LL), "22136"); +} + +TEST(KernelStringfTest, charFormat) +{ + EXPECT_EQ(stringf("%c", 256), std::string_view("\0", 1)); + EXPECT_EQ(stringf("%c", -1), "\377"); +} + +TEST(KernelStringfTest, floatFormat) +{ + EXPECT_EQ(stringf("%g", 1.0), "1"); +} + +TEST(KernelStringfTest, intToFloat) +{ + EXPECT_EQ(stringf("%g", 1), "1"); +} + +TEST(KernelStringfTest, floatToInt) +{ + EXPECT_EQ(stringf("%d", 1.0), "1"); + EXPECT_EQ(stringf("%d", -1.6), "-1"); +} + +TEST(KernelStringfTest, stringParam) +{ + EXPECT_EQ(stringf("%s", std::string("hello")), "hello"); +} + +TEST(KernelStringfTest, stringViewParam) +{ + EXPECT_EQ(stringf("%s", std::string_view("hello")), "hello"); +} + +TEST(KernelStringfTest, escapePercent) +{ + EXPECT_EQ(stringf("%%"), "%"); +} + +TEST(KernelStringfTest, trailingPercent) +{ + EXPECT_EQ(stringf("%"), "%"); +} + +TEST(KernelStringfTest, dynamicWidth) +{ + EXPECT_EQ(stringf("%*s", 8, "hello"), " hello"); +} + +TEST(KernelStringfTest, dynamicPrecision) +{ + EXPECT_EQ(stringf("%.*f", 4, 1.0), "1.0000"); +} + +TEST(KernelStringfTest, dynamicWidthAndPrecision) +{ + EXPECT_EQ(stringf("%*.*f", 8, 4, 1.0), " 1.0000"); +} + +TEST(KernelStringfTest, dynamicPrecisionInt) +{ + EXPECT_EQ(stringf("%.*d", 4, 7), "0007"); +} + +TEST(KernelStringfTest, dynamicWidthAndPrecisionInt) +{ + EXPECT_EQ(stringf("%*.*d", 8, 4, 7), " 0007"); +} + +YOSYS_NAMESPACE_END diff --git a/chips/yosys/tests/unit/kernel/logTest.cc b/chips/yosys/tests/unit/kernel/logTest.cc new file mode 100644 index 0000000000000000000000000000000000000000..62b4f3b98f852e0b053e64171af26109c4fde531 --- /dev/null +++ b/chips/yosys/tests/unit/kernel/logTest.cc @@ -0,0 +1,14 @@ +#include + +#include "kernel/yosys.h" +#include "kernel/log.h" + +YOSYS_NAMESPACE_BEGIN + +TEST(KernelLogTest, logvValidValues) +{ + //TODO: Implement log test + EXPECT_EQ(7, 7); +} + +YOSYS_NAMESPACE_END diff --git a/chips/yosys/tests/unit/kernel/modindexTest.cc b/chips/yosys/tests/unit/kernel/modindexTest.cc new file mode 100644 index 0000000000000000000000000000000000000000..868aa9796bb78fec06c36517d0c5000d0b2e3057 --- /dev/null +++ b/chips/yosys/tests/unit/kernel/modindexTest.cc @@ -0,0 +1,47 @@ +#include + +#include "kernel/modtools.h" +#include "kernel/rtlil.h" + +YOSYS_NAMESPACE_BEGIN + +TEST(ModIndexSwapTest, has) +{ + Design* d = new Design; + Module* m = d->addModule("$m"); + Wire* o = m->addWire("$o", 2); + o->port_input = true; + Wire* i = m->addWire("$i", 2); + i->port_input = true; + m->fixup_ports(); + m->addNot("$not", i, o); + auto mi = ModIndex(m); + mi.reload_module(); + for (auto [sb, info] : mi.database) { + EXPECT_TRUE(mi.database.find(sb) != mi.database.end()); + } + m->swap_names(i, o); + for (auto [sb, info] : mi.database) { + EXPECT_TRUE(mi.database.find(sb) != mi.database.end()); + } +} + +TEST(ModIndexDeleteTest, has) +{ + if (logger().empty()) logger().add_sink(); + Design* d = new Design; + Module* m = d->addModule("$m"); + Wire* w = m->addWire("$w"); + Wire* o = m->addWire("$o"); + o->port_output = true; + m->fixup_ports(); + Cell* not_ = m->addNotGate("$not", w, o); + auto mi = ModIndex(m); + mi.reload_module(); + mi.dump_db(); + Wire* a = m->addWire("\\a"); + not_->setPort(ID::A, a); + EXPECT_TRUE(mi.ok()); +} + +YOSYS_NAMESPACE_END diff --git a/chips/yosys/tests/unit/kernel/ownedIdTest.cc b/chips/yosys/tests/unit/kernel/ownedIdTest.cc new file mode 100644 index 0000000000000000000000000000000000000000..14bb2ccb0bdf66aa37696665b4d8444f7db4dadf --- /dev/null +++ b/chips/yosys/tests/unit/kernel/ownedIdTest.cc @@ -0,0 +1,263 @@ +#include + +#include "kernel/rtlil.h" +#include "kernel/yosys.h" + +YOSYS_NAMESPACE_BEGIN + +namespace { + +struct OwnedIdFixture { + Design design; + Module *mod; + Wire *wire; + Cell *cell; + + OwnedIdFixture() + { + mod = design.addModule(std::string("\\zz_top")); + wire = mod->addWire(std::string("\\zz_alu_result"), 4); + cell = mod->addCell(std::string("\\zz_adder"), ID($and)); + } +}; + +} + +TEST(OwnedIdTest, StringQueries) +{ + OwnedIdFixture f; + const RTLIL::WireNameId &name = f.wire->name; + + EXPECT_TRUE(name.begins_with("\\zz_alu")); + EXPECT_FALSE(name.begins_with("\\zz_alv")); + EXPECT_TRUE(name.ends_with("result")); + EXPECT_FALSE(name.ends_with("resulz")); + EXPECT_TRUE(name.contains("alu")); + EXPECT_FALSE(name.contains("mul")); + EXPECT_EQ(name.substr(1, 2), "zz"); + EXPECT_EQ(name.substr(), name.escaped()); + EXPECT_EQ(name[0], '\\'); + EXPECT_EQ(name.size(), name.escaped().size()); + EXPECT_FALSE(name.empty()); +} + +TEST(OwnedIdTest, SuffixQueries) +{ + Design design; + Module *mod = design.addModule(std::string("\\zz_top")); + IdString prefix = design.twines().add("\\zz_bus"); + IdString suffixed = design.twines().add(TwineSpec{TwineSpec::Suffix{prefix, "_hi"}}); + Wire *w = mod->addWire(suffixed, 1); + + EXPECT_EQ(w->name.escaped(), "\\zz_bus_hi"); + EXPECT_TRUE(w->name.begins_with("\\zz_bus")); + EXPECT_TRUE(w->name.begins_with("\\zz_bus_h")); + EXPECT_TRUE(w->name.begins_with("\\zz_bus_hi")); + EXPECT_FALSE(w->name.begins_with("\\zz_bus_hi_")); + EXPECT_FALSE(w->name.begins_with("\\zz_buT")); + EXPECT_FALSE(w->name.begins_with("\\zz_bus_i")); + EXPECT_TRUE(w->name.ends_with("_hi")); + EXPECT_EQ(w->name.size(), w->name.escaped().size()); + EXPECT_EQ(w->name.substr(4), "bus_hi"); +} + +TEST(OwnedIdTest, PoollessMatchesPooled) +{ + Design design; + IdString id = design.twines().add("\\zz_shared"); + PooledName pooled(&design.twines(), id); + PooledName poolless(ID::A); + + EXPECT_EQ(pooled.pool(), &design.twines()); + EXPECT_EQ(poolless.pool(), nullptr); + + EXPECT_EQ(poolless.escaped(), "\\A"); + EXPECT_EQ(poolless.size(), poolless.escaped().size()); + EXPECT_TRUE(poolless.begins_with("\\A")); + EXPECT_FALSE(poolless.begins_with("\\AB")); + EXPECT_TRUE(poolless.ends_with("A")); + + PooledName same_content(&design.twines(), design.twines().add("\\A")); + EXPECT_EQ(same_content.escaped(), poolless.escaped()); + EXPECT_EQ(same_content.size(), poolless.size()); + EXPECT_EQ(same_content.begins_with("\\A"), poolless.begins_with("\\A")); +} + +TEST(OwnedIdTest, PoollessOrdering) +{ + PooledName a(ID::A); + PooledName b(ID::B); + + EXPECT_EQ(a.pool(), nullptr); + EXPECT_TRUE(a.lt_by_name(b)); + EXPECT_FALSE(b.lt_by_name(a)); + EXPECT_FALSE(a.lt_by_name(a)); +} + +TEST(OwnedIdTest, PooledOrdering) +{ + Design design; + Module *mod = design.addModule(std::string("\\zz_top")); + Wire *first = mod->addWire(std::string("\\zz_aaa"), 1); + Wire *second = mod->addWire(std::string("\\zz_bbb"), 1); + + EXPECT_TRUE(first->name.lt_by_name(second->name)); + EXPECT_FALSE(second->name.lt_by_name(first->name)); + EXPECT_FALSE(first->name.lt_by_name(first->name)); + + EXPECT_NE(first->name < second->name, second->name < first->name); + EXPECT_FALSE(first->name < first->name); +} + +TEST(OwnedIdTest, Membership) +{ + OwnedIdFixture f; + + EXPECT_TRUE(f.cell->type.in(ID($and))); + EXPECT_FALSE(f.cell->type.in(ID($or))); + EXPECT_TRUE(f.cell->type.in(ID($or), ID($and))); + EXPECT_FALSE(f.cell->type.in(ID($or), ID($xor))); + EXPECT_TRUE(f.wire->name.in(IdString(f.wire->name))); +} + +TEST(OwnedIdTest, Equality) +{ + OwnedIdFixture f; + IdString id = f.wire->name; + + EXPECT_TRUE(f.wire->name == id); + EXPECT_TRUE(id == f.wire->name); + EXPECT_FALSE(f.wire->name != id); + EXPECT_TRUE(f.wire->name != ID::A); + + EXPECT_TRUE(f.cell->type == ID($and)); + EXPECT_TRUE(f.cell->type != ID($or)); + + EXPECT_TRUE(f.wire->name == std::string("\\zz_alu_result")); + EXPECT_TRUE(f.wire->name != std::string("\\zz_other")); + + EXPECT_TRUE(f.wire->name == f.wire->name); + EXPECT_TRUE(f.wire->name != f.cell->name); + + PooledName null_name; + EXPECT_TRUE(null_name == IdString::Null); + EXPECT_TRUE(null_name.empty()); + EXPECT_FALSE(f.wire->name == IdString::Null); + EXPECT_TRUE(f.wire->name != IdString::Null); +} + +TEST(OwnedIdTest, CrossIdEquality) +{ + Design design; + Module *mod = design.addModule(std::string("\\zz_top")); + Cell *recursive = mod->addCell(std::string("\\zz_self"), mod->name); + Cell *other = mod->addCell(std::string("\\zz_and"), ID($and)); + + EXPECT_TRUE(mod->name == recursive->type); + EXPECT_TRUE(recursive->type == mod->name); + EXPECT_FALSE(mod->name == other->type); + EXPECT_TRUE(mod->name != other->type); + EXPECT_TRUE(recursive->name != other->name); +} + +TEST(OwnedIdTest, Conversions) +{ + OwnedIdFixture f; + + std::string as_string = f.wire->name; + IdString as_id = f.wire->name; + + EXPECT_EQ(as_string, "\\zz_alu_result"); + EXPECT_EQ(as_string, f.wire->name.str()); + EXPECT_EQ(as_id, f.wire->name.ref()); + EXPECT_EQ(f.wire->name.pool(), &f.design.twines()); + EXPECT_EQ(f.cell->type.pool(), &f.design.twines()); + EXPECT_EQ(f.mod->name.pool(), &f.design.twines()); +} + +TEST(OwnedIdTest, Hashing) +{ + OwnedIdFixture f; + + EXPECT_EQ(run_hash(f.wire->name), run_hash(f.wire->name.ref())); + EXPECT_EQ(run_hash(f.cell->type), run_hash(f.cell->type.ref())); + EXPECT_EQ(run_hash(PooledName(f.wire->name)), run_hash(f.wire->name.ref())); + EXPECT_NE(run_hash(f.wire->name), run_hash(f.cell->name.ref())); +} + +TEST(OwnedIdTest, WireAssignment) +{ + Design design; + Module *mod = design.addModule(std::string("\\zz_top")); + Wire *a = mod->addWire(std::string("\\zz_a"), 1); + Wire *b = mod->addWire(std::string("\\zz_b"), 1); + IdString renamed = design.twines().add("\\zz_renamed"); + + a->name = renamed; + EXPECT_EQ(a->name.str(), "\\zz_renamed"); + + b->name = a->name; + EXPECT_EQ(b->name.str(), "\\zz_renamed"); + EXPECT_TRUE(a->name == b->name); + + Wire *c = mod->addWire(std::string("\\zz_c"), 1); + c->name = std::move(b->name); + EXPECT_EQ(c->name.str(), "\\zz_renamed"); +} + +TEST(OwnedIdTest, TypeAssignment) +{ + OwnedIdFixture f; + Cell *other = f.mod->addCell(std::string("\\zz_other"), ID($or)); + + f.cell->type = ID($xor); + EXPECT_TRUE(f.cell->type == ID($xor)); + EXPECT_EQ(f.cell->type.str(), "$xor"); + + other->type = f.cell->type; + EXPECT_TRUE(other->type == ID($xor)); + + Cell *third = f.mod->addCell(std::string("\\zz_third"), ID($not)); + third->type = std::move(other->type); + EXPECT_TRUE(third->type == ID($xor)); +} + +TEST(OwnedIdTest, ModuleAssignment) +{ + Design design; + Module *mod = design.addModule(std::string("\\zz_top")); + Module *sibling = design.addModule(std::string("\\zz_side")); + IdString renamed = design.twines().add("\\zz_renamed"); + + mod->name = renamed; + EXPECT_EQ(mod->name.str(), "\\zz_renamed"); + EXPECT_TRUE(mod->name == renamed); + + sibling->name = mod->name; + EXPECT_EQ(sibling->name.str(), "\\zz_renamed"); + + EXPECT_EQ(PooledName(mod->name).str(), "\\zz_renamed"); +} + +TEST(OwnedIdTest, MakePair) +{ + OwnedIdFixture f; + + auto left = make_pair(f.wire->name, 7); + auto right = make_pair(7, f.wire->name); + auto both = make_pair(f.wire->name, f.cell->type); + + EXPECT_TRUE((std::is_same_v)); + EXPECT_TRUE((std::is_same_v)); + EXPECT_TRUE((std::is_same_v)); + EXPECT_TRUE((std::is_same_v)); + + EXPECT_EQ(left.first, f.wire->name.ref()); + EXPECT_EQ(left.second, 7); + EXPECT_EQ(right.first, 7); + EXPECT_EQ(right.second, f.wire->name.ref()); + EXPECT_EQ(both.first, f.wire->name.ref()); + EXPECT_EQ(both.second, f.cell->type.ref()); +} + +YOSYS_NAMESPACE_END diff --git a/chips/yosys/tests/unit/kernel/perfHelpers.h b/chips/yosys/tests/unit/kernel/perfHelpers.h new file mode 100644 index 0000000000000000000000000000000000000000..d77692aa9b448bd52a06b0f2d89806709476980b --- /dev/null +++ b/chips/yosys/tests/unit/kernel/perfHelpers.h @@ -0,0 +1,65 @@ +#ifndef PERF_HELPERS_H +#define PERF_HELPERS_H + +#include +#include +#include + +#if defined(__linux__) || defined(__FreeBSD__) +# include +# include +#endif + +#include "kernel/yosys.h" + +YOSYS_NAMESPACE_BEGIN + +inline int env_int(const char *name, int fallback) +{ + const char *value = getenv(name); + if (value == nullptr || *value == 0) + return fallback; + return atoi(value); +} + +inline size_t rss_bytes() +{ +#if defined(__linux__) || defined(__FreeBSD__) + size_t total_pages = 0, resident_pages = 0; + FILE *f = fopen("/proc/self/statm", "r"); + if (f == nullptr) + return 0; + if (fscanf(f, "%zu %zu", &total_pages, &resident_pages) != 2) + resident_pages = 0; + fclose(f); + return resident_pages * (size_t)sysconf(_SC_PAGESIZE); +#else + return 0; +#endif +} + +inline size_t peak_rss_bytes() +{ +#if defined(__linux__) || defined(__FreeBSD__) + struct rusage ru; + if (getrusage(RUSAGE_SELF, &ru) != 0) + return 0; + return (size_t)ru.ru_maxrss * 1024; +#else + return 0; +#endif +} + +inline double mb(size_t bytes) +{ + return bytes / 1048576.0; +} + +inline double ms(std::chrono::steady_clock::duration d) +{ + return std::chrono::duration(d).count(); +} + +YOSYS_NAMESPACE_END + +#endif diff --git a/chips/yosys/tests/unit/kernel/pooledNameTest.cc b/chips/yosys/tests/unit/kernel/pooledNameTest.cc new file mode 100644 index 0000000000000000000000000000000000000000..ab22386515da045e620376e8ad96f4a872abbdc9 --- /dev/null +++ b/chips/yosys/tests/unit/kernel/pooledNameTest.cc @@ -0,0 +1,84 @@ +#include + +#include "kernel/rtlil.h" +#include "kernel/yosys.h" + +YOSYS_NAMESPACE_BEGIN + +TEST(PooledNameTest, OwnPool) +{ + TwinePool pool; + IdString pub = pool.add(std::string("\\zz_alpha")); + IdString priv = pool.add(std::string("$zz_beta")); + + PooledName a(&pool, pub); + PooledName b(&pool, priv); + + EXPECT_EQ(a.str(), "\\zz_alpha"); + EXPECT_EQ(a.unescape(), "zz_alpha"); + EXPECT_TRUE(a.isPublic()); + EXPECT_EQ(b.str(), "$zz_beta"); + EXPECT_EQ(b.unescape(), "$zz_beta"); + EXPECT_FALSE(b.isPublic()); +} + +TEST(PooledNameTest, DivergedPools) +{ + TwinePool pool_a; + TwinePool pool_b; + pool_b.add(std::string("\\zz_filler")); + + IdString in_a = pool_a.add(std::string("\\zz_shared")); + IdString in_b = pool_b.add(std::string("\\zz_shared")); + ASSERT_NE(in_a, in_b); + + PooledName a(&pool_a, in_a); + PooledName b(&pool_b, in_b); + + EXPECT_EQ(a.str(), b.str()); + EXPECT_NE(a.ref(), b.ref()); + EXPECT_FALSE(a == b); +} + +TEST(PooledNameTest, PoollessConstids) +{ + PooledName kind(ID($state)); + EXPECT_EQ(kind.str(), "$state"); + EXPECT_EQ(kind.unescape(), "$state"); + EXPECT_TRUE(kind == ID($state)); +} + +TEST(PooledNameTest, PoollessLookup) +{ + TwinePool pool; + IdString ref = pool.add(std::string("\\zz_gamma")); + + dict by_name; + by_name[PooledName(&pool, ref)] = 7; + + EXPECT_EQ(by_name.at(PooledName(ref)), 7); + EXPECT_EQ(by_name.at(PooledName(&pool, ref)), 7); +} + +TEST(PooledNameTest, FromMasqs) +{ + Design design; + Module *mod = design.addModule(std::string("\\zz_top")); + Wire *w = mod->addWire(std::string("\\zz_wire"), 1); + Cell *cell = mod->addCell(std::string("\\zz_cell"), ID($and)); + + EXPECT_EQ(PooledName(mod->name).str(), "\\zz_top"); + EXPECT_EQ(PooledName(w->name).str(), "\\zz_wire"); + EXPECT_EQ(PooledName(cell->name).unescape(), "zz_cell"); + EXPECT_EQ(PooledName(cell->type).str(), "$and"); +} + +TEST(PooledNameTest, NullName) +{ + PooledName none; + EXPECT_TRUE(none.empty()); + EXPECT_EQ(none.str(), ""); + EXPECT_EQ(none.unescape(), ""); +} + +YOSYS_NAMESPACE_END diff --git a/chips/yosys/tests/unit/kernel/rtlilHelpers.h b/chips/yosys/tests/unit/kernel/rtlilHelpers.h new file mode 100644 index 0000000000000000000000000000000000000000..99585f23b13b58403919bac5bce45394f75928c7 --- /dev/null +++ b/chips/yosys/tests/unit/kernel/rtlilHelpers.h @@ -0,0 +1,71 @@ +#ifndef RTLIL_HELPERS_H +#define RTLIL_HELPERS_H + +#include + +#include "kernel/rtlil.h" + +YOSYS_NAMESPACE_BEGIN + +class SigSpecRepTest : public ::testing::Test { +protected: + Design* d; + Module* m; + + void SetUp() override { + d = new Design; + m = d->addModule("$test"); + } + + void TearDown() override { + delete d; + } + + // Create n wires with given width + std::vector createWires(int count, int width = 4) { + std::vector wires; + for (int i = 0; i < count; i++) { + Wire* w = m->addWire(stringf("$w%d", i), width); + wires.push_back(w); + } + return wires; + } + + // Append all wires to a SigSpec + SigSpec wiresAsSigSpec(const std::vector& wires) { + SigSpec sig; + for (auto w : wires) + sig.append(w); + return sig; + } + + // Create a SigSpec of constants + SigSpec constsAsSigSpec(int count, int width = 4) { + SigSpec sig; + for (int i = 0; i < count; i++) + sig.append(Const(i, width)); + return sig; + } + + // Convert wires to pool of SigBits + pool wiresToPool(const std::vector& wires) { + pool pool; + for (auto w : wires) + for (auto &bit : SigSpec(w)) + pool.insert(bit); + return pool; + } + + // Convert wires to set of SigBits + std::set wiresToSet(const std::vector& wires) { + std::set set; + for (auto w : wires) + for (auto &bit : SigSpec(w)) + set.insert(bit); + return set; + } +}; + +YOSYS_NAMESPACE_END + +#endif /* RTLIL_HELPERS_H */ diff --git a/chips/yosys/tests/unit/kernel/rtlilStringTest.cc b/chips/yosys/tests/unit/kernel/rtlilStringTest.cc new file mode 100644 index 0000000000000000000000000000000000000000..e15cf3170c716710418cee1a8b5baffdd1671ba6 --- /dev/null +++ b/chips/yosys/tests/unit/kernel/rtlilStringTest.cc @@ -0,0 +1,75 @@ +#include + +#include "kernel/rtlil.h" +#include "kernel/yosys.h" + +YOSYS_NAMESPACE_BEGIN + +namespace RTLIL { + + TEST(RtlilStrTest, DesignToString) { + Design design; + Module *mod = design.addModule("\\my_module"); + mod->addWire("\\my_wire", 1); + + std::string design_str = design.to_rtlil_str(); + + EXPECT_NE(design_str.find("module \\my_module"), std::string::npos); + EXPECT_NE(design_str.find("end"), std::string::npos); + } + + TEST(RtlilStrTest, ModuleToString) { + Design design; + Module *mod = design.addModule("\\test_mod"); + Wire *wire = mod->addWire("\\clk", 1); + wire->port_input = true; + + std::string mod_str = mod->to_rtlil_str(); + + EXPECT_NE(mod_str.find("module \\test_mod"), std::string::npos); + EXPECT_NE(mod_str.find("wire"), std::string::npos); + EXPECT_NE(mod_str.find("\\clk"), std::string::npos); + EXPECT_NE(mod_str.find("input"), std::string::npos); + } + + TEST(RtlilStrTest, WireToString) { + Design design; + Module *mod = design.addModule("\\m"); + Wire *wire = mod->addWire("\\data", 8); + + std::string wire_str = wire->to_rtlil_str(); + + EXPECT_NE(wire_str.find("wire"), std::string::npos); + EXPECT_NE(wire_str.find("width 8"), std::string::npos); + EXPECT_NE(wire_str.find("\\data"), std::string::npos); + } + + TEST(RtlilStrTest, CellToString) { + Design design; + Module *mod = design.addModule("\\m"); + Cell *cell = mod->addCell("\\u1", design.twines().add("\\my_cell_type")); + + std::string cell_str = cell->to_rtlil_str(); + + EXPECT_NE(cell_str.find("cell"), std::string::npos); + EXPECT_NE(cell_str.find("\\my_cell_type"), std::string::npos); + EXPECT_NE(cell_str.find("\\u1"), std::string::npos); + } + + TEST(RtlilStrTest, StringViewNames) { + Design design; + std::string_view buf = "\\m\\w\\u\\t"; + Module *mod = design.addModule(buf.substr(0, 2)); + Wire *wire = mod->addWire(buf.substr(2, 2), 4); + Cell *cell = mod->addCell(buf.substr(4, 2), buf.substr(6, 2)); + + EXPECT_EQ(design.module(std::string_view("\\m")), mod); + EXPECT_EQ(mod->wire(std::string_view("\\w")), wire); + EXPECT_EQ(mod->cell(std::string_view("\\u")), cell); + EXPECT_EQ(cell->type, design.twines().find(std::string_view("\\t"))); + EXPECT_NE(mod->to_rtlil_str().find("cell \\t \\u"), std::string::npos); + } + +} + +YOSYS_NAMESPACE_END diff --git a/chips/yosys/tests/unit/kernel/rtlilTest.cc b/chips/yosys/tests/unit/kernel/rtlilTest.cc new file mode 100644 index 0000000000000000000000000000000000000000..ca22810917b244cf792f0287eebcf11b1bbf83a9 --- /dev/null +++ b/chips/yosys/tests/unit/kernel/rtlilTest.cc @@ -0,0 +1,517 @@ +#include +#include +#include "kernel/rtlil.h" + +YOSYS_NAMESPACE_BEGIN + +namespace RTLIL { + + struct SafePrintToStringParamName { + template + std::string operator()(const testing::TestParamInfo& info) const { + std::string name = testing::PrintToString(info.param); + for (auto &c : name) + if (!('0' <= c && c <= '9') && !('a' <= c && c <= 'z') && !('A' <= c && c <= 'Z') ) c = '_'; + return name; + } + }; + + class KernelRtlilTest : public testing::Test { + protected: + KernelRtlilTest() { + if (logger().empty()) logger().add_sink(); + } + virtual void SetUp() override { + StaticTwines::init(); + } + }; + + TEST_F(KernelRtlilTest, ConstAssignCompare) + { + Const c1; + Const c2; + c2 = c1; + Const c3(c2); + EXPECT_TRUE(c2 == c3); + EXPECT_FALSE(c2 < c3); + } + + TEST_F(KernelRtlilTest, ConstConvertibleToInt) { + // A Const whose minimal unsigned size is exactly 32 bits (bit 31 set) + // but whose full width is larger must not be reported as convertible + // to a (signed) int when treated as unsigned + { + // 33 bits: bits 0..31 = 1, bit 32 = 0 => value 0xffffffff + std::vector v(33, S1); + v[32] = S0; + Const c(v); + EXPECT_FALSE(c.convertible_to_int(false)); + EXPECT_EQ(c.as_int_saturating(false), std::numeric_limits::max()); + EXPECT_FALSE(c.convertible_to_int(true)); + EXPECT_EQ(c.as_int_saturating(true), std::numeric_limits::max()); + } + + { + // 32-bit unsigned 0x7fffffff fits in a signed int + std::vector v(32, S1); + v[31] = S0; + Const c(v); + EXPECT_TRUE(c.convertible_to_int(false)); + EXPECT_EQ(c.as_int(false), 0x7fffffff); + } + + { + // 32-bit unsigned 0xffffffff does not fit in a signed int + std::vector v(32, S1); + Const c(v); + EXPECT_FALSE(c.convertible_to_int(false)); + EXPECT_EQ(c.as_int_saturating(false), std::numeric_limits::max()); + } + } + + TEST_F(KernelRtlilTest, ConstStr) { + // We have multiple distinct sections since it's annoying + // to list multiple testcases as friends of Const in kernel/rtlil.h + { + std::string foo = "foo"; + Const c1 = foo; + Const c2; + c2 = c1; + Const c3(c2); + EXPECT_TRUE(c1.is_str()); + EXPECT_TRUE(c2.is_str()); + EXPECT_TRUE(c3.is_str()); + } + + { + // A binary constant is bitvec backed + Const cb1(0, 10); + Const cb2(1, 10); + Const cb3(cb2); + std::vector v1 {false, true}; + std::vector v2 {State::S0, State::S1}; + Const cb4(v1); + Const cb5(v2); + EXPECT_TRUE(cb4 == cb5); + EXPECT_TRUE(cb1.is_bits()); + EXPECT_TRUE(cb2.is_bits()); + EXPECT_TRUE(cb3.is_bits()); + EXPECT_TRUE(cb4.is_bits()); + EXPECT_TRUE(cb5.is_bits()); + EXPECT_EQ(cb1.size(), 10); + EXPECT_EQ(cb2.size(), 10); + EXPECT_EQ(cb3.size(), 10); + } + + { + // A string constructed Const starts off packed + std::string foo = "foo"; + Const cs1 = foo; + EXPECT_TRUE(cs1.is_str()); + + // It can be iterated without mutating + int i = 0; + for (auto bit : cs1) { + i += bit; + } + EXPECT_EQ(i, 16); + EXPECT_TRUE(cs1.is_str()); + + // It can be mutated via bit iteration and decays into unpacked + // when an non-defined bit is set. + for (auto b : cs1) { + b = State::Sx; + } + EXPECT_TRUE(cs1.is_bits()); + } + + { + Const c(0x12345678); + EXPECT_TRUE(c.is_str()); + EXPECT_EQ(c.as_int(), 0x12345678); + EXPECT_TRUE(c.is_str()); + } + + { + Const c(0xab, 8); + EXPECT_TRUE(c.is_str()); + EXPECT_EQ(c.as_int(), 0xab); + EXPECT_TRUE(c.is_str()); + } + + { + Const c(0x12345678, 80); + EXPECT_TRUE(c.is_str()); + EXPECT_EQ(c.as_int(), 0x12345678); + EXPECT_EQ(c[79], S0); + EXPECT_TRUE(c.is_str()); + } + + { + Const c(-1, 80); + EXPECT_TRUE(c.is_str()); + EXPECT_EQ(c.as_int(), -1); + EXPECT_EQ(c[79], S1); + EXPECT_TRUE(c.is_str()); + } + + { + Const c(1 << 24); + EXPECT_TRUE(c.is_str()); + EXPECT_TRUE(c.as_bool()); + EXPECT_TRUE(c.is_str()); + } + + { + Const c(0x2, 8); + EXPECT_TRUE(c.is_str()); + EXPECT_EQ(c.as_string(), "00000010"); + EXPECT_TRUE(c.is_str()); + } + + { + Const c(" "); + EXPECT_TRUE(c.is_str()); + EXPECT_EQ(c.decode_string(), " "); + EXPECT_TRUE(c.is_str()); + } + + { + Const c(" "); + EXPECT_TRUE(c.is_str()); + EXPECT_EQ(c.decode_string(), " "); + EXPECT_TRUE(c.is_str()); + } + + { + std::vector v = {S0, S0, S0, S0, S0, S1, S0, S0}; + Const c(v); + EXPECT_EQ(c.decode_string(), " "); + } + + { + std::vector v = {S0, S0, S0, S0, S0, S1, S0, Sx}; + Const c(v); + EXPECT_EQ(c.decode_string(), " "); + } + + { + Const c(" "); + EXPECT_TRUE(c.is_str()); + EXPECT_FALSE(c.is_fully_zero()); + EXPECT_TRUE(c.is_str()); + } + + { + Const c(" "); + EXPECT_TRUE(c.is_str()); + EXPECT_FALSE(c.is_fully_ones()); + EXPECT_TRUE(c.is_str()); + } + + { + Const c(" "); + EXPECT_TRUE(c.is_str()); + EXPECT_TRUE(c.is_fully_def()); + EXPECT_TRUE(c.is_str()); + } + + { + Const c(" "); + EXPECT_TRUE(c.is_str()); + EXPECT_FALSE(c.is_fully_undef()); + EXPECT_TRUE(c.is_str()); + } + + { + Const c(" "); + EXPECT_TRUE(c.is_str()); + EXPECT_FALSE(c.is_fully_undef_x_only()); + EXPECT_TRUE(c.is_str()); + } + + { + Const c(" "); + EXPECT_TRUE(c.is_str()); + int pos; + EXPECT_TRUE(c.is_onehot(&pos)); + EXPECT_EQ(pos, 5); + EXPECT_TRUE(c.is_str()); + } + } + + TEST_F(KernelRtlilTest, ConstConstIteratorWorks) { + const Const c(0x2, 2); + Const::const_iterator it = c.begin(); + ASSERT_NE(it, c.end()); + EXPECT_EQ(*it, State::S0); + ++it; + ASSERT_NE(it, c.end()); + EXPECT_EQ(*it, State::S1); + ++it; + EXPECT_EQ(it, c.end()); + } + + TEST_F(KernelRtlilTest, ConstConstIteratorPreincrement) { + const Const c(0x2, 2); + Const::const_iterator it = c.begin(); + EXPECT_EQ(*++it, State::S1); + } + + TEST_F(KernelRtlilTest, ConstConstIteratorPostincrement) { + const Const c(0x2, 2); + Const::const_iterator it = c.begin(); + EXPECT_EQ(*it++, State::S0); + } + + TEST_F(KernelRtlilTest, ConstIteratorWorks) { + Const c(0x2, 2); + Const::iterator it = c.begin(); + ASSERT_NE(it, c.end()); + EXPECT_EQ(*it, State::S0); + ++it; + ASSERT_NE(it, c.end()); + EXPECT_EQ(*it, State::S1); + ++it; + ASSERT_EQ(it, c.end()); + } + + TEST_F(KernelRtlilTest, ConstIteratorPreincrement) { + Const c(0x2, 2); + Const::iterator it = c.begin(); + EXPECT_EQ(*++it, State::S1); + } + + TEST_F(KernelRtlilTest, ConstIteratorPostincrement) { + Const c(0x2, 2); + Const::iterator it = c.begin(); + EXPECT_EQ(*it++, State::S0); + } + + TEST_F(KernelRtlilTest, ConstIteratorWriteWorks) { + Const c(0x2, 2); + Const::iterator it = c.begin(); + EXPECT_EQ(*it, State::S0); + *it = State::S1; + EXPECT_EQ(*it, State::S1); + } + + TEST_F(KernelRtlilTest, ConstBuilder) { + Const::Builder b; + EXPECT_EQ(GetSize(b), 0); + b.push_back(S0); + EXPECT_EQ(GetSize(b), 1); + b.push_back(S1); + EXPECT_EQ(GetSize(b), 2); + EXPECT_EQ(b.build(), Const(0x2, 2)); + } + + TEST_F(KernelRtlilTest, ConstSet) { + Const c(0x2, 2); + c.set(0, S1); + EXPECT_EQ(c, Const(0x3, 2)); + } + + TEST_F(KernelRtlilTest, ConstResize) { + Const c(0x2, 2); + c.resize(4, S1); + EXPECT_EQ(c, Const(0xe, 4)); + } + + TEST_F(KernelRtlilTest, ConstResizeWidthLimit) { + Const c; + EXPECT_DEATH(c.resize(RTLIL::WIDTH_LIMIT, Sx), ""); + EXPECT_NO_FATAL_FAILURE(c.resize(RTLIL::WIDTH_LIMIT - 1, Sx)); + } + + TEST_F(KernelRtlilTest, ConstFromLongLongWidthLimit) { + EXPECT_DEATH(Const(0, RTLIL::WIDTH_LIMIT), ""); + EXPECT_NO_FATAL_FAILURE(Const(0, RTLIL::WIDTH_LIMIT - 1)); + } + + TEST_F(KernelRtlilTest, ConstFromStateWidthLimit) { + EXPECT_DEATH(Const(Sx, RTLIL::WIDTH_LIMIT), ""); + EXPECT_NO_FATAL_FAILURE(Const(Sx, RTLIL::WIDTH_LIMIT - 1)); + } + + TEST_F(KernelRtlilTest, ModuleAddWireWidthLimit) { + std::unique_ptr design = std::make_unique(); + Module *mod = design->addModule("$test_mod"); + EXPECT_DEATH(mod->addWire("\\test", RTLIL::WIDTH_LIMIT), ""); + EXPECT_NO_FATAL_FAILURE(mod->addWire("\\test2", RTLIL::WIDTH_LIMIT - 1)); + } + + TEST_F(KernelRtlilTest, ConstEqualStr) { + EXPECT_EQ(Const("abc"), Const("abc")); + EXPECT_NE(Const("abc"), Const("def")); + } + + TEST_F(KernelRtlilTest, ConstEqualBits) { + std::vector v1 = {S0, S1}; + std::vector v2 = {S1, S0}; + EXPECT_EQ(Const(v1), Const(v1)); + EXPECT_NE(Const(v1), Const(v2)); + } + + TEST_F(KernelRtlilTest, ConstEqualStrBits) { + std::vector v1 = {S0, S0, S0, S0, S0, S1, S0, S0}; + EXPECT_EQ(Const(v1), Const(" ")); + EXPECT_NE(Const(v1), Const("a")); + } + + static Hasher::hash_t hash(const Const &c) { + Hasher h; + h = c.hash_into(h); + return h.yield(); + } + + TEST_F(KernelRtlilTest, ConstEqualHashStrBits) { + std::vector v1 = {S0, S0, S0, S0, S0, S1, S0, S0}; + EXPECT_EQ(hash(Const(v1)), hash(Const(" "))); + EXPECT_NE(hash(Const(v1)), hash(Const("a"))); + } + + TEST_F(KernelRtlilTest, ConstIsFullyZero) { + EXPECT_TRUE(Const(0, 8).is_fully_zero()); + EXPECT_FALSE(Const(8, 8).is_fully_zero()); + EXPECT_TRUE(Const().is_fully_zero()); + } + + TEST_F(KernelRtlilTest, ConstIsFullyOnes) { + EXPECT_TRUE(Const(0xf, 4).is_fully_ones()); + EXPECT_FALSE(Const(3, 4).is_fully_ones()); + EXPECT_TRUE(Const().is_fully_ones()); + } + + TEST_F(KernelRtlilTest, ConstIsFullyDef) { + EXPECT_TRUE(Const(0xf, 4).is_fully_def()); + std::vector v1 = {S0, Sx}; + EXPECT_FALSE(Const(v1).is_fully_def()); + EXPECT_TRUE(Const().is_fully_def()); + } + + TEST_F(KernelRtlilTest, ConstIsFullyUndef) { + std::vector v1 = {S0, Sx}; + EXPECT_FALSE(Const(v1).is_fully_undef()); + EXPECT_TRUE(Const(Sz, 2).is_fully_undef()); + EXPECT_TRUE(Const().is_fully_undef()); + } + + TEST_F(KernelRtlilTest, ConstIsFullyUndefXOnly) { + std::vector v1 = {Sx, Sz}; + EXPECT_FALSE(Const(v1).is_fully_undef_x_only()); + EXPECT_TRUE(Const(Sx, 2).is_fully_undef_x_only()); + EXPECT_TRUE(Const().is_fully_undef_x_only()); + } + + TEST_F(KernelRtlilTest, ConstIsOnehot) { + int pos; + EXPECT_TRUE(Const(0x80, 8).is_onehot(&pos)); + EXPECT_EQ(pos, 7); + EXPECT_FALSE(Const(0x82, 8).is_onehot(&pos)); + EXPECT_FALSE(Const(0, 8).is_onehot(&pos)); + EXPECT_TRUE(Const(1, 1).is_onehot(&pos)); + EXPECT_EQ(pos, 0); + EXPECT_FALSE(Const(Sx, 1).is_onehot(&pos)); + std::vector v1 = {Sx, S1}; + EXPECT_FALSE(Const(v1).is_onehot(&pos)); + EXPECT_FALSE(Const().is_onehot(&pos)); + } + + TEST_F(KernelRtlilTest, LookupAutoidxId) { + TwinePool twines; + IdString id = twines.add(NEW_ID); + EXPECT_EQ(twines.find(twines.str(id)), id); + } + + TEST_F(KernelRtlilTest, NewIdBeginsWith) { + TwinePool twines; + std::string id = twines.str(twines.add(NEW_ID)); + EXPECT_TRUE(id.starts_with("$auto")); + EXPECT_FALSE(id.starts_with("xyz")); + EXPECT_TRUE(id.starts_with("$auto$")); + EXPECT_FALSE(id.starts_with("abcdefghijklmn")); + EXPECT_TRUE(id.starts_with("$auto$rtlilTest")); + EXPECT_FALSE(id.starts_with("$auto$rtlilX")); + } + + class WireRtlVsHdlIndexConversionTest : + public KernelRtlilTest, + public testing::WithParamInterface> + {}; + + INSTANTIATE_TEST_SUITE_P( + WireRtlVsHdlIndexConversionInstance, + WireRtlVsHdlIndexConversionTest, + testing::Values( + std::make_tuple(false, 0, 10), + std::make_tuple(true, 0, 10), + std::make_tuple(false, 4, 10), + std::make_tuple(true, 4, 10), + std::make_tuple(false, -4, 10), + std::make_tuple(true, -4, 10), + std::make_tuple(false, 0, 1), + std::make_tuple(true, 0, 1), + std::make_tuple(false, 4, 1), + std::make_tuple(true, 4, 1), + std::make_tuple(false, -4, 1), + std::make_tuple(true, -4, 1) + ), + SafePrintToStringParamName() + ); + + TEST_P(WireRtlVsHdlIndexConversionTest, WireRtlVsHdlIndexConversion) { + std::unique_ptr design = std::make_unique(); + Module *mod = design->addModule("$test_mod"); + Wire *wire = mod->addWire("\\test", 10); + + auto [upto, start_offset, width] = GetParam(); + + wire->upto = upto; + wire->start_offset = start_offset; + wire->width = width; + + int smallest = INT_MAX; + int largest = INT_MIN; + + for (int i = 0; i < wire->width; i++) { + int j = wire->to_hdl_index(i); + smallest = std::min(smallest, j); + largest = std::max(largest, j); + EXPECT_EQ( + std::make_pair(wire->from_hdl_index(j), j), + std::make_pair(i, wire->to_hdl_index(i)) + ); + } + + EXPECT_EQ(smallest, start_offset); + EXPECT_EQ(largest, start_offset + wire->width - 1); + + for (int i = 1; i < wire->width; i++) { + EXPECT_EQ( + wire->to_hdl_index(i) - wire->to_hdl_index(i - 1), + upto ? -1 : 1 + ); + } + + for (int j = smallest; j < largest; j++) { + int i = wire->from_hdl_index(j); + EXPECT_EQ( + std::make_pair(wire->from_hdl_index(j), j), + std::make_pair(i, wire->to_hdl_index(i)) + ); + } + + for (int i = -10; i < 0; i++) + EXPECT_EQ(wire->to_hdl_index(i), INT_MIN); + for (int i = wire->width; i < wire->width + 10; i++) + EXPECT_EQ(wire->to_hdl_index(i), INT_MIN); + for (int j = smallest - 10; j < smallest; j++) + EXPECT_EQ(wire->from_hdl_index(j), INT_MIN); + for (int j = largest + 1; j < largest + 11; j++) + EXPECT_EQ(wire->from_hdl_index(j), INT_MIN); + } + +} + +YOSYS_NAMESPACE_END diff --git a/chips/yosys/tests/unit/kernel/sigbitPerfTest.cc b/chips/yosys/tests/unit/kernel/sigbitPerfTest.cc new file mode 100644 index 0000000000000000000000000000000000000000..7574f463780532cfeab2571ce259442ef9f3b8d9 --- /dev/null +++ b/chips/yosys/tests/unit/kernel/sigbitPerfTest.cc @@ -0,0 +1,133 @@ +#include + +#include +#include + +#include "kernel/rtlil.h" +#include "kernel/sigtools.h" +#include "kernel/yosys.h" +#include "perfHelpers.h" + +YOSYS_NAMESPACE_BEGIN + +namespace { + +uint32_t next_rand(uint32_t &state) +{ + state = state * 1664525u + 1013904223u; + return state >> 8; +} + +std::string padded(const char *stem, int index, int extra_chars) +{ + std::string name = stringf("\\%s_%d", stem, index); + name += std::string(extra_chars, 'n'); + return name; +} + +} + +TEST(SigBitPerf, hash_and_sigmap_stress) +{ + int wire_count = env_int("YOSYS_SIGBIT_PERF_WIRES", 4000); + int wire_width = env_int("YOSYS_SIGBIT_PERF_WIDTH", 16); + int alias_every = env_int("YOSYS_SIGBIT_PERF_ALIAS", 4); + int probe_rounds = env_int("YOSYS_SIGBIT_PERF_ROUNDS", 20); + int name_padding = env_int("YOSYS_SIGBIT_PERF_NAMEPAD", 24); + + ASSERT_GE(wire_count, 2); + ASSERT_GE(wire_width, 1); + ASSERT_GE(alias_every, 2); + ASSERT_GE(probe_rounds, 1); + + RTLIL::Design *design = new RTLIL::Design; + RTLIL::Module *module = design->addModule(padded("sigbit_perf_module", 0, name_padding)); + + std::vector wires; + wires.reserve(wire_count); + for (int i = 0; i < wire_count; i++) + wires.push_back(module->addWire(padded("sigbit_perf_wire", i, name_padding), wire_width)); + + int aliased = 0; + for (int i = alias_every; i < wire_count; i += alias_every) { + module->connect(RTLIL::SigSpec(wires[i]), RTLIL::SigSpec(wires[i - 1])); + aliased++; + } + + std::vector bits; + bits.reserve((size_t)wire_count * wire_width); + for (RTLIL::Wire *wire : wires) + for (int i = 0; i < wire_width; i++) + bits.push_back(RTLIL::SigBit(wire, i)); + + uint32_t rng = 12345; + std::vector probes = bits; + for (size_t i = probes.size(); i > 1; i--) + std::swap(probes[i - 1], probes[next_rand(rng) % i]); + + size_t rss_before = peak_rss_bytes(); + + auto t0 = std::chrono::steady_clock::now(); + SigMap sigmap(module); + auto t1 = std::chrono::steady_clock::now(); + + size_t sigmap_checksum = 0; + for (int round = 0; round < probe_rounds; round++) + for (const RTLIL::SigBit &bit : probes) + sigmap_checksum += sigmap(bit).offset; + auto t2 = std::chrono::steady_clock::now(); + + pool seen; + for (int round = 0; round < probe_rounds; round++) { + seen.clear(); + for (const RTLIL::SigBit &bit : probes) + seen.insert(bit); + } + auto t3 = std::chrono::steady_clock::now(); + + size_t hits = 0; + for (int round = 0; round < probe_rounds; round++) + for (const RTLIL::SigBit &bit : probes) + hits += seen.count(bit); + auto t4 = std::chrono::steady_clock::now(); + + dict owner; + for (int round = 0; round < probe_rounds; round++) { + owner.clear(); + int n = 0; + for (const RTLIL::SigBit &bit : probes) + owner[bit] = n++; + } + auto t5 = std::chrono::steady_clock::now(); + + size_t dict_checksum = 0; + for (int round = 0; round < probe_rounds; round++) + for (const RTLIL::SigBit &bit : probes) + dict_checksum += owner.at(bit); + auto t6 = std::chrono::steady_clock::now(); + + size_t bit_count = probes.size(); + size_t ops = bit_count * (size_t)probe_rounds; + + EXPECT_EQ(seen.size(), bit_count); + EXPECT_EQ(owner.size(), bit_count); + EXPECT_EQ(hits, ops); + + printf("[ PERF ] wires=%d width=%d alias_every=%d aliased=%d namepad=%d rounds=%d\n", + wire_count, wire_width, alias_every, aliased, name_padding, probe_rounds); + printf("[ PERF ] bits=%zu ops_per_phase=%zu checksums=%zu,%zu\n", + bit_count, ops, sigmap_checksum, dict_checksum); + printf("[ PERF ] sigmap_build_ms=%.1f sigmap_lookup_ns=%.2f\n", + ms(t1 - t0), 1e6 * ms(t2 - t1) / (double)ops); + printf("[ PERF ] pool_insert_ns=%.2f pool_lookup_ns=%.2f\n", + 1e6 * ms(t3 - t2) / (double)ops, 1e6 * ms(t4 - t3) / (double)ops); + printf("[ PERF ] dict_insert_ns=%.2f dict_lookup_ns=%.2f\n", + 1e6 * ms(t5 - t4) / (double)ops, 1e6 * ms(t6 - t5) / (double)ops); + printf("[ PERF ] total_ms=%.1f peak_rss_mb=%.1f rss_before_mb=%.1f\n", + ms(t6 - t0), mb(peak_rss_bytes()), mb(rss_before)); + fflush(stdout); + + delete design; +} + +YOSYS_NAMESPACE_END diff --git a/chips/yosys/tests/unit/kernel/sigspecExtractTest.cc b/chips/yosys/tests/unit/kernel/sigspecExtractTest.cc new file mode 100644 index 0000000000000000000000000000000000000000..87bd4f6da21fe58364a1168b1fcccda7aa78fc27 --- /dev/null +++ b/chips/yosys/tests/unit/kernel/sigspecExtractTest.cc @@ -0,0 +1,89 @@ +#include + +#include "kernel/rtlil.h" +#include "tests/unit/kernel/rtlilHelpers.h" + +YOSYS_NAMESPACE_BEGIN + +namespace RTLIL { + TEST_F(SigSpecRepTest, Extract) + { + { + std::vector wires; + SigSpec sig; + for (int i = 0; i < 4; i++) + wires.push_back(m->addWire(stringf("$w%d", i), 4)); + for (auto w : wires) + sig.append(w); + + SigSpec extractedFirst = sig.extract(0, 4); + SigSpec extractedSecond = sig.extract(4, 4); + SigSpec extractedLast = sig.extract(12, 4); + EXPECT_EQ(extractedFirst.rep_, SigSpec::Representation::CHUNK); + EXPECT_EQ(extractedSecond.rep_, SigSpec::Representation::CHUNK); + EXPECT_EQ(extractedLast.rep_, SigSpec::Representation::CHUNK); + EXPECT_EQ(extractedFirst.as_wire(), wires[0]); + EXPECT_EQ(extractedSecond.as_wire(), wires[1]); + EXPECT_EQ(extractedLast.as_wire(), wires[3]); + } + + { + std::vector consts; + SigSpec sig; + for (int i = 0; i < 4; i++) + consts.push_back(Const(i, 4)); + for (auto c : consts) + sig.append(c); + + SigSpec extractedFirst = sig.extract(0, 4); + SigSpec extractedSecond = sig.extract(4, 4); + SigSpec extractedLast = sig.extract(12, 4); + EXPECT_EQ(extractedFirst.rep_, SigSpec::Representation::CHUNK); + EXPECT_EQ(extractedSecond.rep_, SigSpec::Representation::CHUNK); + EXPECT_EQ(extractedLast.rep_, SigSpec::Representation::CHUNK); + EXPECT_EQ(extractedFirst, consts[0]); + EXPECT_EQ(extractedSecond, consts[1]); + EXPECT_EQ(extractedLast, consts[3]); + } + + { + SigSpec sig; + sig.append(Const(0, 4)); + Wire* w = m->addWire("$foo", 4); + sig.append(w); + sig.append(Const(15, 4)); + + SigSpec extractedFirst = sig.extract(0, 4); + SigSpec extractedSecond = sig.extract(4, 4); + SigSpec extractedLast = sig.extract(8, 4); + EXPECT_EQ(extractedFirst.rep_, SigSpec::Representation::CHUNK); + EXPECT_EQ(extractedSecond.rep_, SigSpec::Representation::CHUNK); + EXPECT_EQ(extractedLast.rep_, SigSpec::Representation::CHUNK); + + SigSpec extractedFirstTwo = sig.extract(0, 8); + EXPECT_EQ(extractedFirstTwo.rep_, SigSpec::Representation::BITS); + SigSpec extractedLastTwo = sig.extract(4, 8); + EXPECT_EQ(extractedLastTwo.rep_, SigSpec::Representation::BITS); + + EXPECT_EQ(extractedFirstTwo[0], State::S0); + EXPECT_EQ(extractedFirstTwo[1], State::S0); + EXPECT_EQ(extractedFirstTwo[2], State::S0); + EXPECT_EQ(extractedFirstTwo[3], State::S0); + EXPECT_EQ(extractedFirstTwo[4], SigBit(w, 0)); + EXPECT_EQ(extractedFirstTwo[5], SigBit(w, 1)); + EXPECT_EQ(extractedFirstTwo[6], SigBit(w, 2)); + EXPECT_EQ(extractedFirstTwo[7], SigBit(w, 3)); + + EXPECT_EQ(extractedLastTwo[0], SigBit(w, 0)); + EXPECT_EQ(extractedLastTwo[1], SigBit(w, 1)); + EXPECT_EQ(extractedLastTwo[2], SigBit(w, 2)); + EXPECT_EQ(extractedLastTwo[3], SigBit(w, 3)); + EXPECT_EQ(extractedLastTwo[4], State::S1); + EXPECT_EQ(extractedLastTwo[5], State::S1); + EXPECT_EQ(extractedLastTwo[6], State::S1); + EXPECT_EQ(extractedLastTwo[7], State::S1); + } + } +}; + +YOSYS_NAMESPACE_END diff --git a/chips/yosys/tests/unit/kernel/sigspecRemove2Test.cc b/chips/yosys/tests/unit/kernel/sigspecRemove2Test.cc new file mode 100644 index 0000000000000000000000000000000000000000..9d7bf4863450f7e94f80b54f19e5e6403efab794 --- /dev/null +++ b/chips/yosys/tests/unit/kernel/sigspecRemove2Test.cc @@ -0,0 +1,333 @@ +#include + +#include "kernel/rtlil.h" + +YOSYS_NAMESPACE_BEGIN + +// Test fixture with helper functions +class SigSpecRepTest : public ::testing::Test { +protected: + Design* d; + Module* m; + + void SetUp() override { + d = new Design; + m = d->addModule("$test"); + } + + void TearDown() override { + delete d; + } + + // Create n wires with given width + std::vector createWires(int count, int width = 4) { + std::vector wires; + for (int i = 0; i < count; i++) { + Wire* w = m->addWire(stringf("$w%d", i), width); + wires.push_back(w); + } + return wires; + } + + // Append all wires to a SigSpec + SigSpec wiresAsSigSpec(const std::vector& wires) { + SigSpec sig; + for (auto w : wires) + sig.append(w); + return sig; + } + + // Create a SigSpec of constants + SigSpec constsAsSigSpec(int count, int width = 4) { + SigSpec sig; + for (int i = 0; i < count; i++) + sig.append(Const(i, width)); + return sig; + } + + // Convert wires to pool of SigBits + pool wiresToPool(const std::vector& wires) { + pool pool; + for (auto w : wires) + for (auto &bit : SigSpec(w)) + pool.insert(bit); + return pool; + } + + // Convert wires to set of SigBits + std::set wiresToSet(const std::vector& wires) { + std::set set; + for (auto w : wires) + for (auto &bit : SigSpec(w)) + set.insert(bit); + return set; + } +}; + +TEST_F(SigSpecRepTest, WithSigSpecPattern) +{ + auto wires = createWires(4); + SigSpec sig = wiresAsSigSpec(wires); + SigSpec pattern(wires[1]); // Remove w2 + SigSpec other = constsAsSigSpec(4); + + EXPECT_EQ(sig.size(), 16); + sig.remove2(pattern, &other); + EXPECT_EQ(sig.size(), 12); + EXPECT_EQ(other.size(), 12); + + // Verify correct wires remain (w1, w3, w4) + SigSpec expected; + expected.append(wires[0]); + expected.append(wires[2]); + expected.append(wires[3]); + EXPECT_EQ(sig, expected); +} + +TEST_F(SigSpecRepTest, WithPoolPattern) +{ + auto wires = createWires(3); + SigSpec sig = wiresAsSigSpec(wires); + auto pattern = wiresToPool({wires[1]}); + SigSpec other = constsAsSigSpec(3); + + EXPECT_EQ(sig.size(), 12); + sig.remove2(pattern, &other); + EXPECT_EQ(sig.size(), 8); + EXPECT_EQ(other.size(), 8); + + // Verify correct wires remain (w0, w2) + SigSpec expected; + expected.append(wires[0]); + expected.append(wires[2]); + EXPECT_EQ(sig, expected); +} + +TEST_F(SigSpecRepTest, WithSetPattern) +{ + auto wires = createWires(3); + SigSpec sig = wiresAsSigSpec(wires); + auto pattern = wiresToSet({wires[1]}); + SigSpec other = constsAsSigSpec(3); + + EXPECT_EQ(sig.size(), 12); + sig.remove2(pattern, &other); + EXPECT_EQ(sig.size(), 8); + EXPECT_EQ(other.size(), 8); + + // Verify correct wires remain (w0, w2) + SigSpec expected; + expected.append(wires[0]); + expected.append(wires[2]); + EXPECT_EQ(sig, expected); +} + +TEST_F(SigSpecRepTest, ManyElements) +{ + const int num_wires = 100; + auto wires = createWires(num_wires); + SigSpec sig = wiresAsSigSpec(wires); + + // Remove every other wire + std::vector to_remove; + for (int i = 0; i < num_wires; i += 2) + to_remove.push_back(wires[i]); + auto pattern = wiresToPool(to_remove); + + EXPECT_EQ(sig.size(), num_wires * 4); + sig.remove2(pattern, nullptr); + EXPECT_EQ(sig.size(), (num_wires / 2) * 4); + + // Verify odd-indexed wires remain (w1, w3, w5, ..., w99) + SigSpec expected; + for (int i = 1; i < num_wires; i += 2) + expected.append(wires[i]); + EXPECT_EQ(sig, expected); +} + +// Test remove2 with very large dataset to check scaling +TEST_F(SigSpecRepTest, VeryLargeScalingTest) +{ + const int num_wires = 50000; + auto wires = createWires(num_wires); + SigSpec sig = wiresAsSigSpec(wires); + SigSpec other = constsAsSigSpec(num_wires); + + // Create pattern with many chunks (one per wire) + SigSpec pattern; + for (int i = 0; i < num_wires; i += 2) + pattern.append(wires[i]); + + EXPECT_EQ(sig.size(), num_wires * 4); + sig.remove2(pattern, &other); + EXPECT_EQ(sig.size(), (num_wires / 2) * 4); + EXPECT_EQ(other.size(), (num_wires / 2) * 4); + + // Spot-check: odd-indexed wires should remain at expected positions + for (int i = 0; i < num_wires / 2; i++) { + EXPECT_EQ(sig[i * 4 + 0].wire, wires[i * 2 + 1]); + EXPECT_EQ(sig[i * 4 + 1].wire, wires[i * 2 + 1]); + EXPECT_EQ(sig[i * 4 + 2].wire, wires[i * 2 + 1]); + EXPECT_EQ(sig[i * 4 + 3].wire, wires[i * 2 + 1]); + } +} + +// Test multiple sequential removals (simulates removeSignalFromCaseTree) +TEST_F(SigSpecRepTest, MultipleSequentialRemovals) +{ + const int num_wires = 512; + auto wires = createWires(num_wires); + + // Create many actions, each with one wire + std::vector actions; + for (auto w : wires) + actions.push_back(SigSpec(w)); + + // Remove half the wires from all actions + for (int i = 0; i < num_wires / 2; i++) { + SigSpec pattern(wires[i]); + for (auto &action : actions) + if (action.size() > 0) + action.remove2(pattern, nullptr); + } + + // Verify correct actions were cleared + for (int i = 0; i < num_wires; i++) { + EXPECT_EQ(actions[i].size(), i < num_wires / 2 ? 0 : 4); + } + + // Verify remaining actions contain the correct wires + for (int i = num_wires / 2; i < num_wires; i++) { + SigSpec expected(wires[i]); + EXPECT_EQ(actions[i], expected); + } +} + +// Test remove2 with very large dataset to check scaling +TEST_F(SigSpecRepTest, PoolOverloadLargeDataset) +{ + const int num_wires = 50000; + auto wires = createWires(num_wires, 1); + SigSpec sig = wiresAsSigSpec(wires); + SigSpec other = constsAsSigSpec(num_wires, 1); + + // Remove half + pool pattern; + for (int i = 0; i < num_wires; i += 2) + pattern.insert(SigBit(wires[i], 0)); + + EXPECT_EQ(sig.size(), num_wires); + sig.remove2(pattern, &other); + EXPECT_EQ(sig.size(), num_wires / 2); + EXPECT_EQ(other.size(), num_wires / 2); + + // Spot-check: odd-indexed wires should remain + for (int i = 0; i < num_wires / 2; i++) { + EXPECT_EQ(sig[i].wire, wires[i * 2 + 1]); + } +} + +// Test set overload (same perf characteristics as pool) +TEST_F(SigSpecRepTest, SetOverloadLargeDataset) +{ + const int num_wires = 50000; + auto wires = createWires(num_wires, 1); + SigSpec sig = wiresAsSigSpec(wires); + SigSpec other = constsAsSigSpec(num_wires, 1); + + // Remove half + std::set pattern; + for (int i = 0; i < num_wires; i += 2) + pattern.insert(SigBit(wires[i], 0)); + + EXPECT_EQ(sig.size(), num_wires); + sig.remove2(pattern, &other); + EXPECT_EQ(sig.size(), num_wires / 2); + EXPECT_EQ(other.size(), num_wires / 2); + + // Spot-check: odd-indexed wires should remain + for (int i = 0; i < num_wires / 2; i++) { + EXPECT_EQ(sig[i].wire, wires[i * 2 + 1]); + } +} + +// Worst case: remove almost all elements +TEST_F(SigSpecRepTest, RemoveAlmostAllElements) +{ + const int num_wires = 10000; + auto wires = createWires(num_wires, 1); + SigSpec sig = wiresAsSigSpec(wires); + + // Remove all but last + pool pattern; + for (int i = 0; i < num_wires - 1; i++) + pattern.insert(SigBit(wires[i], 0)); + + EXPECT_EQ(sig.size(), num_wires); + sig.remove2(pattern, nullptr); + EXPECT_EQ(sig.size(), 1); + EXPECT_EQ(sig[0].wire, wires[num_wires - 1]); +} + +TEST_F(SigSpecRepTest, EmptyPattern) +{ + auto wires = createWires(1); + SigSpec sig(wires[0]); + pool empty_pattern; + + EXPECT_EQ(sig.size(), 4); + sig.remove2(empty_pattern, nullptr); + EXPECT_EQ(sig.size(), 4); + + // Verify the wire is unchanged + SigSpec expected(wires[0]); + EXPECT_EQ(sig, expected); +} + +// Test that NULL wire bits (constants) are not removed +TEST_F(SigSpecRepTest, NullWireBitsStay) +{ + auto wires = createWires(1); + SigSpec sig; + sig.append(wires[0]); + sig.append(Const(15, 4)); + + // Try to remove the constants + pool pattern; + SigSpec const_spec(Const(15, 4)); + for (auto &bit : const_spec) + pattern.insert(bit); + + EXPECT_EQ(sig.size(), 8); + sig.remove2(pattern, nullptr); + EXPECT_EQ(sig.size(), 8); // Constants stay + + // Verify original content is preserved + SigSpec expected; + expected.append(wires[0]); + expected.append(Const(15, 4)); + EXPECT_EQ(sig, expected); +} + +TEST_F(SigSpecRepTest, PartialBitRemoval) +{ + Wire* w = m->addWire("$w1", 8); + SigSpec sig(w); + + // Remove bits 2-5 + pool pattern; + for (int i = 2; i < 6; i++) + pattern.insert(SigBit(w, i)); + + EXPECT_EQ(sig.size(), 8); + sig.remove2(pattern, nullptr); + EXPECT_EQ(sig.size(), 4); + + // Verify only bits 0,1,6,7 remain + EXPECT_EQ(sig[0], SigBit(w, 0)); + EXPECT_EQ(sig[1], SigBit(w, 1)); + EXPECT_EQ(sig[2], SigBit(w, 6)); + EXPECT_EQ(sig[3], SigBit(w, 7)); +} + +YOSYS_NAMESPACE_END diff --git a/chips/yosys/tests/unit/kernel/threadingTest.cc b/chips/yosys/tests/unit/kernel/threadingTest.cc new file mode 100644 index 0000000000000000000000000000000000000000..3ce8276668b406650c4c2fa2d545f70be8127110 --- /dev/null +++ b/chips/yosys/tests/unit/kernel/threadingTest.cc @@ -0,0 +1,443 @@ +#include +#include +#include "kernel/threading.h" + +YOSYS_NAMESPACE_BEGIN + +class ThreadingTest : public testing::Test { +protected: + ThreadingTest() { + if (logger().empty()) logger().add_sink(); + } +}; + +TEST_F(ThreadingTest, ParallelDispatchThreadPoolCreate) { + // Test creating a pool with 0 threads (treated as 1) + ParallelDispatchThreadPool pool0(0); + EXPECT_EQ(pool0.num_threads(), 1); + + // Test creating a pool with 1 thread + ParallelDispatchThreadPool pool1(1); + EXPECT_EQ(pool1.num_threads(), 1); + + // Test creating a pool with 2 threads + ParallelDispatchThreadPool pool2(2); + // YOSYS_MAX_THREADS or system configuration could mean we + // decide to only use one thread. + EXPECT_GE(pool2.num_threads(), 1); + EXPECT_LE(pool2.num_threads(), 2); +} + +TEST_F(ThreadingTest, ParallelDispatchThreadPoolRunSimple) { + ParallelDispatchThreadPool pool(2); + + std::atomic counter{0}; + pool.run([&counter](const ParallelDispatchThreadPool::RunCtx &) { + counter.fetch_add(1, std::memory_order_relaxed); + }); + + EXPECT_EQ(counter.load(), pool.num_threads()); +} + +TEST_F(ThreadingTest, ParallelDispatchThreadPoolRunMultiple) { + ParallelDispatchThreadPool pool(2); + + std::atomic counter{0}; + // Run multiple times to verify the pool can be reused + for (int i = 0; i < 5; ++i) + pool.run([&counter](const ParallelDispatchThreadPool::RunCtx &) { + counter.fetch_add(1, std::memory_order_relaxed); + }); + + EXPECT_EQ(counter.load(), pool.num_threads() * 5); +} + +TEST_F(ThreadingTest, ParallelDispatchThreadPoolRunCtxThreadNums) { + ParallelDispatchThreadPool pool(4); + + std::vector thread_nums(pool.num_threads(), -1); + pool.run([&thread_nums](const ParallelDispatchThreadPool::RunCtx &ctx) { + thread_nums[ctx.thread_num] = ctx.thread_num; + }); + + // Every thread should have recorded its own thread number + for (int i = 0; i < pool.num_threads(); ++i) + EXPECT_EQ(thread_nums[i], i); +} + +TEST_F(ThreadingTest, ParallelDispatchThreadPoolItemRange) { + ParallelDispatchThreadPool pool(3); + + const int num_items = 100; + std::vector> item_counts(num_items); + for (std::atomic &c : item_counts) + c.store(0); + + pool.run([&item_counts](const ParallelDispatchThreadPool::RunCtx &ctx) { + for (int i : ctx.item_range(num_items)) + item_counts[i].fetch_add(1); + }); + + // Each item should have been processed exactly once + for (int i = 0; i < num_items; ++i) + EXPECT_EQ(item_counts[i].load(), 1); +} + +TEST_F(ThreadingTest, ParallelDispatchThreadPoolSubpool) { + ParallelDispatchThreadPool pool(4); + + // Subpool limited to 2 threads + ParallelDispatchThreadPool::Subpool subpool(pool, 2); + EXPECT_LE(subpool.num_threads(), 2); + + std::atomic counter{0}; + subpool.run([&counter](const ParallelDispatchThreadPool::RunCtx &) { + counter.fetch_add(1, std::memory_order_relaxed); + }); + + EXPECT_EQ(counter.load(), subpool.num_threads()); +} + +TEST_F(ThreadingTest, IntRangeIteration) { + IntRange range{3, 7}; + std::vector values; + for (int i : range) + values.push_back(i); + EXPECT_THAT(values, testing::ElementsAre(3, 4, 5, 6)); +} + +TEST_F(ThreadingTest, IntRangeEmpty) { + IntRange range{5, 5}; + for (int _ : range) { + (void)_; + FAIL(); + } +} + +TEST_F(ThreadingTest, ItemRangeForWorker) { + EXPECT_EQ(item_range_for_worker(10, 0, 3), (IntRange{0, 4})); + EXPECT_EQ(item_range_for_worker(10, 1, 3), (IntRange{4, 7})); + EXPECT_EQ(item_range_for_worker(10, 2, 3), (IntRange{7, 10})); +} + +TEST_F(ThreadingTest, ItemRangeForWorkerZeroThreads) { + EXPECT_EQ(item_range_for_worker(10, 0, 0), (IntRange{0, 10})); +} + +TEST_F(ThreadingTest, ShardedVectorBasic) { + ParallelDispatchThreadPool pool(2); + ShardedVector vec(pool); + pool.run([&vec](const ParallelDispatchThreadPool::RunCtx &ctx) { + vec.insert(ctx, ctx.thread_num * 10); + vec.insert(ctx, ctx.thread_num * 10 + 1); + }); + + EXPECT_FALSE(vec.empty()); + + // Count elements + std::vector elements; + for (int v : vec) { + elements.push_back(v); + } + + if (pool.num_threads() == 2) + EXPECT_THAT(elements, testing::ElementsAre(0, 1, 10, 11)); + else + EXPECT_THAT(elements, testing::ElementsAre(0, 1)); +} + +TEST_F(ThreadingTest, MonotonicFlagBasic) { + MonotonicFlag flag; + EXPECT_FALSE(flag.load()); + flag.set(); + EXPECT_TRUE(flag.load()); + flag.set(); + EXPECT_TRUE(flag.load()); +} + +TEST_F(ThreadingTest, MonotonicFlagSetAndReturnOld) { + MonotonicFlag flag; + EXPECT_FALSE(flag.set_and_return_old()); + EXPECT_TRUE(flag.load()); + EXPECT_TRUE(flag.set_and_return_old()); +} + +TEST_F(ThreadingTest, ConcurrentQueueBasic) { + ConcurrentQueue queue; + queue.push_back(1); + queue.push_back(2); + queue.push_back(3); + + auto v1 = queue.pop_front(); + auto v2 = queue.pop_front(); + auto v3 = queue.pop_front(); + + ASSERT_TRUE(v1.has_value()); + ASSERT_TRUE(v2.has_value()); + ASSERT_TRUE(v3.has_value()); + EXPECT_EQ(*v1, 1); + EXPECT_EQ(*v2, 2); + EXPECT_EQ(*v3, 3); +} + +TEST_F(ThreadingTest, ConcurrentQueueTryPopEmpty) { + ConcurrentQueue queue; + auto v = queue.try_pop_front(); + EXPECT_FALSE(v.has_value()); +} + +TEST_F(ThreadingTest, ConcurrentQueueClose) { + ConcurrentQueue queue; + queue.push_back(42); + queue.close(); + + // Can still pop existing elements + auto v1 = queue.pop_front(); + ASSERT_TRUE(v1.has_value()); + EXPECT_EQ(*v1, 42); + + // After close and empty, pop_front returns nullopt + auto v2 = queue.pop_front(); + EXPECT_FALSE(v2.has_value()); +} + +TEST_F(ThreadingTest, ThreadPoolCreate) { + // pool_size of 0 means no worker threads + ThreadPool pool0(0, [](int) {}); + EXPECT_EQ(pool0.num_threads(), 0); + + // pool_size of 1 means 1 worker thread + std::atomic counter{0}; + { + ThreadPool pool1(1, [&counter](int thread_num) { + EXPECT_EQ(thread_num, 0); + counter.fetch_add(1); + }); + } +#ifdef YOSYS_ENABLE_THREADS + EXPECT_EQ(counter.load(), 1); +#else + EXPECT_EQ(counter.load(), 0); +#endif +} + +TEST_F(ThreadingTest, ThreadPoolMultipleThreads) { + std::atomic counter{0}; + { + ThreadPool pool(2, [&counter](int) { + counter.fetch_add(1); + }); + EXPECT_LE(pool.num_threads(), 2); + } +#ifdef YOSYS_ENABLE_THREADS + EXPECT_GE(counter.load(), 1); + EXPECT_LE(counter.load(), 2); +#else + EXPECT_EQ(counter.load(), 0); +#endif +} + +// Helper types for ShardedHashtable tests +struct IntValue { + using Accumulated = IntValue; + int value; + operator int() const { return value; } +}; + +struct IntValueEquality { + bool operator()(int a, int b) const { return a == b; } +}; + +TEST_F(ThreadingTest, ShardedHashtableBasic) { + ParallelDispatchThreadPool pool(1); + + using HashSet = ShardedHashtable>; + HashSet::Builder builder(pool); + + // Insert some values + pool.run([&builder](const ParallelDispatchThreadPool::RunCtx &ctx) { + builder.insert(ctx, {{10}, 10}); + builder.insert(ctx, {{20}, 20}); + builder.insert(ctx, {{30}, 30}); + }); + + // Process + pool.run([&builder](const ParallelDispatchThreadPool::RunCtx &ctx) { + builder.process(ctx); + }); + + // Build and lookup + HashSet set(builder); + const IntValue *found10 = set.find({{10}, 10}); + const IntValue *found20 = set.find({{20}, 20}); + const IntValue *found99 = set.find({{99}, 99}); + + ASSERT_NE(found10, nullptr); + ASSERT_NE(found20, nullptr); + EXPECT_EQ(found99, nullptr); + EXPECT_EQ(*found10, 10); + EXPECT_EQ(*found20, 20); +} + +TEST_F(ThreadingTest, ShardedHashtableParallelInsert) { + ParallelDispatchThreadPool pool(3); + + using HashSet = ShardedHashtable>; + HashSet::Builder builder(pool); + + // Insert values from multiple threads + pool.run([&builder](const ParallelDispatchThreadPool::RunCtx &ctx) { + for (int i = 0; i < 10; ++i) { + int val = ctx.thread_num * 100 + i; + builder.insert(ctx, {{val}, static_cast(val)}); + } + }); + + pool.run([&builder](const ParallelDispatchThreadPool::RunCtx &ctx) { + builder.process(ctx); + }); + + HashSet set(builder); + + // Verify all values can be found + for (int t = 0; t < pool.num_threads(); ++t) { + for (int i = 0; i < 10; ++i) { + int val = t * 100 + i; + const IntValue *found = set.find({{val}, static_cast(val)}); + ASSERT_NE(found, nullptr) << "Value " << val << " not found"; + EXPECT_EQ(*found, val); + } + } +} + +// Helper types for ShardedHashtable tests +struct IntDictValue { + using Accumulated = IntDictValue; + int key; + int value; + bool operator==(const IntDictValue &other) const { return key == other.key && value == other.value; } + bool operator!=(const IntDictValue &other) const { return !(*this == other); } +}; + +struct IntDictKeyEquality { + bool operator()(const IntDictValue &a, const IntDictValue &b) const { return a.key == b.key; } +}; + +// Collision handler that sums values +struct SumCollisionHandler { + void operator()(IntDictValue &existing, IntDictValue &incoming) const { + existing.value += incoming.value; + } +}; + +TEST_F(ThreadingTest, ShardedHashtableCollision) { + ParallelDispatchThreadPool pool(1); + + using HashSet = ShardedHashtable; + HashSet::Builder builder(pool); + + // Insert duplicate keys with same hash - duplicates should collapse + pool.run([&builder](const ParallelDispatchThreadPool::RunCtx &ctx) { + builder.insert(ctx, {{5, 10}, 5}); + builder.insert(ctx, {{5, 12}, 5}); // Duplicate key/hash + builder.insert(ctx, {{5, 14}, 5}); // Another duplicate + }); + + pool.run([&builder](const ParallelDispatchThreadPool::RunCtx &ctx) { + builder.process(ctx); + }); + + HashSet set(builder); + const IntDictValue *found = set.find({{5, 0}, 5}); + ASSERT_NE(found, nullptr); + // With default collision handler, first value is kept + EXPECT_EQ(*found, (IntDictValue{5, 36})); +} + +TEST_F(ThreadingTest, ShardedHashtableEmpty) { + ParallelDispatchThreadPool pool(1); + + using HashSet = ShardedHashtable>; + HashSet::Builder builder(pool); + + // Don't insert anything, just process + pool.run([&builder](const ParallelDispatchThreadPool::RunCtx &ctx) { + builder.process(ctx); + }); + + HashSet set(builder); + const IntValue *found = set.find({{42}, 42}); + EXPECT_EQ(found, nullptr); +} + +TEST_F(ThreadingTest, ConcurrentWorkQueueSingleThread) { + ConcurrentWorkQueue queue(1, 10); // 1 thread, batch size 10 + EXPECT_EQ(queue.num_threads(), 1); + + ThreadIndex thread{0}; + + // Push some items (less than batch size) + for (int i = 0; i < 5; ++i) + queue.push(thread, i); + + // Pop should return those items + std::vector batch = queue.pop_batch(thread); + EXPECT_THAT(batch, testing::UnorderedElementsAre(0, 1, 2, 3, 4)); + + // Next pop should return empty (all threads "waiting") + std::vector empty_batch = queue.pop_batch(thread); + EXPECT_TRUE(empty_batch.empty()); +} + +TEST_F(ThreadingTest, ConcurrentWorkQueueBatching) { + ConcurrentWorkQueue queue(1, 3); // batch size 3 + ThreadIndex thread{0}; + + queue.push(thread, 10); + queue.push(thread, 20); + queue.push(thread, 30); + queue.push(thread, 40); + queue.push(thread, 50); + + std::vector popped; + while (true) { + std::vector batch = queue.pop_batch(thread); + if (batch.empty()) + break; + popped.insert(popped.end(), batch.begin(), batch.end()); + } + EXPECT_THAT(popped, testing::UnorderedElementsAre(10, 20, 30, 40, 50)); +} + +TEST_F(ThreadingTest, ConcurrentWorkQueueParallel) { + ParallelDispatchThreadPool pool(2); + if (pool.num_threads() < 2) { + // Skip test if we don't have multiple threads + return; + } + + ConcurrentWorkQueue queue(2, 3); + std::atomic sum{0}; + + pool.run([&queue, &sum](const ParallelDispatchThreadPool::RunCtx &ctx) { + // Each thread pushes some work + for (int i = 0; i < 10; ++i) + queue.push(ctx, ctx.thread_num * 100 + i); + + // Each thread processes work until done + while (true) { + std::vector batch = queue.pop_batch(ctx); + if (batch.empty()) + break; + for (int v : batch) + sum.fetch_add(v); + } + }); + + // Thread 0 pushes: 0+1+2+...+9 = 45 + // Thread 1 pushes: 100+101+...+109 = 1045 + // Total = 45 + 1045 = 1090 + EXPECT_EQ(sum.load(), 1090); +} + +YOSYS_NAMESPACE_END diff --git a/chips/yosys/tests/unit/kernel/twineHashTest.cc b/chips/yosys/tests/unit/kernel/twineHashTest.cc new file mode 100644 index 0000000000000000000000000000000000000000..f337b4fcadc58c317226662f8f28e132e9502167 --- /dev/null +++ b/chips/yosys/tests/unit/kernel/twineHashTest.cc @@ -0,0 +1,81 @@ +#include + +#include + +#include "kernel/rtlil.h" +#include "kernel/yosys.h" + +YOSYS_NAMESPACE_BEGIN + +namespace { + +TEST(TwineHashTest, Fragmentation) +{ + TwinePool pool; + + IdString flat = pool.add(std::string("$abcdefghij")); + IdString base = pool.add(std::string("$abcde")); + IdString split = pool.add(TwineSpec::Suffix{base, "fghij"}); + + EXPECT_EQ(flat, split); + EXPECT_EQ(pool[flat].hash(), TwineNode::extend_hash(0, "$abcdefghij")); +} + +TEST(TwineHashTest, SplitPoints) +{ + const std::string content = "$0123456789abcdefghijklmnopqr"; + const uint64_t want = TwineNode::extend_hash(0, content); + + TwinePool pool; + IdString first; + for (size_t cut = 1; cut < content.size(); cut++) { + IdString base = pool.add(content.substr(0, cut)); + IdString split = pool.add(TwineSpec::Suffix{base, content.substr(cut)}); + if (first == IdString::Null) + first = split; + EXPECT_EQ(split, first) << "split after " << cut; + EXPECT_EQ(pool[split].hash(), want) << "split after " << cut; + } +} + +TEST(TwineHashTest, DistinctContent) +{ + TwinePool twines; + + std::set seen; + for (int i = 0; i < 4096; i++) { + IdString ref = twines.add(stringf("$name%d", i)); + seen.insert(twines[ref].hash()); + } + EXPECT_GT(seen.size(), 4000u); +} + +TEST(TwineHashTest, BenchmarkIntern) +{ + constexpr int kNames = 40000; + + TwinePool pool; + auto t0 = std::chrono::steady_clock::now(); + IdString prefix = pool.add(std::string("$bench")); + std::vector refs; + refs.reserve(kNames); + for (int i = 0; i < kNames; i++) + refs.push_back(pool.add(TwineSpec::Suffix{prefix, stringf("$%d", i)})); + auto t1 = std::chrono::steady_clock::now(); + + for (int i = 0; i < kNames; i++) + ASSERT_EQ(pool.find(pool.str(refs[i])), refs[i]) << "at " << i; + auto t2 = std::chrono::steady_clock::now(); + + auto ms = [](auto a, auto b) { + return std::chrono::duration_cast(b - a).count() / 1000.0; + }; + RecordProperty("intern_ms", std::to_string(ms(t0, t1))); + RecordProperty("find_ms", std::to_string(ms(t1, t2))); + std::cerr << "[ BENCH ] intern " << ms(t0, t1) << " ms, " + << kNames << " finds " << ms(t1, t2) << " ms\n"; +} + +} + +YOSYS_NAMESPACE_END diff --git a/chips/yosys/tests/unit/kernel/twinePublicityTest.cc b/chips/yosys/tests/unit/kernel/twinePublicityTest.cc new file mode 100644 index 0000000000000000000000000000000000000000..f6c0f437d6e748c9acf4c8dc65dcd7249a58216a --- /dev/null +++ b/chips/yosys/tests/unit/kernel/twinePublicityTest.cc @@ -0,0 +1,174 @@ +#include + +#include "kernel/rtlil.h" +#include "kernel/yosys.h" + +YOSYS_NAMESPACE_BEGIN + +TEST(TwinePublicityTest, RootEscape) +{ + TwinePool pool; + IdString pub = pool.add(std::string("\\foo")); + IdString priv = pool.add(std::string("$foo")); + + EXPECT_TRUE(pub.isPublic()); + EXPECT_FALSE(priv.isPublic()); + EXPECT_EQ(pool.str(pub), "\\foo"); + EXPECT_EQ(pool.unescaped_str(pub), "foo"); + EXPECT_EQ(pool.str(priv), "$foo"); + EXPECT_EQ(pool.unescaped_str(priv), "$foo"); +} + +TEST(TwinePublicityTest, EscapedDollar) +{ + // Verilog escaped identifier `\$foo` (public, content "$foo") must not + // collide with the private name `$foo` as a dict key. + TwinePool pool; + IdString pub = pool.add(std::string("\\$foo")); + IdString priv = pool.add(std::string("$foo")); + + EXPECT_EQ(pub.untag(), priv.untag()); // shared content node + EXPECT_NE(pub, priv); // distinct handles + EXPECT_EQ(pool.str(pub), "\\$foo"); + EXPECT_EQ(pool.str(priv), "$foo"); +} + +TEST(TwinePublicityTest, UnescapeIdMatchesUnescapedStr) +{ + TwinePool pool; + for (std::string name : {"\\foo", "$foo", "\\$foo", "\\\\foo\\", "\\1foo"}) { + IdString id = pool.add(name); + EXPECT_EQ(RTLIL::unescape_id(name), pool.unescaped_str(id)) << name; + } + EXPECT_EQ(RTLIL::unescape_id("\\$foo"), "$foo"); + EXPECT_EQ(RTLIL::unescape_id("\\\\foo\\"), "\\foo\\"); + EXPECT_EQ(RTLIL::unescape_id("\\1foo"), "1foo"); + EXPECT_EQ(RTLIL::unescape_id("\\"), ""); + EXPECT_EQ(RTLIL::unescape_id(""), ""); +} + +TEST(TwinePublicityTest, TagStability) +{ + TwinePool pool; + IdString a = pool.add(std::string("\\foo")); + IdString b = pool.add(std::string("\\foo")); + EXPECT_EQ(a, b); +} + +TEST(TwinePublicityTest, SuffixPublicity) +{ + TwinePool pool; + IdString pub = pool.add(std::string("\\base")); + IdString priv = pool.add(std::string("$base")); + + IdString pub_sfx = pool.add(TwineSpec{TwineSpec::Suffix{pub, "_1"}}); + IdString priv_sfx = pool.add(TwineSpec{TwineSpec::Suffix{priv, "_1"}}); + + EXPECT_TRUE(pub_sfx.isPublic()); + EXPECT_FALSE(priv_sfx.isPublic()); + EXPECT_EQ(pool.str(pub_sfx), "\\base_1"); + EXPECT_EQ(pool.str(priv_sfx), "$base_1"); +} + +TEST(TwinePublicityTest, StaticTags) +{ + TwinePool pool; + EXPECT_TRUE((ID::A).isPublic()); + EXPECT_EQ(pool.str(ID::A), "\\A"); + EXPECT_EQ(pool.unescaped_str(ID::A), "A"); + EXPECT_FALSE((ID($and)).isPublic()); + EXPECT_EQ(pool.str(ID($and)), "$and"); +} + +TEST(TwinePublicityTest, LookupTag) +{ + TwinePool pool; + IdString pub = pool.add(std::string("\\net")); + IdString priv = pool.add(std::string("$net")); + + EXPECT_EQ(pool.find(std::string_view("\\net")), pub); + EXPECT_EQ(pool.find(std::string_view("$net")), priv); + EXPECT_EQ(pool.find(std::string_view("\\A")), ID::A); + EXPECT_EQ(pool.find(std::string_view("\\nonexistent")), IdString::Null); +} + +TEST(TwinePublicityTest, SearchUnifies) +{ + TwinePool pool; + IdString flat = pool.add(TwineSpec::Root{"$abc"}); + IdString head = pool.add(TwineSpec::Root{"$a"}); + IdString split = pool.add(TwineSpec::Suffix{head, "bc"}); + + ASSERT_EQ(flat, split); + EXPECT_TRUE(pool[split].is_root()); + + EXPECT_EQ(pool.find(std::string_view("$abc")), flat); + EXPECT_EQ(pool.find(std::string_view("$a")), head); +} + +TEST(TwinePublicityTest, SearchPublicity) +{ + TwinePool pool; + IdString priv = pool.add(TwineSpec::Root{"sig"}); + IdString pub = pool.add(std::string("\\sig")); + + ASSERT_EQ(priv, pub.untag()); + + IdString found_pub = pool.find(std::string_view("\\sig")); + IdString found_priv = pool.find(TwineSpec::Root{"sig"}); + + EXPECT_TRUE(found_pub.isPublic()); + EXPECT_FALSE(found_priv.isPublic()); + EXPECT_EQ(found_pub.untag(), found_priv.untag()); + EXPECT_EQ(found_pub, pub); +} + +TEST(TwinePublicityTest, CopyTag) +{ + TwinePool src, dst; + IdString pub = src.add(std::string("\\xfer")); + IdString copied = dst.copy_from(src, pub); + EXPECT_TRUE(copied.isPublic()); + EXPECT_EQ(dst.str(copied), "\\xfer"); + // Static handles pass through tag and all. + EXPECT_EQ(dst.copy_from(src, ID::A), ID::A); +} + +TEST(TwinePublicityTest, GcRoots) +{ + TwinePool twines; + IdString pub = twines.add("\\keep"); + twines.add("\\drop"); + Yosys::pool roots{pub}; + EXPECT_EQ(twines.gc(roots), 1u); + EXPECT_EQ(twines.str(pub), "\\keep"); +} + +TEST(TwinePublicityTest, WireMasquerade) +{ + RTLIL::Design design; + RTLIL::Module *mod = design.addModule("\\top"); + + RTLIL::Wire *pub = mod->addWire("\\sig"); + RTLIL::Wire *priv = mod->addWire("$sig"); + + EXPECT_TRUE(pub->name.isPublic()); + EXPECT_FALSE(priv->name.isPublic()); + EXPECT_EQ(pub->name.escaped(), "\\sig"); + EXPECT_EQ(pub->name.unescape(), "sig"); + EXPECT_EQ(pub->name.str(), "\\sig"); + EXPECT_EQ(priv->name.escaped(), "$sig"); + EXPECT_EQ(priv->name.unescape(), "$sig"); + + // Distinct dict keys despite shared content. + EXPECT_NE(pub, priv); + EXPECT_EQ(mod->wire("\\sig"), pub); + EXPECT_EQ(mod->wire("$sig"), priv); + + // uniquify keeps publicity. + IdString uniq = mod->uniquify(pub->name); + EXPECT_TRUE(uniq.isPublic()); + EXPECT_EQ(design.twines().str(uniq), "\\sig_1"); +} + +YOSYS_NAMESPACE_END diff --git a/chips/yosys/tests/unit/kernel/twineSortTest.cc b/chips/yosys/tests/unit/kernel/twineSortTest.cc new file mode 100644 index 0000000000000000000000000000000000000000..2f24df9daf15fc917b104253670b4edddd7738fe --- /dev/null +++ b/chips/yosys/tests/unit/kernel/twineSortTest.cc @@ -0,0 +1,126 @@ +#include + +#include + +#include "kernel/rtlil.h" +#include "kernel/yosys.h" + +YOSYS_NAMESPACE_BEGIN + +namespace { + +std::vector bench_refs(TwinePool &twines, int count) +{ + IdString prefix = twines.add("$sortbench"); + std::vector refs; + refs.reserve(count); + for (int i = 0; i < count; i++) + refs.push_back(twines.add(TwineSpec::Suffix{prefix, stringf("$%08d", (count - i) * 7919 % count)})); + return refs; +} + +TEST(TwineSortTest, RenderedOrder) +{ + TwinePool twines; + std::vector refs = { + twines.add("$c"), + twines.add("$a"), + twines.add("$b"), + }; + std::sort(refs.begin(), refs.end(), RTLIL::sort_by_id_str(twines)); + EXPECT_EQ(twines.str(refs[0]), "$a"); + EXPECT_EQ(twines.str(refs[1]), "$b"); + EXPECT_EQ(twines.str(refs[2]), "$c"); +} + +TEST(TwineSortTest, PublicOrder) +{ + TwinePool twines; + IdString pub = twines.add("\\same"); + IdString priv = pub.tag(false); + + ASSERT_EQ(twines.str(pub), "\\same"); + ASSERT_EQ(twines.str(priv), "same"); + + RTLIL::sort_by_id_str less(twines); + EXPECT_NE(less(pub, priv), less(priv, pub)); + EXPECT_TRUE(less(pub, priv)); +} + +TEST(TwineSortTest, WeakOrdering) +{ + TwinePool twines; + std::vector refs = bench_refs(twines, 500); + RTLIL::sort_by_id_str less(twines); + std::sort(refs.begin(), refs.end(), less); + for (size_t i = 1; i < refs.size(); i++) + ASSERT_FALSE(less(refs[i], refs[i - 1])) << "at " << i; +} + +TEST(TwineSortTest, GeneralWalk) +{ + TwinePool twines; + std::vector refs; + + IdString a = twines.add("$alpha"); + IdString b = twines.add("\\alpha"); + IdString c = twines.add("$alphabet"); + refs.insert(refs.end(), {a, b, c}); + + IdString deep = a; + for (int i = 0; i < 12; i++) { + deep = twines.add(TwineSpec::Suffix{deep, stringf(".lvl%d", i)}); + refs.push_back(deep); + refs.push_back(deep.tag(true)); + } + + IdString other = twines.add("$alpha."); + for (int i = 0; i < 12; i++) { + other = twines.add(TwineSpec::Suffix{other, stringf("lvl%d.", i)}); + refs.push_back(other); + } + + RTLIL::sort_by_id_str less(twines); + for (IdString x : refs) + for (IdString y : refs) { + bool want = twines.str(x) < twines.str(y); + EXPECT_EQ(less(x, y), want) + << twines.str(x) << " vs " << twines.str(y); + } +} + +TEST(TwineSortTest, BenchmarkSort) +{ + constexpr int kNames = 50000; + + TwinePool twines; + std::vector refs = bench_refs(twines, kNames); + + auto t0 = std::chrono::steady_clock::now(); + std::sort(refs.begin(), refs.end(), RTLIL::sort_by_id_str(twines)); + auto t1 = std::chrono::steady_clock::now(); + + size_t flattens = 0; + std::vector naive = bench_refs(twines, kNames); + auto t2 = std::chrono::steady_clock::now(); + std::sort(naive.begin(), naive.end(), [&](IdString a, IdString b) { + flattens += 2; + return twines.str(a) < twines.str(b); + }); + auto t3 = std::chrono::steady_clock::now(); + + auto ms = [](auto a, auto b) { + return std::chrono::duration_cast(b - a).count() / 1000.0; + }; + std::cerr << "[ BENCH ] " << kNames << " refs: walked " << ms(t0, t1) + << " ms vs per-comparison " << ms(t2, t3) << " ms (" + << flattens << " flattens vs " << kNames << ")\n"; + RecordProperty("walked_ms", std::to_string(ms(t0, t1))); + RecordProperty("naive_ms", std::to_string(ms(t2, t3))); + + EXPECT_LT(ms(t0, t1), ms(t2, t3)); +} + +} // namespace + +YOSYS_NAMESPACE_END diff --git a/chips/yosys/tests/unit/opt/CMakeLists.txt b/chips/yosys/tests/unit/opt/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..50175e89f494ce6c4cfb1b79ce69d1bbba56f72a --- /dev/null +++ b/chips/yosys/tests/unit/opt/CMakeLists.txt @@ -0,0 +1,6 @@ +yosys_gtest(opt + optDffFindComplementaryPatternTest.cc + COMPONENTS + opt_clean + opt_dff +) diff --git a/chips/yosys/tests/unit/opt/optDffFindComplementaryPatternTest.cc b/chips/yosys/tests/unit/opt/optDffFindComplementaryPatternTest.cc new file mode 100644 index 0000000000000000000000000000000000000000..61a73b9cf339928aa2170a3d8b65d740e209fd9a --- /dev/null +++ b/chips/yosys/tests/unit/opt/optDffFindComplementaryPatternTest.cc @@ -0,0 +1,179 @@ +#include +#include "kernel/pattern.h" + +YOSYS_NAMESPACE_BEGIN + +class FindComplementaryPatternVarTest : public ::testing::Test { +protected: + RTLIL::Design *design; + RTLIL::Module *module; + RTLIL::Wire *wire_a; + RTLIL::Wire *wire_b; + RTLIL::Wire *wire_c; + RTLIL::Wire *bus; + + void SetUp() override { + design = new RTLIL::Design; + module = design->addModule("\\test_module"); + wire_a = module->addWire("\\a"); + wire_b = module->addWire("\\b"); + wire_c = module->addWire("\\c"); + bus = module->addWire("\\bus", 4); + } + + void TearDown() override { + delete design; + } + + RTLIL::SigBit bit(RTLIL::Wire *w, int offset = 0) { + return RTLIL::SigBit(w, offset); + } +}; + +TEST_F(FindComplementaryPatternVarTest, EmptyPatterns) { + pattern_t left, right; + + auto result = find_complementary_pattern_var(left, right); + EXPECT_FALSE(result.has_value()); +} + +TEST_F(FindComplementaryPatternVarTest, IdenticalSingleVar) { + pattern_t left, right; + left[bit(wire_a)] = true; + right[bit(wire_a)] = true; + + auto result = find_complementary_pattern_var(left, right); + EXPECT_FALSE(result.has_value()); +} + +TEST_F(FindComplementaryPatternVarTest, ComplementarySingleVar) { + pattern_t left, right; + left[bit(wire_a)] = true; + right[bit(wire_a)] = false; + + auto result = find_complementary_pattern_var(left, right); + ASSERT_TRUE(result.has_value()); + EXPECT_EQ(result.value(), bit(wire_a)); +} + +TEST_F(FindComplementaryPatternVarTest, MissingKeyInRight) { + pattern_t left, right; + left[bit(wire_a)] = true; + left[bit(wire_b)] = false; + right[bit(wire_a)] = true; + + auto result = find_complementary_pattern_var(left, right); + EXPECT_FALSE(result.has_value()); +} + +TEST_F(FindComplementaryPatternVarTest, TwoVarsOneComplementary) { + pattern_t left, right; + left[bit(wire_a)] = true; + left[bit(wire_b)] = false; + right[bit(wire_a)] = true; + right[bit(wire_b)] = true; + + auto result = find_complementary_pattern_var(left, right); + ASSERT_TRUE(result.has_value()); + EXPECT_EQ(result.value(), bit(wire_b)); +} + +TEST_F(FindComplementaryPatternVarTest, TwoVarsBothComplementary) { + pattern_t left, right; + left[bit(wire_a)] = true; + left[bit(wire_b)] = false; + right[bit(wire_a)] = false; + right[bit(wire_b)] = true; + + auto result = find_complementary_pattern_var(left, right); + EXPECT_FALSE(result.has_value()); +} + +TEST_F(FindComplementaryPatternVarTest, LeftSubsetOfRight) { + pattern_t left, right; + left[bit(wire_a)] = true; + left[bit(wire_b)] = false; + right[bit(wire_a)] = true; + right[bit(wire_b)] = true; + right[bit(wire_c)] = false; + + auto result = find_complementary_pattern_var(left, right); + ASSERT_TRUE(result.has_value()); + EXPECT_EQ(result.value(), bit(wire_b)); +} + +TEST_F(FindComplementaryPatternVarTest, ThreeVarsAllSame) { + pattern_t left, right; + left[bit(wire_a)] = true; + left[bit(wire_b)] = false; + left[bit(wire_c)] = true; + right[bit(wire_a)] = true; + right[bit(wire_b)] = false; + right[bit(wire_c)] = true; + + auto result = find_complementary_pattern_var(left, right); + EXPECT_FALSE(result.has_value()); +} + +TEST_F(FindComplementaryPatternVarTest, PracticalPatternSimplification) { + pattern_t pattern1, pattern2; + pattern1[bit(bus, 0)] = true; + pattern1[bit(bus, 1)] = true; + pattern2[bit(bus, 0)] = true; + pattern2[bit(bus, 1)] = false; + + auto result = find_complementary_pattern_var(pattern1, pattern2); + ASSERT_TRUE(result.has_value()); + EXPECT_EQ(result.value(), bit(bus, 1)); + + // Swapped args + auto result2 = find_complementary_pattern_var(pattern2, pattern1); + ASSERT_TRUE(result2.has_value()); + EXPECT_EQ(result2.value(), bit(bus, 1)); +} + +TEST_F(FindComplementaryPatternVarTest, MuxTreeClockEnableDetection) { + pattern_t feedback_path1, feedback_path2; + feedback_path1[bit(wire_a)] = true; + feedback_path1[bit(wire_b)] = true; + feedback_path2[bit(wire_a)] = true; + feedback_path2[bit(wire_b)] = false; + + auto comp = find_complementary_pattern_var(feedback_path1, feedback_path2); + ASSERT_TRUE(comp.has_value()); + EXPECT_EQ(comp.value(), bit(wire_b)); + + pattern_t simplified = feedback_path1; + simplified.erase(comp.value()); + + EXPECT_EQ(simplified.size(), 1); + EXPECT_TRUE(simplified.count(bit(wire_a))); + EXPECT_TRUE(simplified[bit(wire_a)]); +} + +TEST_F(FindComplementaryPatternVarTest, AsymmetricPatterns) { + pattern_t left, right; + left[bit(wire_a)] = true; + right[bit(wire_a)] = false; + right[bit(wire_b)] = true; + right[bit(wire_c)] = false; + + auto result = find_complementary_pattern_var(left, right); + ASSERT_TRUE(result.has_value()); + EXPECT_EQ(result.value(), bit(wire_a)); +} + +TEST_F(FindComplementaryPatternVarTest, WireOffsetDistinction) { + pattern_t left, right; + left[bit(bus, 0)] = true; + left[bit(bus, 1)] = false; + right[bit(bus, 0)] = true; + right[bit(bus, 1)] = true; + right[bit(bus, 2)] = false; + + auto result = find_complementary_pattern_var(left, right); + ASSERT_TRUE(result.has_value()); + EXPECT_EQ(result.value(), bit(bus, 1)); +} + +YOSYS_NAMESPACE_END diff --git a/chips/yosys/tests/unit/techmap/CMakeLists.txt b/chips/yosys/tests/unit/techmap/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..53ab7945e115e730856daae9e161d684f266e67f --- /dev/null +++ b/chips/yosys/tests/unit/techmap/CMakeLists.txt @@ -0,0 +1,5 @@ +yosys_gtest(techmap + libparseTest.cc + COMPONENTS + libparse +) diff --git a/chips/yosys/tests/unit/techmap/libparseTest.cc b/chips/yosys/tests/unit/techmap/libparseTest.cc new file mode 100644 index 0000000000000000000000000000000000000000..71d67aa4937d5bb69dfec64d893f255e5ba04d88 --- /dev/null +++ b/chips/yosys/tests/unit/techmap/libparseTest.cc @@ -0,0 +1,93 @@ +#include +#include "passes/techmap/libparse.h" + +YOSYS_NAMESPACE_BEGIN + +namespace RTLIL { + + class TechmapLibparseTest : public testing::Test { + protected: + TechmapLibparseTest() { + if (logger().empty()) logger().add_sink(); + } + void checkAll(std::initializer_list expressions, std::string expected) { + for (const auto& e : expressions) { + auto helper = LibertyExpression::Lexer(e); + auto tree_s = LibertyExpression::parse(helper).sexpr_str(); + EXPECT_EQ(tree_s, expected); + } + } + }; + TEST_F(TechmapLibparseTest, LibertyExpressionSpace) + { + checkAll({ + "x", + "x ", + " x", + " x ", + " x ", + }, "(pin \"x\")"); + + checkAll({ + "x y", + " x y ", + "x (y)", + " x (y) ", + "(x) y", + " (x) y ", + + "x & y", + "x&y", + "x &y", + "x& y", + " x&y ", + "x & (y)", + "x&(y)", + "x &(y)", + "x& (y)", + " x&(y) ", + "(x) & y", + "(x)&y", + "(x) &y", + "(x)& y", + " (x)&y ", + }, "(and (pin \"x\")\n" + " (pin \"y\"))" + ); + + checkAll({ + "x ^ y", + "x^y", + "x ^y", + "x^ y", + " x^y ", + }, "(xor (pin \"x\")\n" + " (pin \"y\"))" + ); + checkAll({ + "x !y", + " x !y ", + "x & !y", + "x&!y", + "x &!y", + "x& !y", + " x&!y ", + "x y'", + " x y' ", + "x & y'", + "x&y'", + "x &y'", + "x& y'", + " x&y' ", + }, "(and (pin \"x\")\n" + " (not (pin \"y\")))" + ); + checkAll({ + "( D & EN )", + }, "(and (pin \"D\")\n" + " (pin \"EN\"))" + ); + } +} + +YOSYS_NAMESPACE_END diff --git a/chips/yosys/tests/unit/verific/CMakeLists.txt b/chips/yosys/tests/unit/verific/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..fe6d30f7599fbbb52ab1861a492e8740ead6058f --- /dev/null +++ b/chips/yosys/tests/unit/verific/CMakeLists.txt @@ -0,0 +1,6 @@ +yosys_gtest(verific + verificThreadingTest.cc + COMPONENTS + read_verific + hierarchy +) diff --git a/chips/yosys/tests/unit/verific/verificThreadingTest.cc b/chips/yosys/tests/unit/verific/verificThreadingTest.cc new file mode 100644 index 0000000000000000000000000000000000000000..08738ac5706e530cb4e8c5b6055603e7ebcec1fa --- /dev/null +++ b/chips/yosys/tests/unit/verific/verificThreadingTest.cc @@ -0,0 +1,97 @@ +#include + +#include +#include +#include + +#include "kernel/register.h" + +YOSYS_NAMESPACE_BEGIN + +const char *design_source = R"( +module top +( + input [3:0] x, + input [3:0] y, + + output [3:0] A, + output [3:0] B +); + + assign A = x + y; + assign B = x - y; +endmodule +)"; + +TEST(VerificThreadingTest, DesignsConcurrencyCheck) +{ + if (logger().empty()) + logger().add_sink(false); + + const std::string filename = make_temp_file(get_base_tmpdir() + "/yosys_verific_XXXXXX.sv"); + std::ofstream(filename) << design_source; + + std::vector threads; + for (int i = 0; i < 8; ++i) { + threads.emplace_back([&] { + RTLIL::Design design; + Pass::call(&design, "verific -sv " + filename); + Pass::call(&design, "hierarchy -top top"); + EXPECT_NE(design.module(ID(top)), nullptr); + }); + } + for (auto &thread : threads) + thread.join(); + + remove(filename.c_str()); +} + +TEST(VerificThreadingTest, CleanupReleasesSession) +{ + if (logger().empty()) + logger().add_sink(false); + + const std::string filename = make_temp_file(get_base_tmpdir() + "/yosys_verific_XXXXXX.sv"); + std::ofstream(filename) << design_source; + + // read then cleanup, new design should work + // should help in multithread error handling + RTLIL::Design discarded; + Pass::call(&discarded, "verific -sv " + filename); + Pass::call(&discarded, "verific -cleanup"); + + RTLIL::Design design; + Pass::call(&design, "verific -sv " + filename); + Pass::call(&design, "hierarchy -top top"); + EXPECT_NE(design.module(ID(top)), nullptr); + EXPECT_EQ(discarded.module(ID(top)), nullptr); + + remove(filename.c_str()); +} + +TEST(VerificThreadingTest, HierarchyOnOtherDesign) +{ + if (logger().empty()) + logger().add_sink(false); + + const std::string filename = make_temp_file(get_base_tmpdir() + "/yosys_verific_XXXXXX.sv"); + std::ofstream(filename) << design_source; + + // When we load Verific design first, but then do + // hierarchy on other design, that is not coming + // from Verific but some other source + RTLIL::Design pending; + Pass::call(&pending, "verific -sv " + filename); + + RTLIL::Design other; + other.addModule("\\other"); + Pass::call(&other, "hierarchy -top other"); + EXPECT_NE(other.module("\\other"), nullptr); + + Pass::call(&pending, "hierarchy -top top"); + EXPECT_NE(pending.module(ID(top)), nullptr); + + remove(filename.c_str()); +} + +YOSYS_NAMESPACE_END diff --git a/chips/yosys/tests/unit/yosysSetupEnv.cc b/chips/yosys/tests/unit/yosysSetupEnv.cc new file mode 100644 index 0000000000000000000000000000000000000000..3f6ad2349bf5f465b1d20f566a92ec230bf1d694 --- /dev/null +++ b/chips/yosys/tests/unit/yosysSetupEnv.cc @@ -0,0 +1,11 @@ +#include + +#include "kernel/yosys.h" + +namespace { + struct YosysSetupEnvironment : ::testing::Environment { + void SetUp() override { Yosys::yosys_setup(); } + }; + const ::testing::Environment *yosys_setup_env = + ::testing::AddGlobalTestEnvironment(new YosysSetupEnvironment); +} diff --git a/chips/yosys/tests/various/.gitignore b/chips/yosys/tests/various/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..1431c4096d89372fe5503569bb28e8f8d5c1c226 --- /dev/null +++ b/chips/yosys/tests/various/.gitignore @@ -0,0 +1,12 @@ +/*.sel +/write_gzip.v +/write_gzip.v.gz +/plugin.so +/plugin_search +/plugin.so.dSYM +/ezcmdline_plugin.so +/ezcmdline_plugin.so.dSYM +/temp +/smtlib2_module.smt2 +/smtlib2_module-filtered.smt2 +/*.aig diff --git a/chips/yosys/tests/various/abc9.v b/chips/yosys/tests/various/abc9.v new file mode 100644 index 0000000000000000000000000000000000000000..13d7bf3286fa92417f7aa113f9c9cb2059db8d17 --- /dev/null +++ b/chips/yosys/tests/various/abc9.v @@ -0,0 +1,6 @@ +module abc9_test032(input clk, d, r, output reg q); +initial q = 1'b0; +always @(negedge clk or negedge r) + if (!r) q <= 1'b0; + else q <= d; +endmodule diff --git a/chips/yosys/tests/various/abc9.ys b/chips/yosys/tests/various/abc9.ys new file mode 100644 index 0000000000000000000000000000000000000000..113ee354b2256f0ceece7688f58d99e8c05b4bb9 --- /dev/null +++ b/chips/yosys/tests/various/abc9.ys @@ -0,0 +1,129 @@ +read_verilog abc9.v +hierarchy -top abc9_test032 +proc +clk2fflogic +design -save gold + +abc9 -lut 4 +check +design -stash gate + +design -import gold -as gold +design -import gate -as gate + +miter -equiv -flatten -make_assert -make_outputs gold gate miter +sat -seq 10 -verify -prove-asserts -show-ports miter + + +design -reset +read_verilog -icells < o) = 1; +endspecify +endmodule + +module abc9_test037(input [1:0] i, output o); +LUT2 #(.mask(4'b0)) lut (.i(i), .o(o)); +endmodule +EOT +abc9 + + +design -reset +read_verilog -icells < O) = P; + (I1 => O) = P; + (S => O) = P; +endspecify +endmodule + +module abc9_test039(output O); + mux_with_param #(.P(1)) m ( + .I0(1'b1), + .I1(1'b1), + .O(O), + .S(1'b0) + ); +endmodule +EOT +abc9 -lut 4 +cd abc9_test039 +select -assert-count 1 t:mux_with_param + + +# Check that dangling ABC9 black-boxes are swept away +design -reset +read_verilog -specify < O) = P; + (I1 => O) = P; + (S => O) = P; +endspecify +endmodule + +module abc9_test040(output O); + wire w; + mux_with_param #(.P(1)) m ( + .I0(1'b1), + .I1(1'b1), + .O(w), + .S(1'b0) + ); +endmodule +EOT +abc9 -lut 4 +cd abc9_test040 +select -assert-count 0 t:mux_with_param diff --git a/chips/yosys/tests/various/abstract_init.ys b/chips/yosys/tests/various/abstract_init.ys new file mode 100644 index 0000000000000000000000000000000000000000..2e0cf2e643a48063519d262bb864b7488ebecb86 --- /dev/null +++ b/chips/yosys/tests/various/abstract_init.ys @@ -0,0 +1,121 @@ +design -reset +read_verilog < muxes on inputs and outputs +design -load split_output +select -assert-count 0 t:$mux +abstract -value -enable magic w:* w:magic %d +select -assert-count 3 t:$mux +# All cells selected -> muxes on outputs only +design -load split_output +select -assert-count 0 t:$mux +abstract -value -enable magic t:* +select -assert-count 1 t:$mux +# ----------------------------------------------------------------------------- diff --git a/chips/yosys/tests/various/aiger2.ys b/chips/yosys/tests/various/aiger2.ys new file mode 100644 index 0000000000000000000000000000000000000000..97a3d7c97116f2b8944894eba7cb66e737c4905a --- /dev/null +++ b/chips/yosys/tests/various/aiger2.ys @@ -0,0 +1,299 @@ +read_verilog -icells <, 3, 3, 1) +`BIOP(ge, >=, 3, 3, 1) +`UNOP(not, ~, 3) +`UNOP_REDUCE(logic_not, !, 3) +`UNOP_REDUCE(reduce_and, &, 3) +`UNOP_REDUCE(reduce_or, |, 3) +`UNOP_REDUCE(reduce_xor, ^, 3) +`UNOP_REDUCE(reduce_xnor, ~^, 3) + +wire [3:0] mux_a, mux_b, mux_s, mux_y; +assign mux_y = mux_s ? mux_b : mux_a; + +wire [1:0] fa_a, fa_b, fa_c, fa_x, fa_y; +\$fa #( + .WIDTH(2) +) fa(.A(fa_a), .B(fa_b), .C(fa_c), .X(fa_x), .Y(fa_y)); + +wire [1:0] bwmux_a, bwmux_b, bwmux_s, bwmux_y; +\$bwmux #( + .WIDTH(2) +) bwmux(.A(bwmux_a), .B(bwmux_b), .S(bwmux_s), .Y(bwmux_y)); +endmodule +EOF + +expose -input c:* %ci* w:* %i +expose c:* %co* w:* %i +splitnets -ports +copy test gold +select test +write_aiger2 aiger2_ops.aig +select -clear +delete test +read_aiger -module_name test aiger2_ops.aig +select -assert-none test/t:$_AND_ test/t:$_NOT_ %% test/c:* %D +miter -equiv -make_outcmp -flatten gold test miter +sat -verify -show-ports -prove trigger 0 miter + +design -reset +read_verilog -icells <>, 6, 6, 3) +`BIOP(sshl, <<<, 3, 6, 6) +`BIOP(sshr, >>>, 6, 6, 3) +`BIOP(eqx, ===, 3, 4, 1) +`BIOP(nex, !==, 3, 4, 1) +`BIOP(mul, *, 3, 4, 6) +`BIOP(mul_trunc, *, 4, 4, 3) + +wire [5:0] shift1_a; wire [3:0] shift1_b; wire [2:0] shift1_y; +\$shift #(.A_SIGNED(0), .B_SIGNED(0), .A_WIDTH(6), .B_WIDTH(4), .Y_WIDTH(3)) shift1 (.A(shift1_a), .B(shift1_b), .Y(shift1_y)); +wire [2:0] shift2_a; wire [3:0] shift2_b; wire [5:0] shift2_y; +\$shift #(.A_SIGNED(1), .B_SIGNED(0), .A_WIDTH(3), .B_WIDTH(4), .Y_WIDTH(6)) shift2 (.A(shift2_a), .B(shift2_b), .Y(shift2_y)); +wire [5:0] shift3_a; wire [6:0] shift3_b; wire [2:0] shift3_y; +\$shift #(.A_SIGNED(0), .B_SIGNED(1), .A_WIDTH(6), .B_WIDTH(7), .Y_WIDTH(3)) shift3 (.A(shift3_a), .B(shift3_b), .Y(shift3_y)); +wire [2:0] shift4_a; wire [6:0] shift4_b; wire [5:0] shift4_y; +\$shift #(.A_SIGNED(1), .B_SIGNED(1), .A_WIDTH(3), .B_WIDTH(7), .Y_WIDTH(6)) shift4 (.A(shift4_a), .B(shift4_b), .Y(shift4_y)); +endmodule +EOF + +expose -input c:* %ci* w:* %i +expose c:* %co* w:* %i +splitnets -ports +copy test gold +select test +write_aiger2 aiger2_shift_mul.aig +select -clear +delete test +read_aiger -module_name test aiger2_shift_mul.aig +select -assert-none test/t:$_AND_ test/t:$_NOT_ %% test/c:* %D +miter -equiv -make_outcmp -flatten gold test miter +sat -verify -show-ports -prove trigger 0 miter + +design -reset +read_verilog -icells < async.out +tail async.out +grep PASS async.out +rm -f async_???.v async_sim async.out async.vcd diff --git a/chips/yosys/tests/various/async.v b/chips/yosys/tests/various/async.v new file mode 100644 index 0000000000000000000000000000000000000000..c27e30c4b99050e845d4b3c9b1ac93912acd8ab4 --- /dev/null +++ b/chips/yosys/tests/various/async.v @@ -0,0 +1,108 @@ +`define MAXQ 2 +module uut ( + input clk, + input d, r, e, + output [`MAXQ:0] q +); + reg q0; + always @(posedge clk) begin + if (r) + q0 <= 0; + else if (e) + q0 <= d; + end + + reg q1; + always @(posedge clk, posedge r) begin + if (r) + q1 <= 0; + else if (e) + q1 <= d; + end + + reg q2; + always @(posedge clk, negedge r) begin + if (!r) + q2 <= 0; + else if (!e) + q2 <= d; + end + + assign q = {q2, q1, q0}; +endmodule + +`ifdef TESTBENCH +module \$ff #( + parameter integer WIDTH = 1 +) ( + input [WIDTH-1:0] D, + output reg [WIDTH-1:0] Q +); + wire sysclk = testbench.sysclk; + always @(posedge sysclk) + Q <= D; +endmodule + +module testbench; + reg sysclk; + always #5 sysclk = (sysclk === 1'b0); + + reg clk; + always @(posedge sysclk) clk = (clk === 1'b0); + + reg d, r, e; + + wire [`MAXQ:0] q_uut; + uut uut (.clk(clk), .d(d), .r(r), .e(e), .q(q_uut)); + + wire [`MAXQ:0] q_syn; + syn syn (.clk(clk), .d(d), .r(r), .e(e), .q(q_syn)); + + wire [`MAXQ:0] q_prp; + prp prp (.clk(clk), .d(d), .r(r), .e(e), .q(q_prp)); + + wire [`MAXQ:0] q_a2s; + a2s a2s (.clk(clk), .d(d), .r(r), .e(e), .q(q_a2s)); + + wire [`MAXQ:0] q_ffl; + ffl ffl (.clk(clk), .d(d), .r(r), .e(e), .q(q_ffl)); + + task printq; + reg [5*8-1:0] msg; + begin + msg = "OK"; + if (q_uut !== q_syn) msg = "SYN"; + if (q_uut !== q_prp) msg = "PRP"; + if (q_uut !== q_a2s) msg = "A2S"; + if (q_uut !== q_ffl) msg = "FFL"; + $display("%6t %b %b %b %b %b %s", $time, q_uut, q_syn, q_prp, q_a2s, q_ffl, msg); + if (msg != "OK") $finish; + end + endtask + + initial if(0) begin + $dumpfile("async.vcd"); + $dumpvars(0, testbench); + end + + initial begin + @(posedge clk); + d <= 0; + r <= 0; + e <= 0; + @(posedge clk); + e <= 1; + @(posedge clk); + e <= 0; + repeat (10000) begin + @(posedge clk); + printq; + d <= $random; + r <= $random; + e <= $random; + end + $display("PASS"); + $finish; + end +endmodule +`endif diff --git a/chips/yosys/tests/various/attrib05_port_conn.v b/chips/yosys/tests/various/attrib05_port_conn.v new file mode 100644 index 0000000000000000000000000000000000000000..75e2ebcb77e0f070614183054e77bcd95824f676 --- /dev/null +++ b/chips/yosys/tests/various/attrib05_port_conn.v @@ -0,0 +1,20 @@ +module bar(clk, rst, inp, out); + input wire clk; + input wire rst; + input wire inp; + output reg out; + + always @(posedge clk) + if (rst) out <= 1'd0; + else out <= ~inp; + +endmodule + +module foo(clk, rst, inp, out); + input wire clk; + input wire rst; + input wire inp; + output wire out; + + bar bar_instance ( (* clock_connected *) clk, rst, (* this_is_the_input *) inp, out); +endmodule diff --git a/chips/yosys/tests/various/attrib05_port_conn.ys b/chips/yosys/tests/various/attrib05_port_conn.ys new file mode 100644 index 0000000000000000000000000000000000000000..27a016733a687358cfaee16d1c3e796ea5952f9b --- /dev/null +++ b/chips/yosys/tests/various/attrib05_port_conn.ys @@ -0,0 +1,2 @@ +# Read and parse Verilog file +read_verilog attrib05_port_conn.v diff --git a/chips/yosys/tests/various/attrib07_func_call.v b/chips/yosys/tests/various/attrib07_func_call.v new file mode 100644 index 0000000000000000000000000000000000000000..a91bcec1dac665a5e93b944faece05464cf618a5 --- /dev/null +++ b/chips/yosys/tests/various/attrib07_func_call.v @@ -0,0 +1,20 @@ +function [7:0] do_add; + input [7:0] inp_a; + input [7:0] inp_b; + + do_add = inp_a + inp_b; + +endfunction + +module foo(clk, rst, inp_a, inp_b, out); + input wire clk; + input wire rst; + input wire [7:0] inp_a; + input wire [7:0] inp_b; + output reg [7:0] out; + + always @(posedge clk) + if (rst) out <= 0; + else out <= do_add (* combinational_adder *) (inp_a, inp_b); + +endmodule diff --git a/chips/yosys/tests/various/attrib07_func_call.ys b/chips/yosys/tests/various/attrib07_func_call.ys new file mode 100644 index 0000000000000000000000000000000000000000..7748276510bd6fdc3fc182a8f7e4bb5da6d927dd --- /dev/null +++ b/chips/yosys/tests/various/attrib07_func_call.ys @@ -0,0 +1,2 @@ +# Read and parse Verilog file +read_verilog attrib07_func_call.v diff --git a/chips/yosys/tests/various/autoname.ys b/chips/yosys/tests/various/autoname.ys new file mode 100644 index 0000000000000000000000000000000000000000..22b532f2c3884ac1abff230ee23cbfde077d6c9b --- /dev/null +++ b/chips/yosys/tests/various/autoname.ys @@ -0,0 +1,226 @@ +# prefer output name +design -reset +read_rtlil <' temp/barrier.fir + +write_smv temp/barrier.smv +! grep -qE '_t := resize\(_\$.*and\$' temp/barrier.smv + +write_cxxrtl temp/barrier.cc +! grep -qF '\bar ' temp/barrier.cc + +write_btor temp/barrier.btor +write_aiger2 temp/barrier.aig + +# write_xaiger2 cuts at barriers so the cell is kept by -mapping_prep +write_xaiger2 -mapping_prep -map2 temp/barrier.map2 temp/barrier.xaig +select -assert-count 1 t:$barrier +select -assert-count 0 t:$and diff --git a/chips/yosys/tests/various/barrier_flatten_prep.ys b/chips/yosys/tests/various/barrier_flatten_prep.ys new file mode 100644 index 0000000000000000000000000000000000000000..24142bf302613d040be19f433fa3953903ff90e9 --- /dev/null +++ b/chips/yosys/tests/various/barrier_flatten_prep.ys @@ -0,0 +1,160 @@ +# port connections that drive a public wire get a barrier +# port connections that drive a private wire get a plain connection + +read_rtlil < -1 1` for the zero-width operands of memory_map's address decoder ($eq with +# A_WIDTH = B_WIDTH = 0); neither is valid BTOR2 (a sort width must be positive, -1 is not a node id). +read_verilog -sv -nomem2reg < 0; +endmodule +EOT + + +design -reset +read_verilog <((-3'sd0)>>(4'sd2)))}}; + + assign y8 = (-(!($signed({3{p9}})<(p4?b4:b5)))); +endmodule +EOT + + +design -reset +read_verilog <&2; exit 1' ERR + +cat > chparam1.sv << "EOT" +module top #( + parameter [31:0] X = 0 +) ( + input [31:0] din, + output [31:0] dout +); + assign dout = X-din; +endmodule + +module top_props #( + parameter [31:0] X = 0 +) ( + input [31:0] dout +); + always @* assert (dout != X); +endmodule + +bind top top_props #(.X(123456789)) props (.*); +EOT + +cat > chparam2.sv << "EOT" +module top #( + parameter [31:0] X = 0 +) ( + input [31:0] din, + output [31:0] dout +); + assign dout = X-din; + always @* assert (dout != 123456789); +endmodule +EOT + +if ${YOSYS} -q -p 'verific -sv chparam1.sv'; then + ${YOSYS} -q -p 'verific -sv chparam1.sv; hierarchy -chparam X 123123123 -top top; prep -flatten' \ + -p 'async2sync' \ + -p 'sat -verify -prove-asserts -show-ports -set din[0] 1' \ + -p 'sat -falsify -prove-asserts -show-ports -set din[0] 0' + + ${YOSYS} -q -p 'verific -sv chparam2.sv; hierarchy -chparam X 123123123 -top top; prep -flatten' \ + -p 'async2sync' \ + -p 'sat -verify -prove-asserts -show-ports -set din[0] 1' \ + -p 'sat -falsify -prove-asserts -show-ports -set din[0] 0' +fi +${YOSYS} -q -p 'read_verilog -sv chparam2.sv; hierarchy -chparam X 123123123 -top top; prep -flatten' \ + -p 'async2sync' \ + -p 'sat -verify -prove-asserts -show-ports -set din[0] 1' \ + -p 'sat -falsify -prove-asserts -show-ports -set din[0] 0' + +rm chparam1.sv +rm chparam2.sv diff --git a/chips/yosys/tests/various/clk2fflogic_effects.sh b/chips/yosys/tests/various/clk2fflogic_effects.sh new file mode 100644 index 0000000000000000000000000000000000000000..6d0046161eb8f61eed6a232c139ff030a9c09169 --- /dev/null +++ b/chips/yosys/tests/various/clk2fflogic_effects.sh @@ -0,0 +1,35 @@ +#!/usr/bin/env bash +set -e + +# TODO: when sim gets native $check support, remove the -DNO_ASSERT here +echo Running yosys sim +${YOSYS} -q -p " +read_verilog -formal -DNO_ASSERT clk2fflogic_effects.sv +hierarchy -top top; proc;; + +tee -q -o clk2fflogic_effects.sim.log sim -q -n 32 +" +echo Running yosys clk2fflogic sim +${YOSYS} -q -p " +read_verilog -formal clk2fflogic_effects.sv +hierarchy -top top; proc;; +clk2fflogic;; + +logger -nowarn ^Assertion +tee -q -o clk2fflogic_effects.clk2fflogic.log sim -q -n 32 +" + +echo Running iverilog sim +iverilog -g2012 -DNO_ASSERT -o clk2fflogic_effects.iv.out clk2fflogic_effects.sv + + +./clk2fflogic_effects.iv.out > clk2fflogic_effects.iv.log + +gawk '/([0-9]+):/{T=$1;print};/^Failed/{print T,$0}' clk2fflogic_effects.iv.log | sort > clk2fflogic_effects.iv.sorted.log +gawk '/([0-9]+):/{T=$1;print};/^Failed/{print T,$0}' clk2fflogic_effects.sim.log | sort > clk2fflogic_effects.sim.sorted.log +gawk '/([0-9]+):/{T=$1;print};/^Failed/{print T,$0}' clk2fflogic_effects.clk2fflogic.log | sort > clk2fflogic_effects.clk2fflogic.sorted.log + +echo Comparing iverilog sim vs yosys sim +cmp clk2fflogic_effects.iv.sorted.log clk2fflogic_effects.sim.sorted.log +echo Comparing iverilog sim vs yosys clk2fflogic sim +cmp clk2fflogic_effects.iv.sorted.log clk2fflogic_effects.clk2fflogic.sorted.log diff --git a/chips/yosys/tests/various/clk2fflogic_effects.sv b/chips/yosys/tests/various/clk2fflogic_effects.sv new file mode 100644 index 0000000000000000000000000000000000000000..b38aba3c9bbac3a46d0cee00dfdd6b0dfd13a66a --- /dev/null +++ b/chips/yosys/tests/various/clk2fflogic_effects.sv @@ -0,0 +1,101 @@ +module top; + +(* gclk *) +reg gclk; + +reg clk = 0; +always @(posedge gclk) + clk <= !clk; + +reg [5:0] counter = 0; + +reg eff_0_trg = '0; +reg eff_0_en = '0; + +reg eff_1_trgA = '0; +reg eff_1_trgB = '0; +reg eff_1_en = '0; + +reg eff_2_trgA = '0; +reg eff_2_trgB = '0; +reg eff_2_en = '0; + +reg eff_3_trg = '0; +reg eff_3_en = '0; +reg eff_3_a = '0; + +`ifdef FAST +always @(posedge gclk) begin +`else +always @(posedge clk) begin +`endif + counter <= counter + 1; + + eff_0_trg = 32'b00000000000000110011001100101010 >> counter; + eff_0_en <= 32'b00000000000001100000110110110110 >> counter; + + eff_1_trgA = 32'b00000000000000000011110000011110 >> counter; + eff_1_trgB = 32'b00000000000000001111000001111000 >> counter; + eff_1_en <= 32'b00000000000000001010101010101010 >> counter; + + eff_2_trgA = counter[0]; + eff_2_trgB = !counter[0]; + eff_2_en <= 32'b00000000000000000000001111111100 >> counter; + + eff_3_trg = 32'b10101010101010101010101010101010 >> counter; + eff_3_en <= 32'b11101110010001001110111001000100 >> counter; + eff_3_a <= 32'b11111010111110100101000001010000 >> counter; +end + +always @(posedge eff_0_trg) + if (eff_0_en) + $display("%02d: eff0 +", counter); + +always @(negedge eff_0_trg) + if (eff_0_en) + $display("%02d: eff0 -", counter); + +always @(posedge eff_0_trg, negedge eff_0_trg) + if (eff_0_en) + $display("%02d: eff0 *", counter); + +always @(posedge eff_1_trgA, posedge eff_1_trgB) + if (eff_1_en) + $display("%02d: eff1 ++", counter); + +always @(posedge eff_1_trgA, negedge eff_1_trgB) + if (eff_1_en) + $display("%02d: eff1 +-", counter); + +always @(negedge eff_1_trgA, posedge eff_1_trgB) + if (eff_1_en) + $display("%02d: eff1 -+", counter); + +always @(negedge eff_1_trgA, negedge eff_1_trgB) + if (eff_1_en) + $display("%02d: eff1 --", counter); + +always @(posedge eff_2_trgA, posedge eff_2_trgB) + if (eff_2_en) + $display("repeated"); + +always @(posedge eff_3_trg) + if (eff_3_en) begin + $display("%02d: eff3 vvv", counter); +`ifdef NO_ASSERT + if (!eff_3_a) + $display("Failed assertion eff3 at"); +`else + eff3: assert(eff_3_a); +`endif + end + +`ifdef __ICARUS__ +initial gclk = 0; +always @(gclk) gclk <= #5 !gclk; +always @(posedge gclk) + if (counter == 32) + $finish(0); +`endif + +endmodule diff --git a/chips/yosys/tests/various/const_arg_loop.sv b/chips/yosys/tests/various/const_arg_loop.sv new file mode 100644 index 0000000000000000000000000000000000000000..f28d06e68d1351032cd6f05f7f8e66a9fce64452 --- /dev/null +++ b/chips/yosys/tests/various/const_arg_loop.sv @@ -0,0 +1,92 @@ +module top; + function automatic [31:0] operation1; + input [4:0] rounds; + input integer num; + integer i; + begin + begin : shadow + integer rounds; + rounds = 0; + end + for (i = 0; i < rounds; i = i + 1) + num = num * 2; + operation1 = num; + end + endfunction + + function automatic [31:0] pass_through; + input [31:0] inp; + pass_through = inp; + endfunction + + function automatic [31:0] operation2; + input [4:0] inp; + input integer num; + begin + inp[0] = inp[0] ^ 1; + operation2 = num * inp; + end + endfunction + + function automatic [31:0] operation3; + input [4:0] rounds; + input integer num; + reg [4:0] rounds; + integer i; + begin + begin : shadow + integer rounds; + rounds = 0; + end + for (i = 0; i < rounds; i = i + 1) + num = num * 2; + operation3 = num; + end + endfunction + + function automatic [16:0] operation4; + input [15:0] a; + input b; + operation4 = {a, b}; + endfunction + + function automatic integer operation5; + input x; + integer x; + operation5 = x; + endfunction + + wire [31:0] a; + assign a = 2; + + parameter A = 3; + + wire [31:0] x1; + assign x1 = operation1(A, a); + + wire [31:0] x1b; + assign x1b = operation1(pass_through(A), a); + + wire [31:0] x2; + assign x2 = operation2(A, a); + + wire [31:0] x3; + assign x3 = operation3(A, a); + + wire [16:0] x4; + assign x4 = operation4(a[15:0], 0); + + wire [31:0] x5; + assign x5 = operation5(64); + + always_comb begin + assert(a == 2); + assert(A == 3); + assert(x1 == 16); + assert(x1b == 16); + assert(x2 == 4); + assert(x3 == 16); + assert(x4 == a << 1); + assert(x5 == 64); + end +endmodule diff --git a/chips/yosys/tests/various/const_arg_loop.ys b/chips/yosys/tests/various/const_arg_loop.ys new file mode 100644 index 0000000000000000000000000000000000000000..21554cc0a490a1e9dcbaa057f40ac680f5d5e6da --- /dev/null +++ b/chips/yosys/tests/various/const_arg_loop.ys @@ -0,0 +1,7 @@ +read_verilog -sv const_arg_loop.sv +hierarchy +proc +opt -full +select -module top +async2sync +sat -verify -tempinduct -prove-asserts -show-all diff --git a/chips/yosys/tests/various/const_cmdline.ys b/chips/yosys/tests/various/const_cmdline.ys new file mode 100644 index 0000000000000000000000000000000000000000..b620d9a5066bee19693f0067bdd6f195ee3e4bdb --- /dev/null +++ b/chips/yosys/tests/various/const_cmdline.ys @@ -0,0 +1,15 @@ +# https://github.com/YosysHQ/yosys/issues/6009 +read_verilog <&2; exit 1' ERR + +tmp=$(mktemp -d) +trap 'rm -rf "$tmp"' EXIT + +cat > "$tmp/design.v" <<'EOT' +module top(output [7:0] o); +assign o = 8'hAA; +endmodule +EOT + +printf "setattr -set foo 2'd7 t:*\n" > "$tmp/inner.ys" +cat > "$tmp/outer.ys" <&1) +echo "$out" | grep -E "inner\.ys:1: Warning: While parsing constant \`2'd7'" > /dev/null +echo "$out" | grep -E "outer\.ys:[0-9]+: Warning: While parsing constant \`3'd15'" > /dev/null + +# cmd fallback - no source location prefix +out=$(${YOSYS} -q -p "read_verilog $tmp/design.v; prep -top top; setattr -set foo 2'd7 t:*" 2>&1) +echo "$out" | grep -E "^Warning: While parsing constant \`2'd7'" > /dev/null diff --git a/chips/yosys/tests/various/const_func.sv b/chips/yosys/tests/various/const_func.sv new file mode 100644 index 0000000000000000000000000000000000000000..af65f5c73f78c8db0c720b755c54fcd37e391cec --- /dev/null +++ b/chips/yosys/tests/various/const_func.sv @@ -0,0 +1,86 @@ +module Example(outA, outB, outC, outD); + parameter OUTPUT = "FOO"; + output wire [23:0] outA; + output wire [23:0] outB; + output reg outC, outD; + function automatic [23:0] flip; + input [23:0] inp; + flip = ~inp; + endfunction + + generate + if (flip(OUTPUT) == flip("BAR")) + assign outA = OUTPUT; + else + assign outA = 0; + + case (flip(OUTPUT)) + flip("FOO"): assign outB = OUTPUT; + flip("BAR"): assign outB = 0; + flip("BAZ"): assign outB = "HI"; + endcase + + genvar i; + initial outC = 0; + for (i = 0; i != flip(flip(OUTPUT[15:8])); i = i + 1) + if (i + 1 == flip(flip("O"))) + initial outC = 1; + endgenerate + + integer j; + initial begin + outD = 1; + for (j = 0; j != flip(flip(OUTPUT[15:8])); j = j + 1) + if (j + 1 == flip(flip("O"))) + outD = 0; + end +endmodule + +module top(out); + wire [23:0] a1, a2, a3, a4; + wire [23:0] b1, b2, b3, b4; + wire c1, c2, c3, c4; + wire d1, d2, d3, d4; + Example e1(a1, b1, c1, d1); + Example #("FOO") e2(a2, b2, c2, d2); + Example #("BAR") e3(a3, b3, c3, d3); + Example #("BAZ") e4(a4, b4, c4, d4); + + output wire [24 * 8 - 1 + 4 :0] out; + assign out = { + a1, a2, a3, a4, + b1, b2, b3, b4, + c1, c2, c3, c4, + d1, d2, d3, d4}; + + function signed [31:0] negate; + input integer inp; + negate = ~inp; + endfunction + parameter W = 10; + parameter X = 3; + localparam signed Y = $floor(W / X); + localparam signed Z = negate($floor(W / X)); + + always_comb begin + assert(a1 == 0); + assert(a2 == 0); + assert(a3 == "BAR"); + assert(a4 == 0); + assert(b1 == "FOO"); + assert(b2 == "FOO"); + assert(b3 == 0); + assert(b4 == "HI"); + assert(c1 == 1); + assert(c2 == 1); + assert(c3 == 0); + assert(c4 == 0); + assert(d1 == 0); + assert(d2 == 0); + assert(d3 == 1); + assert(d4 == 1); + + assert(Y == 3); + assert(Z == ~3); + end +endmodule diff --git a/chips/yosys/tests/various/const_func.ys b/chips/yosys/tests/various/const_func.ys new file mode 100644 index 0000000000000000000000000000000000000000..e721e0e815783958c934817cb36e9267408cc13b --- /dev/null +++ b/chips/yosys/tests/various/const_func.ys @@ -0,0 +1,8 @@ +read_verilog -sv const_func.sv +hierarchy +proc +flatten +opt -full +select -module top +async2sync +sat -verify -tempinduct -prove-asserts -show-all diff --git a/chips/yosys/tests/various/const_func_block_var.v b/chips/yosys/tests/various/const_func_block_var.v new file mode 100644 index 0000000000000000000000000000000000000000..cb60844ab241ff5b9f9b381abfee25bc939ac602 --- /dev/null +++ b/chips/yosys/tests/various/const_func_block_var.v @@ -0,0 +1,26 @@ +module top(out); + function integer operation; + input integer num; + localparam incr = 1; + localparam mult = 1; + begin + operation = 0; + begin : op_i + integer i; + for (i = 0; i * mult < 2; i = i + incr) + begin : op_j + integer j; + localparam other_mult = 2; + for (j = i; j < i * other_mult; j = j + incr) + num = num + incr; + end + num = num * 2; + end + operation = num; + end + endfunction + + localparam res = operation(4); + output wire [31:0] out; + assign out = res; +endmodule diff --git a/chips/yosys/tests/various/const_func_block_var.ys b/chips/yosys/tests/various/const_func_block_var.ys new file mode 100644 index 0000000000000000000000000000000000000000..7c2e85c64bd971f1dce3138c274ec50f969f22e6 --- /dev/null +++ b/chips/yosys/tests/various/const_func_block_var.ys @@ -0,0 +1 @@ +read_verilog const_func_block_var.v diff --git a/chips/yosys/tests/various/const_shift_empty_arg.ys b/chips/yosys/tests/various/const_shift_empty_arg.ys new file mode 100644 index 0000000000000000000000000000000000000000..4073e198d3bce204409b21471972c14d978570a3 --- /dev/null +++ b/chips/yosys/tests/various/const_shift_empty_arg.ys @@ -0,0 +1,49 @@ +# Regression test for #5684: const_shift_worker must not crash when arg1 is +# empty. + +read_json << EOF +{ + "modules": { + "sshl": { + "cells": { + "sshlCell": { + "connections": { + "A": [], + "B": [3], + "Y": [1] + }, + "parameters": { + "A_SIGNED": "1", + "A_WIDTH": "0", + "B_SIGNED": "0", + "B_WIDTH": "1", + "Y_WIDTH": "1" + }, + "port_directions": { + "A": "input", + "B": "input", + "Y": "output" + }, + "type": "$sshl" + } + }, + "ports": { + "A": { + "bits": [], + "direction": "input" + }, + "B": { + "bits": [3], + "direction": "input" + }, + "Y": { + "bits": [1], + "direction": "output" + } + } + } + } +} +EOF + +eval -set B 0 -show Y sshl diff --git a/chips/yosys/tests/various/constant_drive_conflict.ys b/chips/yosys/tests/various/constant_drive_conflict.ys new file mode 100644 index 0000000000000000000000000000000000000000..1246cbcae01bc1cc01101388a56a43108f66fcb7 --- /dev/null +++ b/chips/yosys/tests/various/constant_drive_conflict.ys @@ -0,0 +1,51 @@ +read_verilog < o) = 1; +endspecify +endmodule + +(* whitebox *) +module wb(input a, b, output o); +assign o = a ^ b; +endmodule + +module some_mod(input a, b, c, output o); +assign o = a & (b | c); +endmodule +EOT + +hierarchy -top top +design -save hier + +select -assert-none t:$anyseq +select -assert-count 3 =t:?b +cutpoint -blackbox + +select -assert-none =t:?b +select -assert-none r:SOME_PARAM + +select -assert-count 3 t:$anyseq +select -assert-count 3 t:$scopeinfo +select -assert-count 3 t:$scopeinfo r:TYPE=blackbox %i +select -assert-count 3 t:$scopeinfo n:*cutpoint.cc* %i + +# -noscopeinfo works with -blackbox +design -load hier +cutpoint -blackbox -noscopeinfo +select -assert-none t:$scopeinfo + +# cutpoint -blackbox === cutpoint =A:whitebox =A:blackbox %u %C +# (simplified to =A:*box %C) +design -load hier +cutpoint -blackbox +rename -enumerate -pattern A_% t:$scopeinfo +rename -enumerate -pattern B_% t:$anyseq +rename -enumerate -pattern C_% w:*Anyseq* +design -save gold +select -write cutpoint.gold.sel =* + +design -load hier +cutpoint =A:*box %C +rename -enumerate -pattern A_% t:$scopeinfo +rename -enumerate -pattern B_% t:$anyseq +rename -enumerate -pattern C_% w:*Anyseq* +design -save gate +select -write cutpoint.gate.sel +select -read cutpoint.gold.sel +# nothing in gate but not gold +select -assert-none % %n + +design -load gold +select -read cutpoint.gate.sel +# nothing in gold but not gate +select -assert-none % %n + +# replacing the blackbox with a verific-style unknown module should work too +# (note this specific example loses the values of SOME_PARAM which would +# normally be retained by verific) +design -load hier +delete =bb +read_rtlil << EOT +attribute \blackbox 1 +module \bb + parameter \SOME_PARAM 0 + wire inout 3 \o + wire inout 2 \b + wire inout 1 \a +end +EOT +cutpoint -blackbox +check -assert + +# also concatenated signals, and signals between two inout ports +design -load hier +delete top =bb +read_verilog << EOT +module top(input [1:0] a, b, output [1:0] o); + wire [1:0] c, d, e; + bb #(.SOME_PARAM(1)) bb1 (.a ({a[0], e[1]}), .b (b), .o (c)); + bb #(.SOME_PARAM(2)) bb2 (.a ({c[1], a[0]}), .b (c), .o (d)); + wb wb1 (.a (a), .b (b), .o (e)); + some_mod some_inst (.a (c), .b (d), .c (e), .o (o)); +endmodule +EOT +read_rtlil << EOT +attribute \blackbox 1 +module \bb + parameter \SOME_PARAM 0 + wire inout 3 width 2 \o + wire inout 2 width 2 \b + wire inout 1 width 2 \a +end +EOT +cutpoint -blackbox +check -assert diff --git a/chips/yosys/tests/various/cutpoint_whole.ys b/chips/yosys/tests/various/cutpoint_whole.ys new file mode 100644 index 0000000000000000000000000000000000000000..174add205f68d39996e4b431618e56f910ce73c9 --- /dev/null +++ b/chips/yosys/tests/various/cutpoint_whole.ys @@ -0,0 +1,50 @@ +read_verilog << EOT +module top(input a, b, output o); + wire c, d, e; + bb bb1 (.a (a), .b (b), .o (c)); + sub_mod sub_inst (.a (a), .b (b), .o (e)); + some_mod some_inst (.a (c), .b (d), .c (e), .o (o)); +endmodule + +(* blackbox *) +module bb #( parameter SOME_PARAM=0 ) (input a, b, output o); +endmodule + +module sub_mod(input a, b, output o); + bb bb2 (.a (a), .b (b), .o (o)); +endmodule + +module some_mod(input a, b, c, output o); +assign o = a & (b | c); +endmodule +EOT + +hierarchy -top top +design -stash hier + +# removing cell +design -load hier +logger -expect log "Removing cell .*, making all cell outputs cutpoints" 1 +cutpoint sub_mod/bb2 +logger -check-expected +logger -werror "Removing cell .*, making all cell outputs cutpoints" + +# removing wires +design -load hier +logger -expect log "Making wire .* a cutpoint" 1 +cutpoint top/c +logger -check-expected +logger -werror "Making wire .* a cutpoint" + +# removing output wires +design -load hier +logger -expect log "Making output wire .* a cutpoint" 1 +cutpoint sub_mod/o +logger -check-expected +logger -werror "Making output wire .* a cutpoint" + +# whole module optimization, doesn't do any of the previous +design -load hier +logger -expect log "Making all outputs of module .* cut points, removing module contents" 1 +cutpoint sub_mod +logger -check-expected diff --git a/chips/yosys/tests/various/debugon.ys b/chips/yosys/tests/various/debugon.ys new file mode 100644 index 0000000000000000000000000000000000000000..a984a26bba871523a66bf6b734d2304689558058 --- /dev/null +++ b/chips/yosys/tests/various/debugon.ys @@ -0,0 +1,14 @@ +# Test debug -on/-off modes + +design -reset + +read_verilog < exits 10 with v 1 +# - UNSAT: p cnf 1 2; clauses: "1 0" and "-1 0" -> exits 20 +set -e + +if [ "$#" -ne 1 ]; then + echo "usage: $0 " >&2 + exit 1 +fi + +awk ' +BEGIN { + vars = 0; + clauses = 0; + clause_count = 0; + clause_data = ""; + current = ""; +} +$1 == "c" { + next; +} +$1 == "p" && $2 == "cnf" { + vars = $3; + clauses = $4; + next; +} +{ + for (i = 1; i <= NF; i++) { + lit = $i; + if (lit == 0) { + clause_count++; + if (clause_data != "") + clause_data = clause_data ";" current; + else + clause_data = current; + current = ""; + } else { + if (current == "") + current = lit; + else + current = current "," lit; + } + } +} +END { + if (vars == 1 && clause_count == 1 && clause_data == "1") { + print "s SATISFIABLE"; + print "v 1 0"; + exit 10; + } + if (vars == 1 && clause_count == 2 && clause_data == "1;-1") { + print "s UNSATISFIABLE"; + exit 20; + } + print "c unexpected CNF for dummy solver"; + print "c vars=" vars " header_clauses=" clauses " parsed_clauses=" clause_count " data=" clause_data; + exit 1; +} +' "$1" diff --git a/chips/yosys/tests/various/ezcmdline_plugin.cc b/chips/yosys/tests/various/ezcmdline_plugin.cc new file mode 100644 index 0000000000000000000000000000000000000000..b775829b3e42b4583d0669c5e54f8a5286050dba --- /dev/null +++ b/chips/yosys/tests/various/ezcmdline_plugin.cc @@ -0,0 +1,53 @@ +#include "kernel/yosys.h" +#include "libs/ezsat/ezcmdline.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct EzCmdlineTestPass : public Pass { + EzCmdlineTestPass() : Pass("ezcmdline_test", "smoke-test ezCmdlineSAT") { } + void execute(std::vector args, RTLIL::Design *design) override + { + std::string cmd; + size_t argidx = 1; + + while (argidx < args.size()) { + if (args[argidx] == "-cmd" && argidx + 1 < args.size()) { + cmd = args[argidx + 1]; + argidx += 2; + continue; + } + break; + } + + extra_args(args, argidx, design); + + if (cmd.empty()) + log_error("Missing -cmd argument.\n"); + + ezCmdlineSAT sat(cmd); + sat.non_incremental(); + + // assume("A") adds a permanent CNF clause "A". + sat.assume(sat.VAR("A")); + + std::vector model_expressions; + std::vector model_values; + model_expressions.push_back(sat.VAR("A")); + + // Expect SAT with A=true. + if (!sat.solve(model_expressions, model_values)) + log_error("ezCmdlineSAT SAT case failed.\n"); + if (model_values.size() != 1 || !model_values[0]) + log_error("ezCmdlineSAT SAT model mismatch.\n"); + + // Passing NOT("A") here adds a temporary unit clause for this solve call, + // so the solver sees A && !A and must return UNSAT. + if (sat.solve(model_expressions, model_values, sat.NOT("A"))) + log_error("ezCmdlineSAT UNSAT case failed.\n"); + + log("ezcmdline_test passed!\n"); + } +} EzCmdlineTestPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/tests/various/ezcmdline_plugin.sh b/chips/yosys/tests/various/ezcmdline_plugin.sh new file mode 100644 index 0000000000000000000000000000000000000000..102fba06bc15a7e4978675c1c7b6e83100f9b0fa --- /dev/null +++ b/chips/yosys/tests/various/ezcmdline_plugin.sh @@ -0,0 +1,12 @@ +set -e + +DIR=$(cd "$(dirname "$0")" && pwd) +BASEDIR=$(cd "$DIR/../.." && pwd) +rm -f "$DIR/ezcmdline_plugin.so" +chmod +x "$DIR/ezcmdline_dummy_solver" +CXXFLAGS=$(${YOSYS_CONFIG} --cxxflags) +DATDIR=$(${YOSYS_CONFIG} --datdir) +DATDIR=${DATDIR//\//\\\/} +CXXFLAGS=${CXXFLAGS//$DATDIR/$BUILD_DIR/share} +${YOSYS_CONFIG} --exec --cxx ${CXXFLAGS} -I"$BASEDIR" --ldflags -shared -o "$DIR/ezcmdline_plugin.so" "$DIR/ezcmdline_plugin.cc" +${YOSYS} -m "$DIR/ezcmdline_plugin.so" -p "ezcmdline_test -cmd $DIR/ezcmdline_dummy_solver" | grep -q "ezcmdline_test passed!" diff --git a/chips/yosys/tests/various/fib.v b/chips/yosys/tests/various/fib.v new file mode 100644 index 0000000000000000000000000000000000000000..986749626431dc7053337b08b1989534608e05a8 --- /dev/null +++ b/chips/yosys/tests/various/fib.v @@ -0,0 +1,65 @@ +module gate( + off, fib0, fib1, fib2, fib3, fib4, fib5, fib6, fib7, fib8, fib9 +); + input wire signed [31:0] off; + + function automatic integer fib( + input integer k + ); + if (k == 0) + fib = 0; + else if (k == 1) + fib = 1; + else + fib = fib(k - 1) + fib(k - 2); + endfunction + + function automatic integer fib_wrap( + input integer k, + output integer o + ); + o = off + fib(k); + endfunction + + output integer fib0; + output integer fib1; + output integer fib2; + output integer fib3; + output integer fib4; + output integer fib5; + output integer fib6; + output integer fib7; + output integer fib8; + output integer fib9; + + initial begin : blk + integer unused; + unused = fib_wrap(0, fib0); + unused = fib_wrap(1, fib1); + unused = fib_wrap(2, fib2); + unused = fib_wrap(3, fib3); + unused = fib_wrap(4, fib4); + unused = fib_wrap(5, fib5); + unused = fib_wrap(6, fib6); + unused = fib_wrap(7, fib7); + unused = fib_wrap(8, fib8); + unused = fib_wrap(9, fib9); + end +endmodule + +module gold( + off, fib0, fib1, fib2, fib3, fib4, fib5, fib6, fib7, fib8, fib9 +); + input wire signed [31:0] off; + + output integer fib0 = off + 0; + output integer fib1 = off + 1; + output integer fib2 = off + 1; + output integer fib3 = off + 2; + output integer fib4 = off + 3; + output integer fib5 = off + 5; + output integer fib6 = off + 8; + output integer fib7 = off + 13; + output integer fib8 = off + 21; + output integer fib9 = off + 34; +endmodule diff --git a/chips/yosys/tests/various/fib.ys b/chips/yosys/tests/various/fib.ys new file mode 100644 index 0000000000000000000000000000000000000000..946e0738a814779cc73b08de1c87be9c625cf8fe --- /dev/null +++ b/chips/yosys/tests/various/fib.ys @@ -0,0 +1,6 @@ +read_verilog fib.v +hierarchy +proc +equiv_make gold gate equiv +equiv_simple +equiv_status -assert diff --git a/chips/yosys/tests/various/fib_tern.v b/chips/yosys/tests/various/fib_tern.v new file mode 100644 index 0000000000000000000000000000000000000000..fefde74cebdcec4fb372fc3dd2a6899e546a880d --- /dev/null +++ b/chips/yosys/tests/various/fib_tern.v @@ -0,0 +1,70 @@ +module gate( + off, fib0, fib1, fib2, fib3, fib4, fib5, fib6, fib7, fib8, fib9 +); + input wire signed [31:0] off; + + function automatic blah( + input x + ); + blah = x; + endfunction + + function automatic integer fib( + input integer k + ); + fib = k == 0 + ? 0 + : k == 1 + ? 1 + : fib(k - 1) + fib(k - 2); + endfunction + + function automatic integer fib_wrap( + input integer k, + output integer o + ); + o = off + fib(k); + endfunction + + output integer fib0; + output integer fib1; + output integer fib2; + output integer fib3; + output integer fib4; + output integer fib5; + output integer fib6; + output integer fib7; + output integer fib8; + output integer fib9; + + initial begin : blk + integer unused; + unused = fib_wrap(0, fib0); + unused = fib_wrap(1, fib1); + unused = fib_wrap(2, fib2); + unused = fib_wrap(3, fib3); + unused = fib_wrap(4, fib4); + unused = fib_wrap(5, fib5); + unused = fib_wrap(6, fib6); + unused = fib_wrap(7, fib7); + unused = fib_wrap(8, fib8); + unused = fib_wrap(9, fib9); + end +endmodule + +module gold( + off, fib0, fib1, fib2, fib3, fib4, fib5, fib6, fib7, fib8, fib9 +); + input wire signed [31:0] off; + + output integer fib0 = off + 0; + output integer fib1 = off + 1; + output integer fib2 = off + 1; + output integer fib3 = off + 2; + output integer fib4 = off + 3; + output integer fib5 = off + 5; + output integer fib6 = off + 8; + output integer fib7 = off + 13; + output integer fib8 = off + 21; + output integer fib9 = off + 34; +endmodule diff --git a/chips/yosys/tests/various/fib_tern.ys b/chips/yosys/tests/various/fib_tern.ys new file mode 100644 index 0000000000000000000000000000000000000000..e5bf186e1aa22f879034054780be12a82561c840 --- /dev/null +++ b/chips/yosys/tests/various/fib_tern.ys @@ -0,0 +1,6 @@ +read_verilog fib_tern.v +hierarchy +proc +equiv_make gold gate equiv +equiv_simple +equiv_status -assert diff --git a/chips/yosys/tests/various/formalff_declockgate.ys b/chips/yosys/tests/various/formalff_declockgate.ys new file mode 100644 index 0000000000000000000000000000000000000000..3dd47ea7839fc18132b5bdc81df71fdd1f7fc72e --- /dev/null +++ b/chips/yosys/tests/various/formalff_declockgate.ys @@ -0,0 +1,83 @@ +# based on the peepopt_formal.ys test +read_verilog -sv <> 2); + assign cone2_2 = (b ^ {4{c[2:0]}}) & 8'hAA; + + reg [7:0] reg3; + always @(posedge clk or posedge rst) begin + if (rst) + reg3 <= 8'h0F; + else + reg3 <= cone2_1 ^ cone2_2 ^ reg1[7:0]; + end + + wire [7:0] cone2_3; + assign cone2_3 = reg3 | (reg2 ^ 8'h55); + + // Outputs + assign out1 = cone1_3 | (reg1 ^ 8'hA5); + assign out2 = cone2_3 & (reg3 | 8'h5A); + + always @(posedge clk) begin + assert (out1 == 8'h42); + end + +endmodule diff --git a/chips/yosys/tests/various/lcov.ys b/chips/yosys/tests/various/lcov.ys new file mode 100644 index 0000000000000000000000000000000000000000..8122611c0af9eadc845a5baaebe808870f7ecd0a --- /dev/null +++ b/chips/yosys/tests/various/lcov.ys @@ -0,0 +1,8 @@ +read_verilog -formal lcov.v +prep -top top +async2sync +chformal -lower +select -set covered t:$assert %ci* +select -set irrelevant o:* %ci* %n +linecoverage -lcov lcov.out @covered @irrelevant %u +exec -expect-return 0 -- diff -q lcov.out lcov.gold diff --git a/chips/yosys/tests/various/logger_cmd_error.sh b/chips/yosys/tests/various/logger_cmd_error.sh new file mode 100644 index 0000000000000000000000000000000000000000..1a1ca474c86252ea02d90571964a3cb289240526 --- /dev/null +++ b/chips/yosys/tests/various/logger_cmd_error.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash + +trap 'echo "ERROR in logger_cmd_error.sh" >&2; exit 1' ERR + +(${YOSYS} -v 3 -C <&1 | grep -F "ERROR: Module \`nonexistent' not found!" > /dev/null diff --git a/chips/yosys/tests/various/logger_error.ys b/chips/yosys/tests/various/logger_error.ys new file mode 100644 index 0000000000000000000000000000000000000000..46fe7f506c458f679598a2501f277120149ab4a1 --- /dev/null +++ b/chips/yosys/tests/various/logger_error.ys @@ -0,0 +1,6 @@ +logger -werror "is implicitly declared." -expect error "is implicitly declared." 1 +read_verilog << EOF +module top(...); + assign b = w; +endmodule +EOF diff --git a/chips/yosys/tests/various/logger_fail.sh b/chips/yosys/tests/various/logger_fail.sh new file mode 100644 index 0000000000000000000000000000000000000000..0baf5eec090c83ce599b30cb204895ad7d6185f1 --- /dev/null +++ b/chips/yosys/tests/various/logger_fail.sh @@ -0,0 +1,42 @@ +#!/usr/bin/env bash + +fail() { + echo "$1" >&2 + exit 1 +} + +runTest() { + desc="$1" + want="$2" + shift 2 + echo "running '$desc' with args $@" + output=`${YOSYS} -q "$@" 2>&1` + if [ $? -ne 1 ]; then + fail "exit code for '$desc' was not 1" + fi + if [ "$output" != "$want" ]; then + fail "output for '$desc' did not match" + fi +} + +unmet() { + kind=$1 + runTest "unmet $kind" \ + "ERROR: Expected $kind pattern 'foobar' not found !" \ + -p "logger -expect $kind \"foobar\" 1" +} + +unmet log +unmet warning +unmet error + +runTest "too many logs" \ + "ERROR: Expected log pattern 'statistics' found 2 time(s), instead of 1 time(s) !" \ + -p "logger -expect log \"statistics\" 1" -p stat -p stat + +runTest "too many warnings" \ + "Warning: Found log message matching -W regex: +Printing statistics. +ERROR: Expected warning pattern 'statistics' found 2 time(s), instead of 1 time(s) !" \ + -p "logger -warn \"Printing statistics\"" \ + -p "logger -expect warning \"statistics\" 1" -p stat -p stat diff --git a/chips/yosys/tests/various/logger_nowarning.ys b/chips/yosys/tests/various/logger_nowarning.ys new file mode 100644 index 0000000000000000000000000000000000000000..87cbbc644b84271f1d790966d5d86697d9babef5 --- /dev/null +++ b/chips/yosys/tests/various/logger_nowarning.ys @@ -0,0 +1,6 @@ +logger -expect-no-warnings -nowarn "is implicitly declared." +read_verilog << EOF +module top(...); + assign b = w; +endmodule +EOF diff --git a/chips/yosys/tests/various/logger_warn.ys b/chips/yosys/tests/various/logger_warn.ys new file mode 100644 index 0000000000000000000000000000000000000000..2316ae4c6758d973a91a00e45577832204e3c817 --- /dev/null +++ b/chips/yosys/tests/various/logger_warn.ys @@ -0,0 +1,6 @@ +logger -warn "Successfully finished Verilog frontend." -expect warning "Successfully finished Verilog frontend." 1 +read_verilog << EOF +module top(...); + assign b = w; +endmodule +EOF diff --git a/chips/yosys/tests/various/logger_warning.ys b/chips/yosys/tests/various/logger_warning.ys new file mode 100644 index 0000000000000000000000000000000000000000..642b1b97ba371b1a137ebf8809f2ed5e8c70144a --- /dev/null +++ b/chips/yosys/tests/various/logger_warning.ys @@ -0,0 +1,6 @@ +logger -expect warning "is implicitly declared." 2 +read_verilog << EOF +module top(...); + assign b = w; +endmodule +EOF diff --git a/chips/yosys/tests/various/logic_param_simple.ys b/chips/yosys/tests/various/logic_param_simple.ys new file mode 100644 index 0000000000000000000000000000000000000000..968564080753f3d84f33103a350cd4df2804b60f --- /dev/null +++ b/chips/yosys/tests/various/logic_param_simple.ys @@ -0,0 +1,9 @@ +read_verilog -sv <:4.43-4.48 %i +select -assert-count 2 w:data2[*] a:src=:5.41-5.46 %i +select -assert-none a:mem2reg diff --git a/chips/yosys/tests/various/memory_word_as_index.data b/chips/yosys/tests/various/memory_word_as_index.data new file mode 100644 index 0000000000000000000000000000000000000000..d525c18eed2a7c4df6059f28d3dcaaffce77765f --- /dev/null +++ b/chips/yosys/tests/various/memory_word_as_index.data @@ -0,0 +1,4 @@ +00 04 08 0c +10 14 18 1c +20 24 28 2c +30 34 38 3c diff --git a/chips/yosys/tests/various/memory_word_as_index.v b/chips/yosys/tests/various/memory_word_as_index.v new file mode 100644 index 0000000000000000000000000000000000000000..a99ea95664f78599d8b93a19201b49fb57f73d73 --- /dev/null +++ b/chips/yosys/tests/various/memory_word_as_index.v @@ -0,0 +1,21 @@ +`define DATA 64'h492e5c4d7747e032 + +`define GATE(n, expr) \ +module gate``n(sel, out); \ + input wire [3:0] sel; \ + output wire out; \ + reg [63:0] bits; \ + reg [5:0] ptrs[15:0]; \ + initial bits = `DATA; \ + initial $readmemh("memory_word_as_index.data", ptrs); \ + assign out = expr; \ +endmodule + +`GATE(1, bits[ptrs[sel]]) +`GATE(2, bits[ptrs[sel][5:0]]) +`GATE(3, bits[ptrs[sel]+:1]) + +module gold(sel, out); + input wire [3:0] sel; + output wire out = `DATA >> (sel * 4); +endmodule diff --git a/chips/yosys/tests/various/memory_word_as_index.ys b/chips/yosys/tests/various/memory_word_as_index.ys new file mode 100644 index 0000000000000000000000000000000000000000..9a2dea40e8e875ebf04df62233c82b8e81a9504a --- /dev/null +++ b/chips/yosys/tests/various/memory_word_as_index.ys @@ -0,0 +1,23 @@ +read_verilog memory_word_as_index.v + +hierarchy +proc +memory +flatten +opt -full + +equiv_make gold gate1 equiv +equiv_simple +equiv_status -assert + +delete equiv + +equiv_make gold gate2 equiv +equiv_simple +equiv_status -assert + +delete equiv + +equiv_make gold gate3 equiv +equiv_simple +equiv_status -assert diff --git a/chips/yosys/tests/various/muxcover.ys b/chips/yosys/tests/various/muxcover.ys new file mode 100644 index 0000000000000000000000000000000000000000..37a90dcb0759ffeede9c2f909d49414374372b58 --- /dev/null +++ b/chips/yosys/tests/various/muxcover.ys @@ -0,0 +1,550 @@ + +read_verilog -formal < 1 (e.g. boolean result assigned to a wide wire). +read_verilog <> (w * (3'b110)); +endmodule +EOT + +prep -nokeepdc +equiv_opt -assert peepopt +design -load postopt +clean +select -assert-count 1 t:$shr +select -assert-count 1 t:$mul +select -assert-count 0 t:$shr t:$mul %% t:* %D + +#################### + +design -reset +read_verilog <> (S*3); +endmodule +EOT + +prep +design -save gold +peepopt +design -stash gate + +design -import gold -as gold peepopt_shiftmul_2 +design -import gate -as gate peepopt_shiftmul_2 + +miter -equiv -make_assert -make_outputs -ignore_gold_x -flatten gold gate miter +sat -verify -show-public -enable_undef -prove-asserts miter +cd gate +select -assert-count 1 t:$shr +select -assert-count 1 t:$mul +select -assert-count 0 t:$shr t:$mul %% t:* %D + +#################### + +design -reset +read_verilog <> (S*5); +endmodule +EOT + +prep +design -save gold +peepopt +design -stash gate + +design -import gold -as gold peepopt_shiftmul_3 +design -import gate -as gate peepopt_shiftmul_3 + +miter -equiv -make_assert -make_outputs -ignore_gold_x -flatten gold gate miter +sat -verify -show-public -enable_undef -prove-asserts miter +cd gate +clean +select -assert-count 1 t:$bmux +select -assert-count 0 t:$shr +select -assert-count 0 t:$mul + +#################### + +design -reset +read_verilog <> (S*8), checked by SAT miter +design -reset +read_verilog <> (S*8); +endmodule +EOT + +prep +design -save gold +peepopt +design -stash gate + +design -import gold -as gold peepopt_shiftpow2_1 +design -import gate -as gate peepopt_shiftpow2_1 + +miter -equiv -make_assert -make_outputs -ignore_gold_x -flatten gold gate miter +sat -verify -show-public -enable_undef -prove-asserts miter +cd gate +clean +select -assert-count 1 t:$bmux +select -assert-count 0 t:$shr + +#################### + +# shiftpow2: width smaller than stride is non-overlapping +design -reset +read_verilog <> (S*8); +endmodule +EOT + +prep +design -save gold +peepopt +design -stash gate + +design -import gold -as gold peepopt_shiftpow2_narrow +design -import gate -as gate peepopt_shiftpow2_narrow + +miter -equiv -make_assert -make_outputs -ignore_gold_x -flatten gold gate miter +sat -verify -show-public -enable_undef -prove-asserts miter +cd gate +clean +select -assert-count 1 t:$bmux +select -assert-count 0 t:$shr + +#################### + +# shiftpow2: signed part-select with out-of-range padding +design -reset +read_verilog <> (S*8); +endmodule +EOT + +prep +design -save gold +peepopt +design -stash gate + +design -import gold -as gold peepopt_shiftpow2_signed_shr +design -import gate -as gate peepopt_shiftpow2_signed_shr + +miter -equiv -make_assert -make_outputs -flatten gold gate miter +sat -verify -show-public -prove-asserts miter +cd gate +clean +select -assert-count 1 t:$bmux +select -assert-count 0 t:$shr + +#################### + +# shiftpow2 must NOT fire for overlapping selections +design -reset +read_verilog <> (S*4); +endmodule +EOT + +prep -nokeepdc +peepopt +clean +select -assert-count 0 t:$bmux +select -assert-count 1 t:$shr + +#################### + +# shiftpow2: shiftmul can expose a non-overlapping power-of-two stride +design -reset +read_verilog <> 2) >> (1 + in[0])); +endmodule +EOT + +synth +sat -verify -prove Y 1'b1 + +#################### + +# signed $shr sign-extends A to Y_WIDTH, the narrowed A must carry that extension +design -reset +read_verilog <> (S + 1); +endmodule +EOT + +prep +# wreduce narrows A below Y_WIDTH +wreduce +equiv_opt -assert peepopt +design -load postopt +clean +select -assert-count 0 t:$add + +#################### + +# A_WIDTH > Y_WIDTH needs no extension, but A_SIGNED must still be cleared +design -reset +read_rtlil <> amt; +endmodule +EOT + +proc +equiv_opt -assert peepopt + +#################### + +# shiftadd: unsigned add read signed by $shift, MSB of the sum can be set +design -reset +read_rtlil < args, RTLIL::Design *design) override + { + size_t argidx = 1; + extra_args(args, argidx, design); + log("Plugin test passed!\n"); + } +} TestPass; + +YOSYS_NAMESPACE_END diff --git a/chips/yosys/tests/various/plugin.sh b/chips/yosys/tests/various/plugin.sh new file mode 100644 index 0000000000000000000000000000000000000000..d7ea5f501252a8ab211a9a1edffec1d325e281c0 --- /dev/null +++ b/chips/yosys/tests/various/plugin.sh @@ -0,0 +1,12 @@ +set -e +rm -f plugin.so +rm -rf plugin_search +CXXFLAGS=$(${YOSYS_CONFIG} --cxxflags) +DATDIR=$(${YOSYS_CONFIG} --datdir) +DATDIR=${DATDIR//\//\\\/} +CXXFLAGS=${CXXFLAGS//$DATDIR/$BUILD_DIR/share} +${YOSYS_CONFIG} --exec --cxx ${CXXFLAGS} --ldflags -shared -o plugin.so plugin.cc +${YOSYS} -m ./plugin.so -p "test" | grep -q "Plugin test passed!" +mkdir -p plugin_search +mv plugin.so plugin_search/plugin.so +YOSYS_PLUGIN_PATH=$PWD/plugin_search ${YOSYS} -m plugin.so -p "test" | grep -q "Plugin test passed!" diff --git a/chips/yosys/tests/various/pmgen_reduce.ys b/chips/yosys/tests/various/pmgen_reduce.ys new file mode 100644 index 0000000000000000000000000000000000000000..c214d3f25e2840d5f1c1c3aca8d3d761a1507a4a --- /dev/null +++ b/chips/yosys/tests/various/pmgen_reduce.ys @@ -0,0 +1,21 @@ +test_pmgen -generate reduce +hierarchy -top pmtest_test_pmgen_pm_reduce +flatten; opt_clean + +design -save gold +test_pmgen -reduce_chain +design -stash gate + +design -copy-from gold -as gold pmtest_test_pmgen_pm_reduce +design -copy-from gate -as gate pmtest_test_pmgen_pm_reduce +miter -equiv -flatten -make_assert gold gate miter +sat -verify -prove-asserts miter + +design -load gold +test_pmgen -reduce_tree +design -stash gate + +design -copy-from gold -as gold pmtest_test_pmgen_pm_reduce +design -copy-from gate -as gate pmtest_test_pmgen_pm_reduce +miter -equiv -flatten -make_assert gold gate miter +sat -verify -prove-asserts miter diff --git a/chips/yosys/tests/various/pmux2shiftx.v b/chips/yosys/tests/various/pmux2shiftx.v new file mode 100644 index 0000000000000000000000000000000000000000..c1994e92ca62b2c44e6acd7d10b424d1606b5bda --- /dev/null +++ b/chips/yosys/tests/various/pmux2shiftx.v @@ -0,0 +1,44 @@ +module pmux2shiftx_test ( + input [2:0] S1, + input [5:0] S2, + input [1:0] S3, + input [9:0] A, B, C, D, D, E, F, G, H, + input [9:0] I, J, K, L, M, N, O, P, Q, + output reg [9:0] X +); + always @* begin + case (S1) + 3'd 0: X = A; + 3'd 1: X = B; + 3'd 2: X = C; + 3'd 3: X = D; + 3'd 4: X = E; + 3'd 5: X = F; + 3'd 6: X = G; + 3'd 7: X = H; + endcase + case (S2) + 6'd 45: X = I; + 6'd 47: X = J; + 6'd 49: X = K; + 6'd 55: X = L; + 6'd 57: X = M; + 6'd 59: X = N; + endcase + case (S3) + 2'd 1: X = O; + 2'd 2: X = P; + 2'd 3: X = Q; + endcase + end +endmodule + +module issue01135(input [7:0] i, output reg o); +always @* +case (i[6:3]) + 4: o <= i[0]; + 3: o <= i[2]; + 7: o <= i[3]; + default: o <= 1'b0; +endcase +endmodule diff --git a/chips/yosys/tests/various/pmux2shiftx.ys b/chips/yosys/tests/various/pmux2shiftx.ys new file mode 100644 index 0000000000000000000000000000000000000000..51ee2f7be975b9b34362cbbc7f53b17efed3e53a --- /dev/null +++ b/chips/yosys/tests/various/pmux2shiftx.ys @@ -0,0 +1,39 @@ +read_verilog pmux2shiftx.v +design -save read + +hierarchy -top pmux2shiftx_test +prep +design -save gold + +pmux2shiftx -min_density 70 + +opt + +stat +# show -width +select -assert-count 1 t:$sub +select -assert-count 1 t:$mux +select -assert-count 1 t:$shift +select -assert-count 3 t:$shiftx + +design -stash gate + +design -import gold -as gold +design -import gate -as gate + +miter -equiv -flatten -make_assert -make_outputs gold gate miter +sat -verify -prove-asserts -show-ports miter + +#design -load gold +#stat +# +#design -load gate +#stat + +design -load read +hierarchy -top issue01135 +proc +pmux2shiftx -norange +opt -full +select -assert-count 0 t:$shift* +select -assert-count 1 t:$pmux diff --git a/chips/yosys/tests/various/port_sign_extend.v b/chips/yosys/tests/various/port_sign_extend.v new file mode 100644 index 0000000000000000000000000000000000000000..813ceb503124708396f5941d88fb579226311638 --- /dev/null +++ b/chips/yosys/tests/various/port_sign_extend.v @@ -0,0 +1,95 @@ +module GeneratorSigned1(out); + output wire signed out; + assign out = 1; +endmodule + +module GeneratorUnsigned1(out); + output wire out; + assign out = 1; +endmodule + +module GeneratorSigned2(out); + output wire signed [1:0] out; + assign out = 2; +endmodule + +module GeneratorUnsigned2(out); + output wire [1:0] out; + assign out = 2; +endmodule + +module PassThrough(a, b); + input wire [3:0] a; + output wire [3:0] b; + assign b = a; +endmodule + +module act(o1, o2, o3, o4, o5, o6, o7, o8, o9, yay1, nay1, yay2, nay2); + output wire [3:0] o1, o2, o3, o4, o5, o6, o7, o8, o9; + + // unsigned constant + PassThrough pt1(1'b1, o1); + + // unsigned wire + wire tmp2; + assign tmp2 = 1'sb1; + PassThrough pt2(tmp2, o2); + + // signed constant + PassThrough pt3(1'sb1, o3); + + // signed wire + wire signed tmp4; + assign tmp4 = 1'sb1; + PassThrough pt4(tmp4, o4); + + // signed expressions + wire signed [1:0] tmp5a = 2'b11; + wire signed [1:0] tmp5b = 2'b01; + PassThrough pt5(tmp5a ^ tmp5b, o5); + + wire signed [2:0] tmp6a = 3'b100; + wire signed [2:0] tmp6b = 3'b001; + PassThrough pt6(tmp6a ? tmp6a : tmp6b, o6); + + wire signed [2:0] tmp7 = 3'b011; + PassThrough pt7(~tmp7, o7); + + reg signed [2:0] tmp8 [0:0]; + initial tmp8[0] = 3'b101; + PassThrough pt8(tmp8[0], o8); + + wire signed [2:0] tmp9a = 3'b100; + wire signed [1:0] tmp9b = 2'b11; + PassThrough pt9(0 ? tmp9a : tmp9b, o9); + + output wire [2:0] yay1, nay1; + GeneratorSigned1 os1(yay1); + GeneratorUnsigned1 ou1(nay1); + + output wire [2:0] yay2, nay2; + GeneratorSigned2 os2(yay2); + GeneratorUnsigned2 ou2(nay2); +endmodule + +module ref(o1, o2, o3, o4, o5, o6, o7, o8, o9, yay1, nay1, yay2, nay2); + output wire [3:0] o1, o2, o3, o4, o5, o6, o7, o8, o9; + + assign o1 = 4'b0001; + assign o2 = 4'b0001; + assign o3 = 4'b1111; + assign o4 = 4'b1111; + assign o5 = 4'b1110; + assign o6 = 4'b1100; + assign o7 = 4'b1100; + assign o8 = 4'b1101; + assign o9 = 4'b1111; + + output wire [2:0] yay1, nay1; + assign yay1 = 3'b111; + assign nay1 = 3'b001; + + output wire [2:0] yay2, nay2; + assign yay2 = 3'b110; + assign nay2 = 3'b010; +endmodule diff --git a/chips/yosys/tests/various/port_sign_extend.ys b/chips/yosys/tests/various/port_sign_extend.ys new file mode 100644 index 0000000000000000000000000000000000000000..6d1adf7f3506f68c6f03ce867d5e2b574c62d526 --- /dev/null +++ b/chips/yosys/tests/various/port_sign_extend.ys @@ -0,0 +1,29 @@ +read_verilog -nomem2reg port_sign_extend.v +hierarchy +flatten +proc +memory +equiv_make ref act equiv +equiv_simple +equiv_status -assert + +delete + +read_verilog -nomem2reg port_sign_extend.v +flatten +proc +memory +equiv_make ref act equiv +equiv_simple +equiv_status -assert + +delete + +read_verilog -nomem2reg port_sign_extend.v +hierarchy +proc +memory +equiv_make ref act equiv +prep -flatten -top equiv +equiv_induct +equiv_status -assert diff --git a/chips/yosys/tests/various/primitives.ys b/chips/yosys/tests/various/primitives.ys new file mode 100644 index 0000000000000000000000000000000000000000..eeab967704fdb3e05eb03e0e379d761a5fcdb313 --- /dev/null +++ b/chips/yosys/tests/various/primitives.ys @@ -0,0 +1,16 @@ +read_verilog <:2.4-2.17 %i +select -assert-count 1 t:$and a:src=:3.5-3.18 %i +select -assert-count 1 t:$or a:src=:4.3-4.16 %i +select -assert-count 1 t:$or a:src=:5.4-5.17 %i +select -assert-count 1 t:$xor a:src=:6.4-6.17 %i +select -assert-count 1 t:$xor a:src=:7.5-7.18 %i diff --git a/chips/yosys/tests/various/printattr.ys b/chips/yosys/tests/various/printattr.ys new file mode 100644 index 0000000000000000000000000000000000000000..2228d12c8e6ac3d52941494fbdf9a223eb5c1d97 --- /dev/null +++ b/chips/yosys/tests/various/printattr.ys @@ -0,0 +1,14 @@ +logger -expect log ".*cells_not_processed=[01]* .*" 1 +logger -expect log ".*src=.:1\.1-9\.10. .*" 1 +read_verilog <:2$add$1 %% %n diff --git a/chips/yosys/tests/various/rename_src.ys b/chips/yosys/tests/various/rename_src.ys new file mode 100644 index 0000000000000000000000000000000000000000..bd8685c81dd89e79038399567a35e4f80ae6c35a --- /dev/null +++ b/chips/yosys/tests/various/rename_src.ys @@ -0,0 +1,56 @@ +read_rtlil <:*$add$*_Y + +rename -unescape + +select -assert-count 1 w:a_0_ +select -assert-count 1 w:_0b +select -assert-count 1 w:c +select -assert-count 1 w:d_ +select -assert-count 1 w:d__1 +select -assert-count 1 w:_e +select -assert-count 1 w:wire_ +select -assert-count 1 w:$:*$add$*_Y + +# Ports are updated during rename +design -reset +read_verilog << EOT +module top(output \$e ); +submod \a$ (\$e ); +endmodule + +module submod(output \a[0] ); + assign \a[0] = 0; +endmodule +EOT + +rename -unescape +check diff --git a/chips/yosys/tests/various/rename_wire_move_to_cell.ys b/chips/yosys/tests/various/rename_wire_move_to_cell.ys new file mode 100644 index 0000000000000000000000000000000000000000..482447edd78ccd6720e46f77be4550bffeb536d1 --- /dev/null +++ b/chips/yosys/tests/various/rename_wire_move_to_cell.ys @@ -0,0 +1,35 @@ +read_verilog < (Q : D)) = (1, 2:3:4); + $setup(D, posedge CLK &&& EN, 5); + $hold(posedge CLK, D &&& EN, 6); + endspecify +endmodule + +module test2 ( + input A, B, + output Q +); + xor (Q, A, B); + specify + //specparam T_rise = 1; + //specparam T_fall = 2; + `define T_rise 1 + `define T_fall 2 + (A => Q) = (`T_rise,`T_fall); + //(B => Q) = (`T_rise+`T_fall)/2.0; + (B => Q) = 1.5; + endspecify +endmodule + +module issue01144(input clk, d, output q); +specify + (posedge clk => (q +: d)) = (3,1); + (posedge clk *> (q +: d)) = (3,1); +endspecify +endmodule + +module test3(input clk, input [1:0] d, output [1:0] q); +specify + (posedge clk => (q +: d)) = (3,1); + (posedge clk *> (q +: d)) = (3,1); +endspecify +endmodule + +module test4(input clk, d, output q); +specify + $setup(d, posedge clk, 1:2:3); + $setuphold(d, posedge clk, 1:2:3, 4:5:6); +endspecify +endmodule + +module test5(input clk, d, e, output q); +specify + $setup(d, posedge clk &&& e, 1:2:3); +endspecify +endmodule + +module test6(input clk, d, e, output q); +specify + (d[0] *> q[0]) = (3,1); + (posedge clk[0] => (q[0] +: d[0])) = (3,1); +endspecify +endmodule diff --git a/chips/yosys/tests/various/specify.ys b/chips/yosys/tests/various/specify.ys new file mode 100644 index 0000000000000000000000000000000000000000..86471de5e3b5fcd3eb34015b6c41f6be1018a013 --- /dev/null +++ b/chips/yosys/tests/various/specify.ys @@ -0,0 +1,83 @@ +read_verilog -specify specify.v +prep +cd test +select t:$specify2 -assert-count 0 +select t:$specify3 -assert-count 1 +select t:$specrule -assert-count 2 +select t:$specify3 a:src=specify.v:10.3-10.49 %i -assert-count 1 +select t:$specrule a:src=specify.v:11.3-11.36 %i -assert-count 1 +select t:$specrule a:src=specify.v:12.3-12.35 %i -assert-count 1 +cd test2 +select t:$specify2 -assert-count 2 +select t:$specify3 -assert-count 0 +select t:$specrule -assert-count 0 +select t:$specify2 a:src=specify.v:26.3-26.20 %i -assert-count 1 + # ^^ Note use of macro +select t:$specify2 a:src=specify.v:28.3-28.18 %i -assert-count 1 +cd +write_verilog specify.out +design -stash gold + +read_verilog -specify specify.out +prep +cd test +select t:$specify2 -assert-count 0 +select t:$specify3 -assert-count 1 +select t:$specrule -assert-count 2 +cd test2 +select t:$specify2 -assert-count 2 +select t:$specify3 -assert-count 0 +select t:$specrule -assert-count 0 +cd +design -stash gate + +design -copy-from gold -as gold test +design -copy-from gate -as gate test +rename -hide +rename -enumerate -pattern A_% t:$specify3 +rename -enumerate -pattern B_% t:$specrule r:TYPE=$setup %i +rename -enumerate -pattern C_% t:$specrule r:TYPE=$hold %i +select n:A_* -assert-count 2 +select n:B_* -assert-count 2 +select n:C_* -assert-count 2 +equiv_make gold gate equiv +hierarchy -top equiv +equiv_struct +equiv_induct -ignore-unknown-cells -seq 5 +equiv_status -assert +design -reset + +design -copy-from gold -as gold test2 +design -copy-from gate -as gate test2 +rename -hide +rename -enumerate -pattern A_% t:$specify2 r:T_RISE_TYP=1 %i +rename -enumerate -pattern B_% t:$specify2 n:A_* %d +select n:A_* -assert-count 2 +select n:B_* -assert-count 2 +equiv_make gold gate equiv +hierarchy -top equiv +equiv_struct +equiv_induct -ignore-unknown-cells -seq 5 +equiv_status -assert +design -reset + +read_verilog -specify < o) = 1; +endspecify +assign o = ~i; +endmodule + +module test7(input i, output o); + wire w; + test7_sub unused(i, w); + test7_sub used(i, o); +endmodule +EOT +hierarchy +cd test7 +clean +select -assert-count 1 c:used +select -assert-none c:* c:used %d diff --git a/chips/yosys/tests/various/splitnets.ys b/chips/yosys/tests/various/splitnets.ys new file mode 100644 index 0000000000000000000000000000000000000000..29652d508d3a5565e27d9207b268e57ca159ad9c --- /dev/null +++ b/chips/yosys/tests/various/splitnets.ys @@ -0,0 +1,32 @@ +read_verilog <:2.11-2.17" 1 +logger -expect warning "wire '\\p' is assigned in a block at :3.11-3.16" 1 +read_verilog < o) = 10; +endspecify +endmodule + +module top(input i); +wire w; +buffer b(.i(i), .o(w)); +endmodule +EOT + +logger -expect warning "Critical-path does not terminate in a recognised endpoint\." 1 +sta + + +design -reset +read_verilog -specify < o) = 10; +endspecify +endmodule + +module top(input i, output o, p); +buffer b(.i(i), .o(o)); +endmodule +EOT + +sta + + +design -reset +read_verilog -specify < o) = 10; +endspecify +endmodule + +module top(input i, output o, p); +buffer b(.i(i), .o(o)); +const0 c(.o(p)); +endmodule +EOT + +logger -expect warning "Cell type 'const0' not recognised! Ignoring\." 1 +sta + + +design -reset +read_verilog -specify < o) = 10; +endspecify +endmodule +module const0(output o); +endmodule + +module top(input i, output o, p); +buffer b(.i(i), .o(o)); +const0 c(.o(p)); +endmodule +EOT + +sta + +logger -expect-no-warnings diff --git a/chips/yosys/tests/various/stat.ys b/chips/yosys/tests/various/stat.ys new file mode 100644 index 0000000000000000000000000000000000000000..907e7c353386cc469f5c383a4ada8ad301af4b93 --- /dev/null +++ b/chips/yosys/tests/various/stat.ys @@ -0,0 +1,79 @@ +read_rtlil << EOT +module \top + wire input 1 \A + wire output 2 \Y + cell \sg13g2_and2_1 \sub + connect \A \A + connect \B 1'0 + connect \Y \Y + end +end +EOT +logger -expect log "Chip area for module '\\top': 9.072000" 1 +logger -expect-no-warnings +logger -expect log " 1 9.072 cells" 1 +logger -expect log " 1 9.072 sg13g2_and2_1" 1 +stat -liberty ../../tests/liberty/foundry_data/sg13g2_stdcell_typ_1p20V_25C.lib.filtered.gz + + +design -reset +read_rtlil << EOT +module \top + wire input 1 \A + wire output 2 \Y + wire output 3 \N + + cell \sg13g2_and2_1 \sub1 + connect \A \A + connect \B 1'0 + connect \Y \Y + end + + cell \child \sequential + connect \A \A + connect \B 1'0 + connect \R 1'0 + connect \Y \Y + connect \N \N + end + + cell \child \sequential1 + connect \A \A + connect \B 1'0 + connect \R 1'0 + connect \Y \Y + connect \N \N + end + + cell \sg13g2_and2_1 \sub2 + connect \A \A + connect \B 1'0 + connect \Y \Y + end +end + +module \child + wire input 1 \A + wire input 2 \B + wire input 3 \R + + wire output 4 \Y + wire output 5 \N + + cell \sg13g2_dfrbp_1 \sequential_ff + connect \CLK \A + connect \D \B + connect \Q \Y + connect \Q_N \N + connect \RESET_B \R + end + +end +EOT +logger -expect log "Chip area for top module '\\top': 112.492800" 1 +logger -expect log "of which used for sequential elements: 94.348800" 1 +logger -expect log "2 18.144 cells" 1 +logger -expect log "4 112.493 cells" 1 +logger -expect log "2 94.349 sg13g2_dfrbp_1" 1 +logger -expect-no-warnings +stat -liberty ../../tests/liberty/foundry_data/sg13g2_stdcell_typ_1p20V_25C.lib.filtered.gz -top \top diff --git a/chips/yosys/tests/various/stat_area_by_width.lib b/chips/yosys/tests/various/stat_area_by_width.lib new file mode 100644 index 0000000000000000000000000000000000000000..e8be453612e4ca958806eab1f739d9503ee4ace7 --- /dev/null +++ b/chips/yosys/tests/various/stat_area_by_width.lib @@ -0,0 +1,25 @@ + +//library for testcases, can also be used as a template for new libraries +library (mock) { +cell ( "$reduce_xor" ) { + area : 3.0 ; + delay : 2.5 ; + single_area_parameterised ( 3.0, 5.5, 8.0, 10.5, 13.0, 15.5, 18.0, 20.5, 23.0, 25.5, 28.0, 30.5, 33.0, 35.5, 38.0, 40.5, 43.0, 45.5, 48.0, 50.5, 53.0, 55.5, 58.0, 60.5, 63.0, 65.5, 68.0, 70.5, 73.0, 75.5, 78.0, 80.5, 83.0, 85.5, 88.0, 90.5, 93.0, 95.5, 98.0, 100.5, 103.0, 105.5, 108.0, 110.5, 113.0, 115.5, 118.0, 120.5, ) ; + +} + +cell ( "$xor" ) { + area : 5.0 ; + delay : 2.0 ; + single_area_parameterised ( 5.0, 7.5, 10.0, 12.5, 15.0, 17.5, 20.0, 22.5, 25.0, 27.5, 30.0, 32.5, 35.0, 37.5, 40.0, 42.5, 45.0, 47.5, 50.0, 52.5, 55.0, ) ; + +} + +cell ( "$bmux" ) { + area : 3.0 ; + delay : 2.0 ; + port_names ( "Y", "S" ) ; + double_area_parameterised ( " 3.0, 6.0, 9.0, 12.0, 15.0, 18.0, 21.0, 24.0, 27.0, 30.0, 33.0, 36.0, 39.0, 42.0, 45.0, 48.0, 51.0, 54.0, 57.0, 60.0, 63.0, 66.0, 69.0, 72.0, 75.0, 78.0, 81.0, 84.0, 87.0, 90.0, 93.0, 96.0, 99.0, 102.0, 105.0, 108.0, 111.0, 114.0, 117.0, 120.0, 123.0, 126.0, 129.0, 132.0, 135.0, 138.0, 141.0, 144.0, 147.0, 150.0, 153.0, 156.0, 159.0, 162.0, 165.0, 168.0, 171.0, 174.0, 177.0, 180.0, 183.0, 186.0, 189.0, 192.0, 195.0, 198.0, 201.0, 204.0, 207.0, 210.0, 213.0, 216.0, 219.0, 222.0, 225.0, 228.0, 231.0, 234.0, 237.0, 240.0, 243.0, 246.0, 249.0, 252.0, 255.0, 258.0, 261.0, 264.0, 267.0, 270.0, 273.0, 276.0, 279.0, 282.0, 285.0, 288.0, 291.0, 294.0, 297.0, 300.0, 303.0, 306.0, 309.0, 312.0, 315.0, 318.0, 321.0, 324.0, 327.0, 330.0, 333.0, 336.0, 339.0, 342.0, 345.0, 348.0, 351.0, 354.0, 357.0, 360.0, 363.0, 366.0, 369.0, 372.0, 375.0, 378.0, 381.0, 384.0,", " 6.0, 12.0, 18.0, 24.0, 30.0, 36.0, 42.0, 48.0, 54.0, 60.0, 66.0, 72.0, 78.0, 84.0, 90.0, 96.0, 102.0, 108.0, 114.0, 120.0, 126.0, 132.0, 138.0, 144.0, 150.0, 156.0, 162.0, 168.0, 174.0, 180.0, 186.0, 192.0, 198.0, 204.0, 210.0, 216.0, 222.0, 228.0, 234.0, 240.0, 246.0, 252.0, 258.0, 264.0, 270.0, 276.0, 282.0, 288.0, 294.0, 300.0, 306.0, 312.0, 318.0, 324.0, 330.0, 336.0, 342.0, 348.0, 354.0, 360.0, 366.0, 372.0, 378.0, 384.0, 390.0, 396.0, 402.0, 408.0, 414.0, 420.0, 426.0, 432.0, 438.0, 444.0, 450.0, 456.0, 462.0, 468.0, 474.0, 480.0, 486.0, 492.0, 498.0, 504.0, 510.0, 516.0, 522.0, 528.0, 534.0, 540.0, 546.0, 552.0, 558.0, 564.0, 570.0, 576.0, 582.0, 588.0, 594.0, 600.0, 606.0, 612.0, 618.0, 624.0, 630.0, 636.0, 642.0, 648.0, 654.0, 660.0, 666.0, 672.0, 678.0, 684.0, 690.0, 696.0, 702.0, 708.0, 714.0, 720.0, 726.0, 732.0, 738.0, 744.0, 750.0, 756.0, 762.0, 768.0,", " 9.0, 18.0, 27.0, 36.0, 45.0, 54.0, 63.0, 72.0, 81.0, 90.0, 99.0, 108.0, 117.0, 126.0, 135.0, 144.0, 153.0, 162.0, 171.0, 180.0, 189.0, 198.0, 207.0, 216.0, 225.0, 234.0, 243.0, 252.0, 261.0, 270.0, 279.0, 288.0, 297.0, 306.0, 315.0, 324.0, 333.0, 342.0, 351.0, 360.0, 369.0, 378.0, 387.0, 396.0, 405.0, 414.0, 423.0, 432.0, 441.0, 450.0, 459.0, 468.0, 477.0, 486.0, 495.0, 504.0, 513.0, 522.0, 531.0, 540.0, 549.0, 558.0, 567.0, 576.0, 585.0, 594.0, 603.0, 612.0, 621.0, 630.0, 639.0, 648.0, 657.0, 666.0, 675.0, 684.0, 693.0, 702.0, 711.0, 720.0, 729.0, 738.0, 747.0, 756.0, 765.0, 774.0, 783.0, 792.0, 801.0, 810.0, 819.0, 828.0, 837.0, 846.0, 855.0, 864.0, 873.0, 882.0, 891.0, 900.0, 909.0, 918.0, 927.0, 936.0, 945.0, 954.0, 963.0, 972.0, 981.0, 990.0, 999.0, 1008.0, 1017.0, 1026.0, 1035.0, 1044.0, 1053.0, 1062.0, 1071.0, 1080.0, 1089.0, 1098.0, 1107.0, 1116.0, 1125.0, 1134.0, 1143.0, 1152.0,", " 12.0, 24.0, 36.0, 48.0, 60.0, 72.0, 84.0, 96.0, 108.0, 120.0, 132.0, 144.0, 156.0, 168.0, 180.0, 192.0, 204.0, 216.0, 228.0, 240.0, 252.0, 264.0, 276.0, 288.0, 300.0, 312.0, 324.0, 336.0, 348.0, 360.0, 372.0, 384.0, 396.0, 408.0, 420.0, 432.0, 444.0, 456.0, 468.0, 480.0, 492.0, 504.0, 516.0, 528.0, 540.0, 552.0, 564.0, 576.0, 588.0, 600.0, 612.0, 624.0, 636.0, 648.0, 660.0, 672.0, 684.0, 696.0, 708.0, 720.0, 732.0, 744.0, 756.0, 768.0, 780.0, 792.0, 804.0, 816.0, 828.0, 840.0, 852.0, 864.0, 876.0, 888.0, 900.0, 912.0, 924.0, 936.0, 948.0, 960.0, 972.0, 984.0, 996.0, 1008.0, 1020.0, 1032.0, 1044.0, 1056.0, 1068.0, 1080.0, 1092.0, 1104.0, 1116.0, 1128.0, 1140.0, 1152.0, 1164.0, 1176.0, 1188.0, 1200.0, 1212.0, 1224.0, 1236.0, 1248.0, 1260.0, 1272.0, 1284.0, 1296.0, 1308.0, 1320.0, 1332.0, 1344.0, 1356.0, 1368.0, 1380.0, 1392.0, 1404.0, 1416.0, 1428.0, 1440.0, 1452.0, 1464.0, 1476.0, 1488.0, 1500.0, 1512.0, 1524.0, 1536.0,", " 15.0, 30.0, 45.0, 60.0, 75.0, 90.0, 105.0, 120.0, 135.0, 150.0, 165.0, 180.0, 195.0, 210.0, 225.0, 240.0, 255.0, 270.0, 285.0, 300.0, 315.0, 330.0, 345.0, 360.0, 375.0, 390.0, 405.0, 420.0, 435.0, 450.0, 465.0, 480.0, 495.0, 510.0, 525.0, 540.0, 555.0, 570.0, 585.0, 600.0, 615.0, 630.0, 645.0, 660.0, 675.0, 690.0, 705.0, 720.0, 735.0, 750.0, 765.0, 780.0, 795.0, 810.0, 825.0, 840.0, 855.0, 870.0, 885.0, 900.0, 915.0, 930.0, 945.0, 960.0, 975.0, 990.0, 1005.0, 1020.0, 1035.0, 1050.0, 1065.0, 1080.0, 1095.0, 1110.0, 1125.0, 1140.0, 1155.0, 1170.0, 1185.0, 1200.0, 1215.0, 1230.0, 1245.0, 1260.0, 1275.0, 1290.0, 1305.0, 1320.0, 1335.0, 1350.0, 1365.0, 1380.0, 1395.0, 1410.0, 1425.0, 1440.0, 1455.0, 1470.0, 1485.0, 1500.0, 1515.0, 1530.0, 1545.0, 1560.0, 1575.0, 1590.0, 1605.0, 1620.0, 1635.0, 1650.0, 1665.0, 1680.0, 1695.0, 1710.0, 1725.0, 1740.0, 1755.0, 1770.0, 1785.0, 1800.0, 1815.0, 1830.0, 1845.0, 1860.0, 1875.0, 1890.0, 1905.0, 1920.0,", " 18.0, 36.0, 54.0, 72.0, 90.0, 108.0, 126.0, 144.0, 162.0, 180.0, 198.0, 216.0, 234.0, 252.0, 270.0, 288.0, 306.0, 324.0, 342.0, 360.0, 378.0, 396.0, 414.0, 432.0, 450.0, 468.0, 486.0, 504.0, 522.0, 540.0, 558.0, 576.0, 594.0, 612.0, 630.0, 648.0, 666.0, 684.0, 702.0, 720.0, 738.0, 756.0, 774.0, 792.0, 810.0, 828.0, 846.0, 864.0, 882.0, 900.0, 918.0, 936.0, 954.0, 972.0, 990.0, 1008.0, 1026.0, 1044.0, 1062.0, 1080.0, 1098.0, 1116.0, 1134.0, 1152.0, 1170.0, 1188.0, 1206.0, 1224.0, 1242.0, 1260.0, 1278.0, 1296.0, 1314.0, 1332.0, 1350.0, 1368.0, 1386.0, 1404.0, 1422.0, 1440.0, 1458.0, 1476.0, 1494.0, 1512.0, 1530.0, 1548.0, 1566.0, 1584.0, 1602.0, 1620.0, 1638.0, 1656.0, 1674.0, 1692.0, 1710.0, 1728.0, 1746.0, 1764.0, 1782.0, 1800.0, 1818.0, 1836.0, 1854.0, 1872.0, 1890.0, 1908.0, 1926.0, 1944.0, 1962.0, 1980.0, 1998.0, 2016.0, 2034.0, 2052.0, 2070.0, 2088.0, 2106.0, 2124.0, 2142.0, 2160.0, 2178.0, 2196.0, 2214.0, 2232.0, 2250.0, 2268.0, 2286.0, 2304.0,", " 21.0, 42.0, 63.0, 84.0, 105.0, 126.0, 147.0, 168.0, 189.0, 210.0, 231.0, 252.0, 273.0, 294.0, 315.0, 336.0, 357.0, 378.0, 399.0, 420.0, 441.0, 462.0, 483.0, 504.0, 525.0, 546.0, 567.0, 588.0, 609.0, 630.0, 651.0, 672.0, 693.0, 714.0, 735.0, 756.0, 777.0, 798.0, 819.0, 840.0, 861.0, 882.0, 903.0, 924.0, 945.0, 966.0, 987.0, 1008.0, 1029.0, 1050.0, 1071.0, 1092.0, 1113.0, 1134.0, 1155.0, 1176.0, 1197.0, 1218.0, 1239.0, 1260.0, 1281.0, 1302.0, 1323.0, 1344.0, 1365.0, 1386.0, 1407.0, 1428.0, 1449.0, 1470.0, 1491.0, 1512.0, 1533.0, 1554.0, 1575.0, 1596.0, 1617.0, 1638.0, 1659.0, 1680.0, 1701.0, 1722.0, 1743.0, 1764.0, 1785.0, 1806.0, 1827.0, 1848.0, 1869.0, 1890.0, 1911.0, 1932.0, 1953.0, 1974.0, 1995.0, 2016.0, 2037.0, 2058.0, 2079.0, 2100.0, 2121.0, 2142.0, 2163.0, 2184.0, 2205.0, 2226.0, 2247.0, 2268.0, 2289.0, 2310.0, 2331.0, 2352.0, 2373.0, 2394.0, 2415.0, 2436.0, 2457.0, 2478.0, 2499.0, 2520.0, 2541.0, 2562.0, 2583.0, 2604.0, 2625.0, 2646.0, 2667.0, 2688.0,", " 24.0, 48.0, 72.0, 96.0, 120.0, 144.0, 168.0, 192.0, 216.0, 240.0, 264.0, 288.0, 312.0, 336.0, 360.0, 384.0, 408.0, 432.0, 456.0, 480.0, 504.0, 528.0, 552.0, 576.0, 600.0, 624.0, 648.0, 672.0, 696.0, 720.0, 744.0, 768.0, 792.0, 816.0, 840.0, 864.0, 888.0, 912.0, 936.0, 960.0, 984.0, 1008.0, 1032.0, 1056.0, 1080.0, 1104.0, 1128.0, 1152.0, 1176.0, 1200.0, 1224.0, 1248.0, 1272.0, 1296.0, 1320.0, 1344.0, 1368.0, 1392.0, 1416.0, 1440.0, 1464.0, 1488.0, 1512.0, 1536.0, 1560.0, 1584.0, 1608.0, 1632.0, 1656.0, 1680.0, 1704.0, 1728.0, 1752.0, 1776.0, 1800.0, 1824.0, 1848.0, 1872.0, 1896.0, 1920.0, 1944.0, 1968.0, 1992.0, 2016.0, 2040.0, 2064.0, 2088.0, 2112.0, 2136.0, 2160.0, 2184.0, 2208.0, 2232.0, 2256.0, 2280.0, 2304.0, 2328.0, 2352.0, 2376.0, 2400.0, 2424.0, 2448.0, 2472.0, 2496.0, 2520.0, 2544.0, 2568.0, 2592.0, 2616.0, 2640.0, 2664.0, 2688.0, 2712.0, 2736.0, 2760.0, 2784.0, 2808.0, 2832.0, 2856.0, 2880.0, 2904.0, 2928.0, 2952.0, 2976.0, 3000.0, 3024.0, 3048.0, 3072.0,", " 27.0, 54.0, 81.0, 108.0, 135.0, 162.0, 189.0, 216.0, 243.0, 270.0, 297.0, 324.0, 351.0, 378.0, 405.0, 432.0, 459.0, 486.0, 513.0, 540.0, 567.0, 594.0, 621.0, 648.0, 675.0, 702.0, 729.0, 756.0, 783.0, 810.0, 837.0, 864.0, 891.0, 918.0, 945.0, 972.0, 999.0, 1026.0, 1053.0, 1080.0, 1107.0, 1134.0, 1161.0, 1188.0, 1215.0, 1242.0, 1269.0, 1296.0, 1323.0, 1350.0, 1377.0, 1404.0, 1431.0, 1458.0, 1485.0, 1512.0, 1539.0, 1566.0, 1593.0, 1620.0, 1647.0, 1674.0, 1701.0, 1728.0, 1755.0, 1782.0, 1809.0, 1836.0, 1863.0, 1890.0, 1917.0, 1944.0, 1971.0, 1998.0, 2025.0, 2052.0, 2079.0, 2106.0, 2133.0, 2160.0, 2187.0, 2214.0, 2241.0, 2268.0, 2295.0, 2322.0, 2349.0, 2376.0, 2403.0, 2430.0, 2457.0, 2484.0, 2511.0, 2538.0, 2565.0, 2592.0, 2619.0, 2646.0, 2673.0, 2700.0, 2727.0, 2754.0, 2781.0, 2808.0, 2835.0, 2862.0, 2889.0, 2916.0, 2943.0, 2970.0, 2997.0, 3024.0, 3051.0, 3078.0, 3105.0, 3132.0, 3159.0, 3186.0, 3213.0, 3240.0, 3267.0, 3294.0, 3321.0, 3348.0, 3375.0, 3402.0, 3429.0, 3456.0,", " 30.0, 60.0, 90.0, 120.0, 150.0, 180.0, 210.0, 240.0, 270.0, 300.0, 330.0, 360.0, 390.0, 420.0, 450.0, 480.0, 510.0, 540.0, 570.0, 600.0, 630.0, 660.0, 690.0, 720.0, 750.0, 780.0, 810.0, 840.0, 870.0, 900.0, 930.0, 960.0, 990.0, 1020.0, 1050.0, 1080.0, 1110.0, 1140.0, 1170.0, 1200.0, 1230.0, 1260.0, 1290.0, 1320.0, 1350.0, 1380.0, 1410.0, 1440.0, 1470.0, 1500.0, 1530.0, 1560.0, 1590.0, 1620.0, 1650.0, 1680.0, 1710.0, 1740.0, 1770.0, 1800.0, 1830.0, 1860.0, 1890.0, 1920.0, 1950.0, 1980.0, 2010.0, 2040.0, 2070.0, 2100.0, 2130.0, 2160.0, 2190.0, 2220.0, 2250.0, 2280.0, 2310.0, 2340.0, 2370.0, 2400.0, 2430.0, 2460.0, 2490.0, 2520.0, 2550.0, 2580.0, 2610.0, 2640.0, 2670.0, 2700.0, 2730.0, 2760.0, 2790.0, 2820.0, 2850.0, 2880.0, 2910.0, 2940.0, 2970.0, 3000.0, 3030.0, 3060.0, 3090.0, 3120.0, 3150.0, 3180.0, 3210.0, 3240.0, 3270.0, 3300.0, 3330.0, 3360.0, 3390.0, 3420.0, 3450.0, 3480.0, 3510.0, 3540.0, 3570.0, 3600.0, 3630.0, 3660.0, 3690.0, 3720.0, 3750.0, 3780.0, 3810.0, 3840.0,", " 33.0, 66.0, 99.0, 132.0, 165.0, 198.0, 231.0, 264.0, 297.0, 330.0, 363.0, 396.0, 429.0, 462.0, 495.0, 528.0, 561.0, 594.0, 627.0, 660.0, 693.0, 726.0, 759.0, 792.0, 825.0, 858.0, 891.0, 924.0, 957.0, 990.0, 1023.0, 1056.0, 1089.0, 1122.0, 1155.0, 1188.0, 1221.0, 1254.0, 1287.0, 1320.0, 1353.0, 1386.0, 1419.0, 1452.0, 1485.0, 1518.0, 1551.0, 1584.0, 1617.0, 1650.0, 1683.0, 1716.0, 1749.0, 1782.0, 1815.0, 1848.0, 1881.0, 1914.0, 1947.0, 1980.0, 2013.0, 2046.0, 2079.0, 2112.0, 2145.0, 2178.0, 2211.0, 2244.0, 2277.0, 2310.0, 2343.0, 2376.0, 2409.0, 2442.0, 2475.0, 2508.0, 2541.0, 2574.0, 2607.0, 2640.0, 2673.0, 2706.0, 2739.0, 2772.0, 2805.0, 2838.0, 2871.0, 2904.0, 2937.0, 2970.0, 3003.0, 3036.0, 3069.0, 3102.0, 3135.0, 3168.0, 3201.0, 3234.0, 3267.0, 3300.0, 3333.0, 3366.0, 3399.0, 3432.0, 3465.0, 3498.0, 3531.0, 3564.0, 3597.0, 3630.0, 3663.0, 3696.0, 3729.0, 3762.0, 3795.0, 3828.0, 3861.0, 3894.0, 3927.0, 3960.0, 3993.0, 4026.0, 4059.0, 4092.0, 4125.0, 4158.0, 4191.0, 4224.0,", " 36.0, 72.0, 108.0, 144.0, 180.0, 216.0, 252.0, 288.0, 324.0, 360.0, 396.0, 432.0, 468.0, 504.0, 540.0, 576.0, 612.0, 648.0, 684.0, 720.0, 756.0, 792.0, 828.0, 864.0, 900.0, 936.0, 972.0, 1008.0, 1044.0, 1080.0, 1116.0, 1152.0, 1188.0, 1224.0, 1260.0, 1296.0, 1332.0, 1368.0, 1404.0, 1440.0, 1476.0, 1512.0, 1548.0, 1584.0, 1620.0, 1656.0, 1692.0, 1728.0, 1764.0, 1800.0, 1836.0, 1872.0, 1908.0, 1944.0, 1980.0, 2016.0, 2052.0, 2088.0, 2124.0, 2160.0, 2196.0, 2232.0, 2268.0, 2304.0, 2340.0, 2376.0, 2412.0, 2448.0, 2484.0, 2520.0, 2556.0, 2592.0, 2628.0, 2664.0, 2700.0, 2736.0, 2772.0, 2808.0, 2844.0, 2880.0, 2916.0, 2952.0, 2988.0, 3024.0, 3060.0, 3096.0, 3132.0, 3168.0, 3204.0, 3240.0, 3276.0, 3312.0, 3348.0, 3384.0, 3420.0, 3456.0, 3492.0, 3528.0, 3564.0, 3600.0, 3636.0, 3672.0, 3708.0, 3744.0, 3780.0, 3816.0, 3852.0, 3888.0, 3924.0, 3960.0, 3996.0, 4032.0, 4068.0, 4104.0, 4140.0, 4176.0, 4212.0, 4248.0, 4284.0, 4320.0, 4356.0, 4392.0, 4428.0, 4464.0, 4500.0, 4536.0, 4572.0, 4608.0,", " 39.0, 78.0, 117.0, 156.0, 195.0, 234.0, 273.0, 312.0, 351.0, 390.0, 429.0, 468.0, 507.0, 546.0, 585.0, 624.0, 663.0, 702.0, 741.0, 780.0, 819.0, 858.0, 897.0, 936.0, 975.0, 1014.0, 1053.0, 1092.0, 1131.0, 1170.0, 1209.0, 1248.0, 1287.0, 1326.0, 1365.0, 1404.0, 1443.0, 1482.0, 1521.0, 1560.0, 1599.0, 1638.0, 1677.0, 1716.0, 1755.0, 1794.0, 1833.0, 1872.0, 1911.0, 1950.0, 1989.0, 2028.0, 2067.0, 2106.0, 2145.0, 2184.0, 2223.0, 2262.0, 2301.0, 2340.0, 2379.0, 2418.0, 2457.0, 2496.0, 2535.0, 2574.0, 2613.0, 2652.0, 2691.0, 2730.0, 2769.0, 2808.0, 2847.0, 2886.0, 2925.0, 2964.0, 3003.0, 3042.0, 3081.0, 3120.0, 3159.0, 3198.0, 3237.0, 3276.0, 3315.0, 3354.0, 3393.0, 3432.0, 3471.0, 3510.0, 3549.0, 3588.0, 3627.0, 3666.0, 3705.0, 3744.0, 3783.0, 3822.0, 3861.0, 3900.0, 3939.0, 3978.0, 4017.0, 4056.0, 4095.0, 4134.0, 4173.0, 4212.0, 4251.0, 4290.0, 4329.0, 4368.0, 4407.0, 4446.0, 4485.0, 4524.0, 4563.0, 4602.0, 4641.0, 4680.0, 4719.0, 4758.0, 4797.0, 4836.0, 4875.0, 4914.0, 4953.0, 4992.0,", ) ; + +} +} diff --git a/chips/yosys/tests/various/stat_hierarchy.ys b/chips/yosys/tests/various/stat_hierarchy.ys new file mode 100644 index 0000000000000000000000000000000000000000..aff0068bbd20b7da79469a7b221f8ba7576ada2f --- /dev/null +++ b/chips/yosys/tests/various/stat_hierarchy.ys @@ -0,0 +1,60 @@ + +read_rtlil << EOT +module \top + wire input 1 \A + wire output 2 \Y + wire output 3 \N + + cell \sg13g2_and2_1 \sub1 + connect \A \A + connect \B 1'0 + connect \Y \Y + end + + cell \child \sequential + connect \A \A + connect \B 1'0 + connect \R 1'0 + connect \Y \Y + connect \N \N + end + + cell \child \sequential1 + connect \A \A + connect \B 1'0 + connect \R 1'0 + connect \Y \Y + connect \N \N + end + + cell \sg13g2_and2_1 \sub2 + connect \A \A + connect \B 1'0 + connect \Y \Y + end +end + +module \child + wire input 1 \A + wire input 2 \B + wire input 3 \R + + wire output 4 \Y + wire output 5 \N + + cell \sg13g2_dfrbp_1 \sequential_ff + connect \CLK \A + connect \D \B + connect \Q \Y + connect \Q_N \N + connect \RESET_B \R + end + +end +EOT +logger -expect log "4 112.493 2 18.144 cells" 2 +logger -expect log "2 18.144 2 18.144 sg13g2_and2_1" 2 +logger -expect log "2 94.349 - - sg13g2_dfrbp_1" 2 +logger -expect log "2 94.349 2 - submodules" 2 +logger -expect-no-warnings +stat -liberty ../../tests/liberty/foundry_data/sg13g2_stdcell_typ_1p20V_25C.lib.filtered.gz -top \top -hierarchy diff --git a/chips/yosys/tests/various/stat_high_level.ys b/chips/yosys/tests/various/stat_high_level.ys new file mode 100644 index 0000000000000000000000000000000000000000..9f94bf7646634f6cab264598c20c1d33f4f0ce58 --- /dev/null +++ b/chips/yosys/tests/various/stat_high_level.ys @@ -0,0 +1,90 @@ + +read_rtlil << EOT +module \top + wire input 1 \A + wire output 2 \Y + wire output 3 \N + + cell $and \sub1 + parameter \A_SIGNED 0 + parameter \A_WIDTH 1 + parameter \B_SIGNED 0 + parameter \B_WIDTH 1 + parameter \Y_WIDTH 1 + connect \A \A + connect \B 1'0 + connect \Y \Y + end + + cell \child \sequential + connect \A \A + connect \B 1'0 + connect \R 1'0 + connect \Y \Y + connect \N \N + end + + cell \child \sequential1 + connect \A \A + connect \B 1'0 + connect \R 1'0 + connect \Y \Y + connect \N \N + end + + cell $xor \sub2 + parameter \A_SIGNED 0 + parameter \A_WIDTH 1 + parameter \B_SIGNED 0 + parameter \B_WIDTH 1 + parameter \Y_WIDTH 1 + connect \A \A + connect \B 1'0 + connect \Y \Y + end +end + +module \child + wire input 1 \A + wire input 2 \B + wire input 3 \R + + wire output 4 \Y + wire output 5 \N + wire \Y1 + wire \Y2 + cell \sg13g2_dfrbp_1 \sequential_ff + connect \CLK \A + connect \D \Y2 + connect \Q \Y + connect \Q_N \N + connect \RESET_B \R + end + + cell $xor \sub2 + parameter \A_SIGNED 0 + parameter \A_WIDTH 1 + parameter \B_SIGNED 0 + parameter \B_WIDTH 1 + parameter \Y_WIDTH 1 + connect \A \B + connect \B 1'0 + connect \Y \Y1 + end + + cell $reduce_xor \sub3 + parameter \A_SIGNED 0 + parameter \A_WIDTH 10 + parameter \Y_WIDTH 1 + connect \A 10'0000000000 + connect \Y \Y2 + end + +end +EOT +logger -expect log "Chip area for top module '\\top': 66.000000" 1 +logger -expect log "3 30.5 3 30.5 cells" 1 +logger -expect log "2 51 - - \$reduce_xor" 2 +logger -expect log "8 66 2 5 cells" 2 +logger -expect-no-warnings +stat -liberty ./stat_area_by_width.lib -top \top -hierarchy diff --git a/chips/yosys/tests/various/stat_high_level2.ys b/chips/yosys/tests/various/stat_high_level2.ys new file mode 100644 index 0000000000000000000000000000000000000000..3493c1239f5c3171325ae7b74dbdac18871acb0d --- /dev/null +++ b/chips/yosys/tests/various/stat_high_level2.ys @@ -0,0 +1,89 @@ + +read_rtlil << EOT +module \top + wire input 1 \A + wire output 2 \Y + wire output 3 \N + + cell $and \sub1 + parameter \A_SIGNED 0 + parameter \A_WIDTH 1 + parameter \B_SIGNED 0 + parameter \B_WIDTH 1 + parameter \Y_WIDTH 1 + connect \A \A + connect \B 1'0 + connect \Y \Y + end + + cell \child \sequential + connect \A \A + connect \B 1'0 + connect \R 1'0 + connect \Y \Y + connect \N \N + end + + cell \child \sequential1 + connect \A \A + connect \B 1'0 + connect \R 1'0 + connect \Y \Y + connect \N \N + end + + cell $xor \sub2 + parameter \A_SIGNED 0 + parameter \A_WIDTH 1 + parameter \B_SIGNED 0 + parameter \B_WIDTH 1 + parameter \Y_WIDTH 1 + connect \A \A + connect \B 1'0 + connect \Y \Y + end +end + +module \child + wire input 1 \A + wire input 2 \B + wire input 3 \R + + wire output 4 \Y + wire output 5 \N + wire \Y1 + wire \Y2 + wire width 2 \A2 + cell \sg13g2_dfrbp_1 \sequential_ff + connect \CLK \A + connect \D \Y2 + connect \Q \Y + connect \Q_N \N + connect \RESET_B \R + end + + cell $bmux \bmux1 + parameter \WIDTH 2 + parameter \S_WIDTH 2 + connect \A 8'00000000 + connect \S 2'00 + connect \Y \A2 + end + + cell $reduce_xor \sub3 + parameter \A_SIGNED 0 + parameter \A_WIDTH 10 + parameter \Y_WIDTH 1 + connect \A 10'0000000000 + connect \Y \Y2 + end + +end +EOT + +logger -expect log "Chip area for top module '\\top': 80.000000" 1 +logger -expect log "1 12 1 12 \$bmux" 1 +logger -expect log "3 37.5 3 37.5 cells" 1 +logger -expect log "8 80 2 5 cells" 2 +logger -expect-no-warnings +stat -liberty ./stat_area_by_width.lib -top \top -hierarchy diff --git a/chips/yosys/tests/various/struct_access.sv b/chips/yosys/tests/various/struct_access.sv new file mode 100644 index 0000000000000000000000000000000000000000..d41a7114f3b98b944b416faefcff2c4be32a91b3 --- /dev/null +++ b/chips/yosys/tests/various/struct_access.sv @@ -0,0 +1,43 @@ +module dut(); +typedef struct packed { + logic a; + logic b; +} sub_sub_struct_t; + +typedef struct packed { + sub_sub_struct_t c; +} sub_struct_t; + +typedef struct packed { + sub_struct_t d; + sub_struct_t e; +} struct_t; + +parameter struct_t P = 4'b1100; + +localparam sub_struct_t f = P.d; +localparam sub_struct_t g = P.e; +localparam sub_sub_struct_t h = f.c; +localparam logic i = P.d.c.a; +localparam logic j = P.d.c.b; +localparam x = P.e; +localparam y = x.c; +localparam z = y.a; +localparam q = P.d; +localparam n = q.c.a; + +always_comb begin + assert(P == 4'b1100); + assert(f == 2'b11); + assert(g == 2'b00); + assert(h == 2'b11); + assert(i == 1'b1); + assert(j == 1'b1); + assert(x == 2'b00); + assert(y == 2'b00); + assert(x.c == 2'b00); + assert(y.b == 1'b0); + assert(n == 1'b1); + assert(z == 1'b0); +end +endmodule diff --git a/chips/yosys/tests/various/struct_access.ys b/chips/yosys/tests/various/struct_access.ys new file mode 100644 index 0000000000000000000000000000000000000000..43a2ac8b8273db4835192f7cdbee16ac7f1750ac --- /dev/null +++ b/chips/yosys/tests/various/struct_access.ys @@ -0,0 +1,6 @@ +read_verilog -sv struct_access.sv +hierarchy +proc +opt +async2sync +sat -verify -seq 1 -prove-asserts -show-all diff --git a/chips/yosys/tests/various/sub.v b/chips/yosys/tests/various/sub.v new file mode 100644 index 0000000000000000000000000000000000000000..63422ca5ccb0eb7c3666b7df837ac03a84156a65 --- /dev/null +++ b/chips/yosys/tests/various/sub.v @@ -0,0 +1,3 @@ +module sub #(parameter d=1) (input in, output out); + assign out = in; +endmodule diff --git a/chips/yosys/tests/various/submod.ys b/chips/yosys/tests/various/submod.ys new file mode 100644 index 0000000000000000000000000000000000000000..4fb45043bc1bc66c889378588ec9424e1c654c8e --- /dev/null +++ b/chips/yosys/tests/various/submod.ys @@ -0,0 +1,124 @@ +read_verilog <&2; exit 1' ERR + +# Simple case +${YOSYS} -f "verilog -sv" -qp "prep -flatten -top top; select -assert-count 1 t:\$add" - <&1 | grep -F "ERROR: No matching wire for implicit port connection \`b' of cell top.add_i (add)." > /dev/null + +# Incorrectly sized wire +((${YOSYS} -f "verilog -sv" -qp "hierarchy -top top" - || true) <&1 | grep -F "ERROR: Width mismatch between wire (7 bits) and port (8 bits) for implicit port connection \`b' of cell top.add_i (add)." > /dev/null + +# Defaults +${YOSYS} -f "verilog -sv" -qp "prep -flatten -top top; select -assert-count 1 t:\$add" - <&1 | grep -F "ERROR: Width mismatch between wire (8 bits) and port (6 bits) for implicit port connection \`q' of cell top.add_i (add)." > /dev/null + +# Mixed implicit and explicit 1 +${YOSYS} -f "verilog -sv" -qp "prep -flatten -top top; select -assert-count 1 t:\$add" - <&1 | grep -F "Warning: Resizing cell port top.add_i.b from 10 bits to 8 bits." > /dev/null diff --git a/chips/yosys/tests/various/svalways.sh b/chips/yosys/tests/various/svalways.sh new file mode 100644 index 0000000000000000000000000000000000000000..80cd234d4a79f14c0f33429f0e5abd5d0157324e --- /dev/null +++ b/chips/yosys/tests/various/svalways.sh @@ -0,0 +1,77 @@ +#!/usr/bin/env bash + +trap 'echo "ERROR in svalways.sh" >&2; exit 1' ERR + +# Good case +${YOSYS} -f "verilog -sv" -qp proc - <&1 | grep -F ":3: ERROR: syntax error, unexpected '@'" > /dev/null + +# Incorrect use of always_comb +((${YOSYS} -f "verilog -sv" -qp proc -|| true) <&1 | grep -F "ERROR: Latch inferred for signal \`\\top.\\q' from always_comb process" > /dev/null + +# Incorrect use of always_latch +((${YOSYS} -f "verilog -sv" -qp proc -|| true) <&1 | grep -F "ERROR: No latch inferred for signal \`\\top.\\q' from always_latch process" > /dev/null + +# Incorrect use of always_ff +((${YOSYS} -f "verilog -sv" -qp proc -|| true) <&1 | grep -F "ERROR: Found non edge/level sensitive event in always_ff process" > /dev/null diff --git a/chips/yosys/tests/various/synth_latch_warning.ys b/chips/yosys/tests/various/synth_latch_warning.ys new file mode 100644 index 0000000000000000000000000000000000000000..da375b32aaed6adc3a412b3d89ed12af48f76a27 --- /dev/null +++ b/chips/yosys/tests/various/synth_latch_warning.ys @@ -0,0 +1,31 @@ +read_verilog <> 4) - i; +endmodule +EOT + +hierarchy -auto-top +proc +design -save gold + +opt_expr +wreduce + +select -assert-count 1 t:$sub r:A_WIDTH=4 r:B_WIDTH=4 r:Y_WIDTH=5 %i %i %i + +design -stash gate + +design -import gold -as gold +design -import gate -as gate + +miter -equiv -flatten -make_assert -make_outputs gold gate miter +sat -verify -prove-asserts -show-ports miter + +########## + +read_verilog <>> 4) - i; +endmodule +EOT + +hierarchy -auto-top +proc +design -save gold + +opt_expr +wreduce + +select -assert-count 1 t:$sub r:A_WIDTH=4 r:B_WIDTH=4 r:Y_WIDTH=5 %i %i %i + +design -stash gate + +design -import gold -as gold +design -import gate -as gate + +miter -equiv -flatten -make_assert -make_outputs gold gate miter +sat -verify -prove-asserts -show-ports miter + +########## + +# Testcase from: https://github.com/YosysHQ/yosys/commit/25680f6a078bb32f157bd580705656496717bafb +design -reset +read_verilog <