diff --git a/chips/yosys/docs/source/code_examples/macc/macc_xilinx_wrap_map.v b/chips/yosys/docs/source/code_examples/macc/macc_xilinx_wrap_map.v new file mode 100644 index 0000000000000000000000000000000000000000..f23f6c02ac9e31e407d13e4b9c9ccef932fecf67 --- /dev/null +++ b/chips/yosys/docs/source/code_examples/macc/macc_xilinx_wrap_map.v @@ -0,0 +1,89 @@ +(* techmap_celltype = "$mul" *) +module mul_wrap (A, B, Y); + +parameter A_SIGNED = 0; +parameter B_SIGNED = 0; +parameter A_WIDTH = 1; +parameter B_WIDTH = 1; +parameter Y_WIDTH = 1; + +input [A_WIDTH-1:0] A; +input [B_WIDTH-1:0] B; +output [Y_WIDTH-1:0] Y; + +wire [17:0] A_18 = A; +wire [24:0] B_25 = B; +wire [47:0] Y_48; +assign Y = Y_48; + +wire [1023:0] _TECHMAP_DO_ = "proc; clean"; + +reg _TECHMAP_FAIL_; +initial begin + _TECHMAP_FAIL_ <= 0; + if (A_SIGNED || B_SIGNED) + _TECHMAP_FAIL_ <= 1; + if (A_WIDTH < 4 || B_WIDTH < 4) + _TECHMAP_FAIL_ <= 1; + if (A_WIDTH > 18 || B_WIDTH > 25) + _TECHMAP_FAIL_ <= 1; + if (A_WIDTH*B_WIDTH < 100) + _TECHMAP_FAIL_ <= 1; +end + +\$__mul_wrapper #( + .A_SIGNED(A_SIGNED), + .B_SIGNED(B_SIGNED), + .A_WIDTH(A_WIDTH), + .B_WIDTH(B_WIDTH), + .Y_WIDTH(Y_WIDTH) +) _TECHMAP_REPLACE_ ( + .A(A_18), + .B(B_25), + .Y(Y_48) +); + +endmodule + +(* techmap_celltype = "$add" *) +module add_wrap (A, B, Y); + +parameter A_SIGNED = 0; +parameter B_SIGNED = 0; +parameter A_WIDTH = 1; +parameter B_WIDTH = 1; +parameter Y_WIDTH = 1; + +input [A_WIDTH-1:0] A; +input [B_WIDTH-1:0] B; +output [Y_WIDTH-1:0] Y; + +wire [47:0] A_48 = A; +wire [47:0] B_48 = B; +wire [47:0] Y_48; +assign Y = Y_48; + +wire [1023:0] _TECHMAP_DO_ = "proc; clean"; + +reg _TECHMAP_FAIL_; +initial begin + _TECHMAP_FAIL_ <= 0; + if (A_SIGNED || B_SIGNED) + _TECHMAP_FAIL_ <= 1; + if (A_WIDTH < 10 && B_WIDTH < 10) + _TECHMAP_FAIL_ <= 1; +end + +\$__add_wrapper #( + .A_SIGNED(A_SIGNED), + .B_SIGNED(B_SIGNED), + .A_WIDTH(A_WIDTH), + .B_WIDTH(B_WIDTH), + .Y_WIDTH(Y_WIDTH) +) _TECHMAP_REPLACE_ ( + .A(A_48), + .B(B_48), + .Y(Y_48) +); + +endmodule diff --git a/chips/yosys/docs/source/code_examples/macc/macc_xilinx_xmap.v b/chips/yosys/docs/source/code_examples/macc/macc_xilinx_xmap.v new file mode 100644 index 0000000000000000000000000000000000000000..06372f5af0d9b7c290cc2b3f6434f7289ee11da5 --- /dev/null +++ b/chips/yosys/docs/source/code_examples/macc/macc_xilinx_xmap.v @@ -0,0 +1,10 @@ +module DSP48_MACC (a, b, c, y); + +input [17:0] a; +input [24:0] b; +input [47:0] c; +output [47:0] y; + +assign y = a*b + c; + +endmodule diff --git a/chips/yosys/docs/source/code_examples/macro_commands/fsm.ys b/chips/yosys/docs/source/code_examples/macro_commands/fsm.ys new file mode 100644 index 0000000000000000000000000000000000000000..627df1209aef38d6d17ca4532fab44e9562efd27 --- /dev/null +++ b/chips/yosys/docs/source/code_examples/macro_commands/fsm.ys @@ -0,0 +1,27 @@ +#start:It also calls opt_clean as needed: +#end:Options: +# Identify and extract FSMs: +fsm_detect +fsm_extract + +# Basic optimizations: +fsm_opt +opt_clean +fsm_opt + +# Expanding to nearby gate-logic (if called with -expand): +fsm_expand +opt_clean +fsm_opt + +# Re-code FSM states (unless called with -norecode): +fsm_recode + +# Print information about FSMs: +fsm_info + +# Export FSMs in KISS2 file format (if called with -export): +fsm_export + +# Map FSMs to RTL cells (unless called with -nomap): +fsm_map diff --git a/chips/yosys/docs/source/code_examples/macro_commands/memory.ys b/chips/yosys/docs/source/code_examples/macro_commands/memory.ys new file mode 100644 index 0000000000000000000000000000000000000000..ea4800a1cc1e9d8d3e478b51e7b79849769fbf52 --- /dev/null +++ b/chips/yosys/docs/source/code_examples/macro_commands/memory.ys @@ -0,0 +1,15 @@ +#start:passes in a useful order: +#end:This converts memories to word-wide DFFs and address decoders +opt_mem +opt_mem_priority +opt_mem_feedback +memory_bmux2rom +memory_dff +opt_clean +memory_share +opt_mem_widen +memory_memx (when called with -memx) +opt_clean +memory_collect +memory_bram -rules (when called with -bram) +memory_map (skipped if called with -nomap) diff --git a/chips/yosys/docs/source/code_examples/macro_commands/opt.ys b/chips/yosys/docs/source/code_examples/macro_commands/opt.ys new file mode 100644 index 0000000000000000000000000000000000000000..ebd938836acd422d61106def27bb59fe0191e853 --- /dev/null +++ b/chips/yosys/docs/source/code_examples/macro_commands/opt.ys @@ -0,0 +1,15 @@ +#start: passes in the following order: +#end: When called with -fast +opt_expr +opt_merge -nomux + +do + opt_muxtree + opt_reduce + opt_merge + opt_share (-full only) + opt_dff (except when called with -noff) + opt_hier (-hier only) + opt_clean + opt_expr +while diff --git a/chips/yosys/docs/source/code_examples/macro_commands/prep.ys b/chips/yosys/docs/source/code_examples/macro_commands/prep.ys new file mode 100644 index 0000000000000000000000000000000000000000..f1bd41371f9768ae3977587af1104ec9f4d69e3d --- /dev/null +++ b/chips/yosys/docs/source/code_examples/macro_commands/prep.ys @@ -0,0 +1,26 @@ +#start:The following commands are executed by this synthesis command: +#end:$ +begin: + hierarchy -check [-top | -auto-top] + +coarse: + optbarriers (if -barriers) + proc [-ifx] + check + flatten [-barriers] (if -flatten) + future + opt_expr -keepdc + check + opt_clean + opt -noff -keepdc + wreduce -keepdc [-memx] + memory_dff (if -rdff) + memory_memx (if -memx) + opt_clean + memory_collect + opt -noff -keepdc -fast + sort + +check: + stat + check diff --git a/chips/yosys/docs/source/code_examples/macro_commands/proc.ys b/chips/yosys/docs/source/code_examples/macro_commands/proc.ys new file mode 100644 index 0000000000000000000000000000000000000000..7a78ce0c6b88b08839acc9a85fba6fbaa12260fa --- /dev/null +++ b/chips/yosys/docs/source/code_examples/macro_commands/proc.ys @@ -0,0 +1,14 @@ +#start: passes in the most common order. +#end: This replaces the processes +proc_clean # removes empty branches and processes +proc_rmdead # removes unreachable branches +proc_prune +proc_init # special handling of “initial” blocks +proc_arst # identifies modeling of async resets +proc_rom +proc_mux # converts decision trees to multiplexer networks +proc_dlatch +proc_dff # extracts registers from processes +proc_memwr +proc_clean # this should remove all the processes, provided all went fine +opt_expr -keepdc diff --git a/chips/yosys/docs/source/code_examples/macro_commands/synth_ice40.ys b/chips/yosys/docs/source/code_examples/macro_commands/synth_ice40.ys new file mode 100644 index 0000000000000000000000000000000000000000..f949f9e87446210b6167c8c35ad952623030b1e1 --- /dev/null +++ b/chips/yosys/docs/source/code_examples/macro_commands/synth_ice40.ys @@ -0,0 +1,90 @@ +#start:The following commands are executed by this synthesis command: +#end:blif: +begin: + read_verilog -D ICE40_HX -lib -specify +/ice40/cells_sim.v + hierarchy -check -top + proc + +flatten: + check + flatten + tribuf -logic + deminout + +coarse: + opt_expr + check + opt_clean + opt -nodffe -nosdff + fsm + opt + wreduce + peepopt + opt_clean + share + techmap + opt_expr + opt_clean + memory_dff + alumacc -macc-only + maccmap -unmap + opt_clean + wreduce t:$mul + techmap + select a:mul2dsp + setattr -unset mul2dsp + opt_expr -fine + wreduce + select -clear + ice40_dsp + chtype -set $mul t:$__soft_mul + alumacc + opt + memory -nomap [-no-rw-check] + opt_clean + +map_ram: + memory_libmap + techmap + ice40_braminit + +map_ffram: + opt -fast -mux_undef -undriven -fine + memory_map + opt -undriven -fine + +map_gates: + ice40_wrapcarry + techmap + opt -fast + ice40_opt + +map_ffs: + dfflegalize + techmap + opt_expr -mux_undef + simplemap + ice40_opt -full + +map_luts: + check + techmap + simplemap + techmap + read_verilog + abc9 + ice40_wrapcarry -unwrap + techmap + clean + opt_lut -tech ice40 + +map_cells: + techmap + clean + +check: + autoname + hierarchy -check + stat + check -noinit + blackbox =A:whitebox diff --git a/chips/yosys/docs/source/code_examples/opt/Makefile b/chips/yosys/docs/source/code_examples/opt/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..2a59088228e3580634456bbbb094aaaa5363bbd2 --- /dev/null +++ b/chips/yosys/docs/source/code_examples/opt/Makefile @@ -0,0 +1,18 @@ +include ../../../common.mk + +DOT_NAMES = opt_share opt_muxtree opt_merge opt_expr + +DOTS := $(addsuffix .dot,$(DOT_NAMES)) + +.PHONY: all dots examples +all: dots examples +dots: $(DOTS) +examples: + +%.dot: %.ys + @$(YOSYS) $< >/dev/null 2>&1 + @gvpack -u -o $@ $*_full.dot >/dev/null 2>&1 + +.PHONY: clean +clean: + @rm -f *.dot diff --git a/chips/yosys/docs/source/code_examples/opt/opt_expr.ys b/chips/yosys/docs/source/code_examples/opt/opt_expr.ys new file mode 100644 index 0000000000000000000000000000000000000000..f884b222767a66383be77f6a6c1e366284c91d03 --- /dev/null +++ b/chips/yosys/docs/source/code_examples/opt/opt_expr.ys @@ -0,0 +1,17 @@ +read_verilog </dev/null 2>&1 + +.PHONY: clean +clean: + @rm -f *.dot diff --git a/chips/yosys/docs/source/code_examples/scrambler/scrambler.v b/chips/yosys/docs/source/code_examples/scrambler/scrambler.v new file mode 100644 index 0000000000000000000000000000000000000000..d4c1fa2bbc85246407d2ce2f9cfb95cb07cf8920 --- /dev/null +++ b/chips/yosys/docs/source/code_examples/scrambler/scrambler.v @@ -0,0 +1,14 @@ +module scrambler( + input clk, rst, in_bit, + output reg out_bit +); + reg [31:0] xs; + always @(posedge clk) begin + if (rst) + xs = 1; + xs = xs ^ (xs << 13); + xs = xs ^ (xs >> 17); + xs = xs ^ (xs << 5); + out_bit <= in_bit ^ xs[0]; + end +endmodule diff --git a/chips/yosys/docs/source/code_examples/scrambler/scrambler.ys b/chips/yosys/docs/source/code_examples/scrambler/scrambler.ys new file mode 100644 index 0000000000000000000000000000000000000000..c340f4b7664864c26d829457faacfc2bcdc3e237 --- /dev/null +++ b/chips/yosys/docs/source/code_examples/scrambler/scrambler.ys @@ -0,0 +1,21 @@ +read_verilog scrambler.v + +hierarchy; proc;; + +cd scrambler +submod -name xorshift32 xs %c %ci %D %c %ci:+[D] %D %ci*:-$dff xs %co %ci %d +cd .. + +show -prefix scrambler_p01 -format dot -notitle scrambler +show -prefix scrambler_p02 -format dot -notitle xorshift32 + +echo on + +cd xorshift32 +rename n2 in +rename n1 out + +eval -set in 1 -show out +eval -set in 270369 -show out + +sat -set out 632435482 diff --git a/chips/yosys/docs/source/code_examples/selections/Makefile b/chips/yosys/docs/source/code_examples/selections/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..a171cbf71f51ac5cf2a0f33f4365b48202745173 --- /dev/null +++ b/chips/yosys/docs/source/code_examples/selections/Makefile @@ -0,0 +1,32 @@ +include ../../../common.mk + +SUMPROD = sumprod_00 sumprod_01 sumprod_02 sumprod_03 sumprod_04 sumprod_05 +SUMPROD_DOTS := $(addsuffix .dot,$(SUMPROD)) + +MEMDEMO = memdemo_00 memdemo_01 +MEMDEMO_DOTS := $(addsuffix .dot,$(MEMDEMO)) + +SUBMOD = submod_00 submod_01 submod_02 submod_03 +SUBMOD_DOTS := $(addsuffix .dot,$(SUBMOD)) + +.PHONY: all dots examples +all: dots examples +dots: select.dot $(SUMPROD_DOTS) $(MEMDEMO_DOTS) $(SUBMOD_DOTS) +examples: sumprod.out + +select.dot: select.v select.ys + @$(YOSYS) select.ys >/dev/null 2>&1 + +$(SUMPROD_DOTS) sumprod.out: sumprod.v sumprod.ys + @$(YOSYS) sumprod.ys >/dev/null 2>&1 + +$(MEMDEMO_DOTS): memdemo.v memdemo.ys + @$(YOSYS) memdemo.ys >/dev/null 2>&1 + +$(SUBMOD_DOTS): memdemo.v submod.ys + @$(YOSYS) submod.ys >/dev/null 2>&1 + +.PHONY: clean +clean: + @rm -rf *.dot + @rm -f sumprod.out diff --git a/chips/yosys/docs/source/code_examples/selections/foobaraddsub.v b/chips/yosys/docs/source/code_examples/selections/foobaraddsub.v new file mode 100644 index 0000000000000000000000000000000000000000..0f277211d1c1803432b473e55279206e2123d012 --- /dev/null +++ b/chips/yosys/docs/source/code_examples/selections/foobaraddsub.v @@ -0,0 +1,8 @@ +module foobaraddsub(a, b, c, d, fa, fs, ba, bs); + input [7:0] a, b, c, d; + output [7:0] fa, fs, ba, bs; + assign fa = a + (* foo *) b; + assign fs = a - (* foo *) b; + assign ba = c + (* bar *) d; + assign bs = c - (* bar *) d; +endmodule diff --git a/chips/yosys/docs/source/code_examples/selections/memdemo.v b/chips/yosys/docs/source/code_examples/selections/memdemo.v new file mode 100644 index 0000000000000000000000000000000000000000..b39564ddc20355cac3e3519e3203f7b694736fcc --- /dev/null +++ b/chips/yosys/docs/source/code_examples/selections/memdemo.v @@ -0,0 +1,19 @@ +module memdemo(clk, d, y); + +input clk; +input [3:0] d; +output reg [3:0] y; + +integer i; +reg [1:0] s1, s2; +reg [3:0] mem [0:3]; + +always @(posedge clk) begin + for (i = 0; i < 4; i = i+1) + mem[i] <= mem[(i+1) % 4] + mem[(i+2) % 4]; + { s2, s1 } = d ? { s1, s2 } ^ d : 4'b0; + mem[s1] <= d; + y <= mem[s2]; +end + +endmodule diff --git a/chips/yosys/docs/source/code_examples/selections/memdemo.ys b/chips/yosys/docs/source/code_examples/selections/memdemo.ys new file mode 100644 index 0000000000000000000000000000000000000000..cb7700a7e0401d0b4b9d7cb2223be38e0aafd8f1 --- /dev/null +++ b/chips/yosys/docs/source/code_examples/selections/memdemo.ys @@ -0,0 +1,10 @@ +read_verilog memdemo.v +prep -top memdemo; memory; opt + +cd memdemo +show -format dot -prefix memdemo_00 +show -format dot -prefix memdemo_01 y %ci2 +show -format dot -prefix memdemo_02 y %ci5 +show -format dot -prefix memdemo_03 y %ci5:-$mux[S] +show -format dot -prefix memdemo_04 y %ci*:-[CLK,S]:+$dff,$mux +show -format dot -prefix memdemo_05 y %ci2:+$dff[Q,D] %ci*:-$mux[S]:-$dff diff --git a/chips/yosys/docs/source/code_examples/selections/select.v b/chips/yosys/docs/source/code_examples/selections/select.v new file mode 100644 index 0000000000000000000000000000000000000000..1b0bb7eeb67e6f7336a0b641e929de813efb4981 --- /dev/null +++ b/chips/yosys/docs/source/code_examples/selections/select.v @@ -0,0 +1,15 @@ +module test(clk, s, a, y); + input clk, s; + input [15:0] a; + output [15:0] y; + reg [15:0] b, c; + + always @(posedge clk) begin + b <= a; + c <= b; + end + + wire [15:0] state_a = (a ^ b) + c; + wire [15:0] state_b = (a ^ b) - c; + assign y = !s ? state_a : state_b; +endmodule diff --git a/chips/yosys/docs/source/code_examples/selections/select.ys b/chips/yosys/docs/source/code_examples/selections/select.ys new file mode 100644 index 0000000000000000000000000000000000000000..e9a775f1fdf9821a32b41f1929bc80017c0affe5 --- /dev/null +++ b/chips/yosys/docs/source/code_examples/selections/select.ys @@ -0,0 +1,10 @@ +read_verilog select.v +prep -top test + +cd test +select -set cone_a state_a %ci*:-$dff +select -set cone_b state_b %ci*:-$dff +select -set cone_ab @cone_a @cone_b %i +show -prefix select -format dot -notitle \ + -color red @cone_ab -color magenta @cone_a \ + -color blue @cone_b diff --git a/chips/yosys/docs/source/code_examples/selections/submod.ys b/chips/yosys/docs/source/code_examples/selections/submod.ys new file mode 100644 index 0000000000000000000000000000000000000000..c252153c619615824d2cbba35be71d364310ea59 --- /dev/null +++ b/chips/yosys/docs/source/code_examples/selections/submod.ys @@ -0,0 +1,16 @@ +read_verilog memdemo.v +prep -top memdemo; memory; opt + +cd memdemo +select -set outstage y %ci2:+$dff[Q,D] %ci*:-$mux[S]:-$dff +select -set selstage y %ci2:+$dff[Q,D] %ci*:-$dff @outstage %d +select -set scramble mem* %ci2 %ci*:-$dff mem* %d @selstage %d +submod -name scramble @scramble +submod -name outstage @outstage +submod -name selstage @selstage + +cd .. +show -format dot -prefix submod_00 memdemo +show -format dot -prefix submod_01 scramble +show -format dot -prefix submod_02 outstage +show -format dot -prefix submod_03 selstage diff --git a/chips/yosys/docs/source/code_examples/selections/sumprod.v b/chips/yosys/docs/source/code_examples/selections/sumprod.v new file mode 100644 index 0000000000000000000000000000000000000000..4091bf0a15112026a4d48dedaf75ed906cebe352 --- /dev/null +++ b/chips/yosys/docs/source/code_examples/selections/sumprod.v @@ -0,0 +1,12 @@ +module sumprod(a, b, c, sum, prod); + + input [7:0] a, b, c; + output [7:0] sum, prod; + + {* sumstuff *} + assign sum = a + b + c; + {* *} + + assign prod = a * b * c; + +endmodule diff --git a/chips/yosys/docs/source/code_examples/selections/sumprod.ys b/chips/yosys/docs/source/code_examples/selections/sumprod.ys new file mode 100644 index 0000000000000000000000000000000000000000..67e2a28d5c9039d55a5d8fd4a749884d67a60fa9 --- /dev/null +++ b/chips/yosys/docs/source/code_examples/selections/sumprod.ys @@ -0,0 +1,13 @@ +read_verilog sumprod.v +prep -top sumprod +cd sumprod + +show -format dot -prefix sumprod_00 a:sumstuff +show -format dot -prefix sumprod_01 a:sumstuff %x +show -format dot -prefix sumprod_02 prod +show -format dot -prefix sumprod_03 prod %ci +show -format dot -prefix sumprod_04 prod %ci2 +show -format dot -prefix sumprod_05 prod %ci3 + +dump -o sumprod.out prod %ci +dump -a sumprod.out prod %ci2 diff --git a/chips/yosys/docs/source/code_examples/show/Makefile b/chips/yosys/docs/source/code_examples/show/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..5838cb3cd805debcd0fe5d712cd05ad3cec773a7 --- /dev/null +++ b/chips/yosys/docs/source/code_examples/show/Makefile @@ -0,0 +1,29 @@ +include ../../../common.mk + +EXAMPLE = example_first example_second example_third +EXAMPLE_DOTS := $(addsuffix .dot,$(EXAMPLE)) + +CMOS = cmos_00 cmos_01 +CMOS_DOTS := $(addsuffix .dot,$(CMOS)) + +.PHONY: all dots examples +all: dots examples +dots: splice.dot $(EXAMPLE_DOTS) $(CMOS_DOTS) +examples: example.out + +splice.dot: splice.v + @$(YOSYS) -p 'prep -top splice_demo; show -format dot -prefix splice' splice.v >/dev/null 2>&1 + +$(EXAMPLE_DOTS): example.v example.ys + @$(YOSYS) example.ys >/dev/null 2>&1 + +example.out: example_lscd.ys example.v + @$(YOSYS) $< -l $@ -Q -T >/dev/null 2>&1 + +$(CMOS_DOTS): cmos.v cmos.ys + @$(YOSYS) cmos.ys >/dev/null 2>&1 + +.PHONY: clean +clean: + @rm -rf *.dot + @rm -f example.out diff --git a/chips/yosys/docs/source/code_examples/show/cmos.v b/chips/yosys/docs/source/code_examples/show/cmos.v new file mode 100644 index 0000000000000000000000000000000000000000..2912c760a7a27225cad7686b3487f972b98506af --- /dev/null +++ b/chips/yosys/docs/source/code_examples/show/cmos.v @@ -0,0 +1,3 @@ +module cmos_demo(input a, b, output [1:0] y); +assign y = a + b; +endmodule diff --git a/chips/yosys/docs/source/code_examples/show/cmos.ys b/chips/yosys/docs/source/code_examples/show/cmos.ys new file mode 100644 index 0000000000000000000000000000000000000000..922c9919290d82e43066c5337ea42c754f047e4e --- /dev/null +++ b/chips/yosys/docs/source/code_examples/show/cmos.ys @@ -0,0 +1,17 @@ +# pitfall +read_verilog cmos.v +prep -top cmos_demo +techmap +abc -liberty ../intro/mycells.lib;; +show -format dot -prefix cmos_00 + +# reset +design -reset + +# fixed output +read_verilog cmos.v +prep -top cmos_demo +techmap +splitnets -ports +abc -liberty ../intro/mycells.lib;; +show -lib ../intro/mycells.v -format dot -prefix cmos_01 diff --git a/chips/yosys/docs/source/code_examples/show/example.v b/chips/yosys/docs/source/code_examples/show/example.v new file mode 100644 index 0000000000000000000000000000000000000000..8c71989b3653b58ff1772811c000428489a96578 --- /dev/null +++ b/chips/yosys/docs/source/code_examples/show/example.v @@ -0,0 +1,6 @@ +module example(input clk, a, b, c, + output reg [1:0] y); + always @(posedge clk) + if (c) + y <= c ? a + b : 2'd0; +endmodule diff --git a/chips/yosys/docs/source/code_examples/show/example.ys b/chips/yosys/docs/source/code_examples/show/example.ys new file mode 100644 index 0000000000000000000000000000000000000000..a5332f13486c2670ac00bcd052d7d287f15c4ee2 --- /dev/null +++ b/chips/yosys/docs/source/code_examples/show/example.ys @@ -0,0 +1,6 @@ +read_verilog example.v +show -format dot -prefix example_first +proc +show -format dot -prefix example_second +opt +show -format dot -prefix example_third diff --git a/chips/yosys/docs/source/code_examples/show/example_lscd.ys b/chips/yosys/docs/source/code_examples/show/example_lscd.ys new file mode 100644 index 0000000000000000000000000000000000000000..de24842285aa0ce1f407e4175b89bc1c6b2b8b9e --- /dev/null +++ b/chips/yosys/docs/source/code_examples/show/example_lscd.ys @@ -0,0 +1,8 @@ +read_verilog example.v +echo on +ls +cd example +ls +dump $2 +cd .. +echo off diff --git a/chips/yosys/docs/source/code_examples/show/example_show.ys b/chips/yosys/docs/source/code_examples/show/example_show.ys new file mode 100644 index 0000000000000000000000000000000000000000..711af84d9f277506708d83b08c65d731bdf49b66 --- /dev/null +++ b/chips/yosys/docs/source/code_examples/show/example_show.ys @@ -0,0 +1,6 @@ +read_verilog example.v +show -pause # first +proc +show -pause # second +opt +show -pause # third diff --git a/chips/yosys/docs/source/code_examples/show/splice.v b/chips/yosys/docs/source/code_examples/show/splice.v new file mode 100644 index 0000000000000000000000000000000000000000..1f7c92f4d0418422f907be1921e0d95e49dbb318 --- /dev/null +++ b/chips/yosys/docs/source/code_examples/show/splice.v @@ -0,0 +1,11 @@ +module splice_demo(a, b, c, d, e, f, x, y); + +input [1:0] a, b, c, d, e, f; +output [1:0] x; +assign x = {a[0], a[1]}; + +output [11:0] y; +assign {y[11:4], y[1:0], y[3:2]} = + {a, b, -{c, d}, ~{e, f}}; + +endmodule diff --git a/chips/yosys/docs/source/code_examples/stubnets/.gitignore b/chips/yosys/docs/source/code_examples/stubnets/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..fa83c32120a1ef65959334ecf6180eb4f2cdbe99 --- /dev/null +++ b/chips/yosys/docs/source/code_examples/stubnets/.gitignore @@ -0,0 +1,3 @@ +stubnets.so +stubnets.d +*.log diff --git a/chips/yosys/docs/source/code_examples/stubnets/Makefile b/chips/yosys/docs/source/code_examples/stubnets/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..cefaf36cec701729184e8ffc225a552e5cf962a8 --- /dev/null +++ b/chips/yosys/docs/source/code_examples/stubnets/Makefile @@ -0,0 +1,20 @@ +include ../../../common.mk + +.PHONY: all dots examples +all: dots examples +dots: +examples: test + +.PHONY: test +test: stubnets.so + @$(YOSYS) -ql test1.log -m ./stubnets.so test.v -p "stubnets" >/dev/null 2>&1 + @$(YOSYS) -ql test2.log -m ./stubnets.so test.v -p "opt; stubnets" >/dev/null 2>&1 + @$(YOSYS) -ql test3.log -m ./stubnets.so test.v -p "techmap; opt; stubnets -report_bits" >/dev/null 2>&1 + +stubnets.so: stubnets.cc + @$(YOSYS_CONFIG) --exec --cxx --cxxflags --ldflags -o $@ -shared $^ --ldlibs >/dev/null 2>&1 + +.PHONY: clean +clean: + @rm -f test1.log test2.log test3.log + @rm -f stubnets.so stubnets.d diff --git a/chips/yosys/docs/source/code_examples/stubnets/stubnets.cc b/chips/yosys/docs/source/code_examples/stubnets/stubnets.cc new file mode 100644 index 0000000000000000000000000000000000000000..c1582a2a0c1efdf166972bd5aac8be4352ed9605 --- /dev/null +++ b/chips/yosys/docs/source/code_examples/stubnets/stubnets.cc @@ -0,0 +1,130 @@ +// This is free and unencumbered software released into the public domain. +// +// Anyone is free to copy, modify, publish, use, compile, sell, or +// distribute this software, either in source code form or as a compiled +// binary, for any purpose, commercial or non-commercial, and by any +// means. + +#include "kernel/yosys.h" +#include "kernel/sigtools.h" + +#include +#include +#include + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +// this function is called for each module in the design +static void find_stub_nets(RTLIL::Design *design, RTLIL::Module *module, bool report_bits) +{ + // use a SigMap to convert nets to a unique representation + SigMap sigmap(module); + + // count how many times a single-bit signal is used + std::map bit_usage_count; + + // count output lines for this module (needed only for summary output at the end) + int line_count = 0; + + log("Looking for stub wires in module %s:\n", module); + + // For all ports on all cells + for (auto &cell_iter : module->cells_) + for (auto &conn : cell_iter.second->connections()) + { + // Get the signals on the port + // (use sigmap to get a uniqe signal name) + RTLIL::SigSpec sig = sigmap(conn.second); + + // add each bit to bit_usage_count, unless it is a constant + for (auto &bit : sig) + if (bit.wire != NULL) + bit_usage_count[bit]++; + } + + // for each wire in the module + for (auto &wire_iter : module->wires_) + { + RTLIL::Wire *wire = wire_iter.second; + + // .. but only selected wires + if (!design->selected(module, wire)) + continue; + + // add +1 usage if this wire actually is a port + int usage_offset = wire->port_id > 0 ? 1 : 0; + + // we will record which bits of the (possibly multi-bit) wire are stub signals + std::set stub_bits; + + // get a signal description for this wire and split it into separate bits + RTLIL::SigSpec sig = sigmap(wire); + + // for each bit (unless it is a constant): + // check if it is used at least two times and add to stub_bits otherwise + for (int i = 0; i < GetSize(sig); i++) + if (sig[i].wire != NULL && (bit_usage_count[sig[i]] + usage_offset) < 2) + stub_bits.insert(i); + + // continue if no stub bits found + if (stub_bits.size() == 0) + continue; + + // report stub bits and/or stub wires, don't report single bits + // if called with report_bits set to false. + if (GetSize(stub_bits) == GetSize(sig)) { + log(" found stub wire: %s\n", wire); + } else { + if (!report_bits) + continue; + std::string bits; + for (int bit : stub_bits) + bits += stringf("%s%d", bit == *stub_bits.begin() ? "" : ", ", bit); + log(" found wire with stub bits: %s [%s]\n", wire, bits); + } + + // we have outputted a line, increment summary counter + line_count++; + } + + // report summary + if (report_bits) + log(" found %d stub wires or wires with stub bits.\n", line_count); + else + log(" found %d stub wires.\n", line_count); +} + +// each pass contains a singleton object that is derived from Pass +struct StubnetsPass : public Pass { + StubnetsPass() : Pass("stubnets") { } + void execute(std::vector args, RTLIL::Design *design) override + { + // variables to mirror information from passed options + bool report_bits = 0; + + log_header(design, "Executing STUBNETS pass (find stub nets).\n"); + + // parse options + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) { + std::string arg = args[argidx]; + if (arg == "-report_bits") { + report_bits = true; + continue; + } + break; + } + + // handle extra options (e.g. selection) + extra_args(args, argidx, design); + + // call find_stub_nets() for each module that is either + // selected as a whole or contains selected objects. + for (auto &it : design->modules_) + if (design->selected_module(it.first)) + find_stub_nets(design, it.second, report_bits); + } +} StubnetsPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/docs/source/code_examples/stubnets/test.v b/chips/yosys/docs/source/code_examples/stubnets/test.v new file mode 100644 index 0000000000000000000000000000000000000000..201f75006819e2362878afba50547d1487864b4f --- /dev/null +++ b/chips/yosys/docs/source/code_examples/stubnets/test.v @@ -0,0 +1,8 @@ +module uut(in1, in2, in3, out1, out2); + +input [8:0] in1, in2, in3; +output [8:0] out1, out2; + +assign out1 = in1 + in2 + (in3 >> 4); + +endmodule diff --git a/chips/yosys/docs/source/code_examples/synth_flow/Makefile b/chips/yosys/docs/source/code_examples/synth_flow/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..83a5f5b976c6088d3484f096266b8ac906ddf559 --- /dev/null +++ b/chips/yosys/docs/source/code_examples/synth_flow/Makefile @@ -0,0 +1,19 @@ +include ../../../common.mk + +DOT_TARGETS += proc_01 proc_02 proc_03 +DOT_TARGETS += memory_01 memory_02 +DOT_TARGETS += techmap_01 + +DOTS = $(addsuffix .dot,$(DOT_TARGETS)) + +.PHONY: all dots examples +all: dots examples +dots: $(DOTS) +examples: + +%.dot: %.v %.ys + @$(YOSYS) -p 'script $*.ys; show -notitle -prefix $* -format dot' >/dev/null 2>&1 + +.PHONY: clean +clean: + @rm -f *.dot diff --git a/chips/yosys/docs/source/code_examples/synth_flow/memory_01.v b/chips/yosys/docs/source/code_examples/synth_flow/memory_01.v new file mode 100644 index 0000000000000000000000000000000000000000..0a3f9acd71cfcda1aed07aa5aab94231637679ed --- /dev/null +++ b/chips/yosys/docs/source/code_examples/synth_flow/memory_01.v @@ -0,0 +1,9 @@ +module test(input CLK, ADDR, + input [7:0] DIN, + output reg [7:0] DOUT); + reg [7:0] mem [0:1]; + always @(posedge CLK) begin + mem[ADDR] <= DIN; + DOUT <= mem[ADDR]; + end +endmodule diff --git a/chips/yosys/docs/source/code_examples/synth_flow/memory_01.ys b/chips/yosys/docs/source/code_examples/synth_flow/memory_01.ys new file mode 100644 index 0000000000000000000000000000000000000000..2ffd8223ab544b6c624d72c054d700e6e44a67ea --- /dev/null +++ b/chips/yosys/docs/source/code_examples/synth_flow/memory_01.ys @@ -0,0 +1,3 @@ +read_verilog memory_01.v +hierarchy -check -top test +proc;; memory; opt diff --git a/chips/yosys/docs/source/code_examples/synth_flow/memory_02.v b/chips/yosys/docs/source/code_examples/synth_flow/memory_02.v new file mode 100644 index 0000000000000000000000000000000000000000..dbe86ed187e5d074cf19f10d36e70c4828742bcf --- /dev/null +++ b/chips/yosys/docs/source/code_examples/synth_flow/memory_02.v @@ -0,0 +1,27 @@ +module test( + input WR1_CLK, WR2_CLK, + input WR1_WEN, WR2_WEN, + input [7:0] WR1_ADDR, WR2_ADDR, + input [7:0] WR1_DATA, WR2_DATA, + input RD1_CLK, RD2_CLK, + input [7:0] RD1_ADDR, RD2_ADDR, + output reg [7:0] RD1_DATA, RD2_DATA +); + +reg [7:0] memory [0:255]; + +always @(posedge WR1_CLK) + if (WR1_WEN) + memory[WR1_ADDR] <= WR1_DATA; + +always @(posedge WR2_CLK) + if (WR2_WEN) + memory[WR2_ADDR] <= WR2_DATA; + +always @(posedge RD1_CLK) + RD1_DATA <= memory[RD1_ADDR]; + +always @(posedge RD2_CLK) + RD2_DATA <= memory[RD2_ADDR]; + +endmodule diff --git a/chips/yosys/docs/source/code_examples/synth_flow/memory_02.ys b/chips/yosys/docs/source/code_examples/synth_flow/memory_02.ys new file mode 100644 index 0000000000000000000000000000000000000000..9da6fda549365a2fc6d3b41789b3258ff10b4696 --- /dev/null +++ b/chips/yosys/docs/source/code_examples/synth_flow/memory_02.ys @@ -0,0 +1,4 @@ +read_verilog memory_02.v +hierarchy -check -top test +proc;; memory -nomap +opt -mux_undef -mux_bool diff --git a/chips/yosys/docs/source/code_examples/synth_flow/proc_01.v b/chips/yosys/docs/source/code_examples/synth_flow/proc_01.v new file mode 100644 index 0000000000000000000000000000000000000000..6128631955bb09ca2dac5d56133419d0db71e090 --- /dev/null +++ b/chips/yosys/docs/source/code_examples/synth_flow/proc_01.v @@ -0,0 +1,7 @@ +module test(input D, C, R, output reg Q); + always @(posedge C, posedge R) + if (R) + Q <= 0; + else + Q <= D; +endmodule diff --git a/chips/yosys/docs/source/code_examples/synth_flow/proc_01.ys b/chips/yosys/docs/source/code_examples/synth_flow/proc_01.ys new file mode 100644 index 0000000000000000000000000000000000000000..c22a2fd5f06b89999e175c7e45a5ea119b060e7a --- /dev/null +++ b/chips/yosys/docs/source/code_examples/synth_flow/proc_01.ys @@ -0,0 +1,3 @@ +read_verilog proc_01.v +hierarchy -check -top test +proc;; diff --git a/chips/yosys/docs/source/code_examples/synth_flow/proc_02.v b/chips/yosys/docs/source/code_examples/synth_flow/proc_02.v new file mode 100644 index 0000000000000000000000000000000000000000..8e440f6cec80b34c9da0e3faa905149667406870 --- /dev/null +++ b/chips/yosys/docs/source/code_examples/synth_flow/proc_02.v @@ -0,0 +1,8 @@ +module test(input D, C, R, RV, + output reg Q); + always @(posedge C, posedge R) + if (R) + Q <= RV; + else + Q <= D; +endmodule diff --git a/chips/yosys/docs/source/code_examples/synth_flow/proc_02.ys b/chips/yosys/docs/source/code_examples/synth_flow/proc_02.ys new file mode 100644 index 0000000000000000000000000000000000000000..823b18d6e1f25441a92e20aade8454ed62daf4a3 --- /dev/null +++ b/chips/yosys/docs/source/code_examples/synth_flow/proc_02.ys @@ -0,0 +1,3 @@ +read_verilog proc_02.v +hierarchy -check -top test +proc;; diff --git a/chips/yosys/docs/source/code_examples/synth_flow/proc_03.v b/chips/yosys/docs/source/code_examples/synth_flow/proc_03.v new file mode 100644 index 0000000000000000000000000000000000000000..a89c965e443fe089d404a73d2f798ae1f53ea563 --- /dev/null +++ b/chips/yosys/docs/source/code_examples/synth_flow/proc_03.v @@ -0,0 +1,10 @@ +module test(input A, B, C, D, E, + output reg Y); + always @* begin + Y <= A; + if (B) + Y <= C; + if (D) + Y <= E; + end +endmodule diff --git a/chips/yosys/docs/source/code_examples/synth_flow/proc_03.ys b/chips/yosys/docs/source/code_examples/synth_flow/proc_03.ys new file mode 100644 index 0000000000000000000000000000000000000000..3e7e6ddae57e2e82d8688eb44174b38517c18d85 --- /dev/null +++ b/chips/yosys/docs/source/code_examples/synth_flow/proc_03.ys @@ -0,0 +1,3 @@ +read_verilog proc_03.v +hierarchy -check -top test +proc;; diff --git a/chips/yosys/docs/source/code_examples/synth_flow/techmap_01.v b/chips/yosys/docs/source/code_examples/synth_flow/techmap_01.v new file mode 100644 index 0000000000000000000000000000000000000000..c53ca91a8b4cf6d3c44dc68a74bb2991636de5b4 --- /dev/null +++ b/chips/yosys/docs/source/code_examples/synth_flow/techmap_01.v @@ -0,0 +1,4 @@ +module test(input [31:0] a, b, + output [31:0] y); +assign y = a + b; +endmodule diff --git a/chips/yosys/docs/source/code_examples/synth_flow/techmap_01.ys b/chips/yosys/docs/source/code_examples/synth_flow/techmap_01.ys new file mode 100644 index 0000000000000000000000000000000000000000..8ef9de2226d8630b54182753e4363451227cdd40 --- /dev/null +++ b/chips/yosys/docs/source/code_examples/synth_flow/techmap_01.ys @@ -0,0 +1,3 @@ +read_verilog techmap_01.v +hierarchy -check -top test +techmap -map techmap_01_map.v;; diff --git a/chips/yosys/docs/source/code_examples/synth_flow/techmap_01_map.v b/chips/yosys/docs/source/code_examples/synth_flow/techmap_01_map.v new file mode 100644 index 0000000000000000000000000000000000000000..4fd86e85483bf7a814c286c272af463f1ebcb40f --- /dev/null +++ b/chips/yosys/docs/source/code_examples/synth_flow/techmap_01_map.v @@ -0,0 +1,24 @@ +module \$add (A, B, Y); + +parameter A_SIGNED = 0; +parameter B_SIGNED = 0; +parameter A_WIDTH = 1; +parameter B_WIDTH = 1; +parameter Y_WIDTH = 1; + +input [A_WIDTH-1:0] A; +input [B_WIDTH-1:0] B; +output [Y_WIDTH-1:0] Y; + +generate + if ((A_WIDTH == 32) && (B_WIDTH == 32)) + begin + wire [16:0] S1 = A[15:0] + B[15:0]; + wire [15:0] S2 = A[31:16] + B[31:16] + S1[16]; + assign Y = {S2[15:0], S1[15:0]}; + end + else + wire _TECHMAP_FAIL_ = 1; +endgenerate + +endmodule diff --git a/chips/yosys/docs/source/code_examples/techmap/Makefile b/chips/yosys/docs/source/code_examples/techmap/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..4da0baf9332601c5dc1b68644799f344b11d758b --- /dev/null +++ b/chips/yosys/docs/source/code_examples/techmap/Makefile @@ -0,0 +1,25 @@ +include ../../../common.mk + +.PHONY: all dots examples +all: dots examples +dots: red_or3x1.dot sym_mul.dot mymul.dot mulshift.dot addshift.dot +examples: + +red_or3x1.dot: red_or3x1_* + @$(YOSYS) red_or3x1_test.ys >/dev/null 2>&1 + +sym_mul.dot: sym_mul_* + @$(YOSYS) sym_mul_test.ys >/dev/null 2>&1 + +mymul.dot: mymul_* + @$(YOSYS) mymul_test.ys >/dev/null 2>&1 + +mulshift.dot: mulshift_* + @$(YOSYS) mulshift_test.ys >/dev/null 2>&1 + +addshift.dot: addshift_* + @$(YOSYS) addshift_test.ys >/dev/null 2>&1 + +.PHONY: clean +clean: + @rm -f *.dot diff --git a/chips/yosys/docs/source/code_examples/techmap/addshift_map.v b/chips/yosys/docs/source/code_examples/techmap/addshift_map.v new file mode 100644 index 0000000000000000000000000000000000000000..13ecf0bae698c4149a55e4018466e63a90517c12 --- /dev/null +++ b/chips/yosys/docs/source/code_examples/techmap/addshift_map.v @@ -0,0 +1,20 @@ +module \$add (A, B, Y); + parameter A_SIGNED = 0; + parameter B_SIGNED = 0; + parameter A_WIDTH = 1; + parameter B_WIDTH = 1; + parameter Y_WIDTH = 1; + + input [A_WIDTH-1:0] A; + input [B_WIDTH-1:0] B; + output [Y_WIDTH-1:0] Y; + + parameter _TECHMAP_BITS_CONNMAP_ = 0; + parameter _TECHMAP_CONNMAP_A_ = 0; + parameter _TECHMAP_CONNMAP_B_ = 0; + + wire _TECHMAP_FAIL_ = A_WIDTH != B_WIDTH || B_WIDTH < Y_WIDTH || + _TECHMAP_CONNMAP_A_ != _TECHMAP_CONNMAP_B_; + + assign Y = A << 1; +endmodule diff --git a/chips/yosys/docs/source/code_examples/techmap/addshift_test.v b/chips/yosys/docs/source/code_examples/techmap/addshift_test.v new file mode 100644 index 0000000000000000000000000000000000000000..b53271faac6ebcb20bf984091cc9063fa9c7b243 --- /dev/null +++ b/chips/yosys/docs/source/code_examples/techmap/addshift_test.v @@ -0,0 +1,5 @@ +module test (A, B, X, Y); +input [7:0] A, B; +output [7:0] X = A + B; +output [7:0] Y = A + A; +endmodule diff --git a/chips/yosys/docs/source/code_examples/techmap/addshift_test.ys b/chips/yosys/docs/source/code_examples/techmap/addshift_test.ys new file mode 100644 index 0000000000000000000000000000000000000000..c15691b3353ab7dc161832a6af778897e5a47625 --- /dev/null +++ b/chips/yosys/docs/source/code_examples/techmap/addshift_test.ys @@ -0,0 +1,6 @@ +read_verilog addshift_test.v +hierarchy -check -top test + +techmap -map addshift_map.v;; + +show -prefix addshift -format dot -notitle diff --git a/chips/yosys/docs/source/code_examples/techmap/mulshift_map.v b/chips/yosys/docs/source/code_examples/techmap/mulshift_map.v new file mode 100644 index 0000000000000000000000000000000000000000..4a3c2a06240abcc3b1931bc2a93704abb593e707 --- /dev/null +++ b/chips/yosys/docs/source/code_examples/techmap/mulshift_map.v @@ -0,0 +1,26 @@ +module MYMUL(A, B, Y); + parameter WIDTH = 1; + input [WIDTH-1:0] A, B; + output reg [WIDTH-1:0] Y; + + parameter _TECHMAP_CONSTVAL_A_ = WIDTH'bx; + parameter _TECHMAP_CONSTVAL_B_ = WIDTH'bx; + + reg _TECHMAP_FAIL_; + wire [1023:0] _TECHMAP_DO_ = "proc; clean"; + + integer i; + always @* begin + _TECHMAP_FAIL_ <= 1; + for (i = 0; i < WIDTH; i=i+1) begin + if (_TECHMAP_CONSTVAL_A_ === WIDTH'd1 << i) begin + _TECHMAP_FAIL_ <= 0; + Y <= B << i; + end + if (_TECHMAP_CONSTVAL_B_ === WIDTH'd1 << i) begin + _TECHMAP_FAIL_ <= 0; + Y <= A << i; + end + end + end +endmodule diff --git a/chips/yosys/docs/source/code_examples/techmap/mulshift_test.v b/chips/yosys/docs/source/code_examples/techmap/mulshift_test.v new file mode 100644 index 0000000000000000000000000000000000000000..4b975f414c2262fea69c00b47e1fd20a90a5a114 --- /dev/null +++ b/chips/yosys/docs/source/code_examples/techmap/mulshift_test.v @@ -0,0 +1,5 @@ +module test (A, X, Y); +input [7:0] A; +output [7:0] X = A * 8'd 6; +output [7:0] Y = A * 8'd 8; +endmodule diff --git a/chips/yosys/docs/source/code_examples/techmap/mulshift_test.ys b/chips/yosys/docs/source/code_examples/techmap/mulshift_test.ys new file mode 100644 index 0000000000000000000000000000000000000000..79daaf0c4299b93eaaa865412ae0b7685572c9c3 --- /dev/null +++ b/chips/yosys/docs/source/code_examples/techmap/mulshift_test.ys @@ -0,0 +1,7 @@ +read_verilog mulshift_test.v +hierarchy -check -top test + +techmap -map sym_mul_map.v \ + -map mulshift_map.v;; + +show -prefix mulshift -format dot -notitle -lib sym_mul_cells.v diff --git a/chips/yosys/docs/source/code_examples/techmap/mymul_map.v b/chips/yosys/docs/source/code_examples/techmap/mymul_map.v new file mode 100644 index 0000000000000000000000000000000000000000..e888a7a7c26110a3ee0cc79583be4b7fec4f7145 --- /dev/null +++ b/chips/yosys/docs/source/code_examples/techmap/mymul_map.v @@ -0,0 +1,15 @@ +module MYMUL(A, B, Y); + parameter WIDTH = 1; + input [WIDTH-1:0] A, B; + output reg [WIDTH-1:0] Y; + + wire [1023:0] _TECHMAP_DO_ = "proc; clean"; + + integer i; + always @* begin + Y = 0; + for (i = 0; i < WIDTH; i=i+1) + if (A[i]) + Y = Y + (B << i); + end +endmodule diff --git a/chips/yosys/docs/source/code_examples/techmap/mymul_test.v b/chips/yosys/docs/source/code_examples/techmap/mymul_test.v new file mode 100644 index 0000000000000000000000000000000000000000..620a06d9e5314b2c0fc6d42c69bfc87274c1fcae --- /dev/null +++ b/chips/yosys/docs/source/code_examples/techmap/mymul_test.v @@ -0,0 +1,4 @@ +module test(A, B, Y); + input [1:0] A, B; + output [1:0] Y = A * B; +endmodule diff --git a/chips/yosys/docs/source/code_examples/techmap/mymul_test.ys b/chips/yosys/docs/source/code_examples/techmap/mymul_test.ys new file mode 100644 index 0000000000000000000000000000000000000000..b7176fdc49af626416dd268aec2ca8ade4862c89 --- /dev/null +++ b/chips/yosys/docs/source/code_examples/techmap/mymul_test.ys @@ -0,0 +1,15 @@ +read_verilog mymul_test.v +hierarchy -check -top test + +techmap -map sym_mul_map.v \ + -map mymul_map.v;; + +rename test test_mapped +read_verilog mymul_test.v +miter -equiv test test_mapped miter +flatten miter + +sat -verify -prove trigger 0 miter + +splitnets -ports test_mapped/A +show -prefix mymul -format dot -notitle test_mapped diff --git a/chips/yosys/docs/source/code_examples/techmap/red_or3x1_cells.v b/chips/yosys/docs/source/code_examples/techmap/red_or3x1_cells.v new file mode 100644 index 0000000000000000000000000000000000000000..0750a130794016e704bb8a56327b18f6e161bf3b --- /dev/null +++ b/chips/yosys/docs/source/code_examples/techmap/red_or3x1_cells.v @@ -0,0 +1,5 @@ +module OR3X1(A, B, C, Y); + input A, B, C; + output Y; + assign Y = A | B | C; +endmodule diff --git a/chips/yosys/docs/source/code_examples/techmap/red_or3x1_map.v b/chips/yosys/docs/source/code_examples/techmap/red_or3x1_map.v new file mode 100644 index 0000000000000000000000000000000000000000..8c37b1dba43ab6097aabb47aa890c05e435c2393 --- /dev/null +++ b/chips/yosys/docs/source/code_examples/techmap/red_or3x1_map.v @@ -0,0 +1,48 @@ +module \$reduce_or (A, Y); + + parameter A_SIGNED = 0; + parameter A_WIDTH = 0; + parameter Y_WIDTH = 0; + + input [A_WIDTH-1:0] A; + output [Y_WIDTH-1:0] Y; + + function integer min; + input integer a, b; + begin + if (a < b) + min = a; + else + min = b; + end + endfunction + + genvar i; + generate begin + if (A_WIDTH == 0) begin + assign Y = 0; + end + if (A_WIDTH == 1) begin + assign Y = A; + end + if (A_WIDTH == 2) begin + wire ybuf; + OR3X1 g (.A(A[0]), .B(A[1]), .C(1'b0), .Y(ybuf)); + assign Y = ybuf; + end + if (A_WIDTH == 3) begin + wire ybuf; + OR3X1 g (.A(A[0]), .B(A[1]), .C(A[2]), .Y(ybuf)); + assign Y = ybuf; + end + if (A_WIDTH > 3) begin + localparam next_stage_sz = (A_WIDTH+2) / 3; + wire [next_stage_sz-1:0] next_stage; + for (i = 0; i < next_stage_sz; i = i+1) begin + localparam bits = min(A_WIDTH - 3*i, 3); + assign next_stage[i] = |A[3*i +: bits]; + end + assign Y = |next_stage; + end + end endgenerate +endmodule diff --git a/chips/yosys/docs/source/code_examples/techmap/red_or3x1_test.v b/chips/yosys/docs/source/code_examples/techmap/red_or3x1_test.v new file mode 100644 index 0000000000000000000000000000000000000000..bcdd32cbf81655a70629679675181215b5e1b9d7 --- /dev/null +++ b/chips/yosys/docs/source/code_examples/techmap/red_or3x1_test.v @@ -0,0 +1,5 @@ +module test (A, Y); + input [6:0] A; + output Y; + assign Y = |A; +endmodule diff --git a/chips/yosys/docs/source/code_examples/techmap/red_or3x1_test.ys b/chips/yosys/docs/source/code_examples/techmap/red_or3x1_test.ys new file mode 100644 index 0000000000000000000000000000000000000000..891b8177b89f4570d2f8ba86bcaa164f86cca3b8 --- /dev/null +++ b/chips/yosys/docs/source/code_examples/techmap/red_or3x1_test.ys @@ -0,0 +1,7 @@ +read_verilog red_or3x1_test.v +hierarchy -check -top test + +techmap -map red_or3x1_map.v;; + +splitnets -ports +show -prefix red_or3x1 -format dot -notitle -lib red_or3x1_cells.v diff --git a/chips/yosys/docs/source/code_examples/techmap/sym_mul_cells.v b/chips/yosys/docs/source/code_examples/techmap/sym_mul_cells.v new file mode 100644 index 0000000000000000000000000000000000000000..ce1771544f6db2df97d6086b525d7bea4290b2e4 --- /dev/null +++ b/chips/yosys/docs/source/code_examples/techmap/sym_mul_cells.v @@ -0,0 +1,6 @@ +module MYMUL(A, B, Y); + parameter WIDTH = 1; + input [WIDTH-1:0] A, B; + output [WIDTH-1:0] Y; + assign Y = A * B; +endmodule diff --git a/chips/yosys/docs/source/code_examples/techmap/sym_mul_map.v b/chips/yosys/docs/source/code_examples/techmap/sym_mul_map.v new file mode 100644 index 0000000000000000000000000000000000000000..b4dbd9e07cd53f6b9917fe49fef33e1aca1e2a7e --- /dev/null +++ b/chips/yosys/docs/source/code_examples/techmap/sym_mul_map.v @@ -0,0 +1,15 @@ +module \$mul (A, B, Y); + parameter A_SIGNED = 0; + parameter B_SIGNED = 0; + parameter A_WIDTH = 1; + parameter B_WIDTH = 1; + parameter Y_WIDTH = 1; + + input [A_WIDTH-1:0] A; + input [B_WIDTH-1:0] B; + output [Y_WIDTH-1:0] Y; + + wire _TECHMAP_FAIL_ = A_WIDTH != B_WIDTH || B_WIDTH != Y_WIDTH; + + MYMUL #( .WIDTH(Y_WIDTH) ) g ( .A(A), .B(B), .Y(Y) ); +endmodule diff --git a/chips/yosys/docs/source/code_examples/techmap/sym_mul_test.v b/chips/yosys/docs/source/code_examples/techmap/sym_mul_test.v new file mode 100644 index 0000000000000000000000000000000000000000..eb715f83d7151794ab3a3c53f96266a263b08d72 --- /dev/null +++ b/chips/yosys/docs/source/code_examples/techmap/sym_mul_test.v @@ -0,0 +1,5 @@ +module test(A, B, C, Y1, Y2); + input [7:0] A, B, C; + output [7:0] Y1 = A * B; + output [15:0] Y2 = A * C; +endmodule diff --git a/chips/yosys/docs/source/code_examples/techmap/sym_mul_test.ys b/chips/yosys/docs/source/code_examples/techmap/sym_mul_test.ys new file mode 100644 index 0000000000000000000000000000000000000000..f19bee64a954dc57235ffd40d3320bdb38bd0f67 --- /dev/null +++ b/chips/yosys/docs/source/code_examples/techmap/sym_mul_test.ys @@ -0,0 +1,6 @@ +read_verilog sym_mul_test.v +hierarchy -check -top test + +techmap -map sym_mul_map.v;; + +show -prefix sym_mul -format dot -notitle -lib sym_mul_cells.v diff --git a/chips/yosys/docs/source/conf.py b/chips/yosys/docs/source/conf.py new file mode 100644 index 0000000000000000000000000000000000000000..5125971edba3021783585251e8993de7a6ca2915 --- /dev/null +++ b/chips/yosys/docs/source/conf.py @@ -0,0 +1,131 @@ +#!/usr/bin/env python3 +from pathlib import Path +import sys +import os + +project = 'YosysHQ Yosys' +author = 'YosysHQ GmbH' +copyright ='2026 YosysHQ GmbH' +yosys_ver = "0.71" + +# select HTML theme +html_theme = 'furo-ys' +html_css_files = ['custom.css'] +html_theme_options: dict[str] = { + "source_repository": "https://github.com/YosysHQ/yosys/", + "source_branch": "main", + "source_directory": "docs/source/", +} +html_context: dict[str] = {} + +# try to fix the readthedocs detection +if os.getenv("READTHEDOCS"): + html_context.update({ + "READTHEDOCS": True, + "display_github": True, + "github_user": "YosysHQ", + "github_repo": "yosys", + "slug": "yosys", + }) + +# override source_branch if not main +git_slug = os.getenv("READTHEDOCS_VERSION_NAME") +if git_slug not in [None, "latest", "stable"]: + html_theme_options["source_branch"] = git_slug + +# edit only works on branches, not tags +if os.getenv("READTHEDOCS_VERSION_TYPE", "branch") != "branch": + html_theme_options["top_of_page_buttons"] = ["view"] + +# These folders are copied to the documentation's HTML output +html_static_path = ['_static', "_images"] + +# default to no highlight +highlight_language = 'none' + +# default single quotes to attempt auto reference, or fallback to yoscrypt +default_role = 'autoref' +rst_prolog = """ +.. role:: yoscrypt(code) + :language: yoscrypt +""" + +extensions = ['sphinx.ext.autosectionlabel', 'sphinxcontrib.bibtex', 'sphinx_inline_tabs'] + +if os.getenv("READTHEDOCS"): + # Use rtds_action if we are building on read the docs and have a github token env var + if os.getenv("GITHUB_TOKEN"): + extensions += ['rtds_action'] + rtds_action_github_repo = "YosysHQ/yosys" + rtds_action_path = "." + rtds_action_artifact_prefix = "cmd-ref-" + rtds_action_github_token = os.environ["GITHUB_TOKEN"] + else: + # We're on read the docs but have no github token, this is probably a PR preview build + html_theme_options["announcement"] = 'Missing content? Check PR preview limitations.' + html_theme_options["light_css_variables"]["color-announcement-background"] = "var(--color-admonition-title-background--caution)" + html_theme_options["light_css_variables"]["color-announcement-text"] = "var(--color-content-foreground)" + +# Ensure that autosectionlabel will produce unique names +autosectionlabel_prefix_document = True + +# include todos for previews +extensions.append('sphinx.ext.todo') + +# set version +if os.getenv("READTHEDOCS"): + rtds_version = os.getenv("READTHEDOCS_VERSION") + if rtds_version == "latest": + release = yosys_ver + "-dev" + todo_include_todos = False + elif rtds_version.startswith("docs"): + release = rtds_version + todo_include_todos = True + else: + release = yosys_ver + todo_include_todos = False +elif os.getenv("YOSYS_DOCS_RELEASE") is not None: + release = yosys_ver + todo_include_todos = False +else: + release = yosys_ver + todo_include_todos = True + +# assign figure numbers +numfig = True + +bibtex_bibfiles = ['literature.bib'] +latex_elements = { + 'releasename': 'Version', + 'preamble': r''' +\pdfinfoomitdate 1 +\pdfsuppressptexinfo 1 +\pdftrailerid{} +\usepackage{lmodern} +\usepackage{comment} + +''' +} + +# custom cmd-ref parsing/linking +sys.path += [os.path.dirname(__file__) + "/../"] +extensions.append('util.custom_directives') + +# use autodocs +extensions.append('sphinx.ext.autodoc') +extensions.append('util.cell_documenter') +cells_json = Path(__file__).parent / 'generated' / 'cells.json' +extensions.append('util.cmd_documenter') +cmds_json = Path(__file__).parent / 'generated' / 'cmds.json' + +from sphinx.application import Sphinx +def setup(app: Sphinx) -> None: + from util.RtlilLexer import RtlilLexer + app.add_lexer("RTLIL", RtlilLexer) + + try: + from furo_ys.lexers.YoscryptLexer import YoscryptLexer + app.add_lexer("yoscrypt", YoscryptLexer) + except ModuleNotFoundError: + from pygments.lexers.special import TextLexer + app.add_lexer("yoscrypt", TextLexer) diff --git a/chips/yosys/docs/source/getting_started/example_synth.rst b/chips/yosys/docs/source/getting_started/example_synth.rst new file mode 100644 index 0000000000000000000000000000000000000000..9202ba3a6e319c33390890aaa2f74edc40b13d05 --- /dev/null +++ b/chips/yosys/docs/source/getting_started/example_synth.rst @@ -0,0 +1,857 @@ +Synthesis starter +----------------- + +This page will be a guided walkthrough of the prepackaged iCE40 FPGA synthesis +script - `synth_ice40`. We will take a simple design through each step, looking +at the commands being called and what they do to the design. While `synth_ice40` +is specific to the iCE40 platform, most of the operations we will be discussing +are common across the majority of FPGA synthesis scripts. Thus, this document +will provide a good foundational understanding of how synthesis in Yosys is +performed, regardless of the actual architecture being used. + +.. seealso:: Advanced usage docs for + :doc:`/using_yosys/synthesis/synth` + +Demo design +~~~~~~~~~~~ + +.. role:: yoscrypt(code) + :language: yoscrypt + +First, let's quickly look at the design we'll be synthesizing: + +.. todo:: reconsider including the whole (~77 line) design like this + +.. literalinclude:: /code_examples/fifo/fifo.v + :language: Verilog + :linenos: + :caption: :file:`fifo.v` + :name: fifo-v + +.. todo:: fifo.v description + +While the open source `read_verilog` frontend generally does a pretty good job +at processing valid Verilog input, it does not provide very good error handling +or reporting. Using an external tool such as `verilator`_ before running Yosys +is highly recommended. We can quickly check the Verilog syntax of our design by +calling ``verilator --lint-only fifo.v``. + +.. _verilator: https://www.veripool.org/verilator/ + +Loading the design +~~~~~~~~~~~~~~~~~~ + +Let's load the design into Yosys. From the command line, we can call ``yosys +fifo.v``. This will open an interactive Yosys shell session and immediately +parse the code from :ref:`fifo-v` and convert it into an Abstract Syntax Tree +(AST). If you are interested in how this happens, there is more information in +the document, :doc:`/yosys_internals/flow/verilog_frontend`. For now, suffice +it to say that we do this to simplify further processing of the design. You +should see something like the following: + +.. literalinclude:: /code_examples/fifo/fifo.out + :language: console + :start-at: $ yosys fifo.v + :end-before: echo on + +.. seealso:: Advanced usage docs for + :doc:`/using_yosys/more_scripting/load_design` + +Elaboration +~~~~~~~~~~~ + +Now that we are in the interactive shell, we can call Yosys commands directly. +Our overall goal is to call :yoscrypt:`synth_ice40 -top fifo`, but for now we +can run each of the commands individually for a better sense of how each part +contributes to the flow. We will also start with just a single module; +``addr_gen``. + +At the bottom of the `help` output for +`synth_ice40` is the complete list of commands called by this script. +Let's start with the section labeled ``begin``: + +.. literalinclude:: /code_examples/macro_commands/synth_ice40.ys + :language: yoscrypt + :start-after: begin: + :end-before: flatten: + :dedent: + :caption: ``begin`` section + :name: synth_begin + +:yoscrypt:`read_verilog -D ICE40_HX -lib -specify +/ice40/cells_sim.v` loads the +iCE40 cell models which allows us to include platform specific IP blocks in our +design. PLLs are a common example of this, where we might need to reference +``SB_PLL40_CORE`` directly rather than being able to rely on mapping passes +later. Since our simple design doesn't use any of these IP blocks, we can skip +this command for now. Because these cell models will also be needed once we +start mapping to hardware we will still need to load them later. + +.. note:: + + ``+/`` is a dynamic reference to the Yosys ``share`` directory. By default, + this is ``/usr/local/share/yosys``. If using a locally built version of + Yosys from the source directory, this will be the ``share`` folder in the + same directory. + +.. _addr_gen_example: + +The addr_gen module +^^^^^^^^^^^^^^^^^^^ + +Since we're just getting started, let's instead begin with :yoscrypt:`hierarchy +-top addr_gen`. This command declares that the top level module is +``addr_gen``, and everything else can be discarded. + +.. literalinclude:: /code_examples/fifo/fifo.v + :language: Verilog + :start-at: module addr_gen + :end-at: endmodule //addr_gen + :lineno-match: + :caption: ``addr_gen`` module source + :name: addr_gen-v + +.. note:: + + `hierarchy` should always be the first command after the design has been + read. By specifying the top module, `hierarchy` will also set the ``(* top + *)`` attribute on it. This is used by other commands that need to know which + module is the top. + +.. use doscon for a console-like display that supports the `yosys> [command]` format. + +.. literalinclude:: /code_examples/fifo/fifo.out + :language: doscon + :start-at: yosys> hierarchy -top addr_gen + :end-before: yosys> select + :caption: :yoscrypt:`hierarchy -top addr_gen` output + :name: hierarchy_output + +Our ``addr_gen`` circuit now looks like this: + +.. figure:: /_images/code_examples/fifo/addr_gen_hier.* + :class: width-helper invert-helper + :name: addr_gen_hier + + ``addr_gen`` module after `hierarchy` + +Simple operations like ``addr + 1`` and ``addr == MAX_DATA-1`` can be extracted +from our ``always @`` block in :ref:`addr_gen-v`. This gives us the highlighted +`$add` and `$eq` cells we see. But control logic (like the ``if .. else``) and +memory elements (like the ``addr <= 0``) are not so straightforward. These get +put into "processes", shown in the schematic as ``PROC``. Note how the second +line refers to the line numbers of the start/end of the corresponding ``always +@`` block. In the case of an ``initial`` block, we instead see the ``PROC`` +referring to line 0. + +To handle these, let us now introduce the next command: :cmd:title:`proc`. +`proc` is a macro command like `synth_ice40`. Rather than modifying the design +directly, it instead calls a series of other commands. In the case of `proc`, +these sub-commands work to convert the behavioral logic of processes into +multiplexers and registers. Let's see what happens when we run it. For now, we +will call :yoscrypt:`proc -noopt` to prevent some automatic optimizations which +would normally happen. + +.. figure:: /_images/code_examples/fifo/addr_gen_proc.* + :class: width-helper invert-helper + :name: addr_gen_proc + + ``addr_gen`` module after :yoscrypt:`proc -noopt` + +There are now a few new cells from our ``always @``, which have been +highlighted. The ``if`` statements are now modeled with `$mux` cells, while the +register uses an `$adff` cell. If we look at the terminal output we can also +see all of the different ``proc_*`` commands being called. We will look at each +of these in more detail in :doc:`/using_yosys/synthesis/proc`. + +Notice how in the top left of :ref:`addr_gen_proc` we have a floating wire, +generated from the initial assignment of 0 to the ``addr`` wire. However, this +initial assignment is not synthesizable, so this will need to be cleaned up +before we can generate the physical hardware. We can do this now by calling +`clean`. We're also going to call `opt_expr` now, which would normally be +called at the end of `proc`. We can call both commands at the same time by +separating them with a colon and space: :yoscrypt:`opt_expr; clean`. + +.. figure:: /_images/code_examples/fifo/addr_gen_clean.* + :class: width-helper invert-helper + :name: addr_gen_clean + + ``addr_gen`` module after :yoscrypt:`opt_expr; clean` + +You may also notice that the highlighted `$eq` cell input of ``255`` has changed +to ``8'11111111``. Constant values are presented in the format +``'``, with 32-bit values instead using the decimal number. +This indicates that the constant input has been reduced from 32-bit wide to +8-bit wide. This is a side-effect of running `opt_expr`, which performs +constant folding and simple expression rewriting. For more on why this +happens, refer to :doc:`/using_yosys/synthesis/opt` and the :ref:`section on +opt_expr `. + +.. note:: + + :cmd:title:`clean` can also be called with two semicolons after any command, + for example we could have called :yoscrypt:`opt_expr;;` instead of + :yoscrypt:`opt_expr; clean`. You may notice some scripts will end each line + with ``;;``. It is beneficial to run `clean` before inspecting intermediate + products to remove disconnected parts of the circuit which have been left + over, and in some cases can reduce the processing required in subsequent + commands. + +.. todo:: consider a brief glossary for terms like adff + +.. seealso:: Advanced usage docs for + + - :doc:`/using_yosys/synthesis/proc` + - :doc:`/using_yosys/synthesis/opt` + +The full example +^^^^^^^^^^^^^^^^ + +Let's now go back and check on our full design by using :yoscrypt:`hierarchy +-check -top fifo`. By passing the ``-check`` option there we are also telling +the `hierarchy` command that if the design includes any non-blackbox modules +without an implementation it should return an error. + +Note that if we tried to run this command now then we would get an error. This +is because we already removed all of the modules other than ``addr_gen``. We +could restart our shell session, but instead let's use two new commands: + +- :cmd:title:`design`, and +- :cmd:title:`read_verilog`. + +.. literalinclude:: /code_examples/fifo/fifo.out + :language: doscon + :start-at: design -reset + :end-before: yosys> proc + :caption: reloading :file:`fifo.v` and running :yoscrypt:`hierarchy -check -top fifo` + +Notice how this time we didn't see any of those ``$abstract`` modules? That's +because when we ran ``yosys fifo.v``, the first command Yosys called was +:yoscrypt:`read_verilog -defer fifo.v`. The ``-defer`` option there tells +`read_verilog` only read the abstract syntax tree and defer actual compilation +to a later `hierarchy` command. This is useful in cases where the default +parameters of modules yield invalid code which is not synthesizable. This is why +Yosys defers compilation automatically and is one of the reasons why hierarchy +should always be the first command after loading the design. If we know that +our design won't run into this issue, we can skip the ``-defer``. + +.. todo:: `hierarchy` failure modes + +.. note:: + + The number before a command's output increments with each command run. Don't + worry if your numbers don't match ours! The output you are seeing comes from + the same script that was used to generate the images in this document, + included in the source as :file:`fifo.ys`. There are extra commands being run + which you don't see, but feel free to try them yourself, or play around with + different commands. You can always start over with a clean slate by calling + ``exit`` or hitting :kbd:`ctrl+d` (i.e. EOF) and re-launching the Yosys + interactive terminal. :kbd:`ctrl+c` (i.e. SIGINT) will also end the terminal + session but will return an error code rather than exiting gracefully. + +We can also run `proc` now to finish off the full :ref:`synth_begin`. Because +the design schematic is quite large, we will be showing just the data path for +the ``rdata`` output. If you would like to see the entire design for yourself, +you can do so with :cmd:title:`show`. Note that the `show` command only works +with a single module, so you may need to call it with :yoscrypt:`show fifo`. +:ref:`show_intro` section in :doc:`/getting_started/scripting_intro` has more on +how to use `show`. + +.. figure:: /_images/code_examples/fifo/rdata_proc.* + :class: width-helper invert-helper + :name: rdata_proc + + ``rdata`` output after `proc` + +The highlighted ``fifo_reader`` block contains an instance of the +:ref:`addr_gen_proc` that we looked at earlier. Notice how the type is shown as +``$paramod\\addr_gen\\MAX_DATA=s32'...``. This is a "parametric module": an +instance of the ``addr_gen`` module with the ``MAX_DATA`` parameter set to the +given value. + +The other highlighted block is a `$memrd` cell. At this stage of synthesis we +don't yet know what type of memory is going to be implemented, but we *do* know +that ``rdata <= data[raddr];`` could be implemented as a read from memory. Note +that the `$memrd` cell here is asynchronous, with both the clock and enable +signal undefined; shown with the ``1'x`` inputs. + +.. seealso:: Advanced usage docs for + :doc:`/using_yosys/synthesis/proc` + +Flattening +~~~~~~~~~~ + +At this stage of a synthesis flow there are a few other commands we could run. +In `synth_ice40` we get these: + +.. literalinclude:: /code_examples/macro_commands/synth_ice40.ys + :language: yoscrypt + :start-after: flatten: + :end-before: coarse: + :dedent: + :name: synth_flatten + :caption: ``flatten`` section + +We start by runnning `check`. This doesn't affect the design, but it can +identify a few obvious problems which will cause errors later. Calling it here +lets us fail faster rather than wasting time on something we know is impossible. +Next up is `flatten`. Flattening the design like this can allow for +optimizations between modules which would otherwise be missed. Let's run +:yoscrypt:`flatten;;` on our design. + +.. literalinclude:: /code_examples/fifo/fifo.out + :language: doscon + :start-at: yosys> flatten + :end-before: yosys> select + :name: flat_clean + :caption: output of :yoscrypt:`flatten;;` + +.. figure:: /_images/code_examples/fifo/rdata_flat.* + :class: width-helper invert-helper + :name: rdata_flat + + ``rdata`` output after :yoscrypt:`flatten;;` + +.. role:: yoterm(code) + :language: doscon + +The pieces have moved around a bit, but we can see :ref:`addr_gen_proc` from +earlier has replaced the ``fifo_reader`` block in :ref:`rdata_proc`. We can +also see that the ``addr`` output has been renamed to :file:`fifo_reader.addr` +and merged with the ``raddr`` wire feeding into the `$memrd` cell. This wire +merging happened during the call to `clean` which we can see in the +:ref:`flat_clean`. + +.. note:: + + `flatten` and `clean` would normally be combined into a + single :yoterm:`yosys> flatten;;` output, but they appear separately here as + a side effect of using `echo` for generating the terminal style + output. + +Depending on the target architecture, this stage of synthesis might also see +commands such as `tribuf` with the ``-logic`` option and `deminout`. These +remove tristate and inout constructs respectively, replacing them with logic +suitable for mapping to an FPGA. Since we do not have any such constructs in +our example running these commands does not change our design. + +The coarse-grain representation +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +At this stage, the design is in coarse-grain representation. It still looks +recognizable, and cells are word-level operators with parametrizable width. This +is the stage of synthesis where we do things like const propagation, expression +rewriting, and trimming unused parts of wires. + +This is also where we convert our FSMs and hard blocks like DSPs or memories. +Such elements have to be inferred from patterns in the design and there are +special passes for each. Detection of these patterns can also be affected by +optimizations and other transformations done previously. + +.. note:: + + While the iCE40 flow had a :ref:`synth_flatten` and put `proc` in the + :ref:`synth_begin`, some synthesis scripts will instead include these in this + section. + +Part 1 +^^^^^^ + +In the iCE40 flow, we start with the following commands: + +.. literalinclude:: /code_examples/macro_commands/synth_ice40.ys + :language: yoscrypt + :start-after: coarse: + :end-before: wreduce + :dedent: + :caption: ``coarse`` section (part 1) + :name: synth_coarse1 + +We've already come across `opt_expr` and `check`, and `opt_clean` is the same as +`clean` but with more verbose output. Next up is :yoscrypt:`opt -nodffe +-nosdff` performing a set of simple optimizations on the design. This command +also ensures that only a specific subset of FF types are included, in +preparation for the next command: :cmd:title:`fsm`. Both `opt` and `fsm` are +macro commands which are explored in more detail in +:doc:`/using_yosys/synthesis/opt` and :doc:`/using_yosys/synthesis/fsm` +respectively. + +Up until now, the data path for ``rdata`` has remained the same since +:ref:`rdata_flat`. However the next call to `opt` does cause a change. +Specifically, the call to `opt_dff` without the ``-nodffe -nosdff`` options is +able to fold one of the `$mux` cells into the `$adff` to form an `$adffe` cell; +highlighted below: + +.. literalinclude:: /code_examples/fifo/fifo.out + :language: doscon + :start-at: yosys> opt_dff + :end-before: yosys> select + :caption: output of `opt_dff` + +.. figure:: /_images/code_examples/fifo/rdata_adffe.* + :class: width-helper invert-helper + :name: rdata_adffe + + ``rdata`` output after `opt_dff` + +.. seealso:: Advanced usage docs for + + - :doc:`/using_yosys/synthesis/fsm` + - :doc:`/using_yosys/synthesis/opt` + +Part 2 +^^^^^^ + +The next group of commands performs a series of optimizations: + +.. literalinclude:: /code_examples/macro_commands/synth_ice40.ys + :language: yoscrypt + :start-at: wreduce + :end-before: macc-only + :dedent: + :caption: ``coarse`` section (part 2) + :name: synth_coarse2 + +First up is :cmd:title:`wreduce`. If we run this we get the following: + +.. literalinclude:: /code_examples/fifo/fifo.out + :language: doscon + :start-at: yosys> wreduce + :end-before: yosys> select + :caption: output of `wreduce` + +Looking at the data path for ``rdata``, the most relevant of these width +reductions are the ones affecting ``fifo.$flatten\fifo_reader.$add$fifo.v``. +That is the `$add` cell incrementing the fifo_reader address. We can look at +the schematic and see the output of that cell has now changed. + +.. todo:: pending bugfix in `wreduce` and/or `opt_clean` + +.. figure:: /_images/code_examples/fifo/rdata_wreduce.* + :class: width-helper invert-helper + :name: rdata_wreduce + + ``rdata`` output after `wreduce` + +The next two (new) commands are :cmd:title:`peepopt` and :cmd:title:`share`. +Neither of these affect our design, and they're explored in more detail in +:doc:`/using_yosys/synthesis/opt`, so let's skip over them. :yoscrypt:`techmap +-map +/cmp2lut.v -D LUT_WIDTH=4` optimizes certain comparison operators by +converting them to LUTs instead. The usage of `techmap` is explored more in +:doc:`/using_yosys/synthesis/techmap_synth`. + +Our next command to run is +:cmd:title:`memory_dff`. + +.. literalinclude:: /code_examples/fifo/fifo.out + :language: doscon + :start-at: yosys> memory_dff + :end-before: yosys> select + :caption: output of `memory_dff` + +.. figure:: /_images/code_examples/fifo/rdata_memrdv2.* + :class: width-helper invert-helper + :name: rdata_memrdv2 + + ``rdata`` output after `memory_dff` + +As the title suggests, `memory_dff` has merged the output `$dff` into the +`$memrd` cell and converted it to a `$memrd_v2` (highlighted). This has also +connected the ``CLK`` port to the ``clk`` input as it is now a synchronous +memory read with appropriate enable (``EN=1'1``) and reset (``ARST=1'0`` and +``SRST=1'0``) inputs. + +.. seealso:: Advanced usage docs for + + - :doc:`/using_yosys/synthesis/opt` + - :doc:`/using_yosys/synthesis/techmap_synth` + - :doc:`/using_yosys/synthesis/memory` + +Part 3 +^^^^^^ + +The third part of the `synth_ice40` flow is a series of commands for mapping to +DSPs. By default, the iCE40 flow will not map to the hardware DSP blocks and +will only be performed if called with the ``-dsp`` flag: :yoscrypt:`synth_ice40 +-dsp`. While our example has nothing that could be mapped to DSPs we can still +take a quick look at the commands here and describe what they do. + +.. literalinclude:: /code_examples/macro_commands/synth_ice40.ys + :language: yoscrypt + :start-at: macc-only + :end-at: chtype + :dedent: + :caption: ``coarse`` section (part 3) + :name: synth_coarse3 + +The first three commands reassociate sums of products. :yoscrypt:`alumacc +-macc-only` collects each chain of `$mul` and `$add` cells into a single +`$macc_v2` cell, and :yoscrypt:`maccmap -unmap` lowers it straight back to +`$mul` and `$add` cells, but as a chain with the plain addends first, so that +every multiplier has an adder of its own for `ice40_dsp` to absorb. +`opt_clean` then removes the original cells. + +:yoscrypt:`wreduce t:$mul` performs width reduction again, this time targetting +only cells of type `$mul`. :yoscrypt:`techmap -map +/mul2dsp.v -map ++/ice40/dsp_map.v ... -D DSP_NAME=$__MUL16X16` uses `techmap` to map `$mul` +cells to ``$__MUL16X16`` which are, in turn, mapped to the iCE40 ``SB_MAC16``. +Any multipliers which aren't compatible with conversion to ``$__MUL16X16`` are +relabelled to ``$__soft_mul`` before `chtype` changes them back to `$mul`. + +During the mul2dsp conversion, some of the intermediate signals are marked with +the attribute ``mul2dsp``. By calling :yoscrypt:`select a:mul2dsp` we restrict +the following commands to only operate on the cells and wires used for these +signals. `setattr` removes the now unnecessary ``mul2dsp`` attribute. +`opt_expr` we've already come across for const folding and simple expression +rewriting, the ``-fine`` option just enables more fine-grain optimizations. +Then we perform width reduction a final time and clear the selection. + +.. todo:: ``ice40_dsp`` is pmgen + +Finally we have `ice40_dsp`: similar to the `memory_dff` command we saw in the +previous section, this merges any surrounding registers into the ``SB_MAC16`` +cell. This includes not just the input/output registers, but also pipeline +registers and even a post-adder where applicable: turning a multiply + add into +a single multiply-accumulate. + +.. seealso:: Advanced usage docs for + :doc:`/using_yosys/synthesis/techmap_synth` + +Part 4 +^^^^^^ + +That brings us to the fourth and final part for the iCE40 synthesis flow: + +.. literalinclude:: /code_examples/macro_commands/synth_ice40.ys + :language: yoscrypt + :start-after: chtype + :end-before: map_ram: + :dedent: + :caption: ``coarse`` section (part 4) + :name: synth_coarse4 + +Where before each type of arithmetic operation had its own cell, e.g. `$add`, we +now want to extract these into `$alu` and `$macc_v2` cells which can help identify +opportunities for reusing logic. We do this by running `alumacc`, which we can +see produce the following changes in our example design: + +.. literalinclude:: /code_examples/fifo/fifo.out + :language: doscon + :start-at: yosys> alumacc + :end-before: yosys> select + :caption: output of `alumacc` + +.. figure:: /_images/code_examples/fifo/rdata_alumacc.* + :class: width-helper invert-helper + :name: rdata_alumacc + + ``rdata`` output after `alumacc` + +Once these cells have been inserted, the call to `opt` can combine cells which +are now identical but may have been missed due to e.g. the difference between +`$add` and `$sub`. + +The other new command in this part is :cmd:title:`memory`. `memory` is another +macro command which we examine in more detail in +:doc:`/using_yosys/synthesis/memory`. For this document, let us focus just on +the step most relevant to our example: `memory_collect`. Up until this point, +our memory reads and our memory writes have been totally disjoint cells; +operating on the same memory only in the abstract. `memory_collect` combines all +of the reads and writes for a memory block into a single cell. + +.. figure:: /_images/code_examples/fifo/rdata_coarse.* + :class: width-helper invert-helper + :name: rdata_coarse + + ``rdata`` output after `memory_collect` + +Looking at the schematic after running `memory_collect` we see that our +`$memrd_v2` cell has been replaced with a `$mem_v2` cell named ``data``, the +same name that we used in :ref:`fifo-v`. Where before we had a single set of +signals for address and enable, we now have one set for reading (``RD_*``) and +one for writing (``WR_*``), as well as both ``WR_DATA`` input and ``RD_DATA`` +output. + +.. seealso:: Advanced usage docs for + + - :doc:`/using_yosys/synthesis/opt` + - :doc:`/using_yosys/synthesis/memory` + +Final note +^^^^^^^^^^ + +Having now reached the end of the the coarse-grain representation, we could also +have gotten here by running :yoscrypt:`synth_ice40 -top fifo -run :map_ram` +after loading the design. The :yoscrypt:`-run :` option +with an empty ```` starts from the :ref:`synth_begin`, while the +```` runs up to but including the :ref:`map_ram`. + +Hardware mapping +~~~~~~~~~~~~~~~~ + +The remaining sections each map a different type of hardware and are much more +architecture dependent than the previous sections. As such we will only be +looking at each section very briefly. + +If you skipped calling :yoscrypt:`read_verilog -D ICE40_HX -lib -specify ++/ice40/cells_sim.v` earlier, do it now. + +Memory blocks +^^^^^^^^^^^^^ + +Mapping to hard memory blocks uses a combination of `memory_libmap` and +`techmap`. + +.. literalinclude:: /code_examples/macro_commands/synth_ice40.ys + :language: yoscrypt + :start-after: map_ram: + :end-before: map_ffram: + :dedent: + :name: map_ram + :caption: ``map_ram`` section + +.. figure:: /_images/code_examples/fifo/rdata_map_ram.* + :class: width-helper invert-helper + :name: rdata_map_ram + + ``rdata`` output after :ref:`map_ram` + +The :ref:`map_ram` converts the generic `$mem_v2` into the iCE40 ``SB_RAM40_4K`` +(highlighted). We can also see the memory address has been remapped, and the +data bits have been reordered (or swizzled). There is also now a `$mux` cell +controlling the value of ``rdata``. In :ref:`fifo-v` we wrote our memory as +read-before-write, however the ``SB_RAM40_4K`` has undefined behaviour when +reading from and writing to the same address in the same cycle. As a result, +extra logic is added so that the generated circuit matches the behaviour of the +verilog. :ref:`no_rw_check` describes how we could change our verilog to match +our hardware instead. + +If we run `memory_libmap` under the `debug` command we can see candidates which +were identified for mapping, along with the costs of each and what logic +requires emulation. + +.. literalinclude:: /code_examples/fifo/fifo.libmap + :language: doscon + :lines: 2, 6- + +The ``$__ICE40_RAM4K_`` cell is defined in the file |techlibs/ice40/brams.txt|_, +with the mapping to ``SB_RAM40_4K`` done by `techmap` using +|techlibs/ice40/brams_map.v|_. Any leftover memory cells are then converted +into flip flops (the ``logic fallback``) with `memory_map`. + +.. |techlibs/ice40/brams.txt| replace:: :file:`techlibs/ice40/brams.txt` +.. _techlibs/ice40/brams.txt: https://github.com/YosysHQ/yosys/tree/main/techlibs/ice40/brams.txt +.. |techlibs/ice40/brams_map.v| replace:: :file:`techlibs/ice40/brams_map.v` +.. _techlibs/ice40/brams_map.v: https://github.com/YosysHQ/yosys/tree/main/techlibs/ice40/brams_map.v + +.. literalinclude:: /code_examples/macro_commands/synth_ice40.ys + :language: yoscrypt + :start-after: map_ffram: + :end-before: map_gates: + :dedent: + :name: map_ffram + :caption: ``map_ffram`` section + +.. figure:: /_images/code_examples/fifo/rdata_map_ffram.* + :class: width-helper invert-helper + :name: rdata_map_ffram + + ``rdata`` output after :ref:`map_ffram` + +.. note:: + + The visual clutter on the ``RDATA`` output port (highlighted) is an + unfortunate side effect of `opt_clean` on the swizzled data bits. In + connecting the `$mux` input port directly to ``RDATA`` to reduce the number + of wires, the ``$techmap579\data.0.0.RDATA`` wire becomes more visually + complex. + +.. seealso:: Advanced usage docs for + + - :doc:`/using_yosys/synthesis/techmap_synth` + - :doc:`/using_yosys/synthesis/memory` + +Arithmetic +^^^^^^^^^^ + +Uses `techmap` to map basic arithmetic logic to hardware. This sees somewhat of +an explosion in cells as multi-bit `$mux` and `$adffe` are replaced with +single-bit `$_MUX_` and `$_DFFE_PP0P_` cells, while the `$alu` is replaced with +primitive `$_OR_` and `$_NOT_` gates and a `$lut` cell. + +.. literalinclude:: /code_examples/macro_commands/synth_ice40.ys + :language: yoscrypt + :start-after: map_gates: + :end-before: map_ffs: + :dedent: + :name: map_gates + :caption: ``map_gates`` section + +.. figure:: /_images/code_examples/fifo/rdata_map_gates.* + :class: width-helper invert-helper + :name: rdata_map_gates + + ``rdata`` output after :ref:`map_gates` + +.. seealso:: Advanced usage docs for + :doc:`/using_yosys/synthesis/techmap_synth` + +Flip-flops +^^^^^^^^^^ + +Convert FFs to the types supported in hardware with `dfflegalize`, and then use +`techmap` to map them. In our example, this converts the `$_DFFE_PP0P_` cells +to ``SB_DFFER``. + +We also run `simplemap` here to convert any remaining cells which could not be +mapped to hardware into gate-level primitives. This includes optimizing +`$_MUX_` cells where one of the inputs is a constant ``1'0``, replacing it +instead with an `$_AND_` cell. + +.. literalinclude:: /code_examples/macro_commands/synth_ice40.ys + :language: yoscrypt + :start-after: map_ffs: + :end-before: map_luts: + :dedent: + :name: map_ffs + :caption: ``map_ffs`` section + +.. figure:: /_images/code_examples/fifo/rdata_map_ffs.* + :class: width-helper invert-helper + :name: rdata_map_ffs + + ``rdata`` output after :ref:`map_ffs` + +.. seealso:: Advanced usage docs for + :doc:`/using_yosys/synthesis/techmap_synth` + +LUTs +^^^^ + +`abc` and `techmap` are used to map LUTs; converting primitive cell types to use +`$lut` and ``SB_CARRY`` cells. Note that the iCE40 flow uses `abc9` rather than +`abc`. For more on what these do, and what the difference between these two +commands are, refer to :doc:`/using_yosys/synthesis/abc`. + +.. literalinclude:: /code_examples/macro_commands/synth_ice40.ys + :language: yoscrypt + :start-after: map_luts: + :end-before: map_cells: + :dedent: + :name: map_luts + :caption: ``map_luts`` section + +.. figure:: /_images/code_examples/fifo/rdata_map_luts.* + :class: width-helper invert-helper + :name: rdata_map_luts + + ``rdata`` output after :ref:`map_luts` + +Finally we use `techmap` to map the generic `$lut` cells to iCE40 ``SB_LUT4`` +cells. + +.. literalinclude:: /code_examples/macro_commands/synth_ice40.ys + :language: yoscrypt + :start-after: map_cells: + :end-before: check: + :dedent: + :name: map_cells + :caption: ``map_cells`` section + +.. figure:: /_images/code_examples/fifo/rdata_map_cells.* + :class: width-helper invert-helper + :name: rdata_map_cells + + ``rdata`` output after :ref:`map_cells` + +.. seealso:: Advanced usage docs for + + - :doc:`/using_yosys/synthesis/techmap_synth` + - :doc:`/using_yosys/synthesis/abc` + +Other cells +^^^^^^^^^^^ + +The following commands may also be used for mapping other cells: + +`hilomap` + Some architectures require special driver cells for driving a constant hi or + lo value. This command replaces simple constants with instances of such + driver cells. + +`iopadmap` + Top-level input/outputs must usually be implemented using special I/O-pad + cells. This command inserts such cells to the design. + +These commands tend to either be in the :ref:`map_cells` or after the +:ref:`check` depending on the flow. + +Final steps +~~~~~~~~~~~~ + +The next section of the iCE40 synth flow performs some sanity checking and final +tidy up: + +.. literalinclude:: /code_examples/macro_commands/synth_ice40.ys + :language: yoscrypt + :start-after: check: + :dedent: + :name: check + :caption: ``check`` section + +The new commands here are: + +- :cmd:title:`autoname`, +- :cmd:title:`stat`, and +- :cmd:title:`blackbox`. + +The output from `stat` is useful for checking resource utilization; providing a +list of cells used in the design and the number of each, as well as the number +of other resources used such as wires and processes. For this design, the final +call to `stat` should look something like the following: + +.. literalinclude:: /code_examples/fifo/fifo.stat + :language: doscon + :start-at: yosys> stat -top fifo + +Note that the :yoscrypt:`-top fifo` here is optional. `stat` will automatically +use the module with the ``top`` attribute set, which ``fifo`` was when we called +`hierarchy`. If no module is marked ``top``, then stats will be shown for each +module selected. + +The `stat` output is also useful as a kind of sanity-check: Since we have +already run `proc`, we wouldn't expect there to be any processes. We also expect +``data`` to use hard memory; if instead of an ``SB_RAM40_4K`` saw a high number +of flip-flops being used we might suspect something was wrong. + +If we instead called `stat` immediately after :yoscrypt:`read_verilog fifo.v` we +would see something very different: + +.. literalinclude:: /code_examples/fifo/fifo.stat + :language: doscon + :start-at: yosys> stat + :end-before: yosys> stat -top fifo + +Notice how ``fifo`` and ``addr_gen`` are listed separately, and the statistics +for ``fifo`` show 2 ``addr_gen`` modules. Because this is before the memory has +been mapped, we also see that there is 1 memory with 2048 memory bits; matching +our 8-bit wide ``data`` memory with 256 values (:math:`8*256=2048`). + +Synthesis output +^^^^^^^^^^^^^^^^ + +The iCE40 synthesis flow has the following output modes available: + +- `write_blif`, +- `write_edif`, and +- `write_json`. + +As an example, if we called :yoscrypt:`synth_ice40 -top fifo -json fifo.json`, +our synthesized ``fifo`` design will be output as :file:`fifo.json`. We can +then read the design back into Yosys with `read_json`, but make sure you use +:yoscrypt:`design -reset` or open a new interactive terminal first. The JSON +output we get can also be loaded into `nextpnr`_ to do place and route; but that +is beyond the scope of this documentation. + +.. _nextpnr: https://github.com/YosysHQ/nextpnr + +.. seealso:: :cmd:title:`synth_ice40` diff --git a/chips/yosys/docs/source/getting_started/index.rst b/chips/yosys/docs/source/getting_started/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..7a92c212ae63aef3251dcfd926d342782e34a9d3 --- /dev/null +++ b/chips/yosys/docs/source/getting_started/index.rst @@ -0,0 +1,13 @@ +Getting started with Yosys +========================== + +This section covers how to get started with Yosys, from installation to a guided +walkthrough of synthesizing a design for hardware, and finishing with an +introduction to writing re-usable Yosys scripts. + +.. toctree:: + :maxdepth: 3 + + installation + example_synth + scripting_intro diff --git a/chips/yosys/docs/source/getting_started/installation.rst b/chips/yosys/docs/source/getting_started/installation.rst new file mode 100644 index 0000000000000000000000000000000000000000..a58722d9498d16ea236bbdc475a63c2f8eae0d4d --- /dev/null +++ b/chips/yosys/docs/source/getting_started/installation.rst @@ -0,0 +1,366 @@ +Installation +------------ + +This document will guide you through the process of installing Yosys. + +CAD suite(s) +~~~~~~~~~~~~ + +Yosys is part of the `Tabby CAD Suite +`_ and the `OSS CAD Suite +`_! The easiest way to use yosys +is to install the binary software suite, which contains all required +dependencies and related tools. + +* `Contact YosysHQ `_ for a `Tabby CAD Suite + `_ Evaluation License and + download link +* OR go to https://github.com/YosysHQ/oss-cad-suite-build/releases to download + the free OSS CAD Suite +* Follow the `Install Instructions on GitHub + `_ + +Make sure to get a Tabby CAD Suite Evaluation License if you need features such +as industry-grade SystemVerilog and VHDL parsers! + +For more information about the difference between Tabby CAD Suite and the OSS +CAD Suite, please visit https://www.yosyshq.com/tabby-cad-datasheet + +Many Linux distributions also provide Yosys binaries, some more up to date than +others. Check with your package manager! + +Targeted architectures +^^^^^^^^^^^^^^^^^^^^^^ + +The `OSS CAD Suite`_ releases `nightly builds`_ for the following architectures: + +- **linux-x64** - Most personal Linux based computers +- **darwin-x64** - macOS 12 or later with Intel CPU +- **darwin-arm64** - macOS 12 or later with M1/M2 CPU +- **windows-x64** - Targeted for Windows 10 and 11 +- **linux-arm64** - Devices such as Raspberry Pi with 64bit OS + +For more information about the targeted architectures, and the current build +status, check the `OSS CAD Suite`_ git repository. + +.. _OSS CAD Suite: https://github.com/YosysHQ/oss-cad-suite-build +.. _nightly builds: https://github.com/YosysHQ/oss-cad-suite-build/releases/latest + +Building from source +~~~~~~~~~~~~~~~~~~~~ + +The Yosys source files can be obtained from the `YosysHQ/Yosys git repository`_. +`ABC`_ and some of the other libraries used are included as git submodules. To +clone these submodules at the same time, use e.g.: + +.. code:: console + + git clone --recurse-submodules https://github.com/YosysHQ/yosys.git # ..or.. + git clone https://github.com/YosysHQ/yosys.git + cd yosys + git submodule update --init --recursive + +.. _YosysHQ/Yosys git repository: https://github.com/yosyshq/yosys/ +.. _ABC: https://github.com/berkeley-abc/abc + +.. note:: + + As of Yosys v0.47, releases include a ``yosys.tar.gz`` file which includes + all source code and all sub-modules in a single archive. This can be used as + an alternative which does not rely on :program:`git`. + +Supported platforms +^^^^^^^^^^^^^^^^^^^ + +The following platforms are supported and regularly tested: + +- Linux +- macOS + +Other platforms which may work, but instructions may not be up to date and are +not regularly tested: + +- FreeBSD +- WSL +- Windows with (e.g.) Cygwin + +Build prerequisites +^^^^^^^^^^^^^^^^^^^ + +A C++ compiler with C++20 support is required as well as some standard tools +such as GNU Flex, GNU Bison (>=3.8), CMake (>=3.28), Make (or other CMake +generator such as Ninja), and Python (>=3.11). Some additional tools: readline, +libffi, Tcl and zlib; will be used if available but are optional. Graphviz and +Xdot are used by the `show` command to display schematics. + +Installing all prerequisites: + +.. tab:: Ubuntu 22.04 + + .. code:: console + + sudo apt-get install gawk git make python3 lld bison clang flex \ + libffi-dev libfl-dev libreadline-dev pkg-config tcl-dev zlib1g-dev \ + graphviz xdot + sudo snap install cmake --classic + +.. tab:: Ubuntu 24.04 + + .. code:: console + + sudo apt-get install gawk git cmake make python3 lld bison clang flex \ + libffi-dev libfl-dev libreadline-dev pkg-config tcl-dev zlib1g-dev \ + graphviz xdot + +.. tab:: macOS 13 (with Homebrew) + + .. code:: console + + brew tap Homebrew/bundle && brew bundle + +.. tab:: MacPorts + + .. code:: console + + sudo port install bison cmake flex readline gawk libffi graphviz \ + pkgconfig python311 zlib tcl + +.. tab:: FreeBSD + + .. code:: console + + pkg install bison cmake-core flex readline gawk libffi graphviz \ + pkgconf python311 tcl-wrapper + +.. tab:: Nix + + .. code:: console + + nix-shell + + enters a shell with all prerequisites, using the nixpkgs revision pinned in + ``flake.lock``. To have direnv load it automatically, put ``use nix`` in + ``.envrc``. ``nix develop`` gives the same shell, but first copies the source + tree including all submodules into the Nix store. + +.. tab:: Cygwin + + Use the following command to install all prerequisites, or select these + additional packages: + + .. code:: console + + setup-x86_64.exe -q --packages=bison,flex,gcc-core,gcc-g++,git,libffi-devel,libreadline-devel,cmake,make,pkg-config,python3,tcl-devel,zlib-devel + + .. warning:: + + As of this writing, Cygwin only supports up to Python 3.9.16 while the + minimum required version of Python is 3.11. This means that Cygwin is not + compatible with many of the Python-based frontends. While this does not + currently prevent Yosys itself from working, no guarantees are made for + continued support. You may also need to specify ``CXXSTD=gnu++20`` to + resolve missing ``strdup`` function when using gcc. It is instead + recommended to use Windows Subsystem for Linux (WSL) and follow the + instructions for Ubuntu. + +.. + tab:: MSYS2 (MINGW64) + + .. code:: console + + pacman -S bison flex mingw-w64-x86_64-gcc git libffi-devel libreadline-devel make pkg-config python3 tcl-devel zlib-devel + + Not that I can get this to work; it's failing during ld with what looks like + math library issues: ``multiple definition of `tanh'`` and + ``undefined reference to `__imp_acosh'``, as well as issues in `aiger2` with + ``seekg`` et al not being available. + + .. note:: + + The ``config-msys2-64`` target uses the ``mingw-w64-x86_64-`` prefixed + compiler in order to allow compiled exe files to be run without an MSYS2 + shell. + +Build configuration +^^^^^^^^^^^^^^^^^^^ + +The Yosys build is configured via CMake, and uses a number of variables which +influence the build process. When setting one-off variables, CMake provides the +``-D =`` command line option. For example, disabling zlib support: + +.. code:: console + + cmake -B build . -DYOSYS_WITHOUT_ZLIB=ON + +.. warning:: + + Yosys does not support in-tree builds. If calling :program:`cmake` from the + root ``yosys`` directory the ``-B`` option must be provided. + +For a more persistent configuration, we recommend creating and using a +``CMakeUserPresets.json`` file in the root ``yosys`` directory. Below is an +example file which has two configurations, one enables ccache and sets the default compiler to clang when +calling ``cmake --preset clang``, and the other disables zlib support when calling ``cmake --preset without_zlib`` +This can be used instead of manually specifying ``-DYOSYS_WITHOUT_ZLIB=ON``: + +.. code-block:: json + :caption: CMakeUserPresets.json + + { + "version": 1, + "configurePresets": [ + { + "name": "clang", + "inherits": "default", + "generator": "Unix Makefiles", + "cacheVariables": { + "CMAKE_C_COMPILER": "clang", + "CMAKE_CXX_COMPILER": "clang++", + "YOSYS_COMPILER_LAUNCHER": "ccache" + } + }, + { + "name": "without_zlib", + "inherits": "clang", + "cacheVariables": { + "YOSYS_WITHOUT_ZLIB": "ON" + } + } + ] + } + +Once generated, available build variables can be inspected and modified with +:program:`ccmake` or opening the generated ``build/CMakeCache.txt`` file: + +.. code:: console + + ccmake build #..or.. + vi build/CMakeCache.txt + +If you have clang, and (a compatible version of) ``ld.lld`` available in PATH, +it's recommended to speed up incremental builds with lld by enabling LTO with +``CMAKE_INTERPROCEDURAL_OPTIMIZATION=ON``. On macOS, LTO requires using clang +from homebrew rather than clang from xcode. For example: + +.. code:: console + + cmake -B build . -DCMAKE_INTERPROCEDURAL_OPTIMIZATION=ON \ + -DCMAKE_C_COMPILER=$(brew --prefix)/opt/llvm/bin/clang \ + -DCMAKE_CXX_COMPILER=$(brew --prefix)/opt/llvm/bin/clang++ + +This is also available with a preset: + +.. code:: console + + cmake --preset lto + +By default, building (and installing) Yosys will build (and install) `ABC`_, +using :program:`yosys-abc` as the executable name. To use an existing ABC +executable instead, set the :makevar:`YOSYS_ABC_EXECUTABLE` CMake variable to +point to the desired executable. + +Running the build system +^^^^^^^^^^^^^^^^^^^^^^^^ + +To quickly install Yosys with default settings, call the following commands from +the root ``yosys`` directory: + +.. code:: console + + cmake --preset release --fresh + cmake --build build-rel --config Release --parallel $(nproc) + sudo cmake --install build-rel --strip + +To use an existing configuration, use the ``--build`` option, e.g: + +.. code:: console + + cmake --preset default + ccmake build # modify configuration + cmake --build build + +.. seealso:: + + Refer to :doc:`/yosys_internals/extending_yosys/test_suites` for details on + testing Yosys once compiled. + +Source tree and build system +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The Yosys source tree is organized into the following top-level +directories: + +``backends/`` + This directory contains a subdirectory for each of the backend modules. + +``cmake/`` + Additional ``.cmake`` files used by CMake during build generation. + +``docs/`` + Contains the source for this documentation, including images and sample code. + +``examples/`` + Contains example code for using Yosys with some other tools including a demo + of the Yosys Python api, and synthesizing for various toolchains such as + Intel and Anlogic. + +``frontends/`` + This directory contains a subdirectory for each of the frontend modules. + +``kernel/`` + This directory contains all the core functionality of Yosys. This includes + the functions and definitions for working with the RTLIL data structures + (:file:`rtlil.{h|cc}`), the ``main()`` function (:file:`driver.cc`), the + internal framework for generating log messages (:file:`log.{h|cc}`), the + internal framework for registering and calling passes + (:file:`register.{h|cc}`), some core commands that are not really passes + (:file:`select.cc`, :file:`show.cc`, …) and a couple of other small utility + libraries. + +``libs/`` + Libraries packaged with Yosys builds are contained in this folder. See + :doc:`/appendix/auxlibs`. + +``misc/`` + Other miscellany which doesn't fit anywhere else. + +``passes/`` + This directory contains a subdirectory for each pass or group of passes. For + example as of this writing the directory :file:`passes/hierarchy/` contains + the code for three passes: `hierarchy`, `submod`, and `uniquify`. + +``pyosys/`` + Contains the scripts and wrappers necessary for building :doc:`Pyosys + `. + +``techlibs/`` + This directory contains simulation models and standard implementations for + the cells from the internal cell library. + +``tests/`` + This directory contains the suite of unit tests and regression tests used by + Yosys. See :doc:`/yosys_internals/extending_yosys/test_suites`. + +.. TODO:: CMAKE_TODO + + - ``yosys_()`` for each pass + + - see :file:`cmake/YosysComponent.cmake` + + - if using a sub folder, add it to the parent's ``CMakeLists.txt`` with + ``add_subdirectory()`` + + - previous: + + The Yosys kernel automatically detects all commands linked + with Yosys. So it is not needed to add additional commands to a central list of + commands. + + Good starting points for reading example source code to learn how to write + passes are :file:`passes/opt/dff/opt_dff.cc` and :file:`passes/opt/opt_merge.cc`. + + Users of the Qt Creator IDE can generate a QT Creator project file using make + qtcreator. Users of the Eclipse IDE can use the "Makefile Project with Existing + Code" project type in the Eclipse "New Project" dialog (only available after the + CDT plugin has been installed) to create an Eclipse project in order to + programming extensions to Yosys or just browse the Yosys code base. diff --git a/chips/yosys/docs/source/getting_started/scripting_intro.rst b/chips/yosys/docs/source/getting_started/scripting_intro.rst new file mode 100644 index 0000000000000000000000000000000000000000..d6e4824316b2d8e2436cd75ff98213ca61136b3b --- /dev/null +++ b/chips/yosys/docs/source/getting_started/scripting_intro.rst @@ -0,0 +1,232 @@ +Scripting in Yosys +------------------ + +On the previous page we went through a synthesis script, running each command in +the interactive Yosys shell. On this page, we will be introducing the script +file format and how you can make your own synthesis scripts. + +Yosys script files typically use the :file:`.ys` extension and contain a set of +commands for Yosys to run sequentially. These commands are the same ones we +were using on the previous page like `read_verilog` and `hierarchy`. + +Script parsing +~~~~~~~~~~~~~~ + +As with the interactive shell, each command consists of the command name, and an +optional whitespace separated list of arguments. Commands are terminated with +the newline character, and anything after a hash sign ``#`` is a comment (i.e. +it is ignored). + +It is also possible to terminate commands with a semicolon ``;``. This is +particularly useful in conjunction with the ``-p `` command line +option, where ```` can be a string with multiple commands separated by +semicolon. In-line comments can also be made with the colon ``:``, where the end +of the comment is a semicolon ``;`` or a new line. + +.. code-block:: + :caption: Using the ``-p`` option + + $ yosys -p 'read_verilog fifo.v; :this is a comment; prep' + +.. warning:: + + The space after the semicolon is required for correct parsing. ``log a;log + b;`` for example will display ``a;log b`` instead of ``a`` and ``b`` as might + be expected. + +Another special character that can be used in Yosys scripts is the bang ``!``. +Anything after the bang will be executed as a shell command. This can only be +terminated with a new line. Any semicolons, hashes, or other special characters +will be passed to the shell. If an error code is returned from the shell it +will be raised by Yosys. `exec` provides a much more flexible way of executing +commands, allowing the output to be logged and more control over when to +generate errors. + +.. warning:: + + Take care when using the ``yosys -p`` option. Some shells such as bash will + perform substitution options inside of a double quoted string, such as ``!`` + for history substitution and ``$`` for variable substitution; single quotes + should be used instead to pass the string to Yosys without substitution. + +The synthesis starter script +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. role:: yoscrypt(code) + :language: yoscrypt + +All of the images and console output used in +:doc:`/getting_started/example_synth` were generated by Yosys, using Yosys +script files found in :file:`docs/source/code_examples/fifo`. If you haven't +already, let's take a look at some of those script files now. + +.. literalinclude:: /code_examples/fifo/fifo.ys + :language: yoscrypt + :lineno-match: + :start-at: echo on + :end-before: design -reset + :caption: A section of :file:`fifo.ys`, generating the images used for :ref:`addr_gen_example` + :name: fifo-ys + +The first command there, :yoscrypt:`echo on`, uses `echo` to enable command +echoes on. This is how we generated the code listing for +:ref:`hierarchy_output`. Turning command echoes on prints the ``yosys> +hierarchy -top addr_gen`` line, making the output look the same as if it were an +interactive terminal. :yoscrypt:`hierarchy -top addr_gen` is of course the +command we were demonstrating, including the output text and an image of the +design schematic after running it. + +We briefly touched on `select` when it came up in `synth_ice40`, but let's look +at it more now. + +.. _select_intro: + +Selections intro +^^^^^^^^^^^^^^^^ + +The `select` command is used to modify and view the list of selected objects: + +.. literalinclude:: /code_examples/fifo/fifo.out + :language: doscon + :start-at: yosys> select + :end-before: yosys> show + +When we call :yoscrypt:`select -module addr_gen` we are changing the currently +active selection from the whole design, to just the ``addr_gen`` module. Notice +how this changes the ``yosys`` at the start of each command to ``yosys +[addr_gen]``? This indicates that any commands we run at this point will *only* +operate on the ``addr_gen`` module. When we then call :yoscrypt:`select -list` +we get a list of all objects in the ``addr_gen`` module, including the module +itself, as well as all of the wires, inputs, outputs, processes, and cells. + +Next we perform another selection, :yoscrypt:`select t:*`. The ``t:`` part +signifies we are matching on the *cell type*, and the ``*`` means to match +anything. For this (very simple) selection, we are trying to find all of the +cells, regardless of their type. The active selection is now shown as +``[addr_gen]*``, indicating some sub-selection of the ``addr_gen`` module. This +gives us the `$add` and `$eq` cells, which we want to highlight for the +:ref:`addr_gen_hier` image. + +.. _select_new_cells: + +We can assign a name to a selection with :yoscrypt:`select -set`. In our case +we are using the name ``new_cells``, and telling it to use the current +selection, indicated by the ``%`` symbol. We can then use this named selection +by referring to it as ``@new_cells``, which we will see later. Then we clear +the selection so that the following commands can operate on the full design. +While we split that out for this document, we could have done the same thing in +a single line by calling :yoscrypt:`select -set new_cells addr_gen/t:*`. If we +know we only have the one module in our design, we can even skip the +``addr_gen/`` part. Looking further down :ref:`the fifo.ys code ` we +can see this with :yoscrypt:`select -set new_cells t:$mux t:*dff`. We can also +see in that command that selections don't have to be limited to a single +statement. + +Many commands also support an optional ``[selection]`` argument which can be +used to override the currently selected objects. We could, for example, call +:yoscrypt:`clean addr_gen` to have `clean` operate on *just* the ``addr_gen`` +module. + +Detailed documentation of the select framework can be found under +:doc:`/using_yosys/more_scripting/selections` or in the command reference at +:cmd:title:`select`. + +.. _show_intro: + +Displaying schematics +^^^^^^^^^^^^^^^^^^^^^ + +While the `select` command is very useful, sometimes nothing beats being able to +see a design for yourself. This is where `show` comes in. Note that this +document is just an introduction to the `show` command, only covering the +basics. For more information, including a guide on what the different symbols +represent, see :ref:`interactive_show` and the +:doc:`/using_yosys/more_scripting/interactive_investigation` page. + +.. figure:: /_images/code_examples/fifo/addr_gen_show.* + :class: width-helper invert-helper + :name: addr_gen_show + + Calling :yoscrypt:`show addr_gen` after `hierarchy` + +.. note:: + + The `show` command requires a working installation of `GraphViz`_ and `xdot`_ + for displaying the actual circuit diagrams. + +.. _GraphViz: http://www.graphviz.org/ +.. _xdot: https://github.com/jrfonseca/xdot.py + +This is the first :yoscrypt:`show` command we called in :file:`fifo.ys`, +:ref:`as we saw above `. If we look at the log output for this image +we see the following: + +.. literalinclude:: /code_examples/fifo/fifo.out + :language: doscon + :start-at: -prefix addr_gen_show + :end-before: yosys> show + +Calling `show` with :yoscrypt:`-format dot` tells it we want to output a +:file:`.dot` file rather than opening it for display. The :yoscrypt:`-prefix +addr_gen_show` option indicates we want the file to be called +:file:`addr_gen_show.{*}`. Remember, we do this in :file:`fifo.ys` because we +need to store the image for displaying in the documentation you're reading. But +if you just want to display the images locally you can skip these two options. +The ``-format`` option internally calls the ``dot`` command line program from +GraphViz to convert to formats other than :file:`.dot`. Check `GraphViz output +docs`_ for more on available formats. + +.. _GraphViz output docs: https://graphviz.org/docs/outputs/ + +.. note:: + + If you are using a POSIX based version of Yosys (such as for Mac or Linux), + xdot will be opened in the background and Yosys can continue to be used. If + it it still open, future calls to :yoscrypt:`show` will use the same xdot + instance. + +The ``addr_gen`` at the end tells it we only want the ``addr_gen`` module, just +like when we called :yoscrypt:`select -module addr_gen` in :ref:`select_intro`. +That last parameter doesn't have to be a module name, it can be any valid +selection string. Remember when we :ref:`assigned a name to a +selection` and called it ``new_cells``? We saw in the +:yoscrypt:`select -list` output that it contained two cells, an `$add` and an +`$eq`. We can call `show` on that selection just as easily: + +.. figure:: /_images/code_examples/fifo/new_cells_show.* + :class: width-helper invert-helper + :name: new_cells_show + + Calling :yoscrypt:`show -notitle @new_cells` + +We could have gotten the same output with :yoscrypt:`show -notitle t:$add t:$eq` +if we didn't have the named selection. By adding the :yoscrypt:`-notitle` flag +there we can also get rid of the ``addr_gen`` title that would have been +automatically added. The last two images were both added for this introduction. +The next image is the first one we saw in :doc:`/getting_started/example_synth`: +showing the full ``addr_gen`` module while also highlighting ``@new_cells`` and +the two ``PROC`` blocks. To achieve this highlight, we make use of the +:yoscrypt:`-color` option: + +.. figure:: /_images/code_examples/fifo/addr_gen_hier.* + :class: width-helper invert-helper + + Calling :yoscrypt:`show -color maroon3 @new_cells -color cornflowerblue p:* -notitle` + +As described in the the `help` output for `show` (or by clicking on the `show` +link), colors are specified as :yoscrypt:`-color `. Color names +for the ```` portion can be found on the `GraphViz color docs`_. Unlike +the final `show` parameter which can have be any selection string, the +```` part must be a single selection expression or named selection. +That means while we can use ``@new_cells``, we couldn't use ``t:$eq t:$add``. +In general, if a command lists ``[selection]`` as its final parameter it can be +any selection string. Any selections that are not the final parameter, such as +those used in options, must be a single expression instead. + +.. _GraphViz color docs: https://graphviz.org/doc/info/colors + +For all of the options available to `show`, check the command reference at +:cmd:title:`show`. + +.. seealso:: :ref:`interactive_show` on the + :doc:`/using_yosys/more_scripting/interactive_investigation` page. diff --git a/chips/yosys/docs/source/index.rst b/chips/yosys/docs/source/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..40310009388a26b55dd8a0b58150f749e5f539ab --- /dev/null +++ b/chips/yosys/docs/source/index.rst @@ -0,0 +1,43 @@ +================================================================================ +Yosys Open SYnthesis Suite +================================================================================ + +Yosys is an open source framework for RTL synthesis. To learn more about Yosys, +see :doc:`/introduction`. For a quick guide on how to get started using Yosys, +check out :doc:`/getting_started/index`. For the complete list of commands +available, go to :ref:`cmd_ref`. + +.. todo:: look into command ref improvements + + - Search bar with live drop down suggestions for matching on title / + autocompleting commands + - Scroll the left sidebar to the current location on page load + - Also the formatting in pdf uses link formatting instead of code formatting + +.. todolist:: + +.. toctree:: + :maxdepth: 3 + :includehidden: + + Yosys (index) + introduction + + getting_started/index + using_yosys/index + yosys_internals/index + +.. toctree:: + :caption: Appendix + :titlesonly: + :includehidden: + + appendix/primer + appendix/rtlil_text + appendix/auxlibs + appendix/auxprogs + + bib + + cell_index + cmd_ref diff --git a/chips/yosys/docs/source/introduction.rst b/chips/yosys/docs/source/introduction.rst new file mode 100644 index 0000000000000000000000000000000000000000..48a4fb9fd154f39a424d303f2846b29963369756 --- /dev/null +++ b/chips/yosys/docs/source/introduction.rst @@ -0,0 +1,255 @@ +What is Yosys +============= + +Yosys began as a BSc thesis project by Claire Wolf intended to support synthesis +for a CGRA (coarse-grained reconfigurable architecture). It then expanded into +more general infrastructure for research on synthesis. + +Modern Yosys has full support for the synthesizable subset of Verilog-2005 and +has been described as "the GCC of hardware synthesis." Freely available and +`open source`_, Yosys finds use across hobbyist and commercial applications as +well as academic. + +.. _open source: https://github.com/YosysHQ/yosys + +.. note:: Yosys is released under the ISC License: + + A permissive license lets people do anything with your code with proper + attribution and without warranty. The ISC license is functionally equivalent + to the BSD 2-Clause and MIT licenses, removing some language that is no + longer necessary. + +Together with the place and route tool `nextpnr`_, Yosys can be used to program +some FPGAs with a fully end-to-end open source flow (Lattice iCE40 and ECP5). It +also does the synthesis portion for the `OpenLane flow`_, targeting the SkyWater +130nm open source PDK for fully open source ASIC design. Yosys can also do +formal verification with backends for solver formats like `SMT2`_. + +.. _nextpnr: https://github.com/YosysHQ/nextpnr +.. _OpenLane flow: https://github.com/The-OpenROAD-Project/OpenLane +.. _SMT2: https://smtlib.cs.uiowa.edu/ + +Yosys, and the accompanying Open Source EDA ecosystem, is currently maintained +by `Yosys Headquarters`_, with many of the core developers employed by `YosysHQ +GmbH`_. A commercial extension, `Tabby CAD Suite`_, includes the Verific +frontend for industry-grade SystemVerilog and VHDL support, formal verification +with SVA, and formal apps. + +.. _Yosys Headquarters: https://github.com/YosysHQ +.. _YosysHQ GmbH: https://www.yosyshq.com/about +.. _Tabby CAD Suite: https://www.yosyshq.com/tabby-cad-datasheet + +.. figure:: /_static/logo.png + :class: width-helper + +What you can do with Yosys +-------------------------- + +- Read and process (most of) modern Verilog-2005 code +- Perform all kinds of operations on netlist (RTL, Logic, Gate) +- Perform logic optimizations and gate mapping with ABC + +Typical applications for Yosys +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +- Synthesis of final production designs +- Pre-production synthesis (trial runs before investing in other tools) +- Conversion of full-featured Verilog to simple Verilog +- Conversion of Verilog to other formats (BLIF, BTOR, etc) +- Demonstrating synthesis algorithms (e.g. for educational purposes) +- Framework for experimenting with new algorithms +- Framework for building custom flows (Not limited to synthesis but also formal + verification, reverse engineering, ...) + +Things you can't do +~~~~~~~~~~~~~~~~~~~ + +- Process high-level languages such as C/C++/SystemC +- Create physical layouts (place&route) + + - Check out `nextpnr`_ for that + +- Rely on built-in syntax checking + + - Use an external tool like `verilator`_ instead + +.. todo:: nextpnr for FPGAs, consider mentioning openlane, vpr, coriolis + +.. _nextpnr: https://github.com/YosysHQ/nextpnr +.. _verilator: https://www.veripool.org/verilator/ + +The Yosys family +---------------- + +As mentioned above, `YosysHQ`_ maintains not just Yosys but an entire family of +tools built around it. In no particular order: + +.. _YosysHQ: https://github.com/YosysHQ + +SBY for formal verification + Yosys provides input parsing and conversion to the formats used by the solver + engines. Yosys also provides a unified witness framework for providing cover + traces and counter examples for engines which don't natively support this. + `SBY source`_ | `SBY docs`_ + +.. _SBY source: https://github.com/YosysHQ/sby +.. _SBY docs: https://yosyshq.readthedocs.io/projects/sby + +EQY for equivalence checking + In addition to input parsing and preparation, Yosys provides the plugin + support enabling EQY to operate on designs directly. `EQY source`_ | `EQY + docs`_ + +.. _EQY source: https://github.com/YosysHQ/eqy +.. _EQY docs: https://yosyshq.readthedocs.io/projects/eqy + +MCY for mutation coverage + Yosys is used to read the source design, generate a list of possible + mutations to maximise design coverage, and then perform selected mutations. + `MCY source`_ | `MCY docs`_ + +.. _MCY source: https://github.com/YosysHQ/mcy +.. _MCY docs: https://yosyshq.readthedocs.io/projects/mcy + +SCY for deep formal traces + Since SCY generates and runs SBY, Yosys provides the same utility for SCY as + it does for SBY. Yosys additionally provides the trace concatenation needed + for outputting the deep traces. `SCY source`_ + +.. _SCY source: https://github.com/YosysHQ/scy + +The original thesis abstract +---------------------------- + +The first version of the Yosys documentation was published as a bachelor thesis +at the Vienna University of Technology :cite:p:`BACC`. + +:Abstract: + Most of today's digital design is done in HDL code (mostly Verilog or + VHDL) and with the help of HDL synthesis tools. + + In special cases such as synthesis for coarse-grain cell libraries or + when testing new synthesis algorithms it might be necessary to write a + custom HDL synthesis tool or add new features to an existing one. In + these cases the availability of a Free and Open Source (FOSS) synthesis + tool that can be used as basis for custom tools would be helpful. + + In the absence of such a tool, the Yosys Open SYnthesis Suite (Yosys) + was developed. This document covers the design and implementation of + this tool. At the moment the main focus of Yosys lies on the high-level + aspects of digital synthesis. The pre-existing FOSS logic-synthesis tool + ABC is used by Yosys to perform advanced gate-level optimizations. + + An evaluation of Yosys based on real-world designs is included. It is + shown that Yosys can be used as-is to synthesize such designs. The + results produced by Yosys in this tests where successfully verified + using formal verification and are comparable in quality to the results + produced by a commercial synthesis tool. + +Yosys is a Verilog HDL synthesis tool. This means that it takes a behavioural +design description as input and generates an RTL, logical gate or physical gate +level description of the design as output. Yosys' main strengths are behavioural +and RTL synthesis. A wide range of commands (synthesis passes) exist within +Yosys that can be used to perform a wide range of synthesis tasks within the +domain of behavioural, rtl and logic synthesis. Yosys is designed to be +extensible and therefore is a good basis for implementing custom synthesis tools +for specialised tasks. + +.. figure:: /_images/primer/levels_of_abstraction.* + :class: width-helper invert-helper + :name: fig:Levels_of_abstraction + + Where Yosys exists in the layers of abstraction + +Benefits of open source HDL synthesis +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +- Cost (also applies to ``free as in free beer`` solutions): + + Today the cost for a mask set in 180nm technology is far less than the cost + for the design tools needed to design the mask layouts. Open Source ASIC flows + are an important enabler for ASIC-level Open Source Hardware. + +- Availability and Reproducibility: + + If you are a researcher who is publishing, you want to use tools that everyone + else can also use. Even if most universities have access to all major + commercial tools, you usually do not have easy access to the version that was + used in a research project a couple of years ago. With Open Source tools you + can even release the source code of the tool you have used alongside your + data. + +- Framework: + + Yosys is not only a tool. It is a framework that can be used as basis for + other developments, so researchers and hackers alike do not need to re-invent + the basic functionality. Extensibility was one of Yosys' design goals. + +- All-in-one: + + Because of the framework characteristics of Yosys, an increasing number of + features become available in one tool. Yosys not only can be used for circuit + synthesis but also for formal equivalence checking, SAT solving, and for + circuit analysis, to name just a few other application domains. With + proprietary software one needs to learn a new tool for each of these + applications. + +- Educational Tool: + + Proprietary synthesis tools are at times very secretive about their inner + workings. They often are ``black boxes``. Yosys is very open about its + internals and it is easy to observe the different steps of synthesis. + +History of Yosys +~~~~~~~~~~~~~~~~ + +.. todo:: Consider a less academic version of the History of Yosys + +A Hardware Description Language (HDL) is a computer language used to describe +circuits. A HDL synthesis tool is a computer program that takes a formal +description of a circuit written in an HDL as input and generates a netlist that +implements the given circuit as output. + +Currently the most widely used and supported HDLs for digital circuits are +Verilog :cite:p:`Verilog2005,VerilogSynth` and :abbr:`VHDL (VHSIC HDL, where +VHSIC is an acronym for Very-High-Speed Integrated Circuits)` +:cite:p:`VHDL,VHDLSynth`. Both HDLs are used for test and verification purposes +as well as logic synthesis, resulting in a set of synthesizable and a set of +non-synthesizable language features. In this document we only look at the +synthesizable subset of the language features. + +In recent work on heterogeneous coarse-grain reconfigurable logic +:cite:p:`intersynth` the need for a custom application-specific HDL synthesis +tool emerged. It was soon realised that a synthesis tool that understood Verilog +or VHDL would be preferred over a synthesis tool for a custom HDL. Given an +existing Verilog or VHDL front end, the work for writing the necessary +additional features and integrating them in an existing tool can be estimated to +be about the same as writing a new tool with support for a minimalistic custom +HDL. + +The proposed custom HDL synthesis tool should be licensed under a Free and Open +Source Software (FOSS) licence. So an existing FOSS Verilog or VHDL synthesis +tool would have been needed as basis to build upon. The main advantages of +choosing Verilog or VHDL is the ability to synthesize existing HDL code and to +mitigate the requirement for circuit-designers to learn a new language. In order +to take full advantage of any existing FOSS Verilog or VHDL tool, such a tool +would have to provide a feature-complete implementation of the synthesizable HDL +subset. + +Basic RTL synthesis is a well understood field :cite:p:`LogicSynthesis`. Lexing, +parsing and processing of computer languages :cite:p:`Dragonbook` is a +thoroughly researched field. All the information required to write such tools +has been openly available for a long time, and it is therefore likely that a +FOSS HDL synthesis tool with a feature-complete Verilog or VHDL front end must +exist which can be used as a basis for a custom RTL synthesis tool. + +Due to the author's preference for Verilog over VHDL it was decided early on to +go for Verilog instead of VHDL [#]_. So the existing FOSS Verilog synthesis +tools were evaluated. The results of this evaluation are utterly devastating. +Therefore a completely new Verilog synthesis tool was implemented and is +recommended as basis for custom synthesis tools. This is the tool that is +discussed in this document. + +.. [#] + A quick investigation into FOSS VHDL tools yielded similar grim results for + FOSS VHDL synthesis tools. diff --git a/chips/yosys/docs/source/literature.bib b/chips/yosys/docs/source/literature.bib new file mode 100644 index 0000000000000000000000000000000000000000..6d35d2922d04c732b612eab428b712d37eb29b67 --- /dev/null +++ b/chips/yosys/docs/source/literature.bib @@ -0,0 +1,202 @@ + +@inproceedings{intersynth, + title={Example-driven interconnect synthesis for heterogeneous coarse-grain reconfigurable logic}, + author={C. Wolf and Johann Glaser and Florian Schupfer and Jan Haase and Christoph Grimm}, + booktitle={FDL Proceeding of the 2012 Forum on Specification and Design Languages}, + pages={194--201}, + year={2012} +} + +@incollection{intersynthFdlBookChapter, + title={Methodology and Example-Driven Interconnect Synthesis for Designing Heterogeneous Coarse-Grain Reconfigurable Architectures}, + author={Johann Glaser and C. Wolf}, + booktitle={Advances in Models, Methods, and Tools for Complex Chip Design --- Selected contributions from FDL'12}, + editor={Jan Haase}, + publisher={Springer}, + year={2013}, + note={to appear} +} + +@unpublished{BACC, + author = {C. Wolf}, + title = {Design and Implementation of the Yosys Open SYnthesis Suite}, + note = {Bachelor Thesis, Vienna University of Technology}, + year = {2013} +} + +@unpublished{VerilogFossEval, + author = {C. Wolf}, + title = {Evaluation of Open Source Verilog Synthesis Tools for Feature-Completeness and Extensibility}, + note = {Unpublished Student Research Paper, Vienna University of Technology}, + year = {2012} +} + +@article{ABEL, + title={A High-Level Design Language for Programmable Logic Devices}, + author={Kyu Y. Lee and Michael Holley and Mary Bailey and Walter Bright}, + journal={VLSI Design (Manhasset NY: CPM Publications)}, + year={June 1985}, + pages={50-62} +} + +@MISC{Cheng93vl2mv:a, + author = {S-T Cheng and G York and R K Brayton}, + title = {VL2MV: A Compiler from Verilog to BLIF-MV}, + year = {1993} +} + +@MISC{Odin, + author = {Peter Jamieson and Jonathan Rose}, + title = {A VERILOG RTL SYNTHESIS TOOL FOR HETEROGENEOUS FPGAS}, + year = {2005} +} + +@inproceedings{vtr2012, + title={The VTR Project: Architecture and CAD for FPGAs from Verilog to Routing}, + author={Jonathan Rose and Jason Luu and Chi Wai Yu and Opal Densmore and Jeff Goeders and Andrew Somerville and Kenneth B. Kent and Peter Jamieson and Jason Anderson}, + booktitle={Proceedings of the 20th ACM/SIGDA International Symposium on Field-Programmable Gate Arrays}, + pages={77--86}, + year={2012}, + organization={ACM} +} + +@MISC{LogicSynthesis, + author = {G D Hachtel and F Somenzi}, + title = {Logic Synthesis and Verification Algorithms}, + year = {1996} +} + +@ARTICLE{Verilog2005, + journal={IEEE Std 1364-2005 (Revision of IEEE Std 1364-2001)}, + title={IEEE Standard for Verilog Hardware Description Language}, + author={IEEE Standards Association and others}, + year={2006}, + doi={10.1109/IEEESTD.2006.99495} +} + +@ARTICLE{VerilogSynth, + journal={IEEE Std 1364.1-2002}, + title={IEEE Standard for Verilog Register Transfer Level Synthesis}, + author={IEEE Standards Association and others}, + year={2002}, + doi={10.1109/IEEESTD.2002.94220} +} + +@ARTICLE{VHDL, + journal={IEEE Std 1076-2008 (Revision of IEEE Std 1076-2002)}, + title={IEEE Standard VHDL Language Reference Manual}, + author={IEEE Standards Association and others}, + year={2009}, + month={26}, + doi={10.1109/IEEESTD.2009.4772740} +} + +@ARTICLE{VHDLSynth, + journal={IEEE Std 1076.6-2004 (Revision of IEEE Std 1076.6-1999)}, + title={IEEE Standard for VHDL Register Transfer Level (RTL) Synthesis}, + author={IEEE Standards Association and others}, + year={2004}, + doi={10.1109/IEEESTD.2004.94802} +} + +@ARTICLE{IP-XACT, + journal={IEEE Std 1685-2009}, + title={IEEE Standard for IP-XACT, Standard Structure for Packaging, Integrating, and Reusing IP within Tools Flows}, + author={IEEE Standards Association and others}, + year={2010}, + pages={C1-360}, + keywords={abstraction definitions, address space specification, bus definitions, design environment, EDA, electronic design automation, electronic system level, ESL, implementation constraints, IP-XACT, register transfer level, RTL, SCRs, semantic consistency rules, TGI, tight generator interface, tool and data interoperability, use models, XML design meta-data, XML schema}, + doi={10.1109/IEEESTD.2010.5417309} +} + +@book{Dragonbook, + author = {Aho, Alfred V. and Sethi, Ravi and Ullman, Jeffrey D.}, + title = {Compilers: principles, techniques, and tools}, + year = {1986}, + isbn = {0-201-10088-6}, + publisher = {Addison-Wesley Longman Publishing Co., Inc.}, + address = {Boston, MA, USA} +} + +@INPROCEEDINGS{Cummings00, + author = {Clifford E. Cummings and Sunburst Design Inc}, + title = {Nonblocking Assignments in Verilog Synthesis, Coding Styles That Kill}, + booktitle = {SNUG (Synopsys Users Group) 2000 User Papers, section-MC1 (1 st paper}, + year = {2000} +} + +@ARTICLE{MURPHY, + author={D. L. Klipstein}, + journal={Cahners Publishing Co., EEE Magazine, Vol. 15, No. 8}, + title={The Contributions of Edsel Murphy to the Understanding of the Behavior of Inanimate Objects}, + year={August 1967} +} + +@INPROCEEDINGS{fsmextract, + author={Yiqiong Shi and Chan Wai Ting and Bah-Hwee Gwee and Ye Ren}, + booktitle={Circuits and Systems (ISCAS), Proceedings of 2010 IEEE International Symposium on}, + title={A highly efficient method for extracting FSMs from flattened gate-level netlist}, + year={2010}, + pages={2610-2613}, + keywords={circuit CAD;finite state machines;microcontrollers;FSM;control-intensive circuits;finite state machines;flattened gate-level netlist;state register elimination technique;Automata;Circuit synthesis;Continuous wavelet transforms;Design automation;Digital circuits;Hardware design languages;Logic;Microcontrollers;Registers;Signal processing}, + doi={10.1109/ISCAS.2010.5537093}, +} + +@ARTICLE{MultiLevelLogicSynth, + author={Brayton, R.K. and Hachtel, G.D. and Sangiovanni-Vincentelli, A.L.}, + journal={Proceedings of the IEEE}, + title={Multilevel logic synthesis}, + year={1990}, + volume={78}, + number={2}, + pages={264-300}, + keywords={circuit layout CAD;integrated logic circuits;logic CAD;capsule summaries;definitions;detailed analysis;in-depth background;logic decomposition;logic minimisation;logic synthesis;logic synthesis techniques;multilevel combinational logic;multilevel logic synthesis;notation;perspective;survey;synthesis methods;technology mapping;testing;Application specific integrated circuits;Design automation;Integrated circuit synthesis;Logic design;Logic devices;Logic testing;Network synthesis;Programmable logic arrays;Signal synthesis;Silicon}, + doi={10.1109/5.52213}, + ISSN={0018-9219}, +} + +@article{UllmannSubgraphIsomorphism, + author = {Ullmann, J. R.}, + title = {An Algorithm for Subgraph Isomorphism}, + journal = {J. ACM}, + issue_date = {Jan. 1976}, + volume = {23}, + number = {1}, + month = jan, + year = {1976}, + issn = {0004-5411}, + pages = {31--42}, + numpages = {12}, + doi = {10.1145/321921.321925}, + acmid = {321925}, + publisher = {ACM}, + address = {New York, NY, USA}, +} + +@article{een2003temporal, + title={Temporal induction by incremental SAT solving}, + author={E{\'e}n, Niklas and S{\"o}rensson, Niklas}, + journal={Electronic Notes in Theoretical Computer Science}, + volume={89}, + number={4}, + pages={543--560}, + year={2003}, + publisher={Elsevier} +} + +@inproceedings{btor, + title={BTOR: bit-precise modelling of word-level problems for model checking}, + author={Brummayer, Robert and Biere, Armin and Lonsing, Florian}, + booktitle={Proceedings of the joint workshops of the 6th international workshop on satisfiability modulo theories and 1st international workshop on bit-precise reasoning}, + pages={33--38}, + year={2008} +} + +@inproceedings{VIS, + title={VIS: A system for verification and synthesis}, + author={Brayton, Robert K and Hachtel, Gary D and Sangiovanni-Vincentelli, Alberto and Somenzi, Fabio and Aziz, Adnan and Cheng, Szu-Tsung and Edwards, Stephen and Khatri, Sunil and Kukimoto, Yuji and Pardo, Abelardo and others}, + booktitle={Proceedings of the 8th International Conference on Computer Aided Verification}, + pages={428--432}, + year={1996}, + organization={Springer} +} diff --git a/chips/yosys/docs/source/requirements.txt b/chips/yosys/docs/source/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..f33e65627f0ff2dc2cbab2b2b0593b993c9b6531 --- /dev/null +++ b/chips/yosys/docs/source/requirements.txt @@ -0,0 +1,5 @@ +furo-ys @ git+https://github.com/YosysHQ/furo-ys +sphinxcontrib-bibtex +rtds-action +sphinx-inline-tabs +click diff --git a/chips/yosys/docs/source/using_yosys/bugpoint.rst b/chips/yosys/docs/source/using_yosys/bugpoint.rst new file mode 100644 index 0000000000000000000000000000000000000000..71ec3b68d0d2afb486db9b1e1fbc7044d267cd9f --- /dev/null +++ b/chips/yosys/docs/source/using_yosys/bugpoint.rst @@ -0,0 +1,446 @@ +Minimizing failing (or bugged) designs +====================================== + +.. TODO:: pending merge of https://github.com/YosysHQ/yosys/pull/5068 + +This document is a how-to guide for reducing problematic designs to the bare +minimum needed for reproducing the issue. This is a Yosys specific alternative +to the Stack Overflow article: `How to create a Minimal, Reproducible Example`_, +and is intended to help when there's something wrong with your design, or with +Yosys itself. + +.. _How to create a Minimal, Reproducible Example: https://stackoverflow.com/help/minimal-reproducible-example + +.. note:: + + This guide assumes a moderate degree of familiarity with Yosys and requires + some amount of problem solving ability. + + +Before you start +---------------- + +The first (and often overlooked) step, is to check for and *read* any error +messages or warnings. Passing the ``-q`` flag when running Yosys will make it +so that only warnings and error messages are written to the console. Don't just +read the last message either, there may be warnings that indicate a problem +before it happens. While some things may only be regarded as warnings, such as +multiple drivers for the same signal or logic loops, these can cause problems in +some synthesis flows but not others. + +A Yosys error (one that starts with ``ERROR:``) may give you a line number from +your design, or the name of the object causing issues. If so, you may already +have enough information to resolve the problem, or at least understand why it's +happening. + +.. note:: + + If you're not already, try using the latest version from the `Yosys GitHub`_. + You may find that your issue has already been fixed! And even if it isn't, + testing with two different versions is a good way to ensure reproducibility. + +.. _Yosys GitHub: https://github.com/YosysHQ/yosys + +Another thing to be aware of is that Yosys generally doesn't perform rigorous +checking of input designs to ensure they are valid. This is especially true for +the `read_verilog` frontend. It is instead recommended that you try load it +with `iverilog`_ or `verilator`_ first, as an invalid design can often lead to +unexpected issues. + +.. _iverilog: https://steveicarus.github.io/iverilog/ +.. _verilator: https://www.veripool.org/verilator/ + +If you're using a custom synthesis script, try take a bit of time to figure out +which command is failing. Calling ``echo on`` at the start of your script will +`echo` each command executed; the last echo before the error should then be +where the error has come from. Check the help message for the failing command; +does it indicate limited support, or mention some other command that needs to be +run first? You can also try to call `check` and/or ``hierarchy -check`` before +the failure to see if they report and errors or warnings. + + +Minimizing RTLIL designs with bugpoint +-------------------------------------- + +Yosys provides the `bugpoint` command for reducing a failing design to the +smallest portion of that design which still results in failure. While initially +developed for Yosys crashes, `bugpoint` can also be used for designs that lead +to non-fatal errors, or even failures in other tools that use the output of a +Yosys script. + +.. note:: + + Make sure to back up your code (design source and yosys script(s)) before + making any modifications. Even if the code itself isn't important, this can + help avoid "losing" the error while trying to debug it. + +Can I use bugpoint? +~~~~~~~~~~~~~~~~~~~ + +The first thing to be aware of is that `bugpoint` is not available in every +build of Yosys. Because the command works by invoking external processes, it +requires that Yosys can spawn executables. Notably this means `bugpoint` is not +able to be used in WebAssembly builds such as that available via YoWASP. The +easiest way to check your build of Yosys is by running ``yosys -h bugpoint``. If +Yosys displays the help text for `bugpoint` then it is available for use. + +.. code-block:: console + :caption: `bugpoint` is unavailable + + $ yosys -h bugpoint + + -- Running command `help bugpoint' -- + No such command or cell type: bugpoint + +Next you need to separate loading the design from the failure point; you should +be aiming to reproduce the failure by running ``yosys -s -s +``. If the failure occurs while loading the design, such as during +`read_verilog` you will instead have to minimize the input design yourself. +Check out the instructions for :ref:`using_yosys/bugpoint:minimizing verilog +designs` below. + +.. note:: + + You should also be able to run the two scripts separately, calling first + ``yosys -s -p 'write_rtlil design.il'`` and then ``yosys -s + design.il``. If this doesn't work then it may mean that the + failure isn't reproducible from RTLIL and `bugpoint` won't work either. + +When we talk about failure points here, it doesn't just mean crashes or errors +in Yosys. The ```` script can also be a user-defined failure such +as the `select` command with one of the ``-assert-*`` options; an example where +this might be useful is when a pass is supposed to remove a certain kind of +cell, but there is some edge case where the cell is not removed. Another +use-case would be minimizing a design which fails with the `equiv_opt` command, +suggesting that the optimization in question alters the circuit in some way. + +It is even possible to use `bugpoint` with failures *external* to Yosys, by +making use of the `exec` command in ````. This is especially useful +when Yosys is outputting an invalid design, or when some other tool is +incompatible with the design. Be sure to use the ``exec -expect-*`` options so +that the pass/fail can be detected correctly. Multiple calls to `exec` can be +made, or even entire shell scripts: + +.. code-block:: yoscrypt + + exec -expect-return 1 --bash + +Our final failure we can use with `bugpoint` is one returned by a wrapper +process, such as ``valgrind`` or ``timeout``. In this case you will be calling +something like `` yosys -s design.il``. Here, Yosys is +run under a wrapper process which checks for some failure state, like a memory +leak or excessive runtime. + + +How do I use bugpoint? +~~~~~~~~~~~~~~~~~~~~~~ + +At this point you should have: + +1. either an RTLIL file containing the design to minimize (referred to here as + ``design.il``), or a Yosys script, ````, which loads it; and +2. a Yosys script, ````, which produces the failure and returns a + non-zero return status. + +Now call ``yosys -qq -s design.il`` and take note of the error(s) +that get printed. A template script, ````, is provided here which +you can use. Make sure to configure it with the correct filenames and use only +one of the methods to load the design. Fill in the ``-grep`` option with the +error message printed just before. If you are using a wrapper process for your +failure state, add the ``-runner ""`` option to the `bugpoint` call. + +.. code-block:: yoscrypt + :caption: ```` template script + + # Load design + read_rtlil design.il + ## OR + script + + # Call bugpoint with failure + bugpoint -script -grep "" + + # Save minimized design + write_rtlil min.il + +The ``-grep`` option is used to search the log file generated by the Yosys under +test. If the error message is generated by something else, such as a wrapper +process or compiler sanitizer, then you should instead use ``-err_grep``. For +an OS error, like a SEGFAULT, you can also use ``-expect-return`` to check the +error code returned. + +.. note:: + + Checking the error message or return status is optional, but highly + recommended. `bugpoint` can quite easily introduce bugs by creating + malformed designs that commands were not intended to handle. By having some + way to check the error, `bugpoint` can ensure that it is the *right* error + being reproduced. This is even more important when ```` contains + more than one command. + +By default, `bugpoint` is able to remove any part of the design. In order to +keep certain parts, for instance because you already know they are related to +the failure, you can use the ``bugpoint_keep`` attribute. This can be done with +``(* bugpoint_keep *)`` in Verilog, ``attribute \bugpoint_keep 1`` in RTLIL, or +``setattr -set bugpoint_keep 1 [selection]`` from a Yosys script. It is also +possible to limit `bugpoint` to only removing certain *kinds* of objects, such +as only removing entire modules or cells (instances of modules). For more about +the options available, check ``help bugpoint`` or :cmd:title:`bugpoint`. + +In some situations, it may also be helpful to use `setenv` before `bugpoint` to +set environment variables for the spawned processes. An example of this is +``setenv UBSAN_OPTIONS halt_on_error=1`` for where you are trying to raise an +error on undefined behaviour but only want the child process to halt on error. + +.. note:: + + Using `setenv` in this way may or may not affect the current process. For + instance the ``UBSAN_OPTIONS halt_on_error`` here only affects child + processes, as does the :doc:`Yosys environment variable` + ``ABC`` because they are only read on start-up. While others, such as + ``YOSYS_NOVERIFIC`` and ``HOME``, are evaluated each time they are used. + +Once you have finished configuration, you can now run ``yosys ``. +The first thing `bugpoint` will do is test the input design fails. If it +doesn't, make sure you are using the right ``yosys`` executable; unless the +``-yosys`` option is provided, it will use whatever the shell defaults to, *not* +the current ``yosys``. If you are using the ``-runner`` option, try replacing +the `bugpoint` command with ``write_rtlil test.il`` and then on a new line, +``! yosys -s test.il`` to check it works as expected and +returns a non-zero status. + +.. seealso:: + + For more on script parsing and the use of ``!``, check out + :ref:`getting_started/scripting_intro:script parsing`. + +Depending on the size of your design, and the length of your ````, +`bugpoint` may take some time; remember, it will run ``yosys -s `` +on each iteration of the design. The bigger the design, the more iterations. +The longer the ````, the longer each iteration will take. As the +design shrinks and `bugpoint` converges, each iteration should take less and +less time. Once all simplifications are exhausted and there are no more objects +that can be removed, the script will continue and the minimized design can be +saved. + + +What do I do with the minimized design? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +First off, check the minimized design still fails. This is especially important +if you're not using `write_rtlil` to output the minimized design. For example, +if you ran :ref:`bugpoint_script` below, then calling ``yosys -s +min.v`` should still fail in the same way. + +.. code-block:: yoscrypt + :caption: example `bugpoint` minimizer + :name: bugpoint_script + + read_verilog design.v + bugpoint -script + write_verilog min.v + +The `write_rtlil` command is generally more reliable, since `bugpoint` will have +run that exact code through the failing script. Other ``write_*`` commands +convert from the RTLIL and then back again during the ``read_*`` which can +result in differences which mean the design no longer fails. + +.. note:: + + Simply calling Yosys with the output of ``write_*``, as in ``yosys -s + min.v``, does not guarantee that the corresponding ``read_*`` + will be used. For more about this, refer to + :doc:`/using_yosys/more_scripting/load_design`, or load the design explicitly + with ``yosys -p 'read_verilog min.v' -s ``. + +Once you've verified the failure still happens, check out +:ref:`using_yosys/bugpoint:identifying issues` for more on what to do next. + + +Minimizing Verilog designs +-------------------------- + +.. seealso:: + + This section is not specific to Yosys, so feel free to use another guide such + as Stack Overflow's `How to create a Minimal, Reproducible Example`_. + +Be sure to check any errors or warnings for messages that might identify source +lines or object names that might be causing the failure, and back up your source +code before modifying it. If you have multiple source files, you should start +by reducing them down to a single file. If a specific file is failing to read, +try removing everything else and just focus on that one. If your source uses +the ``include`` directive, replace it with the contents of the file referenced. + +Unlike RTLIL designs where we can use `bugpoint`, Yosys does not provide any +tools for minimizing Verilog designs. Instead, you should use an external tool +like `C-Reduce`_ (with the ``--not-c`` flag) or `sv-bugpoint`_. + +.. _C-Reduce: https://github.com/csmith-project/creduce +.. _sv-bugpoint: https://github.com/antmicro/sv-bugpoint + +C-Reduce +~~~~~~~~ + +As a very brief overview for using C-Reduce, you want your failing source design +(``test.v``), and some shell script which checks for the error being +investigated (``test.sh``). Below is an :ref:`egtest` which uses `logger` and +the ``-expect error "" 1`` option to perform a similar role to +``bugpoint -grep``, along with ``verilator`` to lint the code and make sure it +is still valid. + +.. code-block:: bash + :caption: Example test.sh for C-Reduce + :name: egtest + + #!/usr/bin/env bash + verilator --lint-only test.v &&/ + yosys -p 'logger -expect error "unsupported" 1; read_verilog test.v' + +.. code-block:: verilog + :caption: input test.v + + module top(input clk, a, b, c, output x, y, z); + always @(posedge clk) begin + if (a == 1'b1) + $stop; + end + assign x = a; + assign y = a ^ b; + assign z = c; + endmodule + +In this example ``read_verilog test.v`` is giving an error message that contains +the string "unsupported" because the ``$stop`` system task is only supported in +``initial`` blocks. By calling ``creduce ./test.sh test.v --not-c`` we can +minimize the design to just the failing code, while still being valid Verilog. + +.. code-block:: verilog + :caption: output test.v + + module a; + always begin $stop; + end endmodule + + +sv-bugpoint +~~~~~~~~~~~ + +sv-bugpoint works quite similarly to C-Reduce, except it requires an output +directory to be provided and the check script needs to accept the target file as +an input argument: ``sv-bugpoint outDir/ test.sh test.v`` + +.. code-block:: bash + :caption: Example test.sh for sv-bugpoint + + #!/usr/bin/env bash + verilator --lint-only $1 &&/ + yosys -p "logger -expect error \"unsupported\" 1; read_verilog $1" + +Notice that the commands for ``yosys -p`` are now in double quotes (``"``), and +the quotes around the error string are escaped (``\"``). This is necessary for +the ``$1`` argument subsitution to work correctly. + + +Doing it manually +~~~~~~~~~~~~~~~~~ + +If for some reason you are unable to use a tool to minimize your code, you can +still do it manually. But it can be a time consuming process and requires a lot +of iteration. At any point in the process, you can check for anything that is +unused or totally disconnected (ports, wires, etc) and remove them. If a +specific module is causing the problem, try to set that as the top module +instead. Any parameters should have their default values changed to match the +failing usage. + +As a rule of thumb, try to split things roughly in half at each step; similar to +a "binary search". If you have 10 cells (instances of modules) in your top +module, and have no idea what is causing the issue, split them into two groups +of 5 cells. For each group of cells, try remove them and see if the failure +still happens. If the error still occurs with the first group removed, but +disappears when the second group is removed, then the first group can be safely +removed. If a module has no more instances, remove it entirely. Repeat this +for each remaining group of cells until each group only has 1 cell in it and no +more cells can be removed without making the error disappear. You can also +repeat this for each module still in your design. + +After minimizing the number of cells, do the same for the process blocks in your +top module. And again for any generate blocks and combinational blocks. +Remember to check for any ports or signals which are no longer used and remove +those too. Any signals which are written but never read can also be removed. + +.. note:: + + Depending on where the design is failing, there are some commands which may + help in identifying unused objects in the design. `hierarchy` will identify + which modules are used and which are not, but check for ``$paramod`` modules + before removing unused ones. ``debug clean`` will list all unused wires in + each module, as well as unused cells which were automatically generated + (giving the line number of the source that generated them). Adding the + ``-purge`` flag will also include named wires that would normally be ignored + by `clean`. Though when there are large numbers of unused wires it is often + easier to just delete sections of the code and see what happens. + +Next, try to remove or reduce assignments (``a = b``) and operations (``a + +b``). A good place to start is by checking for any wires/registers which are +read but never written. Try removing the signal declaration and replacing +references to it with ``'0`` or ``'x``. Do this with any constants too. Try to +replace strings with numeric values, and wide signals with smaller ones, then +see if the error persists. + +Check if there are any operations that you can simplify, like replacing ``a & +'0`` with ``'0``. If you have enable or reset logic, try removing it and see if +the error still occurs. Try reducing ``if .. else`` and ``case`` blocks to a +single case. Even if that doesn't work, you may still be able to remove some +paths; start with cases that appear to be unreachable and go from there. + +.. note:: + + When sharing code on the `Yosys GitHub`_, please try to keep things in + English. Declarations and strings should stick to the letters a-z and + numbers 0-9, unless the error is arising because of the names/characters + used. + + +Identifying issues +------------------ + +When identifying issues, it is quite useful to understand the conditions under +which the issue is occurring. While there are occasionally bugs that affect a +significant number of designs, Yosys changes are tested on a variety of designs +and operating systems which typically catch any such issues before they make it +into the main branch. So what is is it about your situation that makes it +unusual? + +.. note:: + + If you have access to a different platform you could also check if your issue + is reproducible there. Some issues may be specific to the platform or build + of Yosys. + +Try to match the minimized design back to its original context. Could you +achieve the same thing a different way, and if so, does this other method have +the same issue? Try to change the design in small ways and see what happens; +while `bugpoint` can reduce and simplify a design, it doesn't *change* much. +What happens if you change operators, for example a left shift (or `$shl`) to a +right shift (or `$shr`)? Try to see if the issue is tied to specific +parameters, widths, or values. + +Search `the existing issues`_ and see if someone has already made a bug report. +This is where changing the design and finding the limits of what causes the +failure really comes in handy. If you're more familiar with how the problem can +arise, you may be able to find a related issue more easily. If an issue already +exists for one case of the problem but you've found other cases, you can comment +on the issue and help get it solved. If there are no existing or related issues +already, then check out the steps for +:ref:`yosys_internals/extending_yosys/contributing:reporting bugs`. + +.. _the existing issues: https://github.com/YosysHQ/yosys/issues + +.. warning:: + + If you are using a fuzzer to find bugs, follow the instructions for + :doc:`/yosys_internals/extending_yosys/advanced_bugpoint`. **Do not** open + more than one fuzzer generated issue at a time if you can not identify the + root cause. If you are found to be doing this, your issues may be closed + without further investigation. diff --git a/chips/yosys/docs/source/using_yosys/index.rst b/chips/yosys/docs/source/using_yosys/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..93dd3629b77116547665efa2497faafea33b93ed --- /dev/null +++ b/chips/yosys/docs/source/using_yosys/index.rst @@ -0,0 +1,20 @@ +Using Yosys (advanced) +====================== + +While much of Yosys is focused around synthesis, there are also a number of +other useful things that can be accomplished with Yosys scripts or in an +interactive shell. As such this section is broken into two parts: +:doc:`/using_yosys/synthesis/index` expands on the +:doc:`/getting_started/example_synth` and goes into further detail on the major +commands used in synthesis; :doc:`/using_yosys/more_scripting/index` covers the +ways Yosys can interact with designs for a deeper investigation. + +.. toctree:: + :maxdepth: 2 + :hidden: + + synthesis/index + more_scripting/index + bugpoint + verilog + pyosys diff --git a/chips/yosys/docs/source/using_yosys/more_scripting/data_flow_tracking.rst b/chips/yosys/docs/source/using_yosys/more_scripting/data_flow_tracking.rst new file mode 100644 index 0000000000000000000000000000000000000000..fa8d1be00538fa98cae50216379446f2a21b67a7 --- /dev/null +++ b/chips/yosys/docs/source/using_yosys/more_scripting/data_flow_tracking.rst @@ -0,0 +1,114 @@ +Dataflow tracking +------------------- + +Yosys can be used to answer questions such as "can this signal affect this other +signal?" via its *dataflow tracking* support. For this, four special cells, +`$get_tag`, `$set_tag`, `$overwrite_tag` and `$original_tag` are inserted into +the design (e.g. by a custom Yosys pass) and then the `dft_tag` is run, which +converts these cells into ordinary logic. Typically, one would then use `SBY`_ +to prove assertions involving these cells. + +.. _SBY: https://yosyshq.readthedocs.io/projects/sby + +Ordinarily in Yosys, the state of a bit is simply ``0`` or ``1`` (or one of the +special values, ``z`` and ``x``). During dataflow tracking they are augmented +with a set of tags. For example, the state of a bit could be ``0`` and the set +of tags ``"KEY"`` and ``"OVERFLOW"``. + +In addition to their usual operations on the logical bits, Yosys operations must +now also process the status of the tags. For this, tags are simply *forwarded* +or *propagated* (i.e. copied) from inputs to outputs, according to the following +general rule: + + A tag is forwarded from an input to an output if the input can affect the + output, for that particular state of all other inputs. + +For example, XOR, AND and OR cells propagate tags as follows: + +#. XOR simply forwards all tags from its inputs to its output, because inputs to + XOR can always affect the output. +#. AND forwards tags on a given input only if the other input is ``1``. Because + if one input is ``0``, the other input can never affect the output. +#. Similarly, OR forwards tags only if the other input is ``0``. + +There are two exceptions to this rule: + +#. In general, propagation is only determined approximately. For example, unless + the ``dft_tag`` code knows about a cell, it simply assumes the worst-case + behaviour that all inputs can affect all outputs. Further, the code also does + not consider that, when a signal affects multiple inputs of a cell, the + resulting simultaneous changes of the inputs can cancel each other out, for + example ``A ^ A`` or ``A ^ (B ^ A)`` is independent of ``A``, but its tags + would be propagated nonetheless. +#. If tag groups are used, the rules are modified (see below). + +Because of this propagation behaviour, we can answer questions about what +signals are affected by a certain signal, by injecting a tag at that point in +the circuit, and observing where the tag is visible. + +Example use cases +~~~~~~~~~~~~~~~~~~ + +As an example use case, consider a cryptographic processor which is not supposed +to expose its secret keys to the outside world. We can tag all key bits with the +``"KEY"`` tag and use `SBY`_ to formally verify that no external signal ever +carries the ``"KEY"`` tag, meaning that key information is not visible to the +outside. As a caveat, we have to manually clear the ``"KEY"`` tag during +cryptographic operations, as proving that the cryptographic operations +themselves do not leak key information is beyond the ability of Yosys. However +we can still easily detect, if e.g. an engineer forgot to remove debugging code +that allows reading back key data. + +As a different use case, we can modify all adders in the design to set the +``"OVERFLOW"`` tag on their output bits, if the addition overflowed, and then +add asserts to all flip-flop inputs and output signals that they do not carry +the ``"OVERFLOW"`` tag, i.e. that the results of overflowed additions never +affect system state. Note that in this particular example we use the ability of +tag insertion to be conditional on logic, in this case the overflow condition of +an adder. + +Semantics of dataflow tracking cells +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +``$set_tag`` has inputs ``A``, ``SET``, ``CLR``, an output ``Y`` and a string +parameter ``TAG``. The logic value of ``A`` and all tags other than the one +named by the ``TAG`` parameter are simply copied to ``Y``. If ``SET`` is ``1``, +then the named tag is added to ``Y``. Otherwise, if ``CLR`` is ``1``, then the +named tag is removed. Otherwise, the tag is unchanged, i.e. it is present in +``Y`` if it is present in ``A``. + +``$get_tag`` has an input ``A`` and an output ``Y`` and a string parameter +``TAG``. ``$get_tag`` inspects ``A`` for the presence or absence of a tag of the +given name and sets ``Y`` to ``1`` if the tag is present. The logical value of +``A`` is completely ignored. + +``$overwrite_tag`` functions like ``$set_tag``, but lacks the ``Y`` output. +Instead of providing a modified version of the input signal, it modifies the +signal ``A`` "in-place", i.e. if a signal is input to ``$overwrite_tag``, that +is equivalent to interposing a ``$set_tag`` between its driver and all cells it +is connected to. The main purpose of ``$overwrite_tag`` is adding tags to +signals produced within a module that cannot or should not be modified itself. + +``$original_tag`` functions identically to ``$get_tag``, but ignores +``$overwrite_tag``, i.e. when converting the ``$overwrite_tag`` to ``$set_tag`` +as described above, it is equivalent to inserting the ``$get_tag`` *before* the +``$set_tag``. + +Tag groups +~~~~~~~~~~~~~~ + +Tag groups are an advanced feature that modify the propagation rule discussed +above. To use tag groups, simply name tags according to the schema +``"group:name"``. For example, ``"key:0"``, ``"key:a"``, ``"key:b"`` would be +three tags in the ``"key"`` group. + +The propagation rule is then amended by + + Inputs cannot block the propagation of each other's tags for tags of the same + group. + +For example, an AND gate will propagate a given tag on one input, if the other +input is either 1 or carries a tag of the same group. So if one input is ``0, +"key:a"`` and the other is ``0, "key:b"`` the result would be ``0, "key:a", +"key:b"``, rather than simply ``0``. Note that if we add an unrelated +``"overflow"`` tag to the first input, it would still not be propagated. diff --git a/chips/yosys/docs/source/using_yosys/more_scripting/index.rst b/chips/yosys/docs/source/using_yosys/more_scripting/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..6265e5d0eee25ef295d8f5ca03560273b84af504 --- /dev/null +++ b/chips/yosys/docs/source/using_yosys/more_scripting/index.rst @@ -0,0 +1,17 @@ +More scripting +-------------- + +.. todo:: brief overview for the more scripting index + +.. todo:: troubleshooting document(?) + +.. toctree:: + :maxdepth: 3 + + load_design + selections + interactive_investigation + model_checking + data_flow_tracking + +.. troubleshooting diff --git a/chips/yosys/docs/source/using_yosys/more_scripting/interactive_investigation.rst b/chips/yosys/docs/source/using_yosys/more_scripting/interactive_investigation.rst new file mode 100644 index 0000000000000000000000000000000000000000..ae349bb214f00980efe874d7eafd32e3d4b25743 --- /dev/null +++ b/chips/yosys/docs/source/using_yosys/more_scripting/interactive_investigation.rst @@ -0,0 +1,808 @@ +Interactive design investigation +-------------------------------- + +.. todo:: interactive design opening text + +.. role:: yoscrypt(code) + :language: yoscrypt + +.. _interactive_show: + +A look at the show command +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. TODO:: merge into :doc:`/getting_started/scripting_intro` show section + +This section explores the `show` command and explains the symbols used in the +circuit diagrams generated by it. The code used is included in the Yosys code +base under |code_examples/show|_. + +.. |code_examples/show| replace:: :file:`docs/source/code_examples/show` +.. _code_examples/show: https://github.com/YosysHQ/yosys/tree/main/docs/source/code_examples/show + +A simple circuit +^^^^^^^^^^^^^^^^ + +:ref:`example_v` below provides the Verilog code for a simple circuit which we +will use to demonstrate the usage of `show` in a simple setting. + +.. literalinclude:: /code_examples/show/example.v + :language: Verilog + :caption: :file:`example.v` + :name: example_v + +The Yosys synthesis script we will be running is included as +:numref:`example_ys`. Note that `show` is called with the ``-pause`` option, +that halts execution of the Yosys script until the user presses the Enter key. +Using :yoscrypt:`show -pause` also allows the user to enter an interactive shell +to further investigate the circuit before continuing synthesis. + +.. literalinclude:: /code_examples/show/example_show.ys + :language: yoscrypt + :caption: :file:`example_show.ys` + :name: example_ys + +This script, when executed, will show the design after each of the three +synthesis commands. We will now look at each of these diagrams and explain what +is shown. + +.. note:: + + The images uses in this document are generated from the :file:`example.ys` + file, rather than :file:`example_show.ys`. :file:`example.ys` outputs the + schematics as :file:`.dot` files rather than displaying them directly. You + can view these images yourself by running :file:`yosys example.ys` and then + ``xdot example_first.dot`` etc. + +.. figure:: /_images/code_examples/show/example_first.* + :class: width-helper invert-helper + + Output of the first `show` command in :numref:`example_ys` + +The first output shows the design directly after being read by the Verilog +front-end. Input and output ports are displayed as octagonal shapes. Cells are +displayed as rectangles with inputs on the left and outputs on the right side. +The cell labels are two lines long: The first line contains a unique identifier +for the cell and the second line contains the cell type. Internal cell types are +prefixed with a dollar sign. For more details on the internal cell library, see +:doc:`/cell_index`. + +Constants are shown as ellipses with the constant value as label. The syntax +``'`` is used for constants that are not 32-bit wide and/or +contain bits that are not 0 or 1 (i.e. ``x`` or ``z``). Ordinary 32-bit +constants are written using decimal numbers. + +Single-bit signals are shown as thin arrows pointing from the driver to the +load. Signals that are multiple bits wide are shown as thick arrows. + +Finally *processes* are shown in boxes with round corners. Processes are Yosys' +internal representation of the decision-trees and synchronization events +modelled in a Verilog ``always``-block. The label reads ``PROC`` followed by a +unique identifier in the first line and contains the source code location of the +original ``always``-block in the second line. Note how the multiplexer from the +``?:``-expression is represented as a `$mux` cell but the multiplexer from the +``if``-statement is yet still hidden within the process. + +The `proc` command transforms the process from the first diagram into a +multiplexer and a d-type flip-flop, which brings us to the second diagram: + +.. figure:: /_images/code_examples/show/example_second.* + :class: width-helper invert-helper + + Output of the second `show` command in :numref:`example_ys` + +The Rhombus shape to the right is a dangling wire. (Wire nodes are only shown if +they are dangling or have "public" names, for example names assigned from the +Verilog input.) Also note that the design now contains two instances of a +``BUF``-node. These are artefacts left behind by the `proc` command. It is quite +usual to see such artefacts after calling commands that perform changes in the +design, as most commands only care about doing the transformation in the least +complicated way, not about cleaning up after them. The next call to `clean` (or +`opt`, which includes `clean` as one of its operations) will clean up these +artefacts. This operation is so common in Yosys scripts that it can simply be +abbreviated with the ``;;`` token, which doubles as separator for commands. +Unless one wants to specifically analyze this artefacts left behind some +operations, it is therefore recommended to always call `clean` before calling +`show`. + +In this script we directly call `opt` as the next step, which finally leads us +to the third diagram: + +.. figure:: /_images/code_examples/show/example_third.* + :class: width-helper invert-helper + :name: example_out + + Output of the third `show` command in :ref:`example_ys` + +Here we see that the `opt` command not only has removed the artifacts left +behind by `proc`, but also determined correctly that it can remove the first +`$mux` cell without changing the behavior of the circuit. + +Break-out boxes for signal vectors +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The code listing below shows a simple circuit which uses a lot of spliced signal +accesses. + +.. literalinclude:: /code_examples/show/splice.v + :caption: :file:`splice.v` + :name: splice_src + +Notice how the output for this circuit from the `show` command +(:numref:`splice_dia`) appears quite complex. This is an unfortunate side effect +of the way Yosys handles signal vectors (aka. multi-bit wires or buses) as +native objects. While this provides great advantages when analyzing circuits +that operate on wide integers, it also introduces some additional complexity +when the individual bits of of a signal vector are accessed. + +.. figure:: /_images/code_examples/show/splice.* + :class: width-helper invert-helper + :name: splice_dia + + Output of ``yosys -p 'prep -top splice_demo; show' splice.v`` + +The key elements in understanding this circuit diagram are of course the boxes +with round corners and rows labeled ``: - +:``. Each of these boxes have one signal per row on one +side and a common signal for all rows on the other side. The ``:`` +tuples specify which bits of the signals are broken out and connected. So the +top row of the box connecting the signals ``a`` and ``x`` indicates that the bit +0 (i.e. the range 0:0) from signal ``a`` is connected to bit 1 (i.e. the range +1:1) of signal ``x``. + +Lines connecting such boxes together and lines connecting such boxes to cell +ports have a slightly different look to emphasise that they are not actual +signal wires but a necessity of the graphical representation. This distinction +seems like a technicality, until one wants to debug a problem related to the way +Yosys internally represents signal vectors, for example when writing custom +Yosys commands. + +Gate level netlists +^^^^^^^^^^^^^^^^^^^ + +:numref:`first_pitfall` shows two common pitfalls when working with designs +mapped to a cell library: + +.. figure:: /_images/code_examples/show/cmos_00.* + :class: width-helper invert-helper + :name: first_pitfall + + A half-adder built from simple CMOS gates, demonstrating common pitfalls when + using `show` + +.. literalinclude:: /code_examples/show/cmos.ys + :language: yoscrypt + :start-after: pitfall + :end-at: cmos_00 + :name: pitfall_code + :caption: Generating :numref:`first_pitfall` + +First, Yosys did not have access to the cell library when this diagram was +generated, resulting in all cell ports defaulting to being inputs. This is why +all ports are drawn on the left side the cells are awkwardly arranged in a large +column. Secondly the two-bit vector ``y`` requires breakout-boxes for its +individual bits, resulting in an unnecessary complex diagram. + +.. figure:: /_images/code_examples/show/cmos_01.* + :class: width-helper invert-helper + :name: second_pitfall + + Effects of `splitnets` command and of providing a cell library on design in + :numref:`first_pitfall` + +.. literalinclude:: /code_examples/show/cmos.ys + :language: yoscrypt + :start-after: fixed + :end-at: cmos_01 + :name: pitfall_avoided + :caption: Generating :numref:`second_pitfall` + +For :numref:`second_pitfall`, Yosys has been given a description of the cell +library as Verilog file containing blackbox modules. There are two ways to load +cell descriptions into Yosys: First the Verilog file for the cell library can be +passed directly to the `show` command using the ``-lib `` option. +Secondly it is possible to load cell libraries into the design with the +:yoscrypt:`read_verilog -lib ` command. The second method has the +great advantage that the library only needs to be loaded once and can then be +used in all subsequent calls to the `show` command. + +In addition to that, :numref:`second_pitfall` was generated after +:yoscrypt:`splitnet -ports` was run on the design. This command splits all +signal vectors into individual signal bits, which is often desirable when +looking at gate-level circuits. The ``-ports`` option is required to also split +module ports. Per default the command only operates on interior signals. + +Miscellaneous notes +^^^^^^^^^^^^^^^^^^^ + +Per default the `show` command outputs a temporary dot file and launches +``xdot`` to display it. The options ``-format``, ``-viewer`` and ``-prefix`` can +be used to change format, viewer and filename prefix. Note that the ``pdf`` and +``ps`` format are the only formats that support plotting multiple modules in one +run. The ``dot`` format can be used to output multiple modules, however +``xdot`` will raise an error when trying to read them. + +In densely connected circuits it is sometimes hard to keep track of the +individual signal wires. For these cases it can be useful to call `show` with +the ``-colors `` argument, which randomly assigns colors to the nets. +The integer (> 0) is used as seed value for the random color assignments. +Sometimes it is necessary it try some values to find an assignment of colors +that looks good. + +The command :yoscrypt:`help show` prints a complete listing of all options +supported by the `show` command. + +Navigating the design +~~~~~~~~~~~~~~~~~~~~~ + +Plotting circuit diagrams for entire modules in the design brings us only helps +in simple cases. For complex modules the generated circuit diagrams are just +stupidly big and are no help at all. In such cases one first has to select the +relevant portions of the circuit. + +In addition to *what* to display one also needs to carefully decide *when* to +display it, with respect to the synthesis flow. In general it is a good idea to +troubleshoot a circuit in the earliest state in which a problem can be +reproduced. So if, for example, the internal state before calling the `techmap` +command already fails to verify, it is better to troubleshoot the coarse-grain +version of the circuit before `techmap` than the gate-level circuit after +`techmap`. + +.. Note:: + + It is generally recommended to verify the internal state of a design by + writing it to a Verilog file using :yoscrypt:`write_verilog -noexpr` and + using the simulation models from :file:`simlib.v` and :file:`simcells.v` from + the Yosys data directory (as printed by ``yosys-config --datdir``). + +Interactive navigation +^^^^^^^^^^^^^^^^^^^^^^ + +Once the right state within the synthesis flow for debugging the circuit has +been identified, it is recommended to simply add the `shell` command to the +matching place in the synthesis script. This command will stop the synthesis at +the specified moment and go to shell mode, where the user can interactively +enter commands. + +For most cases, the shell will start with the whole design selected (i.e. when +the synthesis script does not already narrow the selection). The command `ls` +can now be used to create a list of all modules. The command `cd` can be used to +switch to one of the modules (type ``cd ..`` to switch back). Now the `ls` +command lists the objects within that module. This is demonstrated below using +:file:`example.v` from `A simple circuit`_: + +.. literalinclude:: /code_examples/show/example.out + :language: doscon + :start-at: yosys> ls + :end-before: yosys [example]> dump + :caption: Output of `ls` and `cd` after running :file:`yosys example.v` + :name: lscd + +When a module is selected using the `cd` command, all commands (with a few +exceptions, such as the ``read_`` and ``write_`` commands) operate only on the +selected module. This can also be useful for synthesis scripts where different +synthesis strategies should be applied to different modules in the design. + +We can see that the cell names from :numref:`example_out` are just abbreviations +of the actual cell names, namely the part after the last dollar-sign. Most +auto-generated names (the ones starting with a dollar sign) are rather long and +contains some additional information on the origin of the named object. But in +most cases those names can simply be abbreviated using the last part. + +Usually all interactive work is done with one module selected using the `cd` +command. But it is also possible to work from the design-context (``cd ..``). In +this case all object names must be prefixed with ``/``. For example +``a*/b*`` would refer to all objects whose names start with ``b`` from all +modules whose names start with ``a``. + +The `dump` command can be used to print all information about an object. For +example, calling :yoscrypt:`dump $2` after the :yoscrypt:`cd example` above: + +.. literalinclude:: /code_examples/show/example.out + :language: RTLIL + :start-after: yosys [example]> dump + :end-before: yosys [example]> cd + :dedent: + :caption: Output of :yoscrypt:`dump $2` after :numref:`lscd` + :name: dump2 + +This can for example be useful to determine the names of nets connected to +cells, as the net-names are usually suppressed in the circuit diagram if they +are auto-generated. Note that the output is in the RTLIL representation, +described in :doc:`/yosys_internals/formats/rtlil_rep`. + +Design Investigation +~~~~~~~~~~~~~~~~~~~~ + +Yosys can also be used to investigate designs (or netlists created from other +tools). + +- The selection mechanism, especially patterns such as ``%ci`` and ``%co``, can + be used to figure out how parts of the design are connected. +- Commands such as `submod`, `expose`, and `splice` can be used to transform the + design into an equivalent design that is easier to analyse. +- Commands such as `eval` and `sat` can be used to investigate the behavior of + the circuit. +- :cmd:title:`show`. +- :cmd:title:`dump`. +- :cmd:title:`add` and :cmd:title:`delete` can be used to modify and reorganize + a design dynamically. + +The code used is included in the Yosys code base under +|code_examples/scrambler|_. + +.. |code_examples/scrambler| replace:: :file:`docs/source/code_examples/scrambler` +.. _code_examples/scrambler: https://github.com/YosysHQ/yosys/tree/main/docs/source/code_examples/scrambler + +Changing design hierarchy +^^^^^^^^^^^^^^^^^^^^^^^^^ + +Commands such as `flatten` and `submod` can be used to change the design +hierarchy, i.e. flatten the hierarchy or moving parts of a module to a +submodule. This has applications in synthesis scripts as well as in reverse +engineering and analysis. An example using `submod` is shown below for +reorganizing a module in Yosys and checking the resulting circuit. + +.. literalinclude:: /code_examples/scrambler/scrambler.v + :language: verilog + :caption: :file:`scrambler.v` + +.. literalinclude:: /code_examples/scrambler/scrambler.ys + :language: yoscrypt + :caption: :file:`scrambler.ys` + :end-before: cd .. + +.. figure:: /_images/code_examples/scrambler/scrambler_p01.* + :class: width-helper invert-helper + +.. figure:: /_images/code_examples/scrambler/scrambler_p02.* + :class: width-helper invert-helper + +Analyzing the resulting circuit with :cmd:title:`eval`: + +.. todo:: replace inline code + +.. code:: text + + > cd xorshift32 + > rename n2 in + > rename n1 out + + > eval -set in 1 -show out + Eval result: \out = 270369. + + > eval -set in 270369 -show out + Eval result: \out = 67634689. + + > sat -set out 632435482 + Signal Name Dec Hex Bin + -------------------- ---------- ---------- ------------------------------------- + \in 745495504 2c6f5bd0 00101100011011110101101111010000 + \out 632435482 25b2331a 00100101101100100011001100011010 + +Behavioral changes +^^^^^^^^^^^^^^^^^^ + +Commands such as `techmap` can be used to make behavioral changes to the design, +for example changing asynchronous resets to synchronous resets. This has +applications in design space exploration (evaluation of various architectures +for one circuit). + +The following techmap map file replaces all positive-edge async reset flip-flops +with positive-edge sync reset flip-flops. The code is taken from the example +Yosys script for ASIC synthesis of the Amber ARMv2 CPU. + +.. todo:: replace inline code + +.. code:: verilog + + (* techmap_celltype = "$adff" *) + module adff2dff (CLK, ARST, D, Q); + + parameter WIDTH = 1; + parameter CLK_POLARITY = 1; + parameter ARST_POLARITY = 1; + parameter ARST_VALUE = 0; + + input CLK, ARST; + input [WIDTH-1:0] D; + output reg [WIDTH-1:0] Q; + + wire [1023:0] _TECHMAP_DO_ = "proc"; + + wire _TECHMAP_FAIL_ = !CLK_POLARITY || !ARST_POLARITY; + + always @(posedge CLK) + if (ARST) + Q <= ARST_VALUE; + else + Q <= D; + + endmodule + +For more on the `techmap` command, see the page on +:doc:`/yosys_internals/techmap`. + +Advanced investigation techniques +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +When working with very large modules, it is often not enough to just select the +interesting part of the module. Instead it can be useful to extract the +interesting part of the circuit into a separate module. This can for example be +useful if one wants to run a series of synthesis commands on the critical part +of the module and wants to carefully read all the debug output created by the +commands in order to spot a problem. This kind of troubleshooting is much easier +if the circuit under investigation is encapsulated in a separate module. + +Recall the ``memdemo`` design from :ref:`advanced_logic_cones`: + +.. figure:: /_images/code_examples/selections/memdemo_00.* + :class: width-helper invert-helper + + ``memdemo`` + +Because this produces a rather large circuit, it can be useful to split it into +smaller parts for viewing and working with. :numref:`submod` does exactly that, +utilising the `submod` command to split the circuit into three sections: +``outstage``, ``selstage``, and ``scramble``. + +.. literalinclude:: /code_examples/selections/submod.ys + :language: yoscrypt + :caption: Using `submod` to break up the circuit from :file:`memdemo.v` + :start-after: cd memdemo + :end-before: cd .. + :name: submod + +The ``-name`` option is used to specify the name of the new module and also the +name of the new cell in the current module. The resulting circuits are shown +below. + +.. figure:: /_images/code_examples/selections/submod_02.* + :class: width-helper invert-helper + + ``outstage`` + +.. figure:: /_images/code_examples/selections/submod_03.* + :class: width-helper invert-helper + :name: selstage + + ``selstage`` + +.. figure:: /_images/code_examples/selections/submod_01.* + :class: width-helper invert-helper + + ``scramble`` + +Evaluation of combinatorial circuits +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The `eval` command can be used to evaluate combinatorial circuits. As an +example, we will use the ``selstage`` subnet of ``memdemo`` which we found above +and is shown in :numref:`selstage`. + +.. todo:: replace inline code + +:: + + yosys [selstage]> eval -set s2,s1 4'b1001 -set d 4'hc -show n2 -show n1 + + 1. Executing EVAL pass (evaluate the circuit given an input). + Full command line: eval -set s2,s1 4'b1001 -set d 4'hc -show n2 -show n1 + Eval result: \n2 = 2'10. + Eval result: \n1 = 2'10. + +So the ``-set`` option is used to set input values and the ``-show`` option is +used to specify the nets to evaluate. If no ``-show`` option is specified, all +selected output ports are used per default. + +If a necessary input value is not given, an error is produced. The option +``-set-undef`` can be used to instead set all unspecified input nets to undef +(``x``). + +The ``-table`` option can be used to create a truth table. For example: + +:: + + yosys [selstage]> eval -set-undef -set d[3:1] 0 -table s1,d[0] + + 10. Executing EVAL pass (evaluate the circuit given an input). + Full command line: eval -set-undef -set d[3:1] 0 -table s1,d[0] + + \s1 \d [0] | \n1 \n2 + ---- ------ | ---- ---- + 2'00 1'0 | 2'00 2'00 + 2'00 1'1 | 2'xx 2'00 + 2'01 1'0 | 2'00 2'00 + 2'01 1'1 | 2'xx 2'01 + 2'10 1'0 | 2'00 2'00 + 2'10 1'1 | 2'xx 2'10 + 2'11 1'0 | 2'00 2'00 + 2'11 1'1 | 2'xx 2'11 + + Assumed undef (x) value for the following signals: \s2 + +Note that the `eval` command (as well as the `sat` command discussed in the next +sections) does only operate on flattened modules. It can not analyze signals +that are passed through design hierarchy levels. So the `flatten` command must +be used on modules that instantiate other modules before these commands can be +applied. + +Solving combinatorial SAT problems +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Often the opposite of the `eval` command is needed, i.e. the circuits output is +given and we want to find the matching input signals. For small circuits with +only a few input bits this can be accomplished by trying all possible input +combinations, as it is done by the ``eval -table`` command. For larger circuits +however, Yosys provides the `sat` command that uses a `SAT`_ solver, `MiniSAT`_, +to solve this kind of problems. + +.. _SAT: http://en.wikipedia.org/wiki/Circuit_satisfiability + +.. _MiniSAT: http://minisat.se/ + +.. note:: + + While it is possible to perform model checking directly in Yosys, it + is highly recommended to use SBY or EQY for formal hardware verification. + +The `sat` command works very similar to the `eval` command. The main difference +is that it is now also possible to set output values and find the corresponding +input values. For Example: + +.. todo:: replace inline code + +:: + + yosys [selstage]> sat -show s1,s2,d -set s1 s2 -set n2,n1 4'b1001 + + 11. Executing SAT pass (solving SAT problems in the circuit). + Full command line: sat -show s1,s2,d -set s1 s2 -set n2,n1 4'b1001 + + Setting up SAT problem: + Import set-constraint: \s1 = \s2 + Import set-constraint: { \n2 \n1 } = 4'1001 + Final constraint equation: { \n2 \n1 \s1 } = { 4'1001 \s2 } + Imported 3 cells to SAT database. + Import show expression: { \s1 \s2 \d } + + Solving problem with 81 variables and 207 clauses.. + SAT solving finished - model found: + + Signal Name Dec Hex Bin + -------------------- ---------- ---------- --------------- + \d 9 9 1001 + \s1 0 0 00 + \s2 0 0 00 + +Note that the `sat` command supports signal names in both arguments to the +``-set`` option. In the above example we used ``-set s1 s2`` to constraint +``s1`` and ``s2`` to be equal. When more complex constraints are needed, a +wrapper circuit must be constructed that checks the constraints and signals if +the constraint was met using an extra output port, which then can be forced to a +value using the ``-set`` option. (Such a circuit that contains the circuit under +test plus additional constraint checking circuitry is called a ``miter`` +circuit.) + +.. literalinclude:: /code_examples/primetest.v + :language: verilog + :caption: :file:`primetest.v`, a simple miter circuit for testing if a number is + prime. But it has a problem. + :name: primetest + +:numref:`primetest` shows a miter circuit that is supposed to be used as a prime +number test. If ``ok`` is 1 for all input values ``a`` and ``b`` for a given +``p``, then ``p`` is prime, or at least that is the idea. + +.. todo:: replace inline code + +.. code-block:: + :caption: Experiments with the miter circuit from :file:`primetest.v`. + :name: prime_shell + + yosys [primetest]> sat -prove ok 1 -set p 31 + + 1. Executing SAT pass (solving SAT problems in the circuit). + Full command line: sat -prove ok 1 -set p 31 + + Setting up SAT problem: + Import set-constraint: \p = 16'0000000000011111 + Final constraint equation: \p = 16'0000000000011111 + Imported 6 cells to SAT database. + Import proof-constraint: \ok = 1'1 + Final proof equation: \ok = 1'1 + + Solving problem with 2790 variables and 8241 clauses.. + SAT proof finished - model found: FAIL! + + ______ ___ ___ _ _ _ _ + (_____ \ / __) / __) (_) | | | | + _____) )___ ___ ___ _| |__ _| |__ _____ _| | _____ __| | | + | ____/ ___) _ \ / _ (_ __) (_ __|____ | | || ___ |/ _ |_| + | | | | | |_| | |_| || | | | / ___ | | || ____( (_| |_ + |_| |_| \___/ \___/ |_| |_| \_____|_|\_)_____)\____|_| + + + Signal Name Dec Hex Bin + -------------------- ---------- ---------- --------------------- + \a 15029 3ab5 0011101010110101 + \b 4099 1003 0001000000000011 + \ok 0 0 0 + \p 31 1f 0000000000011111 + +The Yosys shell session shown in :numref:`prime_shell` demonstrates that SAT +solvers can even find the unexpected solutions to a problem: Using integer +overflow there actually is a way of "factorizing" 31. The clean solution would +of course be to perform the test in 32 bits, for example by replacing ``p != +a*b`` in the miter with ``p != {16'd0,a}b``, or by using a temporary variable +for the 32 bit product ``a*b``. But as 31 fits well into 8 bits (and as the +purpose of this document is to show off Yosys features) we can also simply force +the upper 8 bits of ``a`` and ``b`` to zero for the `sat` call, as is done +below. + +.. todo:: replace inline code + +.. code-block:: + :caption: Miter circuit from :file:`primetest.v`, with the upper 8 bits of ``a`` + and ``b`` constrained to prevent overflow. + :name: prime_fixed + + yosys [primetest]> sat -prove ok 1 -set p 31 -set a[15:8],b[15:8] 0 + + 1. Executing SAT pass (solving SAT problems in the circuit). + Full command line: sat -prove ok 1 -set p 31 -set a[15:8],b[15:8] 0 + + Setting up SAT problem: + Import set-constraint: \p = 16'0000000000011111 + Import set-constraint: { \a [15:8] \b [15:8] } = 16'0000000000000000 + Final constraint equation: { \a [15:8] \b [15:8] \p } = { 16'0000000000000000 16'0000000000011111 } + Imported 6 cells to SAT database. + Import proof-constraint: \ok = 1'1 + Final proof equation: \ok = 1'1 + + Solving problem with 2790 variables and 8257 clauses.. + SAT proof finished - no model found: SUCCESS! + + /$$$$$$ /$$$$$$$$ /$$$$$$$ + /$$__ $$ | $$_____/ | $$__ $$ + | $$ \ $$ | $$ | $$ \ $$ + | $$ | $$ | $$$$$ | $$ | $$ + | $$ | $$ | $$__/ | $$ | $$ + | $$/$$ $$ | $$ | $$ | $$ + | $$$$$$/ /$$| $$$$$$$$ /$$| $$$$$$$//$$ + \____ $$$|__/|________/|__/|_______/|__/ + \__/ + +The ``-prove`` option used in :numref:`prime_fixed` works similar to ``-set``, +but tries to find a case in which the two arguments are not equal. If such a +case is not found, the property is proven to hold for all inputs that satisfy +the other constraints. + +It might be worth noting, that SAT solvers are not particularly efficient at +factorizing large numbers. But if a small factorization problem occurs as part +of a larger circuit problem, the Yosys SAT solver is perfectly capable of +solving it. + +Solving sequential SAT problems +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The SAT solver functionality in Yosys can not only be used to solve +combinatorial problems, but can also solve sequential problems. Let's consider +the ``memdemo`` design from :ref:`advanced_logic_cones` again, and suppose we +want to know which sequence of input values for ``d`` will cause the output y to +produce the sequence 1, 2, 3 from any initial state. Let's use the following +command: + +.. todo:: replace inline code? + +.. code-block:: yoscrypt + + sat -seq 6 -show y -show d -set-init-undef \ + -max_undef -set-at 4 y 1 -set-at 5 y 2 -set-at 6 y 3 + +The ``-seq 6`` option instructs the `sat` command to solve a sequential problem +in 6 time steps. (Experiments with lower number of steps have show that at least +3 cycles are necessary to bring the circuit in a state from which the sequence +1, 2, 3 can be produced.) + +The ``-set-init-undef`` option tells the `sat` command to initialize all +registers to the undef (``x``) state. The way the ``x`` state is treated in +Verilog will ensure that the solution will work for any initial state. + +The ``-max_undef`` option instructs the `sat` command to find a solution with a +maximum number of undefs. This way we can see clearly which inputs bits are +relevant to the solution. + +Finally the three ``-set-at`` options add constraints for the ``y`` signal to +play the 1, 2, 3 sequence, starting with time step 4. + +This produces the following output: + +.. todo:: replace inline code + +.. code-block:: + :caption: Solving a sequential SAT problem in the ``memdemo`` module. + :name: memdemo_sat + + yosys [memdemo]> sat -seq 6 -show y -show d -set-init-undef \ + -max_undef -set-at 4 y 1 -set-at 5 y 2 -set-at 6 y 3 + + 1. Executing SAT pass (solving SAT problems in the circuit). + Full command line: sat -seq 6 -show y -show d -set-init-undef + -max_undef -set-at 4 y 1 -set-at 5 y 2 -set-at 6 y 3 + + Setting up time step 1: + Final constraint equation: { } = { } + Imported 29 cells to SAT database. + + Setting up time step 2: + Final constraint equation: { } = { } + Imported 29 cells to SAT database. + + Setting up time step 3: + Final constraint equation: { } = { } + Imported 29 cells to SAT database. + + Setting up time step 4: + Import set-constraint for timestep: \y = 4'0001 + Final constraint equation: \y = 4'0001 + Imported 29 cells to SAT database. + + Setting up time step 5: + Import set-constraint for timestep: \y = 4'0010 + Final constraint equation: \y = 4'0010 + Imported 29 cells to SAT database. + + Setting up time step 6: + Import set-constraint for timestep: \y = 4'0011 + Final constraint equation: \y = 4'0011 + Imported 29 cells to SAT database. + + Setting up initial state: + Final constraint equation: { \y \s2 \s1 \mem[3] \mem[2] \mem[1] + \mem[0] } = 24'xxxxxxxxxxxxxxxxxxxxxxxx + + Import show expression: \y + Import show expression: \d + + Solving problem with 10322 variables and 27881 clauses.. + SAT model found. maximizing number of undefs. + SAT solving finished - model found: + + Time Signal Name Dec Hex Bin + ---- -------------------- ---------- ---------- --------------- + init \mem[0] -- -- xxxx + init \mem[1] -- -- xxxx + init \mem[2] -- -- xxxx + init \mem[3] -- -- xxxx + init \s1 -- -- xx + init \s2 -- -- xx + init \y -- -- xxxx + ---- -------------------- ---------- ---------- --------------- + 1 \d 0 0 0000 + 1 \y -- -- xxxx + ---- -------------------- ---------- ---------- --------------- + 2 \d 1 1 0001 + 2 \y -- -- xxxx + ---- -------------------- ---------- ---------- --------------- + 3 \d 2 2 0010 + 3 \y 0 0 0000 + ---- -------------------- ---------- ---------- --------------- + 4 \d 3 3 0011 + 4 \y 1 1 0001 + ---- -------------------- ---------- ---------- --------------- + 5 \d -- -- 001x + 5 \y 2 2 0010 + ---- -------------------- ---------- ---------- --------------- + 6 \d -- -- xxxx + 6 \y 3 3 0011 + +It is not surprising that the solution sets ``d = 0`` in the first step, as this +is the only way of setting the ``s1`` and ``s2`` registers to a known value. The +input values for the other steps are a bit harder to work out manually, but the +SAT solver finds the correct solution in an instant. + +There is much more to write about the `sat` command. For example, there is a set +of options that can be used to performs sequential proofs using temporal +induction :cite:p:`een2003temporal`. The command ``help sat`` can be used to +print a list of all options with short descriptions of their functions. diff --git a/chips/yosys/docs/source/using_yosys/more_scripting/load_design.rst b/chips/yosys/docs/source/using_yosys/more_scripting/load_design.rst new file mode 100644 index 0000000000000000000000000000000000000000..7ef1fd58edf0a80f54943bebe66857406be2aea5 --- /dev/null +++ b/chips/yosys/docs/source/using_yosys/more_scripting/load_design.rst @@ -0,0 +1,156 @@ +Loading a design +---------------- + +.. _input files: + +Input files on the command line +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +- guesses frontend based on file extension + + + ``.v`` -> ``read -vlog2k`` + + ``.sv`` -> ``read -sv`` + + ``.vhd`` and ``.vhdl`` -> ``read -vhdl`` + + ``.blif`` and ``.eblif`` -> `read_blif` + + ``.json`` -> `read_json` + + ``.il`` -> `read_rtlil` (direct textual representation of Yosys internal + state) + +- command line also supports + + + ``.ys`` -> `script` + + ``.tcl`` -> `tcl` + + ``-`` -> reads stdin and treats it as a script + +The `read` command +~~~~~~~~~~~~~~~~~~ + +- standard method of loading designs +- also for defining macros and include directories +- uses `verific` command if available + + + ``-verific`` and ``-noverific`` options to enforce with/without Verific + + check ``help read`` for more about the options available and the filetypes + supported + + elaborate designs with ``verific -import [options] `` (or use + `hierarchy`) + +- fallback to `read_verilog` with ``-defer`` option + + + does not compile design until `hierarchy` command as discussed in + :doc:`/getting_started/example_synth` + + more similar to `verific` behaviour + +- ``read -define`` et al mapped to `verific` or `verilog_defines` +- similarly, ``read -incdir`` et al mapped to `verific` or `verilog_defaults` + +.. note:: + + The Verific frontend for Yosys, which provides the :cmd:ref:`verific` + command, requires Yosys to be built with Verific. For full functionality, + custom modifications to the Verific source code from YosysHQ are required, + but limited useability can be achieved with some stock Verific builds. Check + :doc:`/yosys_internals/extending_yosys/build_verific` for more. + +.. _Frontend: + +Yosys frontends +~~~~~~~~~~~~~~~ + +- :doc:`/cmd/index_frontends` +- typically start with ``read_`` +- built-in support for heredocs + + + in-line code with ``</`` prefix. For example: + +.. code:: yoscrypt + + cd foo # switch to module foo + delete bar # delete object foo/bar + + cd mycpu # switch to module mycpu + dump reg_* # print details on all objects whose names start with reg_ + + cd .. # switch back to design + +Note: Most synthesis scripts never switch to module context. But it is a very +powerful tool which we explore more in +:doc:`/using_yosys/more_scripting/interactive_investigation`. + +Selecting by object property or type +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Special patterns can be used to select by object property or type. For example: + +- select all wires whose names start with ``reg_``: :yoscrypt:`select w:reg_*` +- select all objects with the attribute ``foobar`` set: :yoscrypt:`select + a:foobar` +- select all objects with the attribute ``foobar`` set to 42: :yoscrypt:`select + a:foobar=42` +- select all modules with the attribute ``blabla`` set: :yoscrypt:`select + A:blabla` +- select all `$add` cells from the module foo: :yoscrypt:`select foo/t:$add` + +A complete list of pattern expressions can be found in :cmd:title:`select`. + +Operations on selections +~~~~~~~~~~~~~~~~~~~~~~~~ + +Combining selections +^^^^^^^^^^^^^^^^^^^^ + +The `select` command is actually much more powerful than it might seem at first +glance. When it is called with multiple arguments, each argument is evaluated +and pushed separately on a stack. After all arguments have been processed it +simply creates the union of all elements on the stack. So :yoscrypt:`select +t:$add a:foo` will select all `$add` cells and all objects with the ``foo`` +attribute set: + +.. literalinclude:: /code_examples/selections/foobaraddsub.v + :caption: Test module for operations on selections + :name: foobaraddsub + :language: verilog + +.. code-block:: + :caption: Output for command ``select t:$add a:foo -list`` on :numref:`foobaraddsub` + + yosys> select t:$add a:foo -list + foobaraddsub/$add$foobaraddsub.v:6$3 + foobaraddsub/$sub$foobaraddsub.v:5$2 + foobaraddsub/$add$foobaraddsub.v:4$1 + +In many cases simply adding more and more stuff to the selection is an +ineffective way of selecting the interesting part of the design. Special +arguments can be used to combine the elements on the stack. For example the +``%i`` arguments pops the last two elements from the stack, intersects them, and +pushes the result back on the stack. So :yoscrypt:`select t:$add a:foo %i` will +select all `$add` cells that have the ``foo`` attribute set: + +.. code-block:: + :caption: Output for command ``select t:$add a:foo %i -list`` on :numref:`foobaraddsub` + + yosys> select t:$add a:foo %i -list + foobaraddsub/$add$foobaraddsub.v:4$1 + +Some of the special ``%``-codes: + +- ``%u``: union of top two elements on stack -- pop 2, push 1 +- ``%d``: difference of top two elements on stack -- pop 2, push 1 +- ``%i``: intersection of top two elements on stack -- pop 2, push 1 +- ``%n``: inverse of top element on stack -- pop 1, push 1 + +See :cmd:title:`select` for the full list. + +Expanding selections +^^^^^^^^^^^^^^^^^^^^ + +:numref:`sumprod` uses the Yosys non-standard ``{... *}`` syntax to set the +attribute ``sumstuff`` on all cells generated by the first assign statement. +(This works on arbitrary large blocks of Verilog code and can be used to mark +portions of code for analysis.) + +.. literalinclude:: /code_examples/selections/sumprod.v + :caption: Another test module for operations on selections + :name: sumprod + :language: verilog + +Selecting ``a:sumstuff`` in this module will yield the following circuit +diagram: + +.. figure:: /_images/code_examples/selections/sumprod_00.* + :class: width-helper invert-helper + :name: sumprod_00 + + Output of ``show a:sumstuff`` on :numref:`sumprod` + +As only the cells themselves are selected, but not the temporary wire ``$1_Y``, +the two adders are shown as two disjunct parts. This can be very useful for +global signals like clock and reset signals: just unselect them using a command +such as :yoscrypt:`select -del clk rst` and each cell using them will get its +own net label. + +In this case however we would like to see the cells connected properly. This can +be achieved using the ``%x`` action, that broadens the selection, i.e. for each +selected wire it selects all cells connected to the wire and vice versa. So +:yoscrypt:`show a:sumstuff %x` yields the diagram shown in :numref:`sumprod_01`: + +.. figure:: /_images/code_examples/selections/sumprod_01.* + :class: width-helper invert-helper + :name: sumprod_01 + + Output of ``show a:sumstuff %x`` on :numref:`sumprod` + +.. _selecting_logic_cones: + +Selecting logic cones +^^^^^^^^^^^^^^^^^^^^^ + +:numref:`sumprod_01` shows what is called the ``input cone`` of ``sum``, i.e. +all cells and signals that are used to generate the signal ``sum``. The ``%ci`` +action can be used to select the input cones of all object in the top selection +in the stack maintained by the `select` command. + +As with the ``%x`` action, these commands broaden the selection by one "step". +But this time the operation only works against the direction of data flow. That +means, wires only select cells via output ports and cells only select wires via +input ports. + +The following sequence of diagrams demonstrates this step-wise expansion: + +.. figure:: /_images/code_examples/selections/sumprod_02.* + :class: width-helper invert-helper + + Output of :yoscrypt:`show prod` on :numref:`sumprod` + +.. figure:: /_images/code_examples/selections/sumprod_03.* + :class: width-helper invert-helper + + Output of :yoscrypt:`show prod %ci` on :numref:`sumprod` + +.. figure:: /_images/code_examples/selections/sumprod_04.* + :class: width-helper invert-helper + + Output of :yoscrypt:`show prod %ci %ci` on :numref:`sumprod` + +.. figure:: /_images/code_examples/selections/sumprod_05.* + :class: width-helper invert-helper + + Output of :yoscrypt:`show prod %ci %ci %ci` on :numref:`sumprod` + +Notice the subtle difference between :yoscrypt:`show prod %ci` and +:yoscrypt:`show prod %ci %ci`. Both images show the `$mul` cell driven by some +inputs ``$3_Y`` and ``c``. However it is not until the second image, having +called ``%ci`` the second time, that `show` is able to distinguish between +``$3_Y`` being a wire and ``c`` being an input. We can see this better with the +`dump` command instead: + +.. literalinclude:: /code_examples/selections/sumprod.out + :language: RTLIL + :end-at: end + :caption: Output of :yoscrypt:`dump prod %ci` + +.. literalinclude:: /code_examples/selections/sumprod.out + :language: RTLIL + :start-after: end + :caption: Output of :yoscrypt:`dump prod %ci %ci` + +When selecting many levels of logic, repeating ``%ci`` over and over again can +be a bit dull. So there is a shortcut for that: the number of iterations can be +appended to the action. So for example the action ``%ci3`` is identical to +performing the ``%ci`` action three times. + +The action ``%ci*`` performs the ``%ci`` action over and over again until it has +no effect anymore. + +.. _advanced_logic_cones: + +Advanced logic cone selection +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +In most cases there are certain cell types and/or ports that should not be +considered for the ``%ci`` action, or we only want to follow certain cell types +and/or ports. This can be achieved using additional patterns that can be +appended to the ``%ci`` action. + +Lets consider :numref:`memdemo_src`. It serves no purpose other than being a +non-trivial circuit for demonstrating some of the advanced Yosys features. This +code is available in ``docs/source/code_examples/selections`` of the Yosys +source repository. + +.. literalinclude:: /code_examples/selections/memdemo.v + :caption: :file:`memdemo.v` + :name: memdemo_src + :language: verilog + +The script :file:`memdemo.ys` is used to generate the images included here. +Let's look at the first section: + +.. literalinclude:: /code_examples/selections/memdemo.ys + :caption: Synthesizing :ref:`memdemo_src` + :name: memdemo_ys + :language: yoscrypt + :end-at: opt + +This loads :numref:`memdemo_src` and synthesizes the included module. Note that +this code can be copied and run directly in a Yosys command line session, +provided :file:`memdemo.v` is in the same directory. We can now change to the +``memdemo`` module with ``cd memdemo``, and call `show` to see the diagram in +:numref:`memdemo_00`. + +.. figure:: /_images/code_examples/selections/memdemo_00.* + :class: width-helper invert-helper + :name: memdemo_00 + + Complete circuit diagram for the design shown in :numref:`memdemo_src` + +There's a lot going on there, but maybe we are only interested in the tree of +multiplexers that select the output value. Let's start by just showing the +output signal, ``y``, and its immediate predecessors. Remember `Selecting logic +cones`_ from above, we can use :yoscrypt:`show y %ci2`: + +.. figure:: /_images/code_examples/selections/memdemo_01.* + :class: width-helper invert-helper + :name: memdemo_01 + + Output of :yoscrypt:`show y %ci2` + +From this we would learn that ``y`` is driven by a `$dff` cell, that ``y`` is +connected to the output port ``Q``, that the ``clk`` signal goes into the +``CLK`` input port of the cell, and that the data comes from an auto-generated +wire into the input ``D`` of the flip-flop cell (indicated by the ``$`` at the +start of the name). Let's go a bit further now and try :yoscrypt:`show y %ci5`: + +.. figure:: /_images/code_examples/selections/memdemo_02.* + :class: width-helper invert-helper + :name: memdemo_02 + + Output of :yoscrypt:`show y %ci5` + +That's starting to get a bit messy, so maybe we want to ignore the mux select +inputs. To add a pattern we add a colon followed by the pattern to the ``%ci`` +action. The pattern itself starts with ``-`` or ``+``, indicating if it is an +include or exclude pattern, followed by an optional comma separated list of cell +types, followed by an optional comma separated list of port names in square +brackets. In this case, we want to exclude the ``S`` port of the `$mux` cell +type with :yoscrypt:`show y %ci5:-$mux[S]`: + +.. figure:: /_images/code_examples/selections/memdemo_03.* + :class: width-helper invert-helper + :name: memdemo_03 + + Output of :yoscrypt:`show y %ci5:-$mux[S]` + +We could use a command such as :yoscrypt:`show y %ci2:+$dff[Q,D] +%ci*:-$mux[S]:-$dff` in which the first ``%ci`` jumps over the initial d-type +flip-flop and the 2nd action selects the entire input cone without going over +multiplexer select inputs and flip-flop cells: + +.. figure:: /_images/code_examples/selections/memdemo_05.* + :class: width-helper invert-helper + :name: memdemo_05 + + Output of ``show y %ci2:+$dff[Q,D] %ci*:-$mux[S]:-$dff`` + +Or we could use :yoscrypt:`show y %ci*:-[CLK,S]:+$dff:+$mux` instead, following +the input cone all the way but only following `$dff` and `$mux` cells, and +ignoring any ports named ``CLK`` or ``S``: + +.. TODO:: pending discussion on whether rule ordering is a bug or a feature + +.. figure:: /_images/code_examples/selections/memdemo_04.* + :class: width-helper invert-helper + :name: memdemo_04 + + Output of :yoscrypt:`show y %ci*:-[CLK,S]:+$dff,$mux` + +Similar to ``%ci`` exists an action ``%co`` to select output cones that accepts +the same syntax for pattern and repetition. The ``%x`` action mentioned +previously also accepts this advanced syntax. + +These actions for traversing the circuit graph, combined with the actions for +boolean operations such as intersection (``%i``) and difference (``%d``) are +powerful tools for extracting the relevant portions of the circuit under +investigation. + +Again, see :cmd:title:`select` for full documentation of these expressions. + +Incremental selection +^^^^^^^^^^^^^^^^^^^^^ + +Sometimes a selection can most easily be described by a series of add/delete +operations. As mentioned previously, the commands :yoscrypt:`select -add` and +:yoscrypt:`select -del` respectively add or remove objects from the current +selection instead of overwriting it. + +.. code:: yoscrypt + + select -none # start with an empty selection + select -add reg_* # select a bunch of objects + select -del reg_42 # but not this one + select -add state %ci # and add more stuff + +Within a select expression the token ``%`` can be used to push the previous +selection on the stack. + +.. code:: yoscrypt + + select t:$add t:$sub # select all $add and $sub cells + select % %ci % %d # select only the input wires to those cells + +Storing and recalling selections +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. todo:: reflow for not presentation + +The current selection can be stored in memory with the command ``select -set +``. It can later be recalled using ``select @``. In fact, the +``@`` expression pushes the stored selection on the stack maintained by +the `select` command. So for example :yoscrypt:`select @foo @bar %i` will select +the intersection between the stored selections ``foo`` and ``bar``. + +In larger investigation efforts it is highly recommended to maintain a script +that sets up relevant selections, so they can easily be recalled, for example +when Yosys needs to be re-run after a design or source code change. + +The `history` command can be used to list all recent interactive commands. This +feature can be useful for creating such a script from the commands used in an +interactive session. + +Remember that select expressions can also be used directly as arguments to most +commands. Some commands also accept a single select argument to some options. In +those cases selection variables must be used to capture more complex selections. + +Example code from |code_examples/selections|_: + +.. |code_examples/selections| replace:: :file:`docs/source/code_examples/selections` +.. _code_examples/selections: https://github.com/YosysHQ/yosys/tree/main/docs/source/code_examples/selections + +.. literalinclude:: /code_examples/selections/select.v + :language: verilog + :caption: :file:`select.v` + +.. literalinclude:: /code_examples/selections/select.ys + :language: yoscrypt + :caption: :file:`select.ys` + :name: select_ys + +.. figure:: /_images/code_examples/selections/select.* + :class: width-helper invert-helper + + Circuit diagram produced by :numref:`select_ys` diff --git a/chips/yosys/docs/source/using_yosys/pyosys.rst b/chips/yosys/docs/source/using_yosys/pyosys.rst new file mode 100644 index 0000000000000000000000000000000000000000..b059516e12818c1569d25f7601f74fb3a978634e --- /dev/null +++ b/chips/yosys/docs/source/using_yosys/pyosys.rst @@ -0,0 +1,222 @@ +Scripting with Pyosys +===================== + +.. TODO:: document libyosys sans python + +Pyosys is a limited subset of the Yosys C++ API (aka "libyosys") made available +using the Python programming language. + +Like ``.ys`` and ``.tcl`` scripts, Pyosys provides an interface to write Yosys +scripts in the Python programming language, giving you the benefits of +a type system, control flow, object-oriented programming, and more; especially +that the other options lack a type system and control flow/OOP in Tcl is +limited. + +Though unlike these two, Pyosys goes a bit further, allowing you to use the +Yosys API to implement advanced functionality that would otherwise require +custom passes written in C++. + +.. note:: + + It is recommended to install :program:`uv` for managing python environments: + + .. code:: console + + curl -LsSf https://astral.sh/uv/install.sh | sh + +Getting Pyosys +-------------- + +Pyosys supports CPython 3.8 or higher. You can access Pyosys using one of two +methods: + +1. Compiling Yosys with the CMake flag ``-DYOSYS_WITH_PYTHON=ON`` + + This adds the flag ``-y`` to the Yosys binary, which allows you to execute + Python scripts using an interpreter embedded in Yosys itself: + + ``yosys -y ./my_pyosys_script.py`` + + Do note this requires some build-time dependencies to be available to Python, + namely, ``pybind11`` and ``cxxheaderparser``. :program:`uv` may be used to + create an ephemeral environment with the correct versions of the tools + installed if the current python environment doesn't provide them. + +2. Installing the Pyosys wheels + + On macOS and GNU/Linux you can install pre-built wheels of Yosys using + ``pip``: + + ``python3 -m pip install pyosys`` + + Which then allows you to run your scripts as follows: + + ``python3 ./my_pyosys_script.py`` + + +Scripting and Database Inspection +--------------------------------- + +To start with, you have to import libyosys as follows: + +.. code-block:: python + + from pyosys import libyosys + + +As a reminder, Python allows you to alias imported modules and objects, so +this import may be preferable for terseness: + +.. code-block:: python + + from pyosys import libyosys as ys + + +Now, scripting is actually quite similar to ``.ys`` and ``.tcl`` script in that +you can provide mostly text commands. Albeit, you can construct your scripts +to use Python's amenities like conditional execution, loops, and functions: + +.. code-block:: python + + do_flatten = True + + ys.run_pass("read_verilog tests/simple/fiedler-cooley.v") + ys.run_pass("hierarchy -check -auto-top") + if do_flatten: + ys.run_pass("flatten") + +…but this does not strictly provide anything that Tcl scripts do not provide you +with. The real power of using Pyosys comes from the fact you can manually +instantiate, manage, and interact with the design database. + +As an example, here is the same script with a manually instantiated design. + +.. literalinclude:: /code_examples/pyosys/simple_database.py + :start-after: loading design + :end-before: top module inspection + :language: python + +What's new here is that you can manually inspect the design's database. This +gives you access to a huge chunk of the design database API as declared in +the ``kernel/rtlil.h`` header. + +For example, here's how to list the input and output ports of the top module +of your design: + +.. literalinclude:: /code_examples/pyosys/simple_database.py + :start-after: top module inspection + :end-before: # synth + :language: python + +.. tip:: + + C++ data structures in Yosys are bridged to Python such that they have a + pretty similar API to Python objects, for example: + + - ``std::vector`` supports the same methods as + `iterables `_ in + Python. + - ``std::set`` and hashlib ``pool`` support the same methods as ``set``\s in + Python. While ``set`` is ordered, ``pool`` is not and modifications may + cause a complete reordering of the set. + - ``dict`` supports the same methods as ``dict``\s in Python, albeit it is + unordered, and modifications may cause a complete reordering of the + dictionary. + - ``idict`` uses a custom set of methods because it doesn't map very cleanly + to an existing Python data structure. See ``pyosys/hashlib.h`` for more + info. + + For most operations, the Python equivalents are also supported as arguments + where they will automatically be cast to the right type, so you do not have + to manually instantiate the right underlying C++ object(s) yourself. + +Modifying the Database +---------------------- + +.. warning:: + + Any modifications to the database may invalidate previous references held + by Python, just as if you were writing C++. Pyosys does not currently attempt + to keep deleted objects alive if a reference is held by Python. + +You are not restricted to inspecting the database either: you have the ability +to modify it, and introduce new elements and/or changes to your design. + +As a demonstrative example, let's assume we want to add an enable line to all +flip-flops in our fiedler-cooley design. + +First of all, we will run :yoscrypt:`synth` to convert all of the logic to +Yosys's internal cell structure (see :ref:`sec:celllib_gates`): + +.. literalinclude:: /code_examples/pyosys/simple_database.py + :start-after: # synth + :end-before: adding the enable line + :language: python + +Next, we need to add the new port. The method for this is ``Module::addWire``\. + +.. tip:: + + IdString is Yosys's internal representation of strings used as identifiers + within Verilog designs. They are efficient as only integers are stored and + passed around, but they can be translated to and from normal strings at will. + + Pyosys will automatically cast Python strings to IdStrings for you, but the + rules around IdStrings apply, namely that *broadly*: + + - Identifiers for internal cells must start with ``$``\. + - All other identifiers must start with ``\``\. + +.. literalinclude:: /code_examples/pyosys/simple_database.py + :start-after: adding the enable line + :end-before: hooking the enable line + :language: python + +Notice how we modified the wire then called a method to make Yosys re-process +the ports. + +Next, we can iterate over all constituent cells, and if they are of the type +``$_DFF_P_``, we do two things: + +1. Change their type to ``$_DFFE_PP_`` to enable hooking up an enable signal. +2. Hooking up the enable signal. + +.. literalinclude:: /code_examples/pyosys/simple_database.py + :start-after: hooking the enable line + :end-before: run check + :language: python + +To verify that you did everything correctly, it is prudent to call ``.check()`` +on the module you're manipulating as follows after you're done with a set of +changes: + +.. literalinclude:: /code_examples/pyosys/simple_database.py + :start-after: run check + :end-before: write output + :language: python + +And then finally, write your outputs. Here, I choose an intermediate Verilog +file and :yoscrypt:`synth_ice40` to map it to the iCE40 architecture. + +.. literalinclude:: /code_examples/pyosys/simple_database.py + :start-after: write output + :language: python + +And voilà, you will note that in the intermediate output, all ``always @`` +statements should have an ``if (enable)``\. + +Encapsulating as Passes +----------------------- + +Just like when writing C++, you can encapsulate routines in terms of "passes", +which adds your Pass to a global registry of commands accessible using +``run_pass``\. + +.. literalinclude:: /code_examples/pyosys/pass.py + :language: python + +In general, abstract classes and virtual methods are not really supported by +Pyosys due to their complexity, but there are two exceptions which are: + +- ``Pass`` in ``kernel/register.h`` +- ``Monitor`` in ``kernel/rtlil.h`` diff --git a/chips/yosys/docs/source/using_yosys/synthesis/abc.rst b/chips/yosys/docs/source/using_yosys/synthesis/abc.rst new file mode 100644 index 0000000000000000000000000000000000000000..086205f639192a9c35862a0f1e3bd995f7c28cb9 --- /dev/null +++ b/chips/yosys/docs/source/using_yosys/synthesis/abc.rst @@ -0,0 +1,180 @@ +The ABC toolbox +=============== + +.. role:: yoscrypt(code) + :language: yoscrypt + +ABC_, from the University of California, Berkeley, is a logic toolbox used for +fine-grained optimisation and LUT mapping. + +Yosys has two different commands, which both use this logic toolbox, but use it +in different ways. + +The `abc` pass can be used for both ASIC (e.g. :yoscrypt:`abc -liberty`) and +FPGA (:yoscrypt:`abc -lut`) mapping, but this page will focus on FPGA mapping. + +The `abc9` pass generally provides superior mapping quality due to being aware +of combination boxes and DFF and LUT timings, giving it a more global view of +the mapping problem. + +.. _ABC: https://github.com/berkeley-abc/abc + +ABC: the unit delay model, simple and efficient +----------------------------------------------- + +The `abc` pass uses a highly simplified view of an FPGA: + +- An FPGA is made up of a network of inputs that connect through LUTs to a + network of outputs. These inputs may actually be I/O pins, D flip-flops, + memory blocks or DSPs, but ABC is unaware of this. +- Each LUT has 1 unit of delay between an input and its output, and this applies + for all inputs of a LUT, and for all sizes of LUT up to the maximum LUT size + allowed; e.g. the delay between the input of a LUT2 and its output is the same + as the delay between the input of a LUT6 and its output. +- A LUT may take up a variable number of area units. This is constant for each + size of LUT; e.g. a LUT4 may take up 1 unit of area, but a LUT5 may take up 2 + units of area, but this applies for all LUT4s and LUT5s. + +This is known as the "unit delay model", because each LUT uses one unit of +delay. + +From this view, the problem ABC has to solve is finding a mapping of the network +to LUTs that has the lowest delay, and then optimising the mapping for size +while maintaining this delay. + +This approach has advantages: + +- It is simple and easy to implement. +- Working with unit delays is fast to manipulate. +- It reflects *some* FPGA families, for example, the iCE40HX/LP fits the + assumptions of the unit delay model quite well (almost all synchronous blocks, + except for adders). + +But this approach has drawbacks, too: + +- The network of inputs and outputs with only LUTs means that a lot of + combinational cells (multipliers and LUTRAM) are invisible to the unit delay + model, meaning the critical path it optimises for is not necessarily the + actual critical path. +- LUTs are implemented as multiplexer trees, so there is a delay caused by the + result propagating through the remaining multiplexers. This means the + assumption of delay being equal isn't true in physical hardware, and is + proportionally larger for larger LUTs. +- Even synchronous blocks have arrival times (propagation delay between clock + edge to output changing) and setup times (requirement for input to be stable + before clock edge) which affect the delay of a path. + +ABC9: the generalised delay model, realistic and flexible +--------------------------------------------------------- + +ABC9 uses a more detailed and accurate model of an FPGA: + +- An FPGA is made up of a network of inputs that connect through LUTs and + combinational boxes to a network of outputs. These boxes have specified delays + between inputs and outputs, and may have an associated network ("white boxes") + or not ("black boxes"), but must be treated as a whole. +- Each LUT has a specified delay between an input and its output in arbitrary + delay units, and this varies for all inputs of a LUT and for all sizes of LUT, + but each size of LUT has the same associated delay; e.g. the delay between + input A and output is different between a LUT2 and a LUT6, but is constant for + all LUT6s. +- A LUT may take up a variable number of area units. This is constant for each + size of LUT; e.g. a LUT4 may take up 1 unit of area, but a LUT5 may take up 2 + units of area, but this applies for all LUT4s and LUT5s. + +This is known as the "generalised delay model", because it has been generalised +to arbitrary delay units. ABC9 doesn't actually care what units you use here, +but the Yosys convention is picoseconds. Note the introduction of boxes as a +concept. While the generalised delay model does not require boxes, they +naturally fit into it to represent combinational delays. Even synchronous delays +like arrival and setup can be emulated with combinational boxes that act as a +delay. This is further extended to white boxes, where the mapper is able to see +inside a box, and remove orphan boxes with no outputs, such as adders. + +Again, ABC9 finds a mapping of the network to LUTs that has the lowest delay, +and then minimises it to find the lowest area, but it has a lot more information +to work with about the network. + +The result here is that ABC9 can remove boxes (like adders) to reduce area, +optimise better around those boxes, and also permute inputs to give the critical +path the fastest inputs. + +.. todo:: more about logic minimization & register balancing et al with ABC + +Setting up a flow for ABC9 +-------------------------- + +Much of the configuration comes from attributes and ``specify`` blocks in +Verilog simulation models. + +``specify`` syntax +~~~~~~~~~~~~~~~~~~ + +Since ``specify`` is a relatively obscure part of the Verilog standard, a quick +guide to the syntax: + +.. code-block:: verilog + + specify // begins a specify block + (A => B) = 123; // simple combinational path from A to B with a delay of 123. + (A *> B) = 123; // simple combinational path from A to all bits of B with a delay of 123 for all. + if (FOO) (A => B) = 123; // paths may apply under specific conditions. + (posedge CLK => (Q : D)) = 123; // combinational path triggered on the positive edge of CLK; used for clock-to-Q arrival paths. + $setup(A, posedge CLK, 123); // setup constraint for an input relative to a clock. + endspecify // ends a specify block + +By convention, all delays in ``specify`` blocks are in integer picoseconds. +Files containing ``specify`` blocks should be read with the ``-specify`` option +to `read_verilog` so that they aren't skipped. + +LUTs +^^^^ + +LUTs need to be annotated with an ``(* abc9_lut=N *)`` attribute, where ``N`` is +the relative area of that LUT model. For example, if an architecture can combine +LUTs to produce larger LUTs, then the combined LUTs would have increasingly +larger ``N``. Conversely, if an architecture can split larger LUTs into smaller +LUTs, then the smaller LUTs would have smaller ``N``. + +LUTs are generally specified with simple combinational paths from the LUT inputs +to the LUT output. + +DFFs +^^^^ + +DFFs should be annotated with an ``(* abc9_flop *)`` attribute, however ABC9 has +some specific requirements for this to be valid: - the DFF must initialise to +zero (consider using `dfflegalize` to ensure this). - the DFF cannot have any +asynchronous resets/sets (see the simplification idiom and the Boxes section for +what to do here). + +It is worth noting that in pure ``abc9`` mode, only the setup and arrival times +are passed to ABC9 (specifically, they are modelled as buffers with the given +delay). In ``abc9 -dff``, the flop itself is passed to ABC9, permitting +sequential optimisations. + +Some vendors have universal DFF models which include async sets/resets even when +they're unused. Therefore *the simplification idiom* exists to handle this: by +using a ``techmap`` file to discover flops which have a constant driver to those +asynchronous controls, they can be mapped into an intermediate, simplified flop +which qualifies as an ``(* abc9_flop *)``, ran through `abc9`, and then mapped +back to the original flop. This is used in `synth_intel_alm` and +`synth_quicklogic` for the PolarPro3. + +DFFs are usually specified to have setup constraints against the clock on the +input signals, and an arrival time for the ``Q`` output. + +Boxes +^^^^^ + +A "box" is a purely-combinational piece of hard logic. If the logic is exposed +to ABC9, it's a "whitebox", otherwise it's a "blackbox". Carry chains would be +best implemented as whiteboxes, but a DSP would be best implemented as a +blackbox (multipliers are too complex to easily work with). LUT RAMs can be +implemented as whiteboxes too. + +Boxes are arguably the biggest advantage that ABC9 has over ABC: by being aware +of carry chains and DSPs, it avoids optimising for a path that isn't the actual +critical path, while the generally-longer paths result in ABC9 being able to +reduce design area by mapping other logic to slower cells with greater logic +density. diff --git a/chips/yosys/docs/source/using_yosys/synthesis/cell_libs.rst b/chips/yosys/docs/source/using_yosys/synthesis/cell_libs.rst new file mode 100644 index 0000000000000000000000000000000000000000..073a05213bd73415cf57cf16838e07bf0fbc809c --- /dev/null +++ b/chips/yosys/docs/source/using_yosys/synthesis/cell_libs.rst @@ -0,0 +1,127 @@ +Mapping to cell libraries +------------------------- + +.. role:: yoscrypt(code) + :language: yoscrypt + +While much of this documentation focuses on the use of Yosys with FPGAs, it is +also possible to map to cell libraries which can be used in designing ASICs. +This section will cover a brief `example project`_, available in the Yosys +source code under :file:`docs/source/code_examples/intro/`. The project +contains a simple ASIC synthesis script (:file:`counter.ys`), a digital design +written in Verilog (:file:`counter.v`), and a simple CMOS cell library +(:file:`mycells.lib`). Many of the early steps here are already covered in more +detail in the :doc:`/getting_started/example_synth` document. + +.. note:: + + The :file:`counter.ys` script includes the commands used to generate the + images in this document. Code snippets in this document skip these commands; + including line numbers to allow the reader to follow along with the source. + + To learn more about these commands, check out :ref:`interactive_show`. + +.. _example project: https://github.com/YosysHQ/yosys/tree/main/docs/source/code_examples/intro + +A simple counter +~~~~~~~~~~~~~~~~ + +First, let's quickly look at the design: + +.. literalinclude:: /code_examples/intro/counter.v + :language: Verilog + :linenos: + :name: counter-v + :caption: :file:`counter.v` + +This is a simple counter with reset and enable. If the reset signal, ``rst``, +is high then the counter will reset to 0. Otherwise, if the enable signal, +``en``, is high then the ``count`` register will increment by 1 each rising edge +of the clock, ``clk``. + +Loading the design +~~~~~~~~~~~~~~~~~~ + +.. literalinclude:: /code_examples/intro/counter.ys + :language: yoscrypt + :lines: 1-3 + :lineno-match: + :caption: :file:`counter.ys` - read design + +Our circuit now looks like this: + +.. figure:: /_images/code_examples/intro/counter_00.* + :class: width-helper invert-helper + :name: counter-hierarchy + + ``counter`` after `hierarchy` + +Coarse-grain representation +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. literalinclude:: /code_examples/intro/counter.ys + :language: yoscrypt + :lines: 7-10 + :lineno-match: + :caption: :file:`counter.ys` - the high-level stuff + +.. figure:: /_images/code_examples/intro/counter_01.* + :class: width-helper invert-helper + + Coarse-grain representation of the ``counter`` module + +Logic gate mapping +~~~~~~~~~~~~~~~~~~ + +.. literalinclude:: /code_examples/intro/counter.ys + :language: yoscrypt + :lines: 14-15 + :lineno-match: + :caption: :file:`counter.ys` - mapping to internal cell library + +.. figure:: /_images/code_examples/intro/counter_02.* + :class: width-helper invert-helper + + ``counter`` after `techmap` + +Mapping to hardware +~~~~~~~~~~~~~~~~~~~ + +For this example, we are using a Liberty file to describe a cell library which +our internal cell library will be mapped to: + +.. todo:: find a Liberty pygments style? + +.. literalinclude:: /code_examples/intro/mycells.lib + :language: text + :linenos: + :name: mycells-lib + :caption: :file:`mycells.lib` + +Recall that the Yosys built-in logic gate types are `$_NOT_`, `$_AND_`, `$_OR_`, +`$_XOR_`, and `$_MUX_` with an assortment of dff memory types. +:ref:`mycells-lib` defines our target cells as ``BUF``, ``NOT``, ``NAND``, +``NOR``, and ``DFF``. Mapping between these is performed with the commands +`dfflibmap` and `abc` as follows: + +.. literalinclude:: /code_examples/intro/counter.ys + :language: yoscrypt + :lines: 20-27 + :lineno-match: + :caption: :file:`counter.ys` - mapping to hardware + +The final version of our ``counter`` module looks like this: + +.. figure:: /_images/code_examples/intro/counter_03.* + :class: width-helper invert-helper + + ``counter`` after hardware cell mapping + +Before finally being output as a verilog file with `write_verilog`, which can +then be loaded into another tool: + +.. literalinclude:: /code_examples/intro/counter.ys + :language: yoscrypt + :lines: 30-31 + :lineno-match: + :caption: :file:`counter.ys` - write synthesized design diff --git a/chips/yosys/docs/source/using_yosys/synthesis/extract.rst b/chips/yosys/docs/source/using_yosys/synthesis/extract.rst new file mode 100644 index 0000000000000000000000000000000000000000..c59ac53632827861eae494ef4a8c856259372972 --- /dev/null +++ b/chips/yosys/docs/source/using_yosys/synthesis/extract.rst @@ -0,0 +1,231 @@ +The extract pass +---------------- + +- Like the `techmap` pass, the `extract` pass is called with a map file. It + compares the circuits inside the modules of the map file with the design and + looks for sub-circuits in the design that match any of the modules in the map + file. +- If a match is found, the `extract` pass will replace the matching subcircuit + with an instance of the module from the map file. +- In a way the `extract` pass is the inverse of the techmap pass. + +.. todo:: add/expand supporting text, also mention custom pattern matching and + pmgen + +Example code can be found in |code_examples/macc|_. + +.. |code_examples/macc| replace:: :file:`docs/source/code_examples/macc` +.. _code_examples/macc: https://github.com/YosysHQ/yosys/tree/main/docs/source/code_examples/macc + + +.. literalinclude:: /code_examples/macc/macc_simple_test.ys + :language: yoscrypt + :lines: 1-2 + +.. figure:: /_images/code_examples/macc/macc_simple_test_00a.* + :class: width-helper invert-helper + + before `extract` + +.. literalinclude:: /code_examples/macc/macc_simple_test.ys + :language: yoscrypt + :lines: 6 + +.. figure:: /_images/code_examples/macc/macc_simple_test_00b.* + :class: width-helper invert-helper + + after `extract` + +.. literalinclude:: /code_examples/macc/macc_simple_test.v + :language: verilog + :caption: :file:`macc_simple_test.v` + +.. literalinclude:: /code_examples/macc/macc_simple_xmap.v + :language: verilog + :caption: :file:`macc_simple_xmap.v` + +.. literalinclude:: /code_examples/macc/macc_simple_test_01.v + :language: verilog + :caption: :file:`macc_simple_test_01.v` + +.. figure:: /_images/code_examples/macc/macc_simple_test_01a.* + :class: width-helper invert-helper + +.. figure:: /_images/code_examples/macc/macc_simple_test_01b.* + :class: width-helper invert-helper + +.. literalinclude:: /code_examples/macc/macc_simple_test_02.v + :language: verilog + :caption: :file:`macc_simple_test_02.v` + +.. figure:: /_images/code_examples/macc/macc_simple_test_02a.* + :class: width-helper invert-helper + +.. figure:: /_images/code_examples/macc/macc_simple_test_02b.* + :class: width-helper invert-helper + +The wrap-extract-unwrap method +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Often a coarse-grain element has a constant bit-width, but can be used to +implement operations with a smaller bit-width. For example, a 18x25-bit +multiplier can also be used to implement 16x20-bit multiplication. + +A way of mapping such elements in coarse grain synthesis is the +wrap-extract-unwrap method: + +wrap + Identify candidate-cells in the circuit and wrap them in a cell with a + constant wider bit-width using `techmap`. The wrappers use the same parameters + as the original cell, so the information about the original width of the ports + is preserved. Then use the `connwrappers` command to connect up the + bit-extended in- and outputs of the wrapper cells. + +extract + Now all operations are encoded using the same bit-width as the coarse grain + element. The `extract` command can be used to replace circuits with cells of + the target architecture. + +unwrap + The remaining wrapper cell can be unwrapped using `techmap`. + +Example: DSP48_MACC +~~~~~~~~~~~~~~~~~~~ + +This section details an example that shows how to map MACC operations of +arbitrary size to MACC cells with a 18x25-bit multiplier and a 48-bit adder +(such as the Xilinx DSP48 cells). + +Preconditioning: :file:`macc_xilinx_swap_map.v` + +Make sure ``A`` is the smaller port on all multipliers + +.. todo:: add/expand supporting text + +.. literalinclude:: /code_examples/macc/macc_xilinx_swap_map.v + :language: verilog + :caption: :file:`macc_xilinx_swap_map.v` + +Wrapping multipliers: :file:`macc_xilinx_wrap_map.v` + +.. literalinclude:: /code_examples/macc/macc_xilinx_wrap_map.v + :language: verilog + :lines: 1-46 + :caption: :file:`macc_xilinx_wrap_map.v` + +Wrapping adders: :file:`macc_xilinx_wrap_map.v` + +.. literalinclude:: /code_examples/macc/macc_xilinx_wrap_map.v + :language: verilog + :lines: 48-89 + :caption: :file:`macc_xilinx_wrap_map.v` + +Extract: :file:`macc_xilinx_xmap.v` + +.. literalinclude:: /code_examples/macc/macc_xilinx_xmap.v + :language: verilog + :caption: :file:`macc_xilinx_xmap.v` + +... simply use the same wrapping commands on this module as on the design to +create a template for the `extract` command. + +Unwrapping multipliers: :file:`macc_xilinx_unwrap_map.v` + +.. literalinclude:: /code_examples/macc/macc_xilinx_unwrap_map.v + :language: verilog + :lines: 1-30 + :caption: ``$__mul_wrapper`` module in :file:`macc_xilinx_unwrap_map.v` + +Unwrapping adders: :file:`macc_xilinx_unwrap_map.v` + +.. literalinclude:: /code_examples/macc/macc_xilinx_unwrap_map.v + :language: verilog + :lines: 32-61 + :caption: ``$__add_wrapper`` module in :file:`macc_xilinx_unwrap_map.v` + +.. literalinclude:: /code_examples/macc/macc_xilinx_test.v + :language: verilog + :lines: 1-6 + :caption: ``test1`` of :file:`macc_xilinx_test.v` + +.. figure:: /_images/code_examples/macc/macc_xilinx_test1a.* + :class: width-helper invert-helper + +.. figure:: /_images/code_examples/macc/macc_xilinx_test1b.* + :class: width-helper invert-helper + +.. literalinclude:: /code_examples/macc/macc_xilinx_test.v + :language: verilog + :lines: 8-13 + :caption: ``test2`` of :file:`macc_xilinx_test.v` + +.. figure:: /_images/code_examples/macc/macc_xilinx_test2a.* + :class: width-helper invert-helper + +.. figure:: /_images/code_examples/macc/macc_xilinx_test2b.* + :class: width-helper invert-helper + +Wrapping in ``test1``: + +.. figure:: /_images/code_examples/macc/macc_xilinx_test1b.* + :class: width-helper invert-helper + +.. literalinclude:: /code_examples/macc/macc_xilinx_test.ys + :language: yoscrypt + :start-after: part c + :end-before: end part c + +.. figure:: /_images/code_examples/macc/macc_xilinx_test1c.* + :class: width-helper invert-helper + +Wrapping in ``test2``: + +.. figure:: /_images/code_examples/macc/macc_xilinx_test2b.* + :class: width-helper invert-helper + +.. literalinclude:: /code_examples/macc/macc_xilinx_test.ys + :language: yoscrypt + :start-after: part c + :end-before: end part c + +.. figure:: /_images/code_examples/macc/macc_xilinx_test2c.* + :class: width-helper invert-helper + +Extract in ``test1``: + +.. figure:: /_images/code_examples/macc/macc_xilinx_test1c.* + :class: width-helper invert-helper + +.. literalinclude:: /code_examples/macc/macc_xilinx_test.ys + :language: yoscrypt + :start-after: part d + :end-before: end part d + +.. figure:: /_images/code_examples/macc/macc_xilinx_test1d.* + :class: width-helper invert-helper + +Extract in ``test2``: + +.. figure:: /_images/code_examples/macc/macc_xilinx_test2c.* + :class: width-helper invert-helper + +.. literalinclude:: /code_examples/macc/macc_xilinx_test.ys + :language: yoscrypt + :start-after: part d + :end-before: end part d + +.. figure:: /_images/code_examples/macc/macc_xilinx_test2d.* + :class: width-helper invert-helper + +Unwrap in ``test2``: + +.. figure:: /_images/code_examples/macc/macc_xilinx_test2d.* + :class: width-helper invert-helper + +.. literalinclude:: /code_examples/macc/macc_xilinx_test.ys + :language: yoscrypt + :start-after: part e + :end-before: end part e + +.. figure:: /_images/code_examples/macc/macc_xilinx_test2e.* + :class: width-helper invert-helper diff --git a/chips/yosys/docs/source/using_yosys/synthesis/fsm.rst b/chips/yosys/docs/source/using_yosys/synthesis/fsm.rst new file mode 100644 index 0000000000000000000000000000000000000000..fab25933fb434deb3bfd2dc9f57ded95f39ac26b --- /dev/null +++ b/chips/yosys/docs/source/using_yosys/synthesis/fsm.rst @@ -0,0 +1,137 @@ +FSM handling +============ + +The `fsm` command identifies, extracts, optimizes (re-encodes), and +re-synthesizes finite state machines. It again is a macro that calls a series of +other commands: + +.. literalinclude:: /code_examples/macro_commands/fsm.ys + :language: yoscrypt + :start-after: #end: + :caption: Passes called by `fsm` + +See also :doc:`/cmd/index_passes_fsm`. + +The algorithms used for FSM detection and extraction are influenced by a more +general reported technique :cite:p:`fsmextract`. + +FSM detection +~~~~~~~~~~~~~ + +The `fsm_detect` pass identifies FSM state registers. It sets the +``fsm_encoding = "auto"`` attribute on any (multi-bit) wire that matches the +following description: + +- Does not already have the ``fsm_encoding`` attribute. +- Is not an output of the containing module. +- Is driven by single `$dff` or `$adff` cell. +- The ``D``-Input of this `$dff` or `$adff` cell is driven by a multiplexer + tree that only has constants or the old state value on its leaves. +- The state value is only used in the said multiplexer tree or by simple + relational cells that compare the state value to a constant (usually `$eq` + cells). + +This heuristic has proven to work very well. It is possible to overwrite it by +setting ``fsm_encoding = "auto"`` on registers that should be considered FSM +state registers and setting ``fsm_encoding = "none"`` on registers that match +the above criteria but should not be considered FSM state registers. + +Note however that marking state registers with ``fsm_encoding`` that are not +suitable for FSM recoding can cause synthesis to fail or produce invalid +results. + +FSM extraction +~~~~~~~~~~~~~~ + +The `fsm_extract` pass operates on all state signals marked with the +(``fsm_encoding != "none"``) attribute. For each state signal the following +information is determined: + +- The state registers + +- The asynchronous reset state if the state registers use asynchronous reset + +- All states and the control input signals used in the state transition + functions + +- The control output signals calculated from the state signals and control + inputs + +- A table of all state transitions and corresponding control inputs- and + outputs + +The state registers (and asynchronous reset state, if applicable) is simply +determined by identifying the driver for the state signal. + +From there the `$mux`\ -tree driving the state register inputs is recursively +traversed. All select inputs are control signals and the leaves of the `$mux`\ +-tree are the states. The algorithm fails if a non-constant leaf that is not the +state signal itself is found. + +The list of control outputs is initialized with the bits from the state signal. +It is then extended by adding all values that are calculated by cells that +compare the state signal with a constant value. + +In most cases this will cover all uses of the state register, thus rendering the +state encoding arbitrary. If however a design uses e.g. a single bit of the +state value to drive a control output directly, this bit of the state signal +will be transformed to a control output of the same value. + +Finally, a transition table for the FSM is generated. This is done by using the +ConstEval C++ helper class (defined in kernel/consteval.h) that can be used to +evaluate parts of the design. The ConstEval class can be asked to calculate a +given set of result signals using a set of signal-value assignments. It can also +be passed a list of stop-signals that abort the ConstEval algorithm if the value +of a stop-signal is needed in order to calculate the result signals. + +The `fsm_extract` pass uses the ConstEval class in the following way to create a +transition table. For each state: + +1. Create a ConstEval object for the module containing the FSM +2. Add all control inputs to the list of stop signals +3. Set the state signal to the current state +4. Try to evaluate the next state and control output +5. If step 4 was not successful: + + - Recursively goto step 4 with the offending stop-signal set to 0. + - Recursively goto step 4 with the offending stop-signal set to 1. + +6. If step 4 was successful: Emit transition + +Finally a `$fsm` cell is created with the generated transition table and added +to the module. This new cell is connected to the control signals and the old +drivers for the control outputs are disconnected. + +FSM optimization +~~~~~~~~~~~~~~~~ + +The `fsm_opt` pass performs basic optimizations on `$fsm` cells (not including +state recoding). The following optimizations are performed (in this order): + +- Unused control outputs are removed from the `$fsm` cell. + +- Control inputs that are connected to the same driver are merged. + +- When a control input is driven by a control output, the control input is + removed and the transition table altered to give the same performance without + the external feedback path. + +- Entries in the transition table that yield the same output and only differ in + the value of a single control input bit are merged and the different bit is + removed from the sensitivity list (turned into a don't-care bit). + +- Constant inputs are removed and the transition table is altered to give an + unchanged behaviour. + +- Unused inputs are removed. + +FSM recoding +~~~~~~~~~~~~ + +The `fsm_recode` pass assigns new bit pattern to the states. Usually this also +implies a change in the width of the state signal. At the moment of this writing +only one-hot encoding with all-zero for the reset state is supported. + +The `fsm_recode` pass can also write a text file with the changes performed by +it that can be used when verifying designs synthesized by Yosys using Synopsys +Formality. diff --git a/chips/yosys/docs/source/using_yosys/synthesis/index.rst b/chips/yosys/docs/source/using_yosys/synthesis/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..6ca8b02d545d3f5bd614ba39e9cc84b77f62201b --- /dev/null +++ b/chips/yosys/docs/source/using_yosys/synthesis/index.rst @@ -0,0 +1,33 @@ +Synthesis in detail +------------------- + +Synthesis can generally be broken down into coarse-grain synthesis, and +fine-grain synthesis. We saw this in :doc:`/getting_started/example_synth` +where a design was loaded and elaborated and then went through a series of +coarse-grain optimizations before being mapped to hard blocks and fine-grain +cells. Most commands in Yosys will target either coarse-grain representation or +fine-grain representation, with only a select few compatible with both states. + +Commands such as `proc`, `fsm`, and `memory` rely on the additional information +in the coarse-grain representation, along with a number of optimizations such as +`wreduce`, `share`, and `alumacc`. `opt` provides optimizations which are +useful in both states, while `techmap` is used to convert coarse-grain cells to +the corresponding fine-grain representation. + +Single-bit cells (logic gates, FFs) as well as LUTs, half-adders, and +full-adders make up the bulk of the fine-grain representation and are necessary +for commands such as `abc`\ /`abc9`, `simplemap`, `dfflegalize`, and +`memory_map`. + +.. toctree:: + :maxdepth: 3 + + synth + proc + fsm + memory + opt + techmap_synth + extract + abc + cell_libs diff --git a/chips/yosys/docs/source/using_yosys/synthesis/memory.rst b/chips/yosys/docs/source/using_yosys/synthesis/memory.rst new file mode 100644 index 0000000000000000000000000000000000000000..44d5698b505076ce4f90d453303589e88b0f9402 --- /dev/null +++ b/chips/yosys/docs/source/using_yosys/synthesis/memory.rst @@ -0,0 +1,789 @@ +Memory handling +=============== + +The `memory` command +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +In the RTL netlist, memory reads and writes are individual cells. This makes +consolidating the number of ports for a memory easier. The `memory` pass +transforms memories to an implementation. Per default that is logic for address +decoders and registers. It also is a macro command that calls the other common +``memory_*`` passes in a sensible order: + +.. literalinclude:: /code_examples/macro_commands/memory.ys + :language: yoscrypt + :start-after: #end: + :caption: Passes called by `memory` + +.. todo:: Make ``memory_*`` notes less quick + +Some quick notes: + +- `memory_dff` merges registers into the memory read- and write cells. +- `memory_collect` collects all read and write cells for a memory and + transforms them into one multi-port memory cell. +- `memory_map` takes the multi-port memory cell and transforms it to address + decoder logic and registers. + +For more information about `memory`, such as disabling certain sub commands, see +:doc:`/cmd/index_passes_memory`. + +Example +------- + +.. todo:: describe ``memory`` images + +|code_examples/synth_flow|_. + +.. |code_examples/synth_flow| replace:: :file:`docs/source/code_examples/synth_flow` +.. _code_examples/synth_flow: https://github.com/YosysHQ/yosys/tree/main/docs/source/code_examples/synth_flow + +.. figure:: /_images/code_examples/synth_flow/memory_01.* + :class: width-helper invert-helper + +.. literalinclude:: /code_examples/synth_flow/memory_01.ys + :language: yoscrypt + :caption: :file:`memory_01.ys` + +.. literalinclude:: /code_examples/synth_flow/memory_01.v + :language: verilog + :caption: :file:`memory_01.v` + +.. figure:: /_images/code_examples/synth_flow/memory_02.* + :class: width-helper invert-helper + +.. literalinclude:: /code_examples/synth_flow/memory_02.v + :language: verilog + :caption: :file:`memory_02.v` + +.. literalinclude:: /code_examples/synth_flow/memory_02.ys + :language: yoscrypt + :caption: :file:`memory_02.ys` + +.. _memory_map: + +Memory mapping +^^^^^^^^^^^^^^ + +Usually it is preferred to use architecture-specific RAM resources for memory. +For example: + +.. code-block:: yoscrypt + + memory -nomap + memory_libmap -lib my_memory_map.txt + techmap -map my_memory_map.v + memory_map + +`memory_libmap` attempts to convert memory cells (`$mem_v2` etc) into hardware +supported memory using a provided library (:file:`my_memory_map.txt` in the +example above). Where necessary, emulation logic is added to ensure functional +equivalence before and after this conversion. :yoscrypt:`techmap -map +my_memory_map.v` then uses `techmap` to map to hardware primitives. Any leftover +memory cells unable to be converted are then picked up by `memory_map` and +mapped to DFFs and address decoders. + +.. note:: + + More information about what mapping options are available and associated + costs of each can be found by enabling debug outputs. This can be done with + the `debug` command, or by using the ``-g`` flag when calling Yosys to + globally enable debug messages. + +For more on the lib format for `memory_libmap`, see +`passes/memory/memlib.md +`_ + +Supported memory patterns +^^^^^^^^^^^^^^^^^^^^^^^^^ + +Note that not all supported patterns are included in this document, of +particular note is that combinations of multiple patterns should generally work. +For example, `wbe`_ could be used in conjunction with any of the simple dual +port (SDP) models. In general if a hardware memory definition does not support +a given configuration, additional logic will be instantiated to guarantee +behaviour is consistent with simulation. + +Notes +----- + +Memory kind selection +~~~~~~~~~~~~~~~~~~~~~ + +The memory inference code will automatically pick target memory primitive based +on memory geometry and features used. Depending on the target, there can be up +to four memory primitive classes available for selection: + +- FF RAM (aka logic): no hardware primitive used, memory lowered to a bunch of + FFs and multiplexers + + - Can handle arbitrary number of write ports, as long as all write ports are + in the same clock domain + - Can handle arbitrary number and kind of read ports + +- LUT RAM (aka distributed RAM): uses LUT storage as RAM + + - Supported on most FPGAs (with notable exception of ice40) + - Usually has one synchronous write port, one or more asynchronous read ports + - Small + - Will never be used for ROMs (lowering to plain LUTs is always better) + +- Block RAM: dedicated memory tiles + + - Supported on basically all FPGAs + - Supports only synchronous reads + - Two ports with separate clocks + - Usually supports true dual port (with notable exception of ice40 that only + supports SDP) + - Usually supports asymmetric memories and per-byte write enables + - Several kilobits in size + +- Huge RAM: + + - Only supported on several targets: + + - Some Xilinx UltraScale devices (UltraRAM) + + - Two ports, both with mutually exclusive synchronous read and write + - Single clock + - Initial data must be all-0 + + - Some ice40 devices (SPRAM) + + - Single port with mutually exclusive synchronous read and write + - Does not support initial data + + - Nexus (large RAM) + + - Two ports, both with mutually exclusive synchronous read and write + - Single clock + + - Will not be automatically selected by memory inference code, needs explicit + opt-in via ram_style attribute + +In general, you can expect the automatic selection process to work roughly like +this: + +- If any read port is asynchronous, only LUT RAM (or FF RAM) can be used. +- If there is more than one write port, only block RAM can be used, and this + needs to be a hardware-supported true dual port pattern + + - … unless all write ports are in the same clock domain, in which case FF RAM + can also be used, but this is generally not what you want for anything but + really small memories + +- Otherwise, either FF RAM, LUT RAM, or block RAM will be used, depending on + memory size + +This process can be overridden by attaching a ram_style attribute to the memory: + +- ``(* ram_style = "logic" *)`` selects FF RAM +- ``(* ram_style = "distributed" *)`` selects LUT RAM +- ``(* ram_style = "block" *)`` selects block RAM +- ``(* ram_style = "huge" *)`` selects huge RAM + +It is an error if this override cannot be realized for the given target. + +Many alternate spellings of the attribute are also accepted, for compatibility +with other software. + +Initial data +~~~~~~~~~~~~ + +Most FPGA targets support initializing all kinds of memory to user-provided +values. If explicit initialization is not used the initial memory value is +undefined. Initial data can be provided by either initial statements writing +memory cells one by one of ``$readmemh`` or ``$readmemb`` system tasks. For an +example pattern, see `sr_init`_. + +.. _wbe: + +Write port with byte enables +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +- Byte enables can be used with any supported pattern +- To ensure that multiple writes will be merged into one port, they need to have + disjoint bit ranges, have the same address, and the same clock +- Any write enable granularity will be accepted (down to per-bit write enables), + but using smaller granularity than natively supported by the target is very + likely to be inefficient (eg. using 4-bit bytes on ECP5 will result in either + padding the bytes with 5 dummy bits to native 9-bit units or splitting the RAM + into two block RAMs) + +.. code:: verilog + + reg [31 : 0] mem [2**ADDR_WIDTH - 1 : 0]; + + always @(posedge clk) begin + if (write_enable[0]) + mem[write_addr][7:0] <= write_data[7:0]; + if (write_enable[1]) + mem[write_addr][15:8] <= write_data[15:8]; + if (write_enable[2]) + mem[write_addr][23:16] <= write_data[23:16]; + if (write_enable[3]) + mem[write_addr][31:24] <= write_data[31:24]; + if (read_enable) + read_data <= mem[read_addr]; + end + +Simple dual port (SDP) memory patterns +-------------------------------------- + +.. todo:: assorted enables, e.g. cen, wen+ren + +Asynchronous-read SDP +~~~~~~~~~~~~~~~~~~~~~ + +- This will result in LUT RAM on supported targets + +.. code:: verilog + + reg [DATA_WIDTH - 1 : 0] mem [2**ADDR_WIDTH - 1 : 0]; + always @(posedge clk) + if (write_enable) + mem[write_addr] <= write_data; + assign read_data = mem[read_addr]; + +Synchronous SDP with clock domain crossing +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +- Will result in block RAM or LUT RAM depending on size +- No behavior guarantees in case of simultaneous read and write to the same + address + +.. code:: verilog + + reg [DATA_WIDTH - 1 : 0] mem [2**ADDR_WIDTH - 1 : 0]; + + always @(posedge write_clk) begin + if (write_enable) + mem[write_addr] <= write_data; + end + + always @(posedge read_clk) begin + if (read_enable) + read_data <= mem[read_addr]; + end + +Synchronous SDP read first +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +- The read and write parts can be in the same or different processes. +- Will result in block RAM or LUT RAM depending on size +- As long as the same clock is used for both, yosys will ensure read-first + behavior. This may require extra circuitry on some targets for block RAM. If + this is not necessary, use one of the patterns below. + +.. code:: verilog + + reg [DATA_WIDTH - 1 : 0] mem [2**ADDR_WIDTH - 1 : 0]; + + always @(posedge clk) begin + if (write_enable) + mem[write_addr] <= write_data; + if (read_enable) + read_data <= mem[read_addr]; + end + +.. _no_rw_check: + +Synchronous SDP with undefined collision behavior +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +- Like above, but the read value is undefined when read and write ports target + the same address in the same cycle + +.. code:: verilog + + reg [DATA_WIDTH - 1 : 0] mem [2**ADDR_WIDTH - 1 : 0]; + + always @(posedge clk) begin + if (write_enable) + mem[write_addr] <= write_data; + + if (read_enable) begin + read_data <= mem[read_addr]; + + if (write_enable && read_addr == write_addr) + // this if block + read_data <= 'x; + end + end + +- Or below, using the no_rw_check attribute + +.. code:: verilog + + (* no_rw_check *) + reg [DATA_WIDTH - 1 : 0] mem [2**ADDR_WIDTH - 1 : 0]; + + always @(posedge clk) begin + if (write_enable) + mem[write_addr] <= write_data; + + if (read_enable) + read_data <= mem[read_addr]; + end + +.. _sdp_wf: + +Synchronous SDP with write-first behavior +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +- Will result in block RAM or LUT RAM depending on size +- May use additional circuitry for block RAM if write-first is not natively + supported. Will always use additional circuitry for LUT RAM. + +.. code:: verilog + + reg [DATA_WIDTH - 1 : 0] mem [2**ADDR_WIDTH - 1 : 0]; + + always @(posedge clk) begin + if (write_enable) + mem[write_addr] <= write_data; + + if (read_enable) begin + read_data <= mem[read_addr]; + if (write_enable && read_addr == write_addr) + read_data <= write_data; + end + end + +Synchronous SDP with write-first behavior (alternate pattern) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +- This pattern is supported for compatibility, but is much less flexible than + the above + +.. code:: verilog + + reg [ADDR_WIDTH - 1 : 0] read_addr_reg; + reg [DATA_WIDTH - 1 : 0] mem [2**ADDR_WIDTH - 1 : 0]; + + always @(posedge clk) begin + if (write_enable) + mem[write_addr] <= write_data; + read_addr_reg <= read_addr; + end + + assign read_data = mem[read_addr_reg]; + +Single-port RAM memory patterns +------------------------------- + +Asynchronous-read single-port RAM +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +- Will result in single-port LUT RAM on supported targets + +.. code:: verilog + + reg [DATA_WIDTH - 1 : 0] mem [2**ADDR_WIDTH - 1 : 0]; + always @(posedge clk) + if (write_enable) + mem[addr] <= write_data; + assign read_data = mem[addr]; + +Synchronous single-port RAM with mutually exclusive read/write +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +- Will result in single-port block RAM or LUT RAM depending on size +- This is the correct pattern to infer ice40 SPRAM (with manual ram_style + selection) +- On targets that don't support read/write block RAM ports (eg. ice40), will + result in SDP block RAM instead +- For block RAM, will use "NO_CHANGE" mode if available + +.. code:: verilog + + reg [DATA_WIDTH - 1 : 0] mem [2**ADDR_WIDTH - 1 : 0]; + + always @(posedge clk) begin + if (write_enable) + mem[addr] <= write_data; + else if (read_enable) + read_data <= mem[addr]; + end + +Synchronous single-port RAM with read-first behavior +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +- Will only result in single-port block RAM when read-first behavior is natively + supported; otherwise, SDP RAM with additional circuitry will be used +- Many targets (Xilinx, ECP5, …) can only natively support + read-first/write-first single-port RAM (or TDP RAM) where the write_enable + signal implies the read_enable signal (ie. can never write without reading). + The memory inference code will run a simple SAT solver on the control signals + to determine if this is the case, and insert emulation circuitry if it cannot + be easily proven. + +.. code:: verilog + + reg [DATA_WIDTH - 1 : 0] mem [2**ADDR_WIDTH - 1 : 0]; + + always @(posedge clk) begin + if (write_enable) + mem[addr] <= write_data; + if (read_enable) + read_data <= mem[addr]; + end + +Synchronous single-port RAM with write-first behavior +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +- Will result in single-port block RAM or LUT RAM when supported +- Block RAMs will require extra circuitry if write-first behavior not natively + supported + +.. code:: verilog + + reg [DATA_WIDTH - 1 : 0] mem [2**ADDR_WIDTH - 1 : 0]; + + always @(posedge clk) begin + if (write_enable) + mem[addr] <= write_data; + if (read_enable) + if (write_enable) + read_data <= write_data; + else + read_data <= mem[addr]; + end + +.. _sr_init: + +Synchronous read port with initial value +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +- Initial read port values can be combined with any other supported pattern +- If block RAM is used and initial read port values are not natively supported + by the target, small emulation circuit will be inserted + +.. code:: verilog + + reg [DATA_WIDTH - 1 : 0] mem [2**ADDR_WIDTH - 1 : 0]; + reg [DATA_WIDTH - 1 : 0] read_data; + initial read_data = 'h1234; + + always @(posedge clk) begin + if (write_enable) + mem[write_addr] <= write_data; + if (read_enable) + read_data <= mem[read_addr]; + end + +Read register reset patterns +---------------------------- + +Resets can be combined with any other supported pattern (except that synchronous +reset and asynchronous reset cannot both be used on a single read port). If +block RAM is used and the selected reset (synchronous or asynchronous) is used +but not natively supported by the target, small emulation circuitry will be +inserted. + +Synchronous reset, reset priority over enable +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: verilog + + reg [DATA_WIDTH - 1 : 0] mem [2**ADDR_WIDTH - 1 : 0]; + + always @(posedge clk) begin + if (write_enable) + mem[write_addr] <= write_data; + + if (read_reset) + read_data <= 'h1234; + else if (read_enable) + read_data <= mem[read_addr]; + end + +Synchronous reset, enable priority over reset +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: verilog + + reg [DATA_WIDTH - 1 : 0] mem [2**ADDR_WIDTH - 1 : 0]; + + always @(posedge clk) begin + if (write_enable) + mem[write_addr] <= write_data; + if (read_enable) + if (read_reset) + read_data <= 'h1234; + else + read_data <= mem[read_addr]; + end + +Synchronous read port with asynchronous reset +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: verilog + + reg [DATA_WIDTH - 1 : 0] mem [2**ADDR_WIDTH - 1 : 0]; + + always @(posedge clk) begin + if (write_enable) + mem[write_addr] <= write_data; + end + + always @(posedge clk, posedge read_reset) begin + if (read_reset) + read_data <= 'h1234; + else if (read_enable) + read_data <= mem[read_addr]; + end + +Asymmetric memory patterns +-------------------------- + +To construct an asymmetric memory (memory with read/write ports of differing +widths): + +- Declare the memory with the width of the narrowest intended port +- Split all wide ports into multiple narrow ports +- To ensure the wide ports will be correctly merged: + + - For the address, use a concatenation of actual address in the high bits and + a constant in the low bits + - Ensure the actual address is identical for all ports belonging to the wide + port + - Ensure that clock is identical + - For read ports, ensure that enable/reset signals are identical (for write + ports, the enable signal may vary — this will result in using the byte + enable functionality) + +Asymmetric memory is supported on all targets, but may require emulation +circuitry where not natively supported. Note that when the memory is larger +than the underlying block RAM primitive, hardware asymmetric memory support is +likely not to be used even if present as it is more expensive. + +.. _wide_sr: + +Wide synchronous read port +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: verilog + + reg [7:0] mem [0:255]; + wire [7:0] write_addr; + wire [5:0] read_addr; + wire [7:0] write_data; + reg [31:0] read_data; + + always @(posedge clk) begin + if (write_enable) + mem[write_addr] <= write_data; + if (read_enable) begin + read_data[7:0] <= mem[{read_addr, 2'b00}]; + read_data[15:8] <= mem[{read_addr, 2'b01}]; + read_data[23:16] <= mem[{read_addr, 2'b10}]; + read_data[31:24] <= mem[{read_addr, 2'b11}]; + end + end + +Wide asynchronous read port +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +- Note: the only target natively supporting this pattern is Xilinx UltraScale + +.. code:: verilog + + reg [7:0] mem [0:511]; + wire [8:0] write_addr; + wire [5:0] read_addr; + wire [7:0] write_data; + wire [63:0] read_data; + + always @(posedge clk) begin + if (write_enable) + mem[write_addr] <= write_data; + end + + assign read_data[7:0] = mem[{read_addr, 3'b000}]; + assign read_data[15:8] = mem[{read_addr, 3'b001}]; + assign read_data[23:16] = mem[{read_addr, 3'b010}]; + assign read_data[31:24] = mem[{read_addr, 3'b011}]; + assign read_data[39:32] = mem[{read_addr, 3'b100}]; + assign read_data[47:40] = mem[{read_addr, 3'b101}]; + assign read_data[55:48] = mem[{read_addr, 3'b110}]; + assign read_data[63:56] = mem[{read_addr, 3'b111}]; + +Wide write port +~~~~~~~~~~~~~~~ + +.. code:: verilog + + reg [7:0] mem [0:255]; + wire [5:0] write_addr; + wire [7:0] read_addr; + wire [31:0] write_data; + reg [7:0] read_data; + + always @(posedge clk) begin + if (write_enable[0]) + mem[{write_addr, 2'b00}] <= write_data[7:0]; + if (write_enable[1]) + mem[{write_addr, 2'b01}] <= write_data[15:8]; + if (write_enable[2]) + mem[{write_addr, 2'b10}] <= write_data[23:16]; + if (write_enable[3]) + mem[{write_addr, 2'b11}] <= write_data[31:24]; + if (read_enable) + read_data <= mem[read_addr]; + end + +True dual port (TDP) patterns +----------------------------- + +- Many different variations of true dual port memory can be created by combining + two single-port RAM patterns on the same memory +- When TDP memory is used, memory inference code has much less maneuver room to + create requested semantics compared to individual single-port patterns (which + can end up lowered to SDP memory where necessary) — supported patterns depend + strongly on the target +- In particular, when both ports have the same clock, it's likely that + "undefined collision" mode needs to be manually selected to enable TDP memory + inference +- The examples below are non-exhaustive — many more combinations of port types + are possible +- Note: if two write ports are in the same process, this defines a priority + relation between them (if both ports are active in the same clock, the later + one wins). On almost all targets, this will result in a bit of extra circuitry + to ensure the priority semantics. If this is not what you want, put them in + separate processes. + + - Priority is not supported when using the verific front end and any priority + semantics are ignored. + +TDP with different clocks, exclusive read/write +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: verilog + + reg [DATA_WIDTH - 1 : 0] mem [2**ADDR_WIDTH - 1 : 0]; + + always @(posedge clk_a) begin + if (write_enable_a) + mem[addr_a] <= write_data_a; + else if (read_enable_a) + read_data_a <= mem[addr_a]; + end + + always @(posedge clk_b) begin + if (write_enable_b) + mem[addr_b] <= write_data_b; + else if (read_enable_b) + read_data_b <= mem[addr_b]; + end + +TDP with same clock, read-first behavior +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +- This requires hardware inter-port read-first behavior, and will only work on + some targets (Xilinx, Nexus) + +.. code:: verilog + + reg [DATA_WIDTH - 1 : 0] mem [2**ADDR_WIDTH - 1 : 0]; + + always @(posedge clk) begin + if (write_enable_a) + mem[addr_a] <= write_data_a; + if (read_enable_a) + read_data_a <= mem[addr_a]; + end + + always @(posedge clk) begin + if (write_enable_b) + mem[addr_b] <= write_data_b; + if (read_enable_b) + read_data_b <= mem[addr_b]; + end + +TDP with multiple read ports +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +- The combination of a single write port with an arbitrary amount of read ports + is supported on all targets — if a multi-read port primitive is available + (like Xilinx RAM64M), it'll be used as appropriate. Otherwise, the memory + will be automatically split into multiple primitives. + +.. code:: verilog + + reg [31:0] mem [0:31]; + + always @(posedge clk) begin + if (write_enable) + mem[write_addr] <= write_data; + end + + assign read_data_a = mem[read_addr_a]; + assign read_data_b = mem[read_addr_b]; + assign read_data_c = mem[read_addr_c]; + +Patterns only supported with Verific +------------------------------------ + +The following patterns are only supported when the design is read in using the +Verific front-end. + +Synchronous SDP with write-first behavior via blocking assignments +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +- Use `sdp_wf`_ for compatibility with Yosys + Verilog frontend. + +.. code:: verilog + + reg [DATA_WIDTH - 1 : 0] mem [2**ADDR_WIDTH - 1 : 0]; + + always @(posedge clk) begin + if (write_enable) + mem[write_addr] = write_data; + + if (read_enable) + read_data <= mem[read_addr]; + end + +Asymmetric memories via part selection +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +- Build wide ports out of narrow ports instead (see `wide_sr`_) for + compatibility with Yosys Verilog frontend. + +.. code:: verilog + + reg [31:0] mem [2**ADDR_WIDTH - 1 : 0]; + + wire [1:0] byte_lane; + wire [7:0] write_data; + + always @(posedge clk) begin + if (write_enable) + mem[write_addr][byte_lane * 8 +: 8] <= write_data; + + if (read_enable) + read_data <= mem[read_addr]; + end + + +Undesired patterns +------------------ + +Asynchronous writes +~~~~~~~~~~~~~~~~~~~ + +- Not supported in modern FPGAs +- Not supported in yosys code anyhow + +.. code:: verilog + + reg [DATA_WIDTH - 1 : 0] mem [2**ADDR_WIDTH - 1 : 0]; + + always @* begin + if (write_enable) + mem[write_addr] = write_data; + end + + assign read_data = mem[read_addr]; diff --git a/chips/yosys/docs/source/using_yosys/synthesis/opt.rst b/chips/yosys/docs/source/using_yosys/synthesis/opt.rst new file mode 100644 index 0000000000000000000000000000000000000000..9075016a95ab04b4ef5f0e4720893dd78b282b41 --- /dev/null +++ b/chips/yosys/docs/source/using_yosys/synthesis/opt.rst @@ -0,0 +1,235 @@ +Optimization passes +=================== + +Yosys employs a number of optimizations to generate better and cleaner results. +This chapter outlines these optimizations. + +.. todo:: "outlines these optimizations" or "outlines *some*.."? + +The `opt` macro command +-------------------------------- + +The Yosys pass `opt` runs a number of simple optimizations. This includes +removing unused signals and cells and const folding. It is recommended to run +this pass after each major step in the synthesis script. This macro command +calls the following ``opt_*`` commands: + +.. literalinclude:: /code_examples/macro_commands/opt.ys + :language: yoscrypt + :start-after: #end: + :caption: Passes called by `opt` + +.. _adv_opt_expr: + +Constant folding and simple expression rewriting - `opt_expr` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. todo:: unsure if this is too much detail and should be in :doc:`/yosys_internals/index` + +This pass performs constant folding on the internal combinational cell types +described in :doc:`/cell_index`. This means a cell with all +constant inputs is replaced with the constant value this cell drives. In some +cases this pass can also optimize cells with some constant inputs. + +.. table:: Const folding rules for `$_AND_` cells as used in `opt_expr`. + :name: tab:opt_expr_and + :align: center + + ========= ========= =========== + A-Input B-Input Replacement + ========= ========= =========== + any 0 0 + 0 any 0 + 1 1 1 + --------- --------- ----------- + X/Z X/Z X + 1 X/Z X + X/Z 1 X + --------- --------- ----------- + any X/Z 0 + X/Z any 0 + --------- --------- ----------- + :math:`a` 1 :math:`a` + 1 :math:`b` :math:`b` + ========= ========= =========== + +:numref:`Table %s ` shows the replacement rules used for +optimizing an `$_AND_` gate. The first three rules implement the obvious const +folding rules. Note that 'any' might include dynamic values calculated by other +parts of the circuit. The following three lines propagate undef (X) states. +These are the only three cases in which it is allowed to propagate an undef +according to Sec. 5.1.10 of IEEE Std. 1364-2005 :cite:p:`Verilog2005`. + +The next two lines assume the value 0 for undef states. These two rules are only +used if no other substitutions are possible in the current module. If other +substitutions are possible they are performed first, in the hope that the 'any' +will change to an undef value or a 1 and therefore the output can be set to +undef. + +The last two lines simply replace an `$_AND_` gate with one constant-1 input +with a buffer. + +Besides this basic const folding the `opt_expr` pass can replace 1-bit wide +`$eq` and `$ne` cells with buffers or not-gates if one input is constant. +Equality checks may also be reduced in size if there are redundant bits in the +arguments (i.e. bits which are constant on both inputs). This can, for example, +result in a 32-bit wide constant like ``255`` being reduced to the 8-bit value +of ``8'11111111`` if the signal being compared is only 8-bit as in +:ref:`addr_gen_clean` of :doc:`/getting_started/example_synth`. + +The `opt_expr` pass is very conservative regarding optimizing `$mux` cells, as +these cells are often used to model decision-trees and breaking these trees can +interfere with other optimizations. + +.. literalinclude:: /code_examples/opt/opt_expr.ys + :language: Verilog + :start-after: read_verilog <`. + +- The ``nolatches`` attribute on modules or always-blocks prohibits the + generation of logic-loops for latches. Instead all not explicitly assigned + values default to x-bits. This does not affect clocked storage elements such + as flip-flops. + +- The ``nosync`` attribute on registers prohibits the generation of a storage + element. The register itself will always have all bits set to 'x' (undefined). + The variable may only be used as blocking assigned temporary variable within + an always block. This is mostly used internally by Yosys to synthesize Verilog + functions and access arrays. + +- The ``nowrshmsk`` attribute on a register prohibits the generation of + shift-and-mask type circuits for writing to bit slices of that register. + +- The ``onehot`` attribute on wires mark them as one-hot state register. This is + used for example for memory port sharing and set by the fsm_map pass. + +- The ``blackbox`` attribute on modules is used to mark empty stub modules that + have the same ports as the real thing but do not contain information on the + internal configuration. This modules are only used by the synthesis passes to + identify input and output ports of cells. The Verilog backend also does not + output blackbox modules on default. `read_verilog`, unless called with + ``-noblackbox`` will automatically set the blackbox attribute on any empty + module it reads. + +- The ``noblackbox`` attribute set on an empty module prevents `read_verilog` + from automatically setting the blackbox attribute on the module. + +- The ``whitebox`` attribute on modules triggers the same behavior as + ``blackbox``, but is for whitebox modules, i.e. library modules that contain a + behavioral model of the cell type. + +- The ``lib_whitebox`` attribute overwrites ``whitebox`` when `read_verilog` is + run in ``-lib`` mode. Otherwise it's automatically removed. + +- The ``dynports`` attribute is used by the Verilog front-end to mark modules + that have ports with a width that depends on a parameter. + +- The ``hdlname`` attribute is used by some passes to document the original + (HDL) name of a module when renaming a module. It should contain a single + name, or, when describing a hierarchical name in a flattened design, multiple + names separated by a single space character. + +- The ``keep`` attribute on cells and wires is used to mark objects that should + never be removed by the optimizer. This is used for example for cells that + have hidden connections that are not part of the netlist, such as IO pads. + Setting the ``keep`` attribute on a module has the same effect as setting it + on all instances of the module. + +- The ``keep_hierarchy`` attribute on cells and modules keeps the `flatten` + command from flattening the indicated cells and modules. + +- The ``gate_cost_equivalent`` attribute on a module can be used to specify + the estimated cost of the module as a number of basic gate instances. See + the help message of command `keep_hierarchy` which interprets this + attribute. + +- The ``init`` attribute on wires is set by the frontend when a register is + initialized "FPGA-style" with ``reg foo = val``. It can be used during + synthesis to add the necessary reset logic. + +- The ``top`` attribute on a module marks this module as the top of the design + hierarchy. The `hierarchy` command sets this attribute when called with + ``-top``. Other commands, such as `flatten` and various backends use this + attribute to determine the top module. + +- The ``src`` attribute is set on cells and wires created by to the string + ``:`` by the HDL front-end and is then carried + through the synthesis. When entities are combined, a new \|-separated string + is created that contains all the strings from the original entities. + +- The ``defaultvalue`` attribute is used to store default values for module + inputs. The attribute is attached to the input wire by the HDL front-end when + the input is declared with a default value. + +- The ``parameter`` and ``localparam`` attributes are used to mark wires that + represent module parameters or localparams (when the HDL front-end is run in + ``-pwires`` mode). + +- Wires marked with the ``hierconn`` attribute are connected to wires with the + same name (format ``cell_name.identifier``) when they are imported from + sub-modules by `flatten`. + +- The ``clkbuf_driver`` attribute can be set on an output port of a blackbox + module to mark it as a clock buffer output, and thus prevent `clkbufmap` from + inserting another clock buffer on a net driven by such output. + +- The ``clkbuf_sink`` attribute can be set on an input port of a module to + request clock buffer insertion by the `clkbufmap` pass. + +- The ``clkbuf_inv`` attribute can be set on an output port of a module with the + value set to the name of an input port of that module. When the `clkbufmap` + would otherwise insert a clock buffer on this output, it will instead try + inserting the clock buffer on the input port (this is used to implement clock + inverter cells that clock buffer insertion will "see through"). + +- The ``clkbuf_inhibit`` is the default attribute to set on a wire to prevent + automatic clock buffer insertion by `clkbufmap`. This behaviour can be + overridden by providing a custom selection to `clkbufmap`. + +- The ``invertible_pin`` attribute can be set on a port to mark it as invertible + via a cell parameter. The name of the inversion parameter is specified as the + value of this attribute. The value of the inversion parameter must be of the + same width as the port, with 1 indicating an inverted bit and 0 indicating a + non-inverted bit. + +- The ``iopad_external_pin`` attribute on a blackbox module's port marks it as + the external-facing pin of an I/O pad, and prevents `iopadmap` from inserting + another pad cell on it. + +- The module attribute ``abc9_lut`` is an integer attribute indicating to `abc9` + that this module describes a LUT with an area cost of this value, and + propagation delays described using ``specify`` statements. + +- The module attribute ``abc9_box`` is a boolean specifying a black/white-box + definition, with propagation delays described using ``specify`` statements, + for use by `abc9`. + +- The port attribute ``abc9_carry`` marks the carry-in (if an input port) and + carry-out (if output port) ports of a box. This information is necessary for + `abc9` to preserve the integrity of carry-chains. Specifying this attribute + onto a bus port will affect only its most significant bit. + +- The module attribute ``abc9_flop`` is a boolean marking the module as a + flip-flop. This allows `abc9` to analyse its contents in order to perform + sequential synthesis. + +- The frontend sets attributes ``always_comb``, ``always_latch`` and + ``always_ff`` on processes derived from SystemVerilog style always blocks + according to the type of the always. These are checked for correctness in + ``proc_dlatch``. Latches inferred from ``always_latch`` processes are exempt + from the ``proc -latches `` reporting policy, and the + generated latch cells carry the ``always_latch`` attribute, which also + exempts them from `check` ``-nolatches``. + +- The cell attribute ``wildcard_port_conns`` represents wildcard port + connections (SystemVerilog ``.*``). These are resolved to concrete connections + to matching wires in `hierarchy`. + +- In addition to the ``(* ... *)`` attribute syntax, Yosys supports the + non-standard ``{* ... *}`` attribute syntax to set default attributes for + everything that comes after the ``{* ... *}`` statement. (Reset by adding an + empty ``{* *}`` statement.) + +- In module parameter and port declarations, and cell port and parameter lists, + a trailing comma is ignored. This simplifies writing Verilog code generators a + bit in some cases. + +- Modules can be declared with ``module mod_name(...);`` (with three dots + instead of a list of module ports). With this syntax it is sufficient to + simply declare a module port as 'input' or 'output' in the module body. + +- When defining a macro with ``\`define``, all text between triple double quotes + is interpreted as macro body, even if it contains unescaped newlines. The + triple double quotes are removed from the macro body. For example: + +.. code-block:: verilog + + `define MY_MACRO(a, b) """ + assign a = 23; + assign b = 42; + """ + +- The attribute ``via_celltype`` can be used to implement a Verilog task or + function by instantiating the specified cell type. The value is the name of + the cell type to use. For functions the name of the output port can be + specified by appending it to the cell type separated by a whitespace. The body + of the task or function is unused in this case and can be used to specify a + behavioral model of the cell type for simulation. For example: + +.. code-block:: verilog + + module my_add3(A, B, C, Y); + parameter WIDTH = 8; + input [WIDTH-1:0] A, B, C; + output [WIDTH-1:0] Y; + ... + endmodule + + module top; + ... + (* via_celltype = "my_add3 Y" *) + (* via_celltype_defparam_WIDTH = 32 *) + function [31:0] add3; + input [31:0] A, B, C; + begin + add3 = A + B + C; + end + endfunction + ... + endmodule + +- The ``wiretype`` attribute is added by the verilog parser for wires of a + typedef'd type to indicate the type identifier. + +- Various ``enum_value_{value}`` attributes are added to wires of an enumerated + type to give a map of possible enum items to their values. + +- The ``enum_base_type`` attribute is added to enum items to indicate which enum + they belong to (enums -- anonymous and otherwise -- are automatically named + with an auto-incrementing counter). Note that enums are currently not strongly + typed. + +- A limited subset of DPI-C functions is supported. The plugin mechanism (see + ``help plugin``) can be used to load .so files with implementations of DPI-C + routines. As a non-standard extension it is possible to specify a plugin alias + using the ``:`` syntax. For example: + +.. code-block:: verilog + + module dpitest; + import "DPI-C" function foo:round = real my_round (real); + parameter real r = my_round(12.345); + endmodule + +.. code-block:: + + $ yosys -p 'plugin -a foo -i /lib/libm.so; read_verilog dpitest.v' + +- Sized constants (the syntax ``'s?[bodh]``) support constant + expressions as ````. If the expression is not a simple identifier, it + must be put in parentheses. Examples: ``WIDTH'd42``, ``(4+2)'b101010`` + +- The system tasks ``$finish``, ``$stop`` and ``$display`` are supported in + initial blocks in an unconditional context (only if/case statements on + expressions over parameters and constant values are allowed). The intended use + for this is synthesis-time DRC. + +- There is limited support for converting ``specify`` .. ``endspecify`` + statements to special ``$specify2``, ``$specify3``, and ``$specrule`` cells, + for use in blackboxes and whiteboxes. Use ``read_verilog -specify`` to enable + this functionality. (By default these blocks are ignored.) + +- The ``reprocess_after`` internal attribute is used by the Verilog frontend to + mark cells with bindings which might depend on the specified instantiated + module. Modules with such cells will be reprocessed during the `hierarchy` + pass once the referenced module definition(s) become available. + +- The ``smtlib2_module`` attribute can be set on a blackbox module to specify a + formal model directly using SMT-LIB 2. For such a module, the + ``smtlib2_comb_expr`` attribute can be used on output ports to define their + value using an SMT-LIB 2 expression. For example: + +.. code-block:: verilog + + (* blackbox *) + (* smtlib2_module *) + module submod(a, b); + input [7:0] a; + (* smtlib2_comb_expr = "(bvnot a)" *) + output [7:0] b; + endmodule + +Non-standard or SystemVerilog features for formal verification +-------------------------------------------------------------- + +- Support for ``assert``, ``assume``, ``restrict``, and ``cover`` is enabled + when `read_verilog` is called with ``-formal``. + +- The system task ``$initstate`` evaluates to 1 in the initial state and to 0 + otherwise. + +- The system function ``$anyconst`` evaluates to any constant value. This is + equivalent to declaring a reg as ``rand const``, but also works outside of + checkers. (Yosys also supports ``rand const`` outside checkers.) + +- The system function ``$anyseq`` evaluates to any value, possibly a different + value in each cycle. This is equivalent to declaring a reg as ``rand``, but + also works outside of checkers. (Yosys also supports ``rand`` variables + outside checkers.) + +- The system functions ``$allconst`` and ``$allseq`` can be used to construct + formal exist-forall problems. Assumptions only hold if the trace satisfies the + assumption for all ``$allconst/$allseq`` values. For assertions and cover + statements it is sufficient if just one ``$allconst/$allseq`` value triggers + the property (similar to ``$anyconst/$anyseq``). + +- Wires/registers declared using the ``anyconst/anyseq/allconst/allseq`` + attribute (for example ``(* anyconst *) reg [7:0] foobar;``) will behave as if + driven by a ``$anyconst/$anyseq/$allconst/$allseq`` function. + +- The SystemVerilog tasks ``$past``, ``$stable``, ``$rose`` and ``$fell`` are + supported in any clocked block. + +- The syntax ``@($global_clock)`` can be used to create FFs that have no + explicit clock input (``$ff`` cells). The same can be achieved by using + ``@(posedge )`` or ``@(negedge )`` when ```` is + marked with the ``(* gclk *)`` Verilog attribute. + + +Supported features from SystemVerilog +------------------------------------- + +When `read_verilog` is called with ``-sv``, it accepts some language features +from SystemVerilog: + +- The ``assert`` statement from SystemVerilog is supported in its most basic + form. In module context: ``assert property ();`` and within an + always block: ``assert();``. It is transformed to an ``$assert`` + cell. + +- The ``assume``, ``restrict``, and ``cover`` statements from SystemVerilog are + also supported. The same limitations as with the ``assert`` statement apply. + +- The keywords ``always_comb``, ``always_ff`` and ``always_latch``, ``logic`` + and ``bit`` are supported. + +- Declaring free variables with ``rand`` and ``rand const`` is supported. + +- Checkers without a port list that do not need to be instantiated (but instead + behave like a named block) are supported. + +- SystemVerilog packages are supported. Once a SystemVerilog file is read into a + design with `read_verilog`, all its packages are available to SystemVerilog + files being read into the same design afterwards. + + - nested packages are currently not supported (i.e. calling ``import`` inside + a ``package`` .. ``endpackage`` block) + +- typedefs are supported (including inside packages) + + - type casts are currently not supported + +- enums are supported (including inside packages) + + - but are currently not strongly typed + +- packed structs and unions are supported + + - arrays of packed structs/unions are currently not supported + - structure literals are currently not supported + +- multidimensional arrays are supported + + - array assignment of unpacked arrays is currently not supported + - array literals are currently not supported + +- SystemVerilog interfaces (SVIs), including modports for specifying whether + ports are inputs or outputs, are partially supported. + + - interfaces must be provided as *named* arguments, not positional arguments. + i.e. ``foo bar(.intf(intf0), .x(x));`` is supported but ``foo bar(intf0, + x);`` is not. + +- Assignments within expressions are supported. + +- The ``unique``, ``unique0``, and ``priority`` SystemVerilog keywords are + supported on ``if`` and ``case`` conditionals. (The Verilog frontend + will process conditionals using these keywords by annotating their + representation with the appropriate ``full_case`` and/or ``parallel_case`` + attributes, which are described above.) + +- SystemVerilog string literals are supported (triple-quoted strings and + escape sequences such as line continuations and hex escapes). diff --git a/chips/yosys/docs/source/yosys_internals/extending_yosys/advanced_bugpoint.rst b/chips/yosys/docs/source/yosys_internals/extending_yosys/advanced_bugpoint.rst new file mode 100644 index 0000000000000000000000000000000000000000..64dd36d0ef51a79ba5850cd1a886258726eeb32a --- /dev/null +++ b/chips/yosys/docs/source/yosys_internals/extending_yosys/advanced_bugpoint.rst @@ -0,0 +1,271 @@ +Identifying the root cause of bugs +================================== + +This document references Yosys internals and is intended for people interested +in solving or investigating Yosys bugs. This also applies if you are using a +fuzzing tool; fuzzers have a tendency to find many variations of the same bug, +so identifying the root cause is important for avoiding issue spam. + +If you're familiar with C/C++, you might try to have a look at the source code +of the command that's failing. Even if you can't fix the problem yourself, it +can be very helpful for anyone else investigating if you're able to identify +where the issue is arising. + + +Finding the failing command +--------------------------- + +Using the ``-L`` flag can help here, allowing you to specify a file to log to, +such as ``yosys -L out.log -s script.ys``. Most commands will print a header +message when they begin; something like ``2.48. Executing HIERARCHY pass +(managing design hierarchy).`` The last header message will usually be the +failing command. There are some commands which don't print a header message, so +you may want to add ``echo on`` to the start of your script. The `echo` command +echoes each command executed, along with any arguments given to it. For the +`hierarchy` example above this might be ``yosys> hierarchy -check``. + +.. note:: + + It may also be helpful to use the `log` command to add messages which you can + then search for either in the terminal or the logfile. This can be quite + useful if your script contains script-passes, like the + :doc:`/using_yosys/synthesis/synth`, which call many sub-commands and you're + not sure exactly which script-pass is calling the failing command. + + +Minimizing scripts +------------------ + +.. warning:: + + This section is intended as **advanced usage**, and generally not necessary + for normal bug reports. + +If you're using a command line prompt, such as ``yosys -p 'synth_xilinx' -o +design.json design.v``, consider converting it to a script. It's generally much +easier to iterate over changes to a script in a file rather than one on the +command line, as well as being better for sharing with others. + +.. code-block:: yoscrypt + :caption: example script, ``script.ys``, for prompt ``yosys -p 'synth_xilinx' -o design.json design.v`` + + read_verilog design.v + synth_xilinx + write_json design.json + +Next up you want to remove everything *after* the error occurs. If your final +command calls sub-commands, replace it with its contents first. In the case of +the :doc:`/using_yosys/synthesis/synth`, as well as certain other script-passes, +you can use the ``-run`` option to simplify this. For example we can replace +``synth -top -lut`` with the :ref:`replace_synth`. The options ``-top + -lut`` can be provided to each `synth` step, or to just the step(s) where +it is relevant, as done here. + +.. code-block:: yoscrypt + :caption: example replacement script for `synth` command + :name: replace_synth + + synth -top -run :coarse + synth -lut -run coarse:fine + synth -lut -run fine:check + synth -run check: + +Say we ran :ref:`replace_synth` and were able to remove the ``synth -run +check:`` and still got our error, then we check the log and we see the last +thing before the error was ``7.2. Executing MEMORY_MAP pass (converting memories +to logic and flip-flops)``. By checking the output of ``yosys -h synth`` (or the +`synth` help page) we can see that the `memory_map` pass is called in the +``fine`` step. We can then update our script to the following: + +.. code-block:: yoscrypt + :caption: example replacement script for `synth` when `memory_map` is failing + + synth -top -run :fine + opt -fast -full + memory_map + +By giving `synth` the option ``-run :fine``, we are telling it to run from the +beginning of the script until the ``fine`` step, where we then give it the exact +commands to run. There are some cases where the commands given in the help +output are not an exact match for what is being run, but are instead a +simplification. If you find that replacing the script-pass with its contents +causes the error to disappear, or change, try calling the script-pass with +``echo on`` to see exactly what commands are being called and what options are +used. + +.. warning:: + + Before continuing further, *back up your code*. The following steps can + remove context and lead to over-minimizing scripts, hiding underlying issues. + Check out :ref:`yosys_internals/extending_yosys/advanced_bugpoint:Why + context matters` to learn more. + +When a problem is occurring many steps into a script, minimizing the design at +the start of the script isn't always enough to identify the cause of the issue. +Each extra step of the script can lead to larger sections of the input design +being needed for the specific problem to be preserved until it causes a crash. +So to find the smallest possible reproducer it can sometimes be helpful to +remove commands prior to the failure point. + +The simplest way to do this is by writing out the design, resetting the current +state, and reading back the design: + +.. code-block:: yoscrypt + + write_rtlil ; design -reset; read_rtlil ; + +In most cases, this can be inserted immediately before the failing command while +still producing the error, allowing you to :ref:`minimize your +RTLIL` with the +```` output. For our previous example with `memory_map`, if +:ref:`map_reset` still gives the same error, then we should now be able to call +``yosys design.il -p 'memory_map'`` to reproduce it. + +.. code-block:: yoscrypt + :caption: resetting the design immediately before failure + :name: map_reset + + synth -top -run :fine + opt -fast -full + write_rtlil design.il; design -reset; read_rtlil design.il; + memory_map + +If that doesn't give the error (or doesn't give the same error), then you should +try to move the write/reset/read earlier in the script until it does. If you +have no idea where exactly you should put the reset, the best way is to use a +"binary search" type approach, reducing the possible options by half after each +attempt. + +.. note:: + + By default, `write_rtlil` doesn't include platform specific IP blocks and + other primitive cell models which are typically loaded with a ``read_verilog + -lib`` command at the start of the synthesis script. You may have to + duplicate these commands *after* the call to ``design -reset``. It is also + possible to write out *everything* with ``select =*; write_rtlil -selected + ``. + +As an example, your script has 16 commands in it before failing on the 17th. If +resetting immediately before the 17th doesn't reproduce the error, try between +the 8th and 9th (8 is half of the total 16). If that produces the error then +you can remove everything before the `read_rtlil` and try reset again in the +middle of what's left, making sure to use a different name for the output file +so that you don't overwrite what you've already got. If the error isn't +produced then you need to go earlier still, so in this case you would do between +the 4th and 5th (4 is half of the previous 8). Repeat this until you can't +reduce the remaining commands any further. + +A more conservative, but more involved, method is to remove or comment out +commands prior to the failing command. Each command, or group of commands, can +be disabled one at a time while checking if the error still occurs, eventually +giving the smallest subset of commands needed to take the original input through +to the error. The difficulty with this method is that depending on your design, +some commands may be necessary even if they aren't needed to reproduce the +error. For example, if your design includes ``process`` blocks, many commands +will fail unless you run the `proc` command. While this approach can do a +better job of maintaining context, it is often easier to *recover* the context +after the design has been minimized for producing the error. For more on +recovering context, checkout +:ref:`yosys_internals/extending_yosys/advanced_bugpoint:Why context matters`. + + +Why context matters +------------------- + +Sometimes when a command is raising an error, you're seeing a symptom rather +than the underlying issue. It's possible that an earlier command may be putting +the design in an invalid state, which isn't picked up until the error is raised. +This is particularly true for the pre-packaged +:doc:`/using_yosys/synthesis/synth`, which rely on a combination of generic and +architecture specific passes. As new features are added to Yosys and more +designs are supported, the types of cells output by a pass can grow and change; +and sometimes this leads to a mismatch in what a pass is intended to handle. + +If you minimized your script, and removed commands prior to the failure to get a +smaller reproducer, try to work backwards and find which commands may have +contributed to the design failing. From the minimized design you should have +some understanding of the cell or cells which are producing the error; but where +did those cells come from? The name and/or type of the cell can often point you +in the right direction: + +.. code-block:: + + # internal cell types start with a $ + # lowercase for word-level, uppercase for bit-level + $and + $_AND_ + + # cell types with $__ are typically intermediate cells used in techmapping + $__MUL16X16 + + # cell types without a $ are either user-defined or architecture specific + my_module + SB_MAC16 + + # object names might give you the name of the pass that created them + $procdff$1204 + $memory\rom$rdmux[0][0][0]$a$1550 + + # or even the line number in the Yosys source + $auto$muxcover.cc:557:implement_best_cover$2152 + $auto$alumacc.cc:495:replace_alu$1209 + +Try running the unminimized script and search the log for the names of the +objects in your minimized design. In the case of cells you can also search for +the type of the cell. Remember that calling `stat` will list all the types of +cells currently used in the design, and ``select -list =*`` will list the names +of of all the current objects. You can add these commands to your script, or +use an interactive terminal to run each command individually. Adding them to +the script can be more repeatable, but if it takes a long time to run to the +point you're interested in then an interactive shell session can give you more +flexibility once you reach that point. You can also add a call to the `shell` +command at any point in a script to start an interactive session at a given +point; allowing you to script any preparation steps, then come back once it's +done. + +The ``--dump-design`` option +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Yosys provides the ``--dump-design`` option (or ``-P`` for short) for dumping +the design at specific steps of the script based on the log header. If the last +step before an error is ``7.2. Executing MEMORY_MAP pass (converting memories to +logic and flip-flops)``, then calling Yosys with ``--dump-design 7.2:bad.il`` +will save the design *before* this command runs, in the file ``bad.il``. + +It is also possible to use this option multiple times, e.g. ``-P2:hierarchy.il +-P7 -P7.2:bad.il``, to get multiple dumps in the same run. This can make it +easier to follow the design through each step to find where certain cells or +connections are coming from. ``--dump-design ALL`` is also allowed, writing out +the design at each log header. + +A worked example +~~~~~~~~~~~~~~~~ + +Say you did all the minimization and found that an error in `synth_xilinx` +occurs when a call to ``techmap -map +/xilinx/cells_map.v`` with +``MIN_MUX_INPUTS`` defined parses a `$_MUX16_` with all inputs set to ``1'x``. +You could fix the bug in ``+/xilinx/cells_map.v``, but that might only solve +this one case while leaving other problems that haven't been found yet. So you +step through the original script, calling `stat` after each step to find when +the `$_MUX16_` is added. + +You find that the `$_MUX16_` is introduced by a call to `muxcover`, but all the +inputs are defined, so calling `techmap` now works as expected. From running +`bugpoint` with the failing techmap you know that the cell with index ``2297`` +will fail, so you call ``select top/*$2297`` to limit to just that cell. This +can then be saved with ``design -save pre_bug`` or ``write_rtlil -selected +pre_bug.il``, so that you don't have to re-run all the earlier steps to get back +here. + +Next you step through the remaining commands and call `dump` after each to find +when the inputs are disconnected. You find that ``opt -full`` has optimized +away portions of the circuit, leading to `opt_expr` setting the undriven mux +inputs to ``x``, but failing to remove the now unnecessary `$_MUX16_`. Now +you've identified a problem in `opt_expr` that affects all of the wide muxes, +and could happen in any synthesis flow, not just `synth_xilinx`. + +.. seealso:: + + This example is taken from `YosysHQ/yosys#4590 + `_ and can be reproduced with a + version of Yosys between 0.45 and 0.51. diff --git a/chips/yosys/docs/source/yosys_internals/extending_yosys/build_verific.rst b/chips/yosys/docs/source/yosys_internals/extending_yosys/build_verific.rst new file mode 100644 index 0000000000000000000000000000000000000000..b9ecd352ef35712483e538e5c1d52aa0fc1b28ed --- /dev/null +++ b/chips/yosys/docs/source/yosys_internals/extending_yosys/build_verific.rst @@ -0,0 +1,135 @@ +Compiling with Verific library +============================== + +The easiest way to get Yosys with Verific support is to `contact YosysHQ`_ for a +`Tabby CAD Suite`_ evaluation license and download link. The TabbyCAD Suite +includes additional patches and a custom extensions library in order to get the +most out of the Verific parser when using Yosys. + +If you already have a license for the Verific parser, in either source or binary +form, you may be able to compile Yosys with partial Verific support yourself. + +.. _contact YosysHQ : https://www.yosyshq.com/contact +.. _Tabby CAD Suite: https://www.yosyshq.com/tabby-cad-datasheet + +The Yosys-Verific patch +----------------------- + +YosysHQ maintains and develops a patch for Verific in order to better integrate +with Yosys and to provide features required by some of the formal verification +front-end tools. To license this patch for your own Yosys builds, `contact +YosysHQ`_. + +.. warning:: + + While synthesis from RTL may be possible without this patch, YosysHQ provides + no guarantees of correctness and is unable to provide support. + +We recommend against using unpatched Yosys+Verific builds in conjunction with +the formal verification front-end tools unless you are familiar with their inner +workings. There are cases where the tools will appear to work, while producing +incorrect results. + +.. note:: + + Some of the formal verification front-end tools may not be fully supported + without the full TabbyCAD suite. If you want to use these tools, including + SBY, make sure to ask us if the Yosys-Verific patch is right for you. + +Compile options +--------------- + +To enable Verific support, set the :makevar:`YOSYS_VERIFIC_DIR` CMake variable +to point to the location where the library is located, e.g. + +.. code-block:: console + + cmake -B build . -DYOSYS_VERIFIC_DIR="/usr/local/src/verific_lib" + +During building, CMake will attempt to automatically detect available Verific +library components to enable the corresponding compile-time option in Yosys. +This can be overridden by manually setting the :makevar:`YOSYS_VERIFIC_FEATURES` +CMake variable. This variable should contain a semi-colon separated list, e.g. +``-DYOSYS_VERIFIC_FEATURES="systemverilog;hier_tree"``. The table below lists +the features available to Yosys. + +============== =========== =================================== +Feature Directory Description +============== =========== =================================== +systemverilog verilog SystemVerilog support +vhdl vhdl VHDL support +hier_tree hier_tree Hierarchy tree support +extensions extensions YosysHQ specific extensions support +edif edif EDIF support +liberty synlib Liberty file support +============== =========== =================================== + +.. note:: + + The YosysHQ specific extensions are only available with the TabbyCAD suite. + +Required Verific features +~~~~~~~~~~~~~~~~~~~~~~~~~ + +The following features, along with their corresponding Yosys build parameters, +are required for the Yosys-Verific patch: + +* RTL elaboration with + + * SystemVerilog with ``systemverilog``, and/or + * VHDL support with ``vhdl``. + +* Hierarchy tree support and static elaboration with ``hier_tree``. + +Please be aware that the following Verific configuration build parameter needs +to be enabled in order to create the fully supported build: + +:: + + database/DBCompileFlags.h: + DB_PRESERVE_INITIAL_VALUE + +.. note:: + + Yosys+Verific builds may compile without these features, but we provide no + guarantees and cannot offer support if they are disabled or the Yosys-Verific + patch is not used. + +Optional Verific features +~~~~~~~~~~~~~~~~~~~~~~~~~ + +The following Verific features are available with TabbyCAD and will be +automatically enabled in Yosys builds if the listed directory is included in the +:makevar:`YOSYS_VERIFIC_DIR`: + +* EDIF support with ``edif`` directory, and +* Liberty file support with ``synlib`` directory. + +Partially supported builds +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +This section describes Yosys+Verific configurations which we have confirmed as +working in the past, however they are not a part of our regular tests so we +cannot guarantee they are still functional. + +To be able to compile Yosys with Verific, the Verific library must have support +for at least one HDL language with RTL elaboration enabled. The following table +lists a series of build configurations which are possible, but only provide a +limited subset of features. Please note that support is limited without YosysHQ +specific extensions of Verific library. + +======================================================================= ================================= +Features :makevar:`YOSYS_VERIFIC_FEATURES` +======================================================================= ================================= +SystemVerilog + RTL elaboration systemverilog +VHDL + RTL elaboration vhdl +SystemVerilog + VHDL + RTL elaboration systemverilog;vhdl +SystemVerilog + RTL elaboration + Static elaboration + Hier tree systemverilog;vhdl;hier_tree +VHDL + RTL elaboration + Static elaboration + Hier tree vhdl;hier_tree +SystemVerilog + VHDL + RTL elaboration + Static elaboration + Hier tree systemverilog;vhdl;hier_tree +======================================================================= ================================= + +.. note:: + + In case your Verific build has EDIF and/or Liberty support, you can enable + those options. These are not mentioned above for simplification. diff --git a/chips/yosys/docs/source/yosys_internals/extending_yosys/contributing.rst b/chips/yosys/docs/source/yosys_internals/extending_yosys/contributing.rst new file mode 100644 index 0000000000000000000000000000000000000000..71763f132627ab05e38fc0b21f750aaed6a0039f --- /dev/null +++ b/chips/yosys/docs/source/yosys_internals/extending_yosys/contributing.rst @@ -0,0 +1,420 @@ +Contributing to Yosys +===================== + +LLM usage +--------- + +While we develop a complete policy around the usage of LLMs in Yosys, we have an +`Interim YosysHQ LLM Policy +`_. As a general rule: +Please do not file pull requests to our GitHub projects containing LLM generated +code. + +Reporting bugs +-------------- + +We fix well-reported bugs the fastest. A good bug report is an issue on the `issue tracker`_ +and includes the following information: + +.. _`issue tracker`: https://github.com/YosysHQ/yosys/issues + +Title +~~~~~ + +briefly describe the issue, for example: + + techmap of wide mux with undefined inputs raises error during synth_xilinx + ++ tells us what's happening ("raises error") ++ gives the command affected (`techmap`) ++ an overview of the input design ("wide mux with undefined inputs") ++ and some context where it was found ("during `synth_xilinx`") + + +Reproduction Steps +~~~~~~~~~~~~~~~~~~ + +The reproduction steps should be a minimal, complete and verifiable +example `MVCE`_. +Providing an MVCE with your bug report drastically increases the likelihood that +someone will be able to help resolve your issue. +Make sure that your report input is free of any problems as reported by the +`check` command. +One way to minimize a design is to use the `bugpoint` command. +You can learn more in the :doc:`how-to guide for bugpoint `. + +The reproduction steps are ideally a code-block (starting and ending with +triple backquotes) containing +the minimized design (Verilog or RTLIL), followed by a code-block containing +the minimized yosys script OR a command line call to yosys with +code-formatting (starting and ending with single backquotes). + +.. code-block:: markdown + + min.v + ```verilog + // minimized Verilog design + ``` + + min.ys + ``` + read_verilog min.v + # minimum sequence of commands to reproduce error + ``` + + OR + + `yosys -p ': minimum sequence of commands;' min.v` + +Alternatively, you can provide a single code-block which includes the minimized +design as a "here document" followed by the sequence of commands which reproduce +the error: + +.. code-block:: markdown + + ``` + read_rtlil </path/to/file#L139-L147`` + * clicking on "Preview" should reveal a code block containing the lines of + source specified, with a link to the source file at the given commit + + +Additional Details +~~~~~~~~~~~~~~~~~~ + +Anything else you think might be helpful or relevant when verifying or fixing +the bug. + +Once you have created the issue, any additional details can be added as a +comment on that issue. You can include any additional context as to what you +were doing when you first encountered the bug. + +If this issue discovered through the use of a fuzzer, ALWAYS declare that. +If you've minimized the script, consider including the `bugpoint` script you +used, or the original script, for example: + +.. code-block:: markdown + + Minimized with + ``` + read_verilog design.v + # original sequence of commands prior to error + bugpoint -script -grep "" + write_rtlil min.il + ``` + + OR + + Minimized from + `yosys -p ': original sequence of commands to produce error;' design.v` + +If possible, it may also help to share the original un-minimized design. +If the design is too big for a comment, consider turning it into a `Gist`_ + +.. _Gist: https://gist.github.com/ + +Contributing code +----------------- + +Code that matters +~~~~~~~~~~~~~~~~~ + +If you're adding complex functionality, or modifying core parts of yosys, +we highly recommend discussing your motivation and approach +ahead of time on the `Discourse forum`_. Please, be as explicit and concrete +as possible when explaining the motivation for what you're building. +Additionally, if you do so on the forum first before you starting hacking +away at C++, you might solve your problem without writing a single line +of code! + +PRs are considered for relevance, priority, and quality +based on their descriptions first, code second. + +Before you build or fix something, also search for existing `issues`_. + +We have open `developer 'jour fixe' (Dev JF) meetings`_ +where developers from YosysHQ and the +community come together to discuss open issues and PRs. This is also a good +place to talk to us about how to implement larger PRs. + +.. _`developer 'jour fixe' (Dev JF) meetings`: https://docs.google.com/document/d/1SapA6QAsJcsgwsdKJDgnGR2mr97pJjV4eeXg_TVJhRU/edit?usp=sharing +.. _`Discourse forum`: https://yosyshq.discourse.group/ +.. _`issues`: https://github.com/YosysHQ/yosys/issues + +Making sense +~~~~~~~~~~~~ + +Given enough effort, the behavior of any code can be figured out to any +desired extent. However, the author of the code is by far in the best +position to make this as easy as possible. + +Yosys is a long-standing project and has accumulated a lot of C-style code +that's not written to be read, just written to run. We improve this bit +by bit when opportunities arise, but it is what it is. +New additions are expected to be a lot cleaner. + +The purpose and behavior of the code changed should be described clearly. +Your change should contain exactly what it needs to match that description. +This means: + +* nothing more than that - no dead code, no undocumented features +* nothing missing - if something is partially built, that's fine, + but you have to make that clear. For example, some passes + only support some types of cells + +Here are some software engineering approaches that help: + +* Use abstraction to model the problem and hide details + + * Maximize the usage of types (structs over loose variables), + not necessarily in an object-oriented way + * Use functions, scopes, type aliases + +* In new passes, make sure the logic behind how and why it works is actually provided + in coherent comments, and that variable and type naming is consistent with the terms + you use in the description. +* The logic of the implementation should be described in mathematical + or algorithm theory terms. Correctness, termination, computational complexity. + Make it clear if you're re-implementing a classic data structure for logic synthesis + or graph traversal etc. + +* There's various ways of traversing the design with use-def indices (for getting + drivers and driven signals) available in Yosys. They have advantages and sometimes + disadvantages. Prefer not re-implementing these +* Prefer references over pointers, and smart pointers over raw pointers +* Aggressively deduplicate code. Within functions, within passes, + across passes, even against existing code +* Prefer declaring things ``const`` +* Prefer range-based for loops over C-style + +Common mistakes +~~~~~~~~~~~~~~~ + +* Deleting design objects invalidates iterators. Defer deletions or hold a copy + of the list of pointers to design objects +* Deleting wires can get sketchy and is intended to be done solely by + the ``opt_clean`` pass so just don't do it +* Iterating over an entire design and checking if things are selected is more + inefficient than using the ``selected_*`` methods +* Remember to call ``fixup_ports`` at the end if you're modifying module interfaces + +Testing your change +~~~~~~~~~~~~~~~~~~~ + +Untested code can't be maintained. Inevitable codebase-wide changes +are likely to break anything untested. Tests also help reviewers understand +the purpose of the code change in practice. + +Your code needs to come with tests. If it's a feature, a test that covers +representative examples of the added behavior. If it's a bug fix, it should +reproduce the original isolated bug. But in some situations, adding a test +isn't viable. If you can't provide a test, explain this decision. + +Prefer writing unit tests (:file:`tests/unit`) for isolated tests to +the internals of more serious code changes, like those to the core of yosys, +or more algorithmic ones. + +The rest of the test suite is mostly based on running Yosys on various Yosys +and Tcl scripts that manually call Yosys commands. +See :doc:`/yosys_internals/extending_yosys/test_suites` for more information +about how our test suite is structured. +The basic test writing approach is checking +for the presence of some kind of object or pattern with ``-assert-count`` in +:doc:`/using_yosys/more_scripting/selections`. + +It's often best to use equivalence checking with ``equiv_opt -assert`` +or similar to prove that the changes done to the design by a modified pass +preserve equivalence. But some code isn't meant to preserve equivalence. +Sometimes proving equivalence takes an impractically long time for larger +inputs. Also beware, the ``equiv_`` passes are a bit quirky and might even +have incorrect results in unusual situations. + +.. Changes to core parts of Yosys or passes that are included in synthesis flows +.. can change runtime and memory usage - for the better or for worse. This strongly +.. depends on the design involved. Such risky changes should then be benchmarked +.. with various designs. + +.. TODO Emil benchmarking + +Coding style +~~~~~~~~~~~~ + +Yosys is written in C++20. + +In general Yosys uses ``int`` instead of ``size_t``. To avoid compiler warnings +for implicit type casts, always use ``GetSize(foobar)`` instead of +``foobar.size()``. (``GetSize()`` is defined in :file:`kernel/yosys.h`) + +For auto formatting code, a :file:`.clang-format` file is present top-level. +Yosys code is using tabs for indentation. A tab is 8 characters wide, +but prefer not relying on it. A continuation of a statement +in the following line is indented by two additional tabs. Lines are +as long as you want them to be. A good rule of thumb is to break lines +at about column 150. Opening braces can be put on the same or next line +as the statement opening the block (if, switch, for, while, do). +Put the opening brace on its own line for larger blocks, especially +blocks that contains blank lines. Remove trailing whitespace on sight. + +Otherwise stick to the `Linux Kernel Coding Style`_. + +.. _Linux Kernel Coding Style: https://www.kernel.org/doc/Documentation/process/coding-style.rst + +Pull requests (PRs) +~~~~~~~~~~~~~~~~~~~ + +If you are working on something to add to Yosys, or fix something that isn't +working quite right, +make a `pull request (PR)`_. + +An open PR, even as a draft, tells everyone that you're working on it and they +don't have to. It can also be a useful way to solicit feedback on in-progress +changes. + +We use `labels`_ to help categorise +issues and PRs. If a label seems relevant to your work, please do add it; this +also includes the labels beginning with 'status-'. The 'merge-' labels are used +by maintainers for tracking and communicating which PRs are ready and pending +merge; please do not use these labels if you are not a maintainer. + +.. _`pull request (PR)`: https://github.com/YosysHQ/yosys/pulls +.. _`labels`: https://github.com/YosysHQ/yosys/labels + +Git style +~~~~~~~~~ + +We don't have a strict commit message style. + +Some style hints: + +* Refactor and document existing code if you touch it, + but in separate commits from your functional changes +* Prefer smaller commits organized by good chunks. Git has a lot of features + like fixup commits, interactive rebase with autosquash + +Reviewing PRs +------------- + +Reviewing PRs is a totally valid form of external contributing to the project! + +Who's the reviewer? +~~~~~~~~~~~~~~~~~~~ + +YosysHQ GmbH is a company with a mandate to make decisions for the good +of YosysHQ open source software. It was co-founded by Claire Xenia Wolf, +the original author of Yosys. +Within it, we allocate reviews based on expertise with the topic at hand +as well as member time constraints. However, decisions including reviews +are also contributed by people external to the company. + +If you're intimately acquainted with a part of the codebase, we will be happy +to defer to your experience and have you review PRs. The official way we like +is our CODEOWNERS file in the git repository. What we're looking for in code +owners is activity and trust. For activity, if you're only interested in +a yosys pass for example for the time you spend writing a thesis, it might be +better to focus on writing good tests and docs in the PRs you submit rather than +to commit to code ownership and therefore to be responsible for fixing things +and reviewing other people's PRs at various unexpected points later. If you're +prolific in some part of the codebase and not a code owner, we still value your +experience and may tag you in PRs. + +As a matter of fact, the purpose of code ownership is to avoid maintainer +burnout by removing orphaned parts of the codebase. If you become a code owner +and stop being responsive, in the future, we might decide to remove such code +if convenient and costly to maintain. It's simply more respectful of the users' +time to explicitly cut something out than let it "bitrot". Larger projects like +LLVM or linux could not survive without such things, but Yosys is far smaller, +and there are implicit expectations of stability we aim to +respect within reason. + +.. TODO this deserves its own section elsewhere I think? But it would be distracting elsewhere + +Sometimes, multiple maintainers may add review comments. This is considered +healthy collaborative even if it might create disagreement at times. If +somebody is already reviewing a PR, others, even non-maintainers are free to +leave comments with extra observations and alternate perspectives in a +collaborative spirit. + +How to review +~~~~~~~~~~~~~ + +First, read everything above about contributing. Those are the values you +should gently enforce as a reviewer. They're ordered by importance, but +explicitly, descriptions are more important than code, long-form comments +describing the design are more important than piecemeal comments, etc. + +If a PR is poorly described, incomplete, tests are broken, or if the +author is not responding, please don't feel pressured to take over their +role by reverse engineering the code or fixing things for them, unless +there are good reasons to do so. + +If a PR author submits LLM outputs they haven't understood themselves, +they will not be able to implement feedback. Take this into consideration +as well. We do not ban LLM code from the codebase, we ban bad code. + +Reviewers may have diverse styles of communication while reviewing - one +may do one thorough review, another may prefer a back and forth with the +basics out the way before digging into the code. Generally, PRs may have +several requests for modifications and long discussions, but often +they just are good enough to merge as-is. + +The CI is required to go green for merging. New contributors need a CI +run to be triggered by a maintainer before their PRs take up computing +resources. It's a single click from the github web interface. +We test on various platforms and compilers. Sanitizer builds are only +tested on the main branch. diff --git a/chips/yosys/docs/source/yosys_internals/extending_yosys/extensions.rst b/chips/yosys/docs/source/yosys_internals/extending_yosys/extensions.rst new file mode 100644 index 0000000000000000000000000000000000000000..633276d331111bc571df0303d1203fed48faf0bb --- /dev/null +++ b/chips/yosys/docs/source/yosys_internals/extending_yosys/extensions.rst @@ -0,0 +1,260 @@ +Writing extensions +================== + +.. role:: yoscrypt(code) + :language: yoscrypt + +.. todo:: check text is coherent + +.. todo:: update to use :file:`/code_examples/extensions/test*.log` + +This chapter contains some bits and pieces of information about programming +yosys extensions. Don't be afraid to ask questions on the YosysHQ Discourse. + +.. todo:: mention coding guide + +Quick guide +----------- + +Code examples from this section are included in the |code_examples/extensions|_ +directory of the Yosys source code. + +.. |code_examples/extensions| replace:: :file:`docs/source/code_examples/extensions` +.. _code_examples/extensions: https://github.com/YosysHQ/yosys/tree/main/docs/source/code_examples/extensions + + +Program components and data formats +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +See :doc:`/yosys_internals/formats/rtlil_rep` document for more information +about the internal data storage format used in Yosys and the classes that it +provides. + +This document will focus on the much simpler version of RTLIL left after the +commands `proc` and `memory` (or :yoscrypt:`memory -nomap`): + +.. figure:: /_images/internals/simplified_rtlil.* + :class: width-helper invert-helper + :name: fig:Simplified_RTLIL + + Simplified RTLIL entity-relationship diagram without memories and processes + +It is possible to only work on this simpler version: + +.. todo:: consider replacing inline code + +.. code:: c++ + + for (RTLIL::Module *module : design->selected_modules() { + if (module->has_memories_warn() || module->has_processes_warn()) + continue; + .... + } + +When trying to understand what a command does, creating a small test case to +look at the output of `dump` and `show` before and after the command has been +executed can be helpful. :doc:`/using_yosys/more_scripting/selections` has more +information on using these commands. + +Creating a command +~~~~~~~~~~~~~~~~~~ + +.. todo:: add/expand supporting text + +Let's create a very simple test command which prints the arguments we called it +with, and lists off the current design's modules. + +.. literalinclude:: /code_examples/extensions/my_cmd.cc + :language: c++ + :lines: 1, 4, 6, 7-20 + :caption: Example command :yoscrypt:`my_cmd` from :file:`my_cmd.cc` + +Note that we are making a global instance of a class derived from +``Yosys::Pass``, which we get by including :file:`kernel/yosys.h`. + +Compiling to a plugin +~~~~~~~~~~~~~~~~~~~~~ + +Yosys can be extended by adding additional C++ code to the Yosys code base, or +by loading plugins into Yosys. For maintainability it is generally recommended +to create plugins. + +The following command compiles our example :yoscrypt:`my_cmd` to a Yosys plugin: + +.. todo:: replace inline code + +.. code:: shell + + yosys-config --exec --cxx --cxxflags --ldflags \ + -o my_cmd.so -shared my_cmd.cc --ldlibs + +Or shorter: + +.. code:: shell + + yosys-config --build my_cmd.so my_cmd.cc + +Running Yosys with the ``-m`` option allows the plugin to be used. Here's a +quick example that also uses the ``-p`` option to run :yoscrypt:`my_cmd foo +bar`. + +.. code:: shell-session + + $ yosys -m ./my_cmd.so -p 'my_cmd foo bar' + + -- Running command `my_cmd foo bar' -- + Arguments to my_cmd: + my_cmd + foo + bar + Modules in current design: + +Creating modules from scratch +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Let's create the following module using the RTLIL API: + +.. literalinclude:: /code_examples/extensions/absval_ref.v + :language: Verilog + :caption: absval_ref.v + +We'll do the same as before and format it as a a ``Yosys::Pass``. + +.. literalinclude:: /code_examples/extensions/my_cmd.cc + :language: c++ + :lines: 23-47 + :caption: :yoscrypt:`test1` - creating the absval module, from :file:`my_cmd.cc` + +.. code:: shell-session + + $ yosys -m ./my_cmd.so -p 'test1' -Q + + -- Running command `test1' -- + Name of this module: absval + +And if we look at the schematic for this new module we see the following: + +.. figure:: /_images/code_examples/extensions/test1.* + :class: width-helper invert-helper + + Output of ``yosys -m ./my_cmd.so -p 'test1; show'`` + +Modifying modules +~~~~~~~~~~~~~~~~~ + +Most commands modify existing modules, not create new ones. + +When modifying existing modules, stick to the following DOs and DON'Ts: + +- Do not remove wires. Simply disconnect them and let a successive `clean` + command worry about removing it. +- Use ``module->fixup_ports()`` after changing the ``port_*`` properties of + wires. +- You can safely remove cells or change the ``connections`` property of a cell, + but be careful when changing the size of the ``SigSpec`` connected to a cell + port. +- Use the ``SigMap`` helper class (see next section) when you need a unique + handle for each signal bit. + +Using the SigMap helper class +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Consider the following module: + +.. literalinclude:: /code_examples/extensions/sigmap_test.v + :language: Verilog + :caption: :file:`sigmap_test.v` + +In this case ``a``, ``x``, and ``y`` are all different names for the same +signal. However: + +.. todo:: use my_cmd.cc literalincludes + +.. code:: C++ + + RTLIL::SigSpec a(module->wire("\\a")), x(module->wire("\\x")), + y(module->wire("\\y")); + log("%d %d %d\n", a == x, x == y, y == a); // will print "0 0 0" + +The ``SigMap`` helper class can be used to map all such aliasing signals to a +unique signal from the group (usually the wire that is directly driven by a cell +or port). + +.. code:: C++ + + SigMap sigmap(module); + log("%d %d %d\n", sigmap(a) == sigmap(x), sigmap(x) == sigmap(y), + sigmap(y) == sigmap(a)); // will print "1 1 1" + +Printing log messages +~~~~~~~~~~~~~~~~~~~~~ + +The ``log()`` function is a ``printf()``-like function that can be used to +create log messages. + +Use ``log_signal()`` to create a C-string for a SigSpec object: + +.. code:: C++ + + log("Mapped signal x: %s\n", log_signal(sigmap(x))); + +The pointer returned by ``log_signal()`` is automatically freed by the log +framework at a later time. + +Use ``log_header()`` and ``log_push()``/\ ``log_pop()`` to structure log +messages: + +.. todo:: replace inline code + +.. code:: C++ + + log_header(design, "Doing important stuff!\n"); + log_push(); + for (int i = 0; i < 10; i++) + log("Log message #%d.\n", i); + log_pop(); + +Error handling +~~~~~~~~~~~~~~ + +Use ``log_error()`` to report a non-recoverable error: + +.. todo:: replace inline code + +.. code:: C++ + + if (design->modules.count(module->name) != 0) + log_error("A module with the name %s already exists!\n", module); + +Use ``log_cmd_error()`` to report a recoverable error: + +.. code:: C++ + + if (design->selection().empty()) + log_cmd_error("This command can't operator on an empty selection!\n"); + +Use ``log_assert()`` and ``log_abort()`` instead of ``assert()`` and ``abort()``. + +The "stubnets" example module +------------------------------ + +The following is the complete code of the "stubnets" example module. It is +included in the Yosys source distribution under |code_examples/stubnets|_. + +.. |code_examples/stubnets| replace:: :file:`docs/source/code_examples/stubnets` +.. _code_examples/stubnets: https://github.com/YosysHQ/yosys/tree/main/docs/source/code_examples/stubnets + +.. literalinclude:: /code_examples/stubnets/stubnets.cc + :language: c++ + :linenos: + :caption: :file:`stubnets.cc` + +.. literalinclude:: /code_examples/stubnets/Makefile + :language: makefile + :linenos: + :caption: :file:`Makefile` + +.. literalinclude:: /code_examples/stubnets/test.v + :language: verilog + :linenos: + :caption: :file:`test.v` diff --git a/chips/yosys/docs/source/yosys_internals/extending_yosys/functional_ir.rst b/chips/yosys/docs/source/yosys_internals/extending_yosys/functional_ir.rst new file mode 100644 index 0000000000000000000000000000000000000000..1c4ab528194ef4ab2de0fedb1f3f0feb8739170c --- /dev/null +++ b/chips/yosys/docs/source/yosys_internals/extending_yosys/functional_ir.rst @@ -0,0 +1,524 @@ +Writing a new backend using FunctionalIR +======================================== + +What is FunctionalIR +-------------------- + +To simplify the writing of backends for functional languages or similar targets, +Yosys provides an alternative intermediate representation called FunctionalIR +which maps more directly on those targets. + +FunctionalIR represents the design as a function ``(inputs, current_state) -> +(outputs, next_state)``. This function is broken down into a series of +assignments to variables. Each assignment is a simple operation, such as an +addition. Complex operations are broken up into multiple steps. For example, an +RTLIL addition will be translated into a sign/zero extension of the inputs, +followed by an addition. + +Like SSA form, each variable is assigned to exactly once. We can thus treat +variables and assignments as equivalent and, since this is a graph-like +representation, those variables are also called "nodes". Unlike RTLIL's cells +and wires representation, this representation is strictly ordered (topologically +sorted) with definitions preceding their use. + +Every node has a "sort" (the FunctionalIR term for what might otherwise be +called a "type"). The sorts available are + +- ``bit[n]`` for an ``n``-bit bitvector, and +- ``memory[n,m]`` for an immutable array of ``2**n`` values of sort ``bit[m]``. + +In terms of actual code, Yosys provides a class ``Functional::IR`` that +represents a design in FunctionalIR. ``Functional::IR::from_module`` generates +an instance from an RTLIL module. The entire design is stored as a whole in an +internal data structure. To access the design, the ``Functional::Node`` class +provides a reference to a particular node in the design. The ``Functional::IR`` +class supports the syntax ``for(auto node : ir)`` to iterate over every node. + +``Functional::IR`` also keeps track of inputs, outputs and states. By a "state" +we mean a pair of a "current state" input and a "next state" output. One such +pair is created for every register and for every memory. Every input, output and +state has a name (equal to their name in RTLIL), a sort and a kind. The kind +field usually remains as the default value ``$input``, ``$output`` or +``$state``, however some RTLIL cells such as ``$assert`` or ``$anyseq`` generate +auxiliary inputs/outputs/states that are given a different kind to distinguish +them from ordinary RTLIL inputs/outputs/states. + +- To access an individual input/output/state, use ``ir.input(name, kind)``, + ``ir.output(name, kind)`` or ``ir.state(name, kind)``. ``kind`` defaults to + the default kind. +- To iterate over all inputs/outputs/states of a certain kind, methods + ``ir.inputs``, ``ir.outputs``, ``ir.states`` are provided. Their argument + defaults to the default kinds mentioned. +- To iterate over inputs/outputs/states of any kind, use ``ir.all_inputs``, + ``ir.all_outputs`` and ``ir.all_states``. +- Outputs have a node that indicate the value of the output, this can be + retrieved via ``output.value()``. +- States have a node that indicate the next value of the state, this can be + retrieved via ``state.next_value()``. They also have an initial value that is + accessed as either ``state.initial_value_signal()`` or + ``state.initial_value_memory()``, depending on their sort. + +Each node has a "function", which defines its operation (for a complete list of +functions and a specification of their operation, see ``functional.h``). +Functions are represented as an enum ``Functional::Fn`` and the function field +can be accessed as ``node.fn()``. Since the most common operation is a switch +over the function that also accesses the arguments, the ``Node`` class provides +a method ``visit`` that implements the visitor pattern. For example, for an +addition node ``node`` with arguments ``n1`` and ``n2``, ``node.visit(visitor)`` +would call ``visitor.add(node, n1, n2)``. Thus typically one would implement a +class with a method for every function. Visitors should inherit from either +``Functional::AbstractVisitor`` or +``Functional::DefaultVisitor``. The former will produce a compiler +error if a case is unhandled, the latter will call ``default_handler(node)`` +instead. Visitor methods should be marked as ``override`` to provide compiler +errors if the arguments are wrong. + +Utility classes +~~~~~~~~~~~~~~~ + +``functional.h`` also provides utility classes that are independent of the main +FunctionalIR representation but are likely to be useful for backends. + +``Functional::Writer`` provides a simple formatting class that wraps a +``std::ostream`` and provides the following methods: + +- ``writer << value`` wraps ``os << value``. +- ``writer.print(fmt, value0, value1, value2, ...)`` replaces ``{0}``, ``{1}``, + ``{2}``, etc in the string ``fmt`` with ``value0``, ``value1``, ``value2``, + resp. Each value is formatted using ``os << value``. It is also possible to + write ``{}`` to refer to one past the last index, i.e. ``{1} {} {} {7} {}`` is + equivalent to ``{1} {2} {3} {7} {8}``. +- ``writer.print_with(fn, fmt, value0, value1, value2, ...)`` functions much the + same as ``print`` but it uses ``os << fn(value)`` to print each value and + falls back to ``os << value`` if ``fn(value)`` is not legal. + +``Functional::Scope`` keeps track of variable names in a target language. It is +used to translate between different sets of legal characters and to avoid +accidentally re-defining identifiers. Users should derive a class from ``Scope`` +and supply the following: + +- ``Scope`` takes a template argument that specifies a type that's used to + uniquely distinguish variables. Typically this would be ``int`` (if variables + are used for ``Functional::IR`` nodes) or ``IdString``. +- The derived class should provide a constructor that calls ``reserve`` for + every reserved word in the target language. +- A method ``bool is_character_legal(char c, int index)`` has to be provided + that returns ``true`` iff ``c`` is legal in an identifier at position + ``index``. + +Given an instance ``scope`` of the derived class, the following methods are then +available: + +- ``scope.reserve(std::string name)`` marks the given name as being in-use +- ``scope.unique_name(IdString suggestion)`` generates a previously unused name + and attempts to make it similar to ``suggestion``. +- ``scope(Id id, IdString suggestion)`` functions similar to ``unique_name``, + except that multiple calls with the same ``id`` are guaranteed to retrieve the + same name (independent of ``suggestion``). + +``sexpr.h`` provides classes that represent and pretty-print s-expressions. +S-expressions can be constructed with ``SExpr::list``, for example ``SExpr expr += SExpr::list("add", "x", SExpr::list("mul", "y", "z"))`` represents ``(add x +(mul y z))`` (by adding ``using SExprUtil::list`` to the top of the file, +``list`` can be used as shorthand for ``SExpr::list``). For prettyprinting, +``SExprWriter`` wraps an ``std::ostream`` and provides the following methods: + +- ``writer << sexpr`` writes the provided expression to the output, breaking + long lines and adding appropriate indentation. +- ``writer.open(sexpr)`` is similar to ``writer << sexpr`` but will omit the + last closing parenthesis. Further arguments can then be added separately with + ``<<`` or ``open``. This allows for printing large s-expressions without + needing to construct the whole expression in memory first. +- ``writer.open(sexpr, false)`` is similar to ``writer.open(sexpr)`` but further + arguments will not be indented. This is used to avoid unlimited indentation on + structures with unlimited nesting. +- ``writer.close(n = 1)`` closes the last ``n`` open s-expressions. +- ``writer.push()`` and ``writer.pop()`` are used to automatically close + s-expressions. ``writer.pop()`` closes all s-expressions opened since the last + call to ``writer.push()``. +- ``writer.comment(string)`` writes a comment on a separate-line. + ``writer.comment(string, true)`` appends a comment to the last printed + s-expression. +- ``writer.flush()`` flushes any buffering and should be called before any + direct access to the underlying ``std::ostream``. It does not close unclosed + parentheses. +- The destructor calls ``flush`` but also closes all unclosed parentheses. + +.. _minimal backend: + +Example: A minimal functional backend +------------------------------------- + +At its most basic, there are three steps we need to accomplish for a minimal +functional backend. First, we need to convert our design into FunctionalIR. +This is most easily done by calling the ``Functional::IR::from_module()`` static +method with our top-level module, or iterating over and converting each of the +modules in our design. Second, we need to handle each of the +``Functional::Node``\ s in our design. Iterating over the ``Functional::IR`` +includes reading the module inputs and current state, but not writing the +results. So our final step is to handle the outputs and next state. + +In order to add an output command to Yosys, we implement the ``Yosys::Backend`` +class and provide an instance of it: + +.. literalinclude:: /code_examples/functional/dummy.cc + :language: c++ + :caption: Example source code for a minimal functional backend, ``dummy.cc`` + +Because we are using the ``Backend`` class, our ``"functional_dummy"`` is +registered as the ``write_functional_dummy`` command. The ``execute`` method is +the part that runs when the user calls the command, handling any options, +preparing the output file for writing, and iterating over selected modules in +the design. Since we don't have any options here, we set ``argidx = 1`` and +call the ``extra_args()`` method. This method will read the command arguments, +raising an error if there are any unexpected ones. It will also assign the +pointer ``f`` to the output file, or stdout if none is given. + +.. note:: + + For more on adding new commands to Yosys and how they work, refer to + :doc:`/yosys_internals/extending_yosys/extensions`. + +For this minimal example all we are doing is printing out each node. The +``node.name()`` method returns an ``RTLIL::IdString``, which we convert for +printing with ``unescape()``. Then, to print the function of the node, we use +``node.to_string()`` which gives us a string of the form ``function(args)``. The +``function`` part is the result of ``Functional::IR::fn_to_string(node.fn())``; +while ``args`` is the zero or more arguments passed to the function, most +commonly the name of another node. Behind the scenes, the ``node.to_string()`` +method actually wraps ``node.visit(visitor)`` with a private visitor whose +return type is ``std::string``. + +Finally we iterate over the module's outputs and states, using +``Functional::IROutput::value()`` and ``Functional::IRState::next_value()`` +respectively in order to get the results of the transfer function. + +Example: Adapting SMT-LIB backend for Rosette +--------------------------------------------- + +This section will introduce the SMT-LIB functional backend +(`write_functional_smt2`) and what changes are needed to work with another +s-expression target, `Rosette`_ (`write_functional_rosette`). + +.. _Rosette: http://emina.github.io/rosette/ + +Overview +~~~~~~~~ + + Rosette is a solver-aided programming language that extends `Racket`_ with + language constructs for program synthesis, verification, and more. To verify + or synthesize code, Rosette compiles it to logical constraints solved with + off-the-shelf `SMT`_ solvers. + + -- https://emina.github.io/rosette/ + +.. _Racket: http://racket-lang.org/ +.. _SMT: http://smtlib.cs.uiowa.edu/ + +Rosette, being backed by SMT solvers and written with s-expressions, uses code +very similar to the `write_functional_smt2` output. As a result, the SMT-LIB +functional backend can be used as a starting point for implementing a Rosette +backend. + +Full code listings for the initial SMT-LIB backend and the converted Rosette +backend are included in the Yosys source repository under +:file:`backends/functional` as ``smtlib.cc`` and ``smtlib_rosette.cc`` +respectively. Note that the Rosette language is an extension of the Racket +language; this guide tends to refer to Racket when talking about the underlying +semantics/syntax of the language. + +The major changes from the SMT-LIB backend are as follows: + +- all of the ``Smt`` prefixes in names are replaced with ``Smtr`` to mean + ``smtlib_rosette``; +- syntax is adjusted for Racket; +- data structures for input/output/state are changed from using + ``declare-datatype`` with statically typed fields, to using ``struct`` with no + static typing; +- the transfer function also loses its static typing; +- sign/zero extension in Rosette use the output width instead of the number of + extra bits, gaining static typing; +- the single scope is traded for a global scope with local scope for each + struct; +- initial state is provided as a constant value instead of a set of assertions; +- and the ``-provides`` option is introduced to more easily use generated code + within Rosette based applications. + +Scope +~~~~~ + +Our first addition to the `minimal backend`_ above is that for both SMT-LIB and +Rosette backends, we are now targetting real languages which bring with them +their own sets of constraints with what we can use as identifiers. This is +where the ``Functional::Scope`` class described above comes in; by using this +class we can safely rename our identifiers in the generated output without +worrying about collisions or illegal names/characters. + +In the SMT-LIB version, the ``SmtScope`` class implements ``Scope``; +provides a constructor that iterates over a list of reserved keywords, calling +``reserve`` on each; and defines the ``is_character_legal`` method to reject any +characters which are not allowed in SMT-LIB variable names to then be replaced +with underscores in the output. To use this scope we create an instance of it, +and call the ``Scope::unique_name()`` method to generate a unique and legal name +for each of our identifiers. + +In the Rosette version we update the list of legal ascii characters in the +``is_character_legal`` method to only those allowed in Racket variable names. + +.. literalinclude:: /generated/functional/rosette.diff + :language: diff + :caption: diff of ``Scope`` class + :start-at: -struct SmtScope : public Functional::Scope { + :end-at: }; + +For the reserved keywords we trade the SMT-LIB specification for Racket to +prevent parts of our design from accidentally being treated as Racket code. We +also no longer need to reserve ``pair``, ``first``, and ``second``. In +`write_functional_smt2` these are used for combining the ``(inputs, +current_state)`` and ``(outputs, next_state)`` into a single variable. Racket +provides this functionality natively with ``cons``, which we will see later. + +.. inlined diff for skipping the actual lists +.. code-block:: diff + :caption: diff of ``reserved_keywords`` list + + const char *reserved_keywords[] = { + - // reserved keywords from the smtlib spec + - ... + + // reserved keywords from the racket spec + + ... + + // reserved for our own purposes + - "pair", "Pair", "first", "second", + - "inputs", "state", + + "inputs", "state", "name", + nullptr + }; + +.. note:: We skip over the actual list of reserved keywords from both the smtlib + and racket specifications to save on space in this document. + +Sort +~~~~ + +Next up in `write_functional_smt2` we see the ``Sort`` class. This is a wrapper +for the ``Functional::Sort`` class, providing the additional functionality of +mapping variable declarations to s-expressions with the ``to_sexpr()`` method. +The main change from ``SmtSort`` to ``SmtrSort`` is a syntactical one with +signals represented as ``bitvector``\ s, and memories as ``list``\ s of signals. + +.. literalinclude:: /generated/functional/rosette.diff + :language: diff + :caption: diff of ``Sort`` wrapper + :start-at: SExpr to_sexpr() const { + :end-before: }; + +Struct +~~~~~~ + +As we saw in the `minimal backend`_ above, the ``Functional::IR`` class tracks +the set of inputs, the set of outputs, and the set of "state" variables. The +SMT-LIB backend maps each of these sets into its own ``SmtStruct``, with each +variable getting a corresponding field in the struct and a specified `Sort`_. +`write_functional_smt2` then defines each of these structs as a new +``datatype``, with each element being strongly-typed. + +In Rosette, rather than defining new datatypes for our structs, we use the +native ``struct``. We also only declare each field by name because Racket +provides less static typing. For ease of use, we provide the expected type for +each field as comments. + +.. literalinclude:: /generated/functional/rosette.diff + :language: diff + :caption: diff of ``write_definition`` method + :start-at: void write_definition + :end-before: template void write_value + +Each field is added to the ``SmtStruct`` with the ``insert`` method, which also +reserves a unique name (or accessor) within the `Scope`_. These accessors +combine the struct name and field name and are globally unique, being used in +the ``access`` method for reading values from the input/current state. + +.. literalinclude:: /generated/functional/smtlib.cc + :language: c++ + :caption: ``Struct::access()`` method + :start-at: SExpr access( + :end-before: }; + +In Rosette, struct fields are accessed as ``-`` so +including the struct name in the field name would be redundant. For +`write_functional_rosette` we instead choose to make field names unique only +within the struct, while accessors are unique across the whole module. We thus +modify the class constructor and ``insert`` method to support this; providing +one scope that is local to the struct (``local_scope``) and one which is shared +across the whole module (``global_scope``), leaving the ``access`` method +unchanged. + +.. literalinclude:: /generated/functional/rosette.diff + :language: diff + :caption: diff of struct constructor + :start-at: SmtStruct(std::string name, SmtScope &scope) + :end-before: void write_definition + +Finally, ``SmtStruct`` also provides a ``write_value`` template method which +calls a provided function on each element in the struct. This is used later for +assigning values to the output/next state pair. The only change here is to +remove the check for zero-argument constructors since this is not necessary with +Rosette ``struct``\ s. + +.. literalinclude:: /generated/functional/rosette.diff + :language: diff + :caption: diff of ``write_value`` method + :start-at: template void write_value + :end-before: SExpr access + +PrintVisitor +~~~~~~~~~~~~ + +Remember in the `minimal backend`_ we converted nodes into strings for writing +using the ``node.to_string()`` method, which wrapped ``node.visit()`` with a +private visitor. We now want a custom visitor which can convert nodes into +s-expressions. This is where the ``PrintVisitor`` comes in, implementing the +abstract ``Functional::AbstractVisitor`` class with a return type of ``SExpr``. +For most functions, the Rosette output is very similar to the corresponding +SMT-LIB function with minor adjustments for syntax. + +.. literalinclude:: /generated/functional/rosette.diff + :language: diff + :caption: portion of ``Functional::AbstractVisitor`` implementation diff showing similarities + :start-at: SExpr logical_shift_left + :end-at: "list-set-bv" + +However there are some differences in the two formats with regards to how +booleans are handled, with Rosette providing built-in functions for conversion. + +.. literalinclude:: /generated/functional/rosette.diff + :language: diff + :caption: portion of ``Functional::AbstractVisitor`` implementation diff showing differences + :start-at: SExpr from_bool + :end-before: SExpr extract + +Of note here is the rare instance of the Rosette implementation *gaining* static +typing rather than losing it. Where SMT_LIB calls zero/sign extension with the +number of extra bits needed (given by ``out_width - a.width()``), Rosette +instead specifies the type of the output (given by ``list("bitvector", +out_width)``). + +.. literalinclude:: /generated/functional/rosette.diff + :language: diff + :caption: zero/sign extension implementation diff + :start-after: SExpr buf( + :end-before: SExpr concat( + :lines: 2-3, 5-6 + +.. note:: Be sure to check the source code for the full list of differences here. + +Module +~~~~~~ + +With most of the supporting classes out of the way, we now reach our three main +steps from the `minimal backend`_. These are all handled by the ``SmtModule`` +class, with the mapping from RTLIL module to FunctionalIR happening in the +constructor. Each of the three ``SmtStruct``\ s; inputs, outputs, and state; +are also created in the constructor, with each value in the corresponding lists +in the IR being ``insert``\ ed. + +.. literalinclude:: /generated/functional/smtlib.cc + :language: c++ + :caption: ``SmtModule`` constructor + :start-at: SmtModule(Module + :end-at: } + +Since Racket uses the ``-`` to access struct fields, the ``SmtrModule`` instead +uses an underscore for the name of the initial state. + +.. literalinclude:: /generated/functional/rosette.diff + :language: diff + :caption: diff of ``Module`` constructor + :start-at: scope.reserve(name + :end-before: for (auto input + +The ``write`` method is then responsible for writing the FunctionalIR to the +output file, formatted for the corresponding backend. ``SmtModule::write()`` +breaks the output file down into four parts: defining the three structs, +declaring the ``pair`` datatype, defining the transfer function ``(inputs, +current_state) -> (outputs, next_state)`` with ``write_eval``, and declaring the +initial state with ``write_initial``. The only change for the ``SmtrModule`` is +that the ``pair`` declaration isn't needed. + +.. literalinclude:: /generated/functional/rosette.diff + :language: diff + :caption: diff of ``Module::write()`` method + :start-at: void write(std::ostream &out) + :end-at: } + +The ``write_eval`` method is where the FunctionalIR nodes, outputs, and next +state are handled. Just as with the `minimal backend`_, we iterate over the +nodes with ``for(auto n : ir)``, and then use the ``Struct::write_value()`` +method for the ``output_struct`` and ``state_struct`` to iterate over the +outputs and next state respectively. + +.. literalinclude:: /generated/functional/smtlib.cc + :language: c++ + :caption: iterating over FunctionalIR nodes in ``SmtModule::write_eval()`` + :start-at: for(auto n : ir) + :end-at: } + +The main differences between our two backends here are syntactical. First we +change the ``define-fun`` for the Racket style ``define`` which drops the +explicitly typed inputs/outputs. And then we change the final result from a +``pair`` to the native ``cons`` which acts in much the same way, returning both +the ``outputs`` and the ``next_state`` in a single variable. + +.. literalinclude:: /generated/functional/rosette.diff + :language: diff + :caption: diff of ``Module::write_eval()`` transfer function declaration + :start-at: w.open(list("define-fun" + :end-at: w.open(list("define" + +.. literalinclude:: /generated/functional/rosette.diff + :language: diff + :caption: diff of output/next state handling ``Module::write_eval()`` + :start-at: w.open(list("pair" + :end-at: w.pop(); + +For the ``write_initial`` method, the SMT-LIB backend uses ``declare-const`` and +``assert``\ s which must always hold true. For Rosette we instead define the +initial state as any other variable that can be used by external code. This +variable, ``[name]_initial``, can then be used in the ``[name]`` function call; +allowing the Rosette code to be used in the generation of the ``next_state``, +whereas the SMT-LIB code can only verify that a given ``next_state`` is correct. + +.. literalinclude:: /generated/functional/rosette.diff + :language: diff + :caption: diff of ``Module::write_initial()`` method + :start-at: void write_initial + :end-before: void write + +Backend +~~~~~~~ + +The final part is the ``Backend`` itself, with much of the same boiler plate as +the `minimal backend`_. The main difference is that we use the `Module`_ to +perform the actual processing. + +.. literalinclude:: /generated/functional/smtlib.cc + :language: c++ + :caption: The ``FunctionalSmtBackend`` + :start-at: struct FunctionalSmtBackend + :end-at: } FunctionalSmtBackend; + +There are two additions here for Rosette. The first is that the output file +needs to start with the ``#lang`` definition which tells the +compiler/interpreter that we want to use the Rosette language module. The +second is that the `write_functional_rosette` command takes an optional +argument, ``-provides``. If this argument is given, then the output file gets +an additional line declaring that everything in the file should be exported for +use; allowing the file to be treated as a Racket package with structs and +mapping function available for use externally. + +.. literalinclude:: /generated/functional/rosette.diff + :language: diff + :caption: relevant portion of diff of ``Backend::execute()`` method + :start-at: lang rosette/safe + :end-before: for (auto module diff --git a/chips/yosys/docs/source/yosys_internals/extending_yosys/index.rst b/chips/yosys/docs/source/yosys_internals/extending_yosys/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..d7ef48b089d0ffe7fe9c60947103955cdb2dda58 --- /dev/null +++ b/chips/yosys/docs/source/yosys_internals/extending_yosys/index.rst @@ -0,0 +1,16 @@ +Working with the Yosys codebase +------------------------------- + +This section goes into additional detail on the Yosys source code and git +repository. This information is not needed for simply using Yosys, but may be +of interest for developers looking to customise Yosys builds. + +.. toctree:: + :maxdepth: 3 + + extensions + build_verific + functional_ir + advanced_bugpoint + contributing + test_suites diff --git a/chips/yosys/docs/source/yosys_internals/extending_yosys/test_suites.rst b/chips/yosys/docs/source/yosys_internals/extending_yosys/test_suites.rst new file mode 100644 index 0000000000000000000000000000000000000000..e74b035983eaaf27ccf06ec12daec9dba29f54c0 --- /dev/null +++ b/chips/yosys/docs/source/yosys_internals/extending_yosys/test_suites.rst @@ -0,0 +1,196 @@ +Testing Yosys +============= + +.. todo:: adding tests (makefile-tests vs seed-tests) + +Running the included test suite +------------------------------- + +The Yosys source comes with a test suite to avoid regressions and keep +everything working as expected. Tests can be run by building the ``test`` +target from the root Yosys directory. By default, this runs vanilla and unit +tests. + +.. code:: console + + cmake --preset default + cmake --build build --target test --parallel $(nproc) + +.. warning:: + + There are limitations when using ``Ninja`` as generator, so we suggest using + ``Unix Makefiles`` to make running tests in parallel possible. However, it is + possible to use it directly by running: + +.. code:: console + + cd tests + make -j9 + +Please note that in this case default build directory is ``build`` but can be +overwritten by providing :makevar:`BUILD_DIR` variable. + +Vanilla tests +~~~~~~~~~~~~~ + +.. TODO:: update for test infra changes + +These make up the majority of our testing coverage. They can be run with the +``test-vanilla`` CMake target. Usually their structure looks something like +this: you write a .ys file that gets automatically run, which runs a frontend +like ``read_verilog`` or ``read_rtlil`` with a relative path or a heredoc, then +runs some commands including the command under test, and then uses +:doc:`/using_yosys/more_scripting/selections` with ``-assert-count``. Usually +it's unnecessary to "register" the test anywhere as if it's being added to an +existing directory, depending on how the ``run-test.sh`` in that directory +works. + +Unit tests +~~~~~~~~~~ + +Running the unit tests requires the following additional packages: + +.. tab:: Ubuntu + + .. code:: console + + sudo apt-get install libgtest-dev + +.. tab:: macOS + + No additional requirements. + +Unit tests can be run with the ``test-unit`` CMake target. + +Functional tests +~~~~~~~~~~~~~~~~ + +Testing functional backends (see +:doc:`/yosys_internals/extending_yosys/functional_ir`) has a few requirements in +addition to those listed in :ref:`getting_started/installation:Build +prerequisites`: + +.. tab:: Ubuntu + + .. code:: console + + sudo apt-get install racket + raco pkg install rosette + pip install pytest-xdist pytest-xdist-gnumake + +.. tab:: macOS + + .. code:: console + + brew install racket + raco pkg install rosette + pip install pytest-xdist pytest-xdist-gnumake + +If you don't have one of the :ref:`getting_started/installation:CAD suite(s)` +installed, you should also install Z3 `following their +instructions `_. + +Functional tests are disabled by default, to enable them use next code snippet +and run tests as usual: + +.. code:: console + + cmake -B build . -DYOSYS_ENABLE_FUNCTIONAL_TESTS=ON + cmake --build build --target test --parallel $(nproc) + +Or run just functional tests with: + +.. code:: console + + cmake --build build --target test-functional + +Docs tests +~~~~~~~~~~ + +There are some additional tests for checking examples included in the +documentation, which can be run with the ``test-docs`` CMake target. This also +includes checking some macro commands to ensure that descriptions of them are +kept up to date, and is mostly intended for CI. + + +Automatic testing +----------------- + +The `Yosys Git repo`_ has automatic testing of builds and running of the +included test suite on both Ubuntu and macOS, as well as across range of +compiler versions. For up to date information, including OS versions, refer to +`the git actions page`_. + +.. _Yosys Git repo: https://github.com/YosysHQ/yosys +.. _the git actions page: https://github.com/YosysHQ/yosys/actions + +.. + How to add a unit test + ---------------------- + + Unit test brings some advantages, briefly, we can list some of them (reference + [1](https://en.wikipedia.org/wiki/Unit_testing)): + + * Tests reduce bugs in new features; + * Tests reduce bugs in existing features; + * Tests are good documentation; + * Tests reduce the cost of change; + * Tests allow refactoring; + + With those advantages in mind, it was required to choose a framework which fits + well with C/C++ code. Hence, `google test`_ was chosen, because it is widely + used and it is relatively easy learn. + + .. _google test: https://github.com/google/googletest + + Install and configure google test (manually) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + In this section, you will see a brief description of how to install google test. + However, it is strongly recommended that you take a look to the official + repository (https://github.com/google/googletest) and refers to that if you have + any problem to install it. Follow the steps below: + + * Install: cmake and pthread + * Clone google test project from: https://github.com/google/googletest and enter + in the project directory + * Inside project directory, type: + + .. code-block:: console + + cmake -DBUILD_SHARED_LIBS=ON . + make + + * After compilation, copy all ``*.so`` inside directory ``googlemock`` and + ``googlemock/gtest`` to ``/usr/lib/`` + * Done! Now you can compile your tests. + + If you have any problem, go to the official repository to find help. + + Ps.: Some distros already have googletest packed. If your distro supports it, + you can use it instead of compile. + + Create a new unit test + ~~~~~~~~~~~~~~~~~~~~~~ + + If you want to add new unit tests for Yosys, just follow the steps below: + + * Go to directory :file:`test/unit/` + * In this directory you can find something similar Yosys's directory structure. + To create your unit test file you have to follow this pattern: + fileNameToImplementUnitTest + Test.cc. E.g.: if you want to implement the unit + test for ``kernel/celledges.cc``, you will need to create a file like this: + ``tests/unit/kernel/celledgesTest.cc``; + * Implement your unit test + * Add unit test to file list in `CMakeLists.txt` + In case unit tests are added to new directory, note that you need also to + create new `CmakeList.txt` file and add ``yosys_gtest(dir-name unit-test.cc)``` + + Run unit tests + ~~~~~~~~~~~~~~ + + To compile and run all unit tests, just go to yosys root directory and type: + + .. code-block:: console + + cmake --build build --target test-unit diff --git a/chips/yosys/docs/source/yosys_internals/flow/control_and_data.rst b/chips/yosys/docs/source/yosys_internals/flow/control_and_data.rst new file mode 100644 index 0000000000000000000000000000000000000000..70a84747f9ec1973b6f465ff98fff2bbd191b633 --- /dev/null +++ b/chips/yosys/docs/source/yosys_internals/flow/control_and_data.rst @@ -0,0 +1,31 @@ +Control and data flow +===================== + +.. todo:: less academic + +The data- and control-flow of a typical synthesis tool is very similar to the +data- and control-flow of a typical compiler: different subsystems are called in +a predetermined order, each consuming the data generated by the last subsystem +and generating the data for the next subsystem (see :numref:`Fig. %s +`). + +.. figure:: /_images/internals/approach_flow.* + :class: width-helper invert-helper + :name: fig:approach_flow + + General data- and control-flow of a synthesis tool + +The first subsystem to be called is usually called a frontend. It does not +process the data generated by another subsystem but instead reads the user +input—in the case of a HDL synthesis tool, the behavioural HDL code. + +The subsystems that consume data from previous subsystems and produce data for +the next subsystems (usually in the same or a similar format) are called passes. + +The last subsystem that is executed transforms the data generated by the last +pass into a suitable output format and writes it to a disk file. This subsystem +is usually called the backend. + +In Yosys all frontends, passes and backends are directly available as commands +in the synthesis script. Thus the user can easily create a custom synthesis flow +just by calling passes in the right order in a synthesis script. diff --git a/chips/yosys/docs/source/yosys_internals/flow/index.rst b/chips/yosys/docs/source/yosys_internals/flow/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..565cea2bbba9d668ac0f37cb4584f7351429c8f1 --- /dev/null +++ b/chips/yosys/docs/source/yosys_internals/flow/index.rst @@ -0,0 +1,18 @@ +Internal flow +============= + +A (usually short) synthesis script controls Yosys. + +These scripts contain three types of commands: + +- **Frontends**, that read input files (usually Verilog); +- **Passes**, that perform transformations on the design in memory; +- **Backends**, that write the design in memory to a file (various formats are + available: Verilog, BLIF, EDIF, SPICE, BTOR, . . .). + +.. toctree:: + :maxdepth: 3 + + overview + control_and_data + verilog_frontend diff --git a/chips/yosys/docs/source/yosys_internals/flow/overview.rst b/chips/yosys/docs/source/yosys_internals/flow/overview.rst new file mode 100644 index 0000000000000000000000000000000000000000..3effe462bc720f30ff675a9e867b85d26e82fb34 --- /dev/null +++ b/chips/yosys/docs/source/yosys_internals/flow/overview.rst @@ -0,0 +1,49 @@ +Flow overview +============= + +.. todo:: less academic + +:numref:`Figure %s ` shows the simplified data flow within +Yosys. Rectangles in the figure represent program modules and ellipses internal +data structures that are used to exchange design data between the program +modules. + +Design data is read in using one of the frontend modules. The high-level HDL +frontends for Verilog and VHDL code generate an abstract syntax tree (AST) that +is then passed to the AST frontend. Note that both HDL frontends use the same +AST representation that is powerful enough to cover the Verilog HDL and VHDL +language. + +The AST Frontend then compiles the AST to Yosys's main internal data format, the +RTL Intermediate Language (RTLIL). A more detailed description of this format is +given in :doc:`/yosys_internals/formats/rtlil_rep`. + +There is also a text representation of the RTLIL data structure that can be +parsed using the RTLIL Frontend which is described in +:doc:`/appendix/rtlil_text`. + +The design data may then be transformed using a series of passes that all +operate on the RTLIL representation of the design. + +Finally the design in RTLIL representation is converted back to text by one of +the backends, namely the Verilog Backend for generating Verilog netlists and the +RTLIL Backend for writing the RTLIL data in the same format that is understood +by the RTLIL Frontend. + +With the exception of the AST Frontend, which is called by the high-level HDL +frontends and can't be called directly by the user, all program modules are +called by the user (usually using a synthesis script that contains text commands +for Yosys). + +By combining passes in different ways and/or adding additional passes to Yosys +it is possible to adapt Yosys to a wide range of applications. For this to be +possible it is key that (1) all passes operate on the same data structure +(RTLIL) and (2) that this data structure is powerful enough to represent the +design in different stages of the synthesis. + +.. figure:: /_images/internals/overview_flow.* + :class: width-helper invert-helper + :name: fig:Overview_flow + + Yosys simplified data flow (ellipses: data structures, rectangles: + program modules) diff --git a/chips/yosys/docs/source/yosys_internals/flow/verilog_frontend.rst b/chips/yosys/docs/source/yosys_internals/flow/verilog_frontend.rst new file mode 100644 index 0000000000000000000000000000000000000000..73a67f2f24b0f38efa3947c4c2f3c9425c962c8c --- /dev/null +++ b/chips/yosys/docs/source/yosys_internals/flow/verilog_frontend.rst @@ -0,0 +1,657 @@ +.. _chapter:verilog: + +The Verilog and AST frontends +============================= + +This chapter provides an overview of the implementation of the Yosys Verilog and +AST frontends. The Verilog frontend reads Verilog-2005 code and creates an +abstract syntax tree (AST) representation of the input. This AST representation +is then passed to the AST frontend that converts it to RTLIL data, as +illustrated in :numref:`Fig. %s `. + +.. figure:: /_images/internals/verilog_flow.* + :class: width-helper invert-helper + :name: fig:Verilog_flow + + Simplified Verilog to RTLIL data flow + +Transforming Verilog to AST +--------------------------- + +The Verilog frontend converts the Verilog sources to an internal AST +representation that closely resembles the structure of the original Verilog +code. The Verilog frontend consists of three components, the Preprocessor, the +Lexer and the Parser. + +The source code to the Verilog frontend can be found in +:file:`frontends/verilog/` in the Yosys source tree. + +The Verilog preprocessor +~~~~~~~~~~~~~~~~~~~~~~~~ + +The Verilog preprocessor scans over the Verilog source code and interprets some +of the Verilog compiler directives such as :literal:`\`include`, +:literal:`\`define` and :literal:`\`ifdef`. + +It is implemented as a C++ function that is passed a file descriptor as input +and returns the pre-processed Verilog code as a ``std::string``. + +The source code to the Verilog Preprocessor can be found in +:file:`frontends/verilog/preproc.cc` in the Yosys source tree. + +The Verilog lexer +~~~~~~~~~~~~~~~~~ + +The Verilog Lexer is written using the lexer generator flex. Its source code can +be found in :file:`frontends/verilog/verilog_lexer.l` in the Yosys source tree. +The lexer does little more than identifying all keywords and literals recognised +by the Yosys Verilog frontend. + +The lexer keeps track of the current location in the Verilog source code with +a ``VerilogLexer::out_loc`` and uses it to construct parser-defined +symbol objects. + +Finally the lexer identifies and handles special comments such as "``// synopsys +translate_off``" and "``// synopsys full_case``". (It is recommended to use +:literal:`\`ifdef` constructs instead of the Synsopsys translate_on/off comments +and attributes such as ``(* full_case *)`` over "``// synopsys full_case``" +whenever possible.) + +The Verilog parser +~~~~~~~~~~~~~~~~~~ + +The Verilog Parser is written using the parser generator bison. Its source code +can be found in :file:`frontends/verilog/verilog_parser.y` in the Yosys source +tree. + +It generates an AST using the ``AST::AstNode`` data structure defined in +:file:`frontends/ast/ast.h`. An ``AST::AstNode`` object has the following +properties: + +.. list-table:: AST node types with their corresponding Verilog constructs. + :name: tab:Verilog_AstNodeType + :widths: 50 50 + + * - AST Node Type + - Corresponding Verilog Construct + * - AST_NONE + - This Node type should never be used. + * - AST_DESIGN + - This node type is used for the top node of the AST tree. It has no + corresponding Verilog construct. + * - AST_MODULE, AST_TASK, AST_FUNCTION + - ``module``, ``task`` and ``function`` + * - AST_WIRE + - ``input``, ``output``, ``wire``, ``reg`` and ``integer`` + * - AST_MEMORY + - Verilog Arrays + * - AST_AUTOWIRE + - Created by the simplifier when an undeclared signal name is used. + * - AST_PARAMETER, AST_LOCALPARAM + - ``parameter`` and ``localparam`` + * - AST_PARASET + - Parameter set in cell instantiation + * - AST_ARGUMENT + - Port connection in cell instantiation + * - AST_RANGE + - Bit-Index in a signal or element index in array + * - AST_CONSTANT + - A literal value + * - AST_CELLTYPE + - The type of cell in cell instantiation + * - AST_IDENTIFIER + - An Identifier (signal name in expression or cell/task/etc. name in other + contexts) + * - AST_PREFIX + - Construct an identifier in the form []. (used + only in advanced generate constructs) + * - AST_FCALL, AST_TCALL + - Call to function or task + * - AST_TO_SIGNED, AST_TO_UNSIGNED + - The ``$signed()`` and ``$unsigned()`` functions + * - AST_CONCAT, AST_REPLICATE + - The ``{...}`` and ``{...{...}}`` operators + * - AST_BIT_NOT, AST_BIT_AND, AST_BIT_OR, AST_BIT_XOR, AST_BIT_XNOR + - The bitwise operators ``~``, ``&``, ``|``, ``^`` and ``~^`` + * - AST_REDUCE_AND, AST_REDUCE_OR, AST_REDUCE_XOR, AST_REDUCE_XNOR + - The unary reduction operators ``~``, ``&``, ``|``, ``^`` and ``~^`` + * - AST_REDUCE_BOOL + - Conversion from multi-bit value to boolean value (equivalent to + AST_REDUCE_OR) + * - AST_SHIFT_LEFT, AST_SHIFT_RIGHT, AST_SHIFT_SLEFT, AST_SHIFT_SRIGHT + - The shift operators ``<<``, ``>>``, ``<<<`` and ``>>>`` + * - AST_LT, AST_LE, AST_EQ, AST_NE, AST_GE, AST_GT + - The relational operators ``<``, ``<=``, ``==``, ``!=``, ``>=`` and ``>`` + * - AST_ADD, AST_SUB, AST_MUL, AST_DIV, AST_MOD, AST_POW + - The binary operators ``+``, ``-``, ``*``, ``/``, ``%`` and ``**`` + * - AST_POS, AST_NEG + - The prefix operators ``+`` and ``-`` + * - AST_LOGIC_AND, AST_LOGIC_OR, AST_LOGIC_NOT + - The logic operators ``&&``, ``||`` and ``!`` + * - AST_TERNARY + - The ternary ``?:``-operator + * - AST_MEMRD AST_MEMWR + - Read and write memories. These nodes are generated by the AST simplifier + for writes/reads to/from Verilog arrays. + * - AST_ASSIGN + - An ``assign`` statement + * - AST_CELL + - A cell instantiation + * - AST_PRIMITIVE + - A primitive cell (``and``, ``nand``, ``or``, etc.) + * - AST_ALWAYS, AST_INITIAL + - Verilog ``always``- and ``initial``-blocks + * - AST_BLOCK + - A ``begin``-``end``-block + * - AST_ASSIGN_EQ. AST_ASSIGN_LE + - Blocking (``=``) and nonblocking (``<=``) assignments within an + ``always``- or ``initial``-block + * - AST_CASE. AST_COND, AST_DEFAULT + - The ``case`` (``if``) statements, conditions within a case and the + default case respectively + * - AST_FOR + - A ``for``-loop with an ``always``- or ``initial``-block + * - AST_GENVAR, AST_GENBLOCK, AST_GENFOR, AST_GENIF + - The ``genvar`` and ``generate`` keywords and ``for`` and ``if`` within a + generate block. + * - AST_POSEDGE, AST_NEGEDGE, AST_EDGE + - Event conditions for ``always`` blocks. + +- | The node type + | This enum (``AST::AstNodeType``) specifies the role of the node. + :numref:`Table %s ` contains a list of all node + types. + +- | The child nodes + | This is a list of pointers to all children in the abstract syntax tree. + +- | Attributes + | As almost every AST node might have Verilog attributes assigned to it, the + ``AST::AstNode`` has direct support for attributes. Note that the attribute + values are again AST nodes. + +- | Node content + | Each node might have additional content data. A series of member variables + exist to hold such data. For example the member ``std::string str`` can + hold a string value and is used e.g. in the ``AST_IDENTIFIER`` node type to + store the identifier name. + +- | Source code location + | Each ``AST::AstNode`` is automatically annotated with the current source + code location by the ``AST::AstNode`` constructor. The ``location`` type + is a manual reimplementation of the bison-provided location type. This + type is defined at ``frontends/verilog/verilog_location.h``. + +The ``AST::AstNode`` constructor can be called with up to 4 child nodes. This +simplifies the creation of AST nodes for simple expressions a bit. For example +the bison code for parsing multiplications: + +.. code:: none + :number-lines: + + basic_expr TOK_ASTER attr basic_expr { + $$ = std::make_unique(AST_MUL, std::move($1), std::move($4)); + SET_AST_NODE_LOC($$.get(), @1, @4); + append_attr($$.get(), $3); + } | + +The generated AST data structure is then passed directly to the AST frontend +that performs the actual conversion to RTLIL. + +Note that the Yosys command ``read_verilog`` provides the options ``-yydebug`` +and ``-dump_ast`` that can be used to print the parse tree or abstract syntax +tree respectively. + +Transforming AST to RTLIL +------------------------- + +The AST frontend converts a set of modules in AST representation to modules in +RTLIL representation and adds them to the current design. This is done in two +steps: simplification and RTLIL generation. + +The source code to the AST frontend can be found in ``frontends/ast/`` in the +Yosys source tree. + +AST simplification +~~~~~~~~~~~~~~~~~~ + +A full-featured AST is too complex to be transformed into RTLIL directly. +Therefore it must first be brought into a simpler form. This is done by calling +the ``AST::AstNode::simplify()`` method of all ``AST_MODULE`` nodes in the AST. +This initiates a recursive process that performs the following transformations +on the AST data structure: + +- Inline all task and function calls. + +- Evaluate all ``generate``-statements and unroll all ``for``-loops. + +- Perform const folding where it is necessary (e.g. in the value part of + ``AST_PARAMETER``, ``AST_LOCALPARAM``, ``AST_PARASET`` and ``AST_RANGE`` + nodes). + +- Replace ``AST_PRIMITIVE`` nodes with appropriate ``AST_ASSIGN`` nodes. + +- Replace dynamic bit ranges in the left-hand-side of assignments with + ``AST_CASE`` nodes with ``AST_COND`` children for each possible case. + +- Detect array access patterns that are too complicated for the + ``RTLIL::Memory`` abstraction and replace them with a set of signals and + cases for all reads and/or writes. + +- Otherwise replace array accesses with ``AST_MEMRD`` and ``AST_MEMWR`` nodes. + +In addition to these transformations, the simplifier also annotates the +AST with additional information that is needed for the RTLIL generator, +namely: + +- All ranges (width of signals and bit selections) are not only const + folded but (when a constant value is found) are also written to + member variables in the AST_RANGE node. + +- All identifiers are resolved and all ``AST_IDENTIFIER`` nodes are annotated + with a pointer to the AST node that contains the declaration of the + identifier. If no declaration has been found, an ``AST_AUTOWIRE`` node is + created and used for the annotation. + +This produces an AST that is fairly easy to convert to the RTLIL format. + +Generating RTLIL +~~~~~~~~~~~~~~~~ + +After AST simplification, the ``AST::AstNode::genRTLIL()`` method of each +``AST_MODULE`` node in the AST is called. This initiates a recursive process +that generates equivalent RTLIL data for the AST data. + +The ``AST::AstNode::genRTLIL()`` method returns an ``RTLIL::SigSpec`` structure. +For nodes that represent expressions (operators, constants, signals, etc.), the +cells needed to implement the calculation described by the expression are +created and the resulting signal is returned. That way it is easy to generate +the circuits for large expressions using depth-first recursion. For nodes that +do not represent an expression (such as ``AST_CELL``), the corresponding circuit +is generated and an empty ``RTLIL::SigSpec`` is returned. + +Synthesizing Verilog always blocks +-------------------------------------- + +For behavioural Verilog code (code utilizing ``always``- and ``initial``-blocks) +it is necessary to also generate ``RTLIL::Process`` objects. This is done in the +following way: + +Whenever ``AST::AstNode::genRTLIL()`` encounters an ``always``- or +``initial``-block, it creates an instance of ``AST_INTERNAL::ProcessGenerator``. +This object then generates the ``RTLIL::Process`` object for the block. It also +calls ``AST::AstNode::genRTLIL()`` for all right-hand-side expressions contained +within the block. + +First the ``AST_INTERNAL::ProcessGenerator`` creates a list of all signals +assigned within the block. It then creates a set of temporary signals using the +naming scheme ``$ \ `` for each of the assigned signals. + +Then an ``RTLIL::Process`` is created that assigns all intermediate values for +each left-hand-side signal to the temporary signal in its +``RTLIL::CaseRule``/``RTLIL::SwitchRule`` tree. + +Finally a ``RTLIL::SyncRule`` is created for the ``RTLIL::Process`` that assigns +the temporary signals for the final values to the actual signals. + +A process may also contain memory writes. A ``RTLIL::MemWriteAction`` is created +for each of them. + +Calls to ``AST::AstNode::genRTLIL()`` are generated for right hand sides as +needed. When blocking assignments are used, ``AST::AstNode::genRTLIL()`` is +configured using global variables to use the temporary signals that hold the +correct intermediate values whenever one of the previously assigned signals is +used in an expression. + +Unfortunately the generation of a correct +``RTLIL::CaseRule``/\ ``RTLIL::SwitchRule`` tree for behavioural code is a +non-trivial task. The AST frontend solves the problem using the approach +described on the following pages. The following example illustrates what the +algorithm is supposed to do. Consider the following Verilog code: + +.. code:: verilog + :number-lines: + + always @(posedge clock) begin + out1 = in1; + if (in2) + out1 = !out1; + out2 <= out1; + if (in3) + out2 <= out2; + if (in4) + if (in5) + out3 <= in6; + else + out3 <= in7; + out1 = out1 ^ out2; + end + +This is translated by the Verilog and AST frontends into the following RTLIL +code (attributes, cell parameters and wire declarations not included): + +.. code:: RTLIL + :number-lines: + + cell $logic_not $logic_not$:4$2 + connect \A \in1 + connect \Y $logic_not$:4$2_Y + end + cell $xor $xor$:13$3 + connect \A $1\out1[0:0] + connect \B \out2 + connect \Y $xor$:13$3_Y + end + process $proc$:1$1 + assign $0\out3[0:0] \out3 + assign $0\out2[0:0] $1\out1[0:0] + assign $0\out1[0:0] $xor$:13$3_Y + switch \in2 + case 1'1 + assign $1\out1[0:0] $logic_not$:4$2_Y + case + assign $1\out1[0:0] \in1 + end + switch \in3 + case 1'1 + assign $0\out2[0:0] \out2 + case + end + switch \in4 + case 1'1 + switch \in5 + case 1'1 + assign $0\out3[0:0] \in6 + case + assign $0\out3[0:0] \in7 + end + case + end + sync posedge \clock + update \out1 $0\out1[0:0] + update \out2 $0\out2[0:0] + update \out3 $0\out3[0:0] + end + +Note that the two operators are translated into separate cells outside the +generated process. The signal ``out1`` is assigned using blocking assignments +and therefore ``out1`` has been replaced with a different signal in all +expressions after the initial assignment. The signal ``out2`` is assigned using +nonblocking assignments and therefore is not substituted on the right-hand-side +expressions. + +The ``RTLIL::CaseRule``/\ ``RTLIL::SwitchRule`` tree must be interpreted the +following way: + +- On each case level (the body of the process is the root case), first the + actions on this level are evaluated and then the switches within the case are + evaluated. (Note that the last assignment on line 13 of the Verilog code has + been moved to the beginning of the RTLIL process to line 13 of the RTLIL + listing.) + + I.e. the special cases deeper in the switch hierarchy override the defaults + on the upper levels. The assignments in lines 12 and 22 of the RTLIL code + serve as an example for this. + + Note that in contrast to this, the order within the ``RTLIL::SwitchRule`` + objects within a ``RTLIL::CaseRule`` is preserved with respect to the + original AST and Verilog code. + +- The whole ``RTLIL::CaseRule``/\ ``RTLIL::SwitchRule`` tree describes an + asynchronous circuit. I.e. the decision tree formed by the switches can be + seen independently for each assigned signal. Whenever one assigned signal + changes, all signals that depend on the changed signals are to be updated. + For example the assignments in lines 16 and 18 in the RTLIL code in fact + influence the assignment in line 12, even though they are in the "wrong + order". + +The only synchronous part of the process is in the ``RTLIL::SyncRule`` object +generated at line 35 in the RTLIL code. The sync rule is the only part of the +process where the original signals are assigned. The synchronization event from +the original Verilog code has been translated into the synchronization type +(posedge) and signal (``\clock``) for the ``RTLIL::SyncRule`` object. In the +case of this simple example the ``RTLIL::SyncRule`` object is later simply +transformed into a set of d-type flip-flops and the +``RTLIL::CaseRule``/\ ``RTLIL::SwitchRule`` tree to a decision tree using +multiplexers. + +In more complex examples (e.g. asynchronous resets) the part of the +``RTLIL::CaseRule``/\ ``RTLIL::SwitchRule`` tree that describes the asynchronous +reset must first be transformed to the correct ``RTLIL::SyncRule`` objects. This +is done by the ``proc_arst`` pass. + +The ProcessGenerator algorithm +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The ``AST_INTERNAL::ProcessGenerator`` uses the following internal state +variables: + +- | ``subst_rvalue_from`` and ``subst_rvalue_to`` + | These two variables hold the replacement pattern that should be used by + ``AST::AstNode::genRTLIL()`` for signals with blocking assignments. After + initialization of ``AST_INTERNAL::ProcessGenerator`` these two variables are + empty. + +- | ``subst_lvalue_from`` and ``subst_lvalue_to`` + | These two variables contain the mapping from left-hand-side signals (``\ + ``) to the current temporary signal for the same thing (initially + ``$0\ ``). + +- | ``current_case`` + | A pointer to a ``RTLIL::CaseRule`` object. Initially this is the root case + of the generated ``RTLIL::Process``. + +As the algorithm runs these variables are continuously modified as well as +pushed to the stack and later restored to their earlier values by popping from +the stack. + +On startup the ProcessGenerator generates a new ``RTLIL::Process`` object with +an empty root case and initializes its state variables as described above. Then +the ``RTLIL::SyncRule`` objects are created using the synchronization events +from the AST_ALWAYS node and the initial values of ``subst_lvalue_from`` and +``subst_lvalue_to``. Then the AST for this process is evaluated recursively. + +During this recursive evaluation, three different relevant types of AST nodes +can be discovered: ``AST_ASSIGN_LE`` (nonblocking assignments), +``AST_ASSIGN_EQ`` (blocking assignments) and ``AST_CASE`` (``if`` or ``case`` +statement). + +Handling of nonblocking assignments +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +When an ``AST_ASSIGN_LE`` node is discovered, the following actions are +performed by the ProcessGenerator: + +- The left-hand-side is evaluated using ``AST::AstNode::genRTLIL()`` and mapped + to a temporary signal name using ``subst_lvalue_from`` and + ``subst_lvalue_to``. + +- The right-hand-side is evaluated using ``AST::AstNode::genRTLIL()``. For this + call, the values of ``subst_rvalue_from`` and ``subst_rvalue_to`` are used to + map blocking-assigned signals correctly. + +- Remove all assignments to the same left-hand-side as this assignment from the + ``current_case`` and all cases within it. + +- Add the new assignment to the ``current_case``. + +Handling of blocking assignments +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +When an ``AST_ASSIGN_EQ`` node is discovered, the following actions are +performed by the ProcessGenerator: + +- Perform all the steps that would be performed for a nonblocking assignment + (see above). + +- Remove the found left-hand-side (before lvalue mapping) from + ``subst_rvalue_from`` and also remove the respective bits from + ``subst_rvalue_to``. + +- Append the found left-hand-side (before lvalue mapping) to + ``subst_rvalue_from`` and append the found right-hand-side to + ``subst_rvalue_to``. + +Handling of cases and if-statements +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +When an ``AST_CASE`` node is discovered, the following actions are performed by +the ProcessGenerator: + +- The values of ``subst_rvalue_from``, ``subst_rvalue_to``, + ``subst_lvalue_from`` and ``subst_lvalue_to`` are pushed to the stack. + +- A new ``RTLIL::SwitchRule`` object is generated, the selection expression is + evaluated using ``AST::AstNode::genRTLIL()`` (with the use of + ``subst_rvalue_from`` and ``subst_rvalue_to``) and added to the + ``RTLIL::SwitchRule`` object and the object is added to the ``current_case``. + +- All lvalues assigned to within the ``AST_CASE`` node using blocking + assignments are collected and saved in the local variable + ``this_case_eq_lvalue``. + +- New temporary signals are generated for all signals in + ``this_case_eq_lvalue`` and stored in ``this_case_eq_ltemp``. + +- The signals in ``this_case_eq_lvalue`` are mapped using ``subst_rvalue_from`` + and ``subst_rvalue_to`` and the resulting set of signals is stored in + ``this_case_eq_rvalue``. + +Then the following steps are performed for each ``AST_COND`` node within the +``AST_CASE`` node: + +- Set ``subst_rvalue_from``, ``subst_rvalue_to``, ``subst_lvalue_from`` and + ``subst_lvalue_to`` to the values that have been pushed to the stack. + +- Remove ``this_case_eq_lvalue`` from + ``subst_lvalue_from``/``subst_lvalue_to``. + +- Append ``this_case_eq_lvalue`` to ``subst_lvalue_from`` and append + ``this_case_eq_ltemp`` to ``subst_lvalue_to``. + +- Push the value of ``current_case``. + +- Create a new ``RTLIL::CaseRule``. Set ``current_case`` to the new object and + add the new object to the ``RTLIL::SwitchRule`` created above. + +- Add an assignment from ``this_case_eq_rvalue`` to ``this_case_eq_ltemp`` to + the new ``current_case``. + +- Evaluate the compare value for this case using + ``AST::AstNode::genRTLIL()`` (with the use of ``subst_rvalue_from`` + and ``subst_rvalue_to``) modify the new ``current_case`` accordingly. + +- Recursion into the children of the ``AST_COND`` node. + +- Restore ``current_case`` by popping the old value from the stack. + +Finally the following steps are performed: + +- The values of ``subst_rvalue_from``, ``subst_rvalue_to``, + ``subst_lvalue_from`` and ``subst_lvalue_to`` are popped from the stack. + +- The signals from ``this_case_eq_lvalue`` are removed from the + ``subst_rvalue_from``/``subst_rvalue_to``-pair. + +- The value of ``this_case_eq_lvalue`` is appended to ``subst_rvalue_from`` and + the value of ``this_case_eq_ltemp`` is appended to ``subst_rvalue_to``. + +- Map the signals in ``this_case_eq_lvalue`` using + ``subst_lvalue_from``/``subst_lvalue_to``. + +- Remove all assignments to signals in ``this_case_eq_lvalue`` in + ``current_case`` and all cases within it. + +- Add an assignment from ``this_case_eq_ltemp`` to ``this_case_eq_lvalue`` to + ``current_case``. + +Further analysis of the algorithm for cases and if-statements +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +With respect to nonblocking assignments the algorithm is easy: later assignments +invalidate earlier assignments. For each signal assigned using nonblocking +assignments exactly one temporary variable is generated (with the ``$0``-prefix) +and this variable is used for all assignments of the variable. + +Note how all the ``_eq_``-variables become empty when no blocking assignments +are used and many of the steps in the algorithm can then be ignored as a result +of this. + +For a variable with blocking assignments the algorithm shows the following +behaviour: First a new temporary variable is created. This new temporary +variable is then registered as the assignment target for all assignments for +this variable within the cases for this ``AST_CASE`` node. Then for each case +the new temporary variable is first assigned the old temporary variable. This +assignment is overwritten if the variable is actually assigned in this case and +is kept as a default value otherwise. + +This yields an ``RTLIL::CaseRule`` that assigns the new temporary variable in +all branches. So when all cases have been processed a final assignment is added +to the containing block that assigns the new temporary variable to the old one. +Note how this step always overrides a previous assignment to the old temporary +variable. Other than nonblocking assignments, the old assignment could still +have an effect somewhere in the design, as there have been calls to +``AST::AstNode::genRTLIL()`` with a +``subst_rvalue_from``/\ ``subst_rvalue_to``-tuple that contained the +right-hand-side of the old assignment. + +The proc pass +~~~~~~~~~~~~~ + +The ProcessGenerator converts a behavioural model in AST representation to a +behavioural model in ``RTLIL::Process`` representation. The actual conversion +from a behavioural model to an RTL representation is performed by the `proc` +pass and the passes it launches: + +- | `proc_clean` and `proc_rmdead` + | These two passes just clean up the ``RTLIL::Process`` structure. The + `proc_clean` pass removes empty parts (eg. empty assignments) from the + process and `proc_rmdead` detects and removes unreachable branches from the + process's decision trees. + +- | `proc_arst` + | This pass detects processes that describe d-type flip-flops with + asynchronous resets and rewrites the process to better reflect what they + are modelling: Before this pass, an asynchronous reset has two + edge-sensitive sync rules and one top-level ``RTLIL::SwitchRule`` for the + reset path. After this pass the sync rule for the reset is level-sensitive + and the top-level ``RTLIL::SwitchRule`` has been removed. + +- | `proc_mux` + | This pass converts the ``RTLIL::CaseRule``/\ ``RTLIL::SwitchRule``-tree to + a tree of multiplexers per written signal. After this, the + ``RTLIL::Process`` structure only contains the ``RTLIL::SyncRule`` s that + describe the output registers. + +- | `proc_dff` + | This pass replaces the ``RTLIL::SyncRule``\ s to d-type flip-flops (with + asynchronous resets if necessary). + +- | `proc_memwr` + | This pass replaces the ``RTLIL::MemWriteAction``\ s with `$memwr` cells. + +- | `proc_clean` + | A final call to `proc_clean` removes the now empty ``RTLIL::Process`` + objects. + +Performing these last processing steps in passes instead of in the Verilog +frontend has two important benefits: + +First it improves the transparency of the process. Everything that happens in a +separate pass is easier to debug, as the RTLIL data structures can be easily +investigated before and after each of the steps. + +Second it improves flexibility. This scheme can easily be extended to support +other types of storage-elements, such as sr-latches or d-latches, without having +to extend the actual Verilog frontend. + +.. todo:: Synthesizing Verilog arrays + + Add some information on the generation of `$memrd` and `$memwr` cells and how + they are processed in the memory pass. + + +.. todo:: Synthesizing parametric designs + + Add some information on the ``RTLIL::Module::derive()`` method and how it is + used to synthesize parametric modules via the hierarchy pass. diff --git a/chips/yosys/docs/source/yosys_internals/formats/index.rst b/chips/yosys/docs/source/yosys_internals/formats/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..a6c29955e6283d2dbe0729ec0054e76c36bd4aca --- /dev/null +++ b/chips/yosys/docs/source/yosys_internals/formats/index.rst @@ -0,0 +1,58 @@ +Internal formats +================ + +Yosys uses two different internal formats. The first is used to store an +abstract syntax tree (AST) of a Verilog input file. This format is simply called +AST and is generated by the Verilog Frontend. This data structure is consumed by +a subsystem called AST Frontend [1]_. This AST Frontend then generates a design +in Yosys' main internal format, the +Register-Transfer-Level-Intermediate-Language (RTLIL) representation. It does +that by first performing a number of simplifications within the AST +representation and then generating RTLIL from the simplified AST data structure. + +The RTLIL representation is used by all passes as input and outputs. This has +the following advantages over using different representational formats between +different passes: + +- The passes can be rearranged in a different order and passes can be removed + or inserted. + +- Passes can simply pass-thru the parts of the design they don't change without + the need to convert between formats. In fact Yosys passes output the same + data structure they received as input and performs all changes in place. + +- All passes use the same interface, thus reducing the effort required to + understand a pass when reading the Yosys source code, e.g. when adding + additional features. + +The RTLIL representation is basically a netlist representation with the +following additional features: + +- An internal cell library with fixed-function cells to represent RTL datapath + and register cells as well as logical gate-level cells (single-bit gates and + registers). + +- Support for multi-bit values that can use individual bits from wires as well + as constant bits to represent coarse-grain netlists. + +- Support for basic behavioural constructs (if-then-else structures and + multi-case switches with a sensitivity list for updating the outputs). + +- Support for multi-port memories. + +The use of RTLIL also has the disadvantage of having a very powerful format +between all passes, even when doing gate-level synthesis where the more advanced +features are not needed. In order to reduce complexity for passes that operate +on a low-level representation, these passes check the features used in the input +RTLIL and fail to run when unsupported high-level constructs are used. In such +cases a pass that transforms the higher-level constructs to lower-level +constructs must be called from the synthesis script first. + +.. toctree:: + :maxdepth: 3 + + rtlil_rep + +.. [1] + In Yosys the term pass is only used to refer to commands that operate on the + RTLIL data structure. diff --git a/chips/yosys/docs/source/yosys_internals/formats/rtlil_rep.rst b/chips/yosys/docs/source/yosys_internals/formats/rtlil_rep.rst new file mode 100644 index 0000000000000000000000000000000000000000..0fa09a3bcf7b32b447b6e4332e116cb981b21303 --- /dev/null +++ b/chips/yosys/docs/source/yosys_internals/formats/rtlil_rep.rst @@ -0,0 +1,416 @@ +The RTL Intermediate Language (RTLIL) +===================================== + +All frontends, passes and backends in Yosys operate on a design in RTLIL +representation. The only exception are the high-level frontends that use the AST +representation as an intermediate step before generating RTLIL data. + +In order to avoid reinventing names for the RTLIL classes, they are simply +referred to by their full C++ name, i.e. including the ``RTLIL::`` namespace +prefix, in this document. + +:numref:`Figure %s ` shows a simplified Entity-Relationship +Diagram (ER Diagram) of RTLIL. In :math:`1:N` relationships the arrow points +from the :math:`N` side to the :math:`1`. For example one ``RTLIL::Design`` +contains :math:`N` (zero to many) instances of ``RTLIL::Module`` . A two-pointed +arrow indicates a :math:`1:1` relationship. + +The ``RTLIL::Design`` is the root object of the RTLIL data structure. There is +always one "current design" in memory which passes operate on, frontends add +data to and backends convert to exportable formats. But in some cases passes +internally generate additional ``RTLIL::Design`` objects. For example when a +pass is reading an auxiliary Verilog file such as a cell library, it might +create an additional ``RTLIL::Design`` object and call the Verilog frontend with +this other object to parse the cell library. + +.. figure:: /_images/internals/overview_rtlil.* + :class: width-helper invert-helper + :name: fig:Overview_RTLIL + + Simplified RTLIL Entity-Relationship Diagram + +There is only one active ``RTLIL::Design`` object that is used by all frontends, +passes and backends called by the user, e.g. using a synthesis script. The +``RTLIL::Design`` then contains zero to many ``RTLIL::Module`` objects. This +corresponds to modules in Verilog or entities in VHDL. Each module in turn +contains objects from three different categories: + +- ``RTLIL::Cell`` and ``RTLIL::Wire`` objects represent classical netlist data. + +- ``RTLIL::Process`` objects represent the decision trees (if-then-else statements, + etc.) and synchronization declarations (clock signals and sensitivity) from + Verilog always and VHDL process blocks. + +- ``RTLIL::Memory`` objects represent addressable memories (arrays). + +Usually the output of the synthesis procedure is a netlist, i.e. all +``RTLIL::Process`` and ``RTLIL::Memory`` objects must be replaced by +``RTLIL::Cell`` and ``RTLIL::Wire`` objects by synthesis passes. + +All features of the HDL that cannot be mapped directly to these RTLIL classes +must be transformed to an RTLIL-compatible representation by the HDL frontend. +This includes Verilog-features such as generate-blocks, loops and parameters. + +The following sections contain a more detailed description of the different +parts of RTLIL and rationale behind some of the design decisions. + +RTLIL identifiers +----------------- + +All identifiers in RTLIL (such as module names, port names, signal names, cell +types, etc.) follow the following naming convention: they must either start with +a backslash (``\``) or a dollar sign (``$``). + +Identifiers starting with a backslash are public visible identifiers. Usually +they originate from one of the HDL input files. For example the signal name +``\sig42`` is most likely a signal that was declared using the name ``sig42`` in +an HDL input file. On the other hand the signal name ``$sig42`` is an +auto-generated signal name. The backends convert all identifiers that start with +a dollar sign to identifiers that do not collide with identifiers that start +with a backslash. + +This has three advantages: + +- First, it is impossible that an auto-generated identifier collides with an + identifier that was provided by the user. + +- Second, the information about which identifiers were originally provided by + the user is always available which can help guide some optimizations. For + example, `opt_clean` tries to preserve signals with a user-provided name but + doesn't hesitate to delete signals that have auto-generated names when they + just duplicate other signals. Note that this can be overridden with the + ``-purge`` option to also delete internal nets with user-provided names. + +- Third, the delicate job of finding suitable auto-generated public visible + names is deferred to one central location. Internally auto-generated names + that may hold important information for Yosys developers can be used without + disturbing external tools. For example the Verilog backend assigns names in + the form ``_123_``. + +Whitespace and control characters (any character with an ASCII code 32 or less) +are not allowed in RTLIL identifiers; most frontends and backends cannot support +these characters in identifiers. + +In order to avoid programming errors, the RTLIL data structures check if all +identifiers start with either a backslash or a dollar sign, and contain no +whitespace or control characters. Violating these rules results in a runtime +error. + +All RTLIL identifiers are case sensitive. + +Some transformations, such as flattening, may have to change identifiers +provided by the user to avoid name collisions. When that happens, attribute +``hdlname`` is attached to the object with the changed identifier. This +attribute contains one name (if emitted directly by the frontend, or is a result +of disambiguation) or multiple names separated by spaces (if a result of +flattening). All names specified in the ``hdlname`` attribute are public and do +not include the leading ``\``. + +RTLIL::Design and RTLIL::Module +------------------------------- + +The ``RTLIL::Design`` object is basically just a container for ``RTLIL::Module`` +objects. In addition to a list of ``RTLIL::Module`` objects the +``RTLIL::Design`` also keeps a list of selected objects, i.e. the objects that +passes should operate on. In most cases the whole design is selected and +therefore passes operate on the whole design. But this mechanism can be useful +for more complex synthesis jobs in which only parts of the design should be +affected by certain passes. + +Besides the objects shown in the :ref:`ER diagram ` above, +an ``RTLIL::Module`` object contains the following additional properties: + +- The module name +- A list of attributes +- A list of connections between wires +- An optional frontend callback used to derive parametrized variations of the + module + +The attributes can be Verilog attributes imported by the Verilog frontend or +attributes assigned by passes. They can be used to store additional metadata +about modules or just mark them to be used by certain part of the synthesis +script but not by others. + +Verilog and VHDL both support parametric modules (known as "generic entities" in +VHDL). The RTLIL format does not support parametric modules itself. Instead each +module contains a callback function into the AST frontend to generate a +parametrized variation of the ``RTLIL::Module`` as needed. This callback then +returns the auto-generated name of the parametrized variation of the module. (A +hash over the parameters and the module name is used to prohibit the same +parametrized variation from being generated twice. For modules with only a few +parameters, a name directly containing all parameters is generated instead of a +hash string.) + +.. _sec:rtlil_cell_wire: + +RTLIL::Cell and RTLIL::Wire +--------------------------- + +A module contains zero to many ``RTLIL::Cell`` and ``RTLIL::Wire`` objects. +Objects of these types are used to model netlists. Usually the goal of all +synthesis efforts is to convert all modules to a state where the functionality +of the module is implemented only by cells from a given cell library and wires +to connect these cells with each other. Note that module ports are just wires +with a special property. + +An ``RTLIL::Wire`` object has the following properties: + +- The wire name +- A list of attributes +- A width (buses are just wires with a width more than 1) +- Bus direction (MSb to LSb or vice versa) +- Lowest valid bit index (LSb or MSb depending on bus direction) +- If the wire is a port: port number and direction (input/output/inout) + +As with modules, the attributes can be Verilog attributes imported by the +Verilog frontend or attributes assigned by passes. + +In Yosys, busses (signal vectors) are represented using a single wire object +with a width more than 1. So Yosys does not convert signal vectors to individual +signals. This makes some aspects of RTLIL more complex but enables Yosys to be +used for coarse grain synthesis where the cells of the target architecture +operate on entire signal vectors instead of single bit wires. + +In Verilog and VHDL, busses may have arbitrary bounds, and LSb can have either +the lowest or the highest bit index. In RTLIL, bit 0 always corresponds to LSb; +however, information from the HDL frontend is preserved so that the bus will be +correctly indexed in error messages, backend output, constraint files, etc. + +An ``RTLIL::Cell`` object has the following properties: + +- The cell name and type +- A list of attributes +- A list of parameters (for parametric cells) +- Cell ports and the connections of ports to wires and constants + +The connections of ports to wires are coded by assigning an ``RTLIL::SigSpec`` +to each cell port. The ``RTLIL::SigSpec`` data type is described in the next +section. + +.. _sec:rtlil_sigspec: + +RTLIL::SigSpec +-------------- + +A "signal" is everything that can be applied to a cell port. I.e. + +- | A bit from a wire (``RTLIL::SigBit``) + | 1em For example: ``mywire[24]`` + +- | A range of bits from a wire (wire variant of ``RTLIL::SigChunk``) + | 1em For example: ``mywire, mywire[15:8]`` + +- | Any constant value of arbitrary bit-width (``std::vector>`` variant of ``RTLIL::SigChunk``) + | 1em For example: ``1337, 16'b0000010100111001, 1'b1, 1'bx`` + +The ``RTLIL::SigSpec`` data type is used to represent signals. +It contains a single ``RTLIL::SigChunk`` or a vector of ``RTLIL::SigBit``. +The ``RTLIL::Cell`` object contains one ``RTLIL::SigSpec`` for each cell port. + +In addition, connections between wires are represented using a pair of +``RTLIL::SigSpec`` objects. Such pairs are needed in different locations. +Therefore the type name ``RTLIL::SigSig`` was defined for such a pair. + +.. _sec:rtlil_process: + +RTLIL::Process +-------------- + +When a high-level HDL frontend processes behavioural code it splits it up into +data path logic (e.g. the expression ``a + b`` is replaced by the output of an +adder that takes a and b as inputs) and an ``RTLIL::Process`` that models the +control logic of the behavioural code. Let's consider a simple example: + +.. code:: verilog + :number-lines: + + module ff_with_en_and_async_reset(clock, reset, enable, d, q); + input clock, reset, enable, d; + output reg q; + always @(posedge clock, posedge reset) + if (reset) + q <= 0; + else if (enable) + q <= d; + endmodule + +In this example there is no data path and therefore the ``RTLIL::Module`` +generated by the frontend only contains a few ``RTLIL::Wire`` objects and an +``RTLIL::Process``. The ``RTLIL::Process`` in RTLIL syntax: + +.. code:: RTLIL + :number-lines: + + process $proc$ff_with_en_and_async_reset.v:4$1 + assign $0\q[0:0] \q + switch \reset + case 1'1 + assign $0\q[0:0] 1'0 + case + switch \enable + case 1'1 + assign $0\q[0:0] \d + case + end + end + sync posedge \clock + update \q $0\q[0:0] + sync posedge \reset + update \q $0\q[0:0] + end + +This ``RTLIL::Process`` contains two ``RTLIL::SyncRule`` objects, two +``RTLIL::SwitchRule`` objects and five ``RTLIL::CaseRule`` objects. The wire +``$0\q[0:0]`` is an automatically created wire that holds the next value of +``\q``. The lines 2..12 describe how ``$0\q[0:0]`` should be calculated. The +lines 13..16 describe how the value of ``$0\q[0:0]`` is used to update ``\q``. + +An ``RTLIL::Process`` is a container for zero or more ``RTLIL::SyncRule`` +objects and exactly one ``RTLIL::CaseRule`` object, which is called the root +case. + +An ``RTLIL::SyncRule`` object contains an (optional) synchronization condition +(signal and edge-type), zero or more assignments (``RTLIL::SigSig``), and zero +or more memory writes (``RTLIL::MemWriteAction``). The always synchronization +condition is used to break combinatorial loops when a latch should be inferred +instead. + +An ``RTLIL::CaseRule`` is a container for zero or more assignments +(``RTLIL::SigSig``) and zero or more ``RTLIL::SwitchRule`` objects. An +``RTLIL::SwitchRule`` objects is a container for zero or more +``RTLIL::CaseRule`` objects. + +In the above example the lines 2..12 are the root case. Here ``$0\q[0:0]`` is +first assigned the old value ``\q`` as default value (line 2). The root case +also contains an ``RTLIL::SwitchRule`` object (lines 3..12). Such an object is +very similar to the C switch statement as it uses a control signal (``\reset`` +in this case) to determine which of its cases should be active. The +``RTLIL::SwitchRule`` object then contains one ``RTLIL::CaseRule`` object per +case. In this example there is a case [1]_ for ``\reset == 1`` that causes +``$0\q[0:0]`` to be set (lines 4 and 5) and a default case that in turn contains +a switch that sets ``$0\q[0:0]`` to the value of ``\d`` if ``\enable`` is active +(lines 6..11). + +A case can specify zero or more compare values that will determine whether it +matches. Each of the compare values must be the exact same width as the control +signal. When more than one compare value is specified, the case matches if any +of them matches the control signal; when zero compare values are specified, the +case always matches (i.e. it is the default case). + +A switch prioritizes cases from first to last: multiple cases can match, but +only the first matched case becomes active. This normally synthesizes to a +priority encoder. The parallel_case attribute allows passes to assume that no +more than one case will match, and full_case attribute allows passes to assume +that exactly one case will match; if these invariants are ever dynamically +violated, the behavior is undefined. These attributes are useful when an +invariant invisible to the synthesizer causes the control signal to never take +certain bit patterns. + +The lines 13..16 then cause ``\q`` to be updated whenever there is a positive +clock edge on ``\clock`` or ``\reset``. + +In order to generate such a representation, the language frontend must be able +to handle blocking and nonblocking assignments correctly. However, the language +frontend does not need to identify the correct type of storage element for the +output signal or generate multiplexers for the decision tree. This is done by +passes that work on the RTLIL representation. Therefore it is relatively easy to +substitute these steps with other algorithms that target different target +architectures or perform optimizations or other transformations on the decision +trees before further processing them. + +One of the first actions performed on a design in RTLIL representation in most +synthesis scripts is identifying asynchronous resets. This is usually done using +the `proc_arst` pass. This pass transforms the above example to the following +``RTLIL::Process``: + +.. code:: RTLIL + :number-lines: + + process $proc$ff_with_en_and_async_reset.v:4$1 + assign $0\q[0:0] \q + switch \enable + case 1'1 + assign $0\q[0:0] \d + case + end + sync posedge \clock + update \q $0\q[0:0] + sync high \reset + update \q 1'0 + end + +This pass has transformed the outer ``RTLIL::SwitchRule`` into a modified +``RTLIL::SyncRule`` object for the ``\reset`` signal. Further processing +converts the ``RTLIL::Process`` into e.g. a d-type flip-flop with asynchronous +reset and a multiplexer for the enable signal: + +.. code:: RTLIL + :number-lines: + + cell $adff $procdff$6 + parameter \ARST_POLARITY 1'1 + parameter \ARST_VALUE 1'0 + parameter \CLK_POLARITY 1'1 + parameter \WIDTH 1 + connect \ARST \reset + connect \CLK \clock + connect \D $0\q[0:0] + connect \Q \q + end + cell $mux $procmux$3 + parameter \WIDTH 1 + connect \A \q + connect \B \d + connect \S \enable + connect \Y $0\q[0:0] + end + +Different combinations of passes may yield different results. Note that `$adff` +and `$mux` are internal cell types that still need to be mapped to cell types +from the target cell library. + +Some passes refuse to operate on modules that still contain ``RTLIL::Process`` +objects as the presence of these objects in a module increases the complexity. +Therefore the passes to translate processes to a netlist of cells are usually +called early in a synthesis script. The proc pass calls a series of other passes +that together perform this conversion in a way that is suitable for most +synthesis tasks. + +.. _sec:rtlil_memory: + +RTLIL::Memory +------------- + +For every array (memory) in the HDL code an ``RTLIL::Memory`` object is created. +A memory object has the following properties: + +- The memory name +- A list of attributes +- The width of an addressable word +- The size of the memory in number of words + +All read accesses to the memory are transformed to `$memrd` cells and all write +accesses to `$memwr` cells by the language frontend. These cells consist of +independent read- and write-ports to the memory. Memory initialization is +transformed to `$meminit` cells by the language frontend. The ``\MEMID`` +parameter on these cells is used to link them together and to the +``RTLIL::Memory`` object they belong to. + +The rationale behind using separate cells for the individual ports versus +creating a large multiport memory cell right in the language frontend is that +the separate `$memrd` and `$memwr` cells can be consolidated using resource +sharing. As resource sharing is a non-trivial optimization problem where +different synthesis tasks can have different requirements it lends itself to do +the optimisation in separate passes and merge the ``RTLIL::Memory`` objects and +`$memrd` and `$memwr` cells to multiport memory blocks after resource sharing is +completed. + +The memory pass performs this conversion and can (depending on the options +passed to it) transform the memories directly to d-type flip-flops and address +logic or yield multiport memory blocks (represented using `$mem` cells). + +See :ref:`sec:memcells` for details about the memory cell types. + +.. [1] + The syntax ``1'1`` in the RTLIL code specifies a constant with a length of + one bit (the first ``1``), and this bit is a one (the second ``1``). diff --git a/chips/yosys/docs/source/yosys_internals/hashing.rst b/chips/yosys/docs/source/yosys_internals/hashing.rst new file mode 100644 index 0000000000000000000000000000000000000000..966c065af3bcc9f15d27289bd57d2b34fd234f61 --- /dev/null +++ b/chips/yosys/docs/source/yosys_internals/hashing.rst @@ -0,0 +1,170 @@ +Hashing and associative data structures in Yosys +------------------------------------------------ + +Container classes based on hashing +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Yosys uses ``dict`` and ``pool`` as main container classes. +``dict`` is essentially a replacement for ``std::unordered_map`` +and ``pool`` is a replacement for ``std::unordered_set``. +The main characteristics are: + +* ``dict`` and ``pool`` are about 2x faster than the std containers + (though this claim hasn't been verified for over 10 years) + +* references to elements in a ``dict`` or ``pool`` are invalidated by + insert and remove operations (similar to ``std::vector`` on ``push_back()``). + +* some iterators are invalidated by ``erase()``. specifically, iterators + that have not passed the erased element yet are invalidated. (``erase()`` + itself returns valid iterator to the next element.) + +* no iterators are invalidated by ``insert()``. elements are inserted at + ``begin()``. i.e. only a new iterator that starts at ``begin()`` will see the + inserted elements. + +* the method ``.count(key, iterator)`` is like ``.count(key)`` but only + considers elements that can be reached via the iterator. + +* iterators can be compared. ``it1 < it2`` means that the position of ``t2`` + can be reached via ``t1`` but not vice versa. + +* the method ``.sort()`` can be used to sort the elements in the container + the container stays sorted until elements are added or removed. + +* ``dict`` and ``pool`` will have the same order of iteration across + all compilers, standard libraries and architectures. + +In addition to ``dict`` and ``pool`` there is also an ``idict`` that +creates a bijective map from ``K`` to incrementing integers. For example: + +:: + + idict si; + log("%d\n", si("hello")); // will print 42 + log("%d\n", si("world")); // will print 43 + log("%d\n", si.at("world")); // will print 43 + log("%d\n", si.at("dummy")); // will throw exception + log("%s\n", si[42])); // will print hello + log("%s\n", si[43])); // will print world + log("%s\n", si[44])); // will throw exception + +It is not possible to remove elements from an idict. + +Finally ``mfp`` implements a merge-find set data structure (aka. disjoint-set +or union-find) over the type ``K`` ("mfp" = merge-find-promote). + +The hash function +~~~~~~~~~~~~~~~~~ + +The hash function generally used in Yosys is the XOR version of DJB2: + +:: + + state = ((state << 5) + state) ^ value + +This is an old-school hash designed to hash ASCII characters. Yosys doesn't hash +a lot of ASCII text, but it still happens to be a local optimum due to factors +described later. + +Hash function quality is multi-faceted and highly dependent on what is being +hashed. Yosys isn't concerned by any cryptographic qualities, instead the goal +is minimizing total hashing collision risk given the data patterns within Yosys. +In general, a good hash function typically folds values into a state accumulator +with a mathematical function that is fast to compute and has some beneficial +properties. One of these is the avalanche property, which demands that a small +change such as flipping a bit or incrementing by one in the input produces a +large, unpredictable change in the output. Additionally, the bit independence +criterion states that any pair of output bits should change independently when +any single input bit is inverted. These properties are important for avoiding +hash collision on data patterns like the hash of a sequence not colliding with +its permutation, not losing from the state the information added by hashing +preceding elements, etc. + +DJB2 lacks these properties. Instead, since Yosys hashes large numbers of data +structures composed of incrementing integer IDs, Yosys abuses the predictability +of DJB2 to get lower hash collisions, with regular nature of the hashes +surviving through the interaction with the "modulo prime" operations in the +associative data structures. For example, some most common objects in Yosys are +interned ``IdString``\ s of incrementing indices or ``SigBit``\ s with bit +offsets into wire (represented by its unique ``IdString`` name) as the typical +case. This is what makes DJB2 a local optimum. Additionally, the ADD version of +DJB2 (like above but with addition instead of XOR) is used to this end for some +types, abandoning the general pattern of folding values into a state value. + +Making a type hashable +~~~~~~~~~~~~~~~~~~~~~~ + +Let's first take a look at the external interface on a simplified level. +Generally, to get the hash for ``T obj``, you would call the utility function +``run_hash(const T& obj)``, corresponding to ``hash_ops::hash(obj)``, +the default implementation of which uses ``hash_ops::hash_into(Hasher(), obj)``. +``Hasher`` is the class actually implementing the hash function, hiding its +initialized internal state, and passing it out on ``hash_t yield()`` with +perhaps some finalization steps. + +``hash_ops`` is the star of the show. By default it pulls the ``Hasher h`` +through a ``Hasher T::hash_into(Hasher h)`` method. That's the method you have to +implement to make a record (class or struct) type easily hashable with Yosys +hashlib associative data structures. + +``hash_ops`` is specialized for built-in types like ``int`` or ``bool`` and +treats pointers the same as integers, so it doesn't dereference pointers. Since +many RTLIL data structures like ``RTLIL::Wire`` carry their own unique index +``Hasher::hash_t hashidx_;``, there are specializations for ``hash_ops`` +and others in ``kernel/hashlib.h`` that actually dereference the pointers and +call ``hash_into`` on the instances pointed to. +The index comes from a counter owned by the ``RTLIL::Design`` the object +belongs to, so the hashes, and with them the iteration order of hashlib +containers of RTLIL objects, only depend on the history of that design. +``design -reset`` restarts the counter. + +``hash_ops`` is also specialized for simple compound types like +``std::pair`` by calling hash_into in sequence on its members. For flexible +size containers like ``std::vector`` the size of the container is hashed +first. That is also how implementing hashing for a custom record data type +should be - unless there is strong reason to do otherwise, call ``h.eat(m)`` on +the ``Hasher h`` you have received for each member in sequence and ``return +h;``. + +The ``hash_ops::hash(obj)`` method is not indended to be called when +context of implementing the hashing for a record or other compound type. +When writing it, you should connect it to ``hash_ops::hash_into(Hasher h)`` +as shown below. If you have a strong reason to do so, and you have +to create a special implementation for top-level hashing, look at how +``hash_ops::hash(...)`` is implemented in ``kernel/rtlil.h``. + +Porting plugins from the legacy interface +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Previously, the interface to implement hashing on custom types was just +``unsigned int T::hash() const``. This meant hashes for members were computed +independently and then ad-hoc combined with the hash function with some xorshift +operations thrown in to mix bits together somewhat. A plugin can stay compatible +with both versions prior and after the break by implementing both interfaces +based on the existance and value of ``YS_HASHING_VERSION``. + +.. code-block:: cpp + :caption: Example hash compatibility wrapper + :name: hash_plugin_compat + + #ifndef YS_HASHING_VERSION + unsigned int T::hash() const { + return mkhash(a, b); + } + #elif YS_HASHING_VERSION == 1 + Hasher T::hash_into(Hasher h) const { + h.eat(a); + h.eat(b); + return h; + } + Hasher T::hash() const { + Hasher h; + h.eat(*this); + return h; + } + #else + #error "Unsupported hashing interface" + #endif + +Feel free to contact Yosys maintainers with related issues. diff --git a/chips/yosys/docs/source/yosys_internals/idstring.rst b/chips/yosys/docs/source/yosys_internals/idstring.rst new file mode 100644 index 0000000000000000000000000000000000000000..f31d57b866ba47a2e8c205a3f30f9cbad56c8645 --- /dev/null +++ b/chips/yosys/docs/source/yosys_internals/idstring.rst @@ -0,0 +1,223 @@ +IdString +-------- + +Design +~~~~~~ + +String interning is a practice that deduplicates strings held in memory. +An integer then exactly represents a unique string. This also allows string +comparison to be replaced with integer comparison, which is faster. + +For performance, memory efficiency, and future parallelism, +``IdString`` is an index into a per-``Design`` ``TwinePool``, which +deduplicates prefixes. + +The killer feature is that it allows you to construct a new ``IdString`` by +appending a suffix to an existing ``IdString`` without copying its contents: + +.. code-block:: cpp + :caption: Example suffix node construction + :name: idstring_suffix + + Wire *enable = module->addWire(TwineSpec::Suffix{cell->name, "_EN"}, 1); + +A ``TwinePool`` holds a slab of ``TwineNode``\ s with free-list +bump allocation by inheriting from ``HashConsPool`` backed by +an ``std::deque``. +``HashConsPool`` provides deduplicating storage indexed by content hash. +``IdString``, being an interned string, is hashed as the underlying string. + +``TwineSpec`` models an uninterned temporary twine node, +``TwineNode`` models an interned one. +``IdString`` then is an index into the vector +of ``TwineNode``\ s inside a ``TwinePool``. +More concretely, it is 32-bit, offset, and publicity-tagged. +The offset allows it to represent compilation-time allocated identifiers +in ``kernel/constids.inc``. Tagging implements "publicity", which historically +was determined by the first character being ``$`` or ``\``, +by stealing the top bit of the integer. +User-specified names coming in from design sources are public, +while Yosys-created names are private. + +``TwineNode`` uses ``SmallString`` to store small strings inline and larger +ones behind a pointer. This keeps its own size at 24 bytes. +``AutoSuffix`` is a ``TwineSpec`` variant produced by ``NEW_ID`` +and ``NEW_ID_SUFFIX`` macros. These are ``TwineSpec``s which skip string hashing +on the constant per-callsite prefix when repeatedly interned. +The ``TwinePool`` appends its own autoidx counter value when interning them, +so each ``Design`` numbers its generated names independently. +The integer suffix fits the ``SmallString`` inline storage. + +Garbage collection traces a ``Design`` in parallel. + +Migration from globally interned IdStrings +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +C++ core change +^^^^^^^^^^^^^^^ + +``IdString`` <-> string conversion now requires accessing a per-``Design`` +``TwinePool``, accessible with ``design->twines()``, ``module->twines()``, +``wire->twines()``, ``cell->twines()``, ``memory->twines()``, +``process->twines()`` + +.. code-block:: diff + + -IdString id = "hello"; + +IdString id = design->twines().add("\\hello"); + +.. code-block:: diff + + -void thing(IdString id) { + - std::string s = id; + - log("%s\n", id); + +void thing(Design* design, IdString id) { + + std::string s = design->twines().str(id); + + log("%s\n", s); + // ... + } + +C++ helpers +^^^^^^^^^^^ + +When passing an IdString around that should then be stringified/printed or +assigned from string, you can use a ``PooledName`` which is effectively this but +with lots of convenient methods: + +.. code-block:: cpp + + class PooledName { const TwinePool *pool_; IdString id_; } + +so that you can + +.. code-block:: diff + + -void foo(IdString name) { + +void foo(PooledName name) { + log("%s\n", name); + } + + for (IdString name : names) + - foo(name); + + foo({design, name}); + + // This then works without a change, since Cell::name + // can magically convert to PooledName + for (Cell* cell : cells) + foo(cell->name); + +In ``name`` fields on RTLIL objects and in ``Cell::type``, a ``Design*`` is +contextually available, so those fields are magically wrapping an IdString for +read access. That means you don't need a change here: + +.. code-block:: cpp + + log("Cell type %s, cell name %s\n", cell->type, cell->name); + +but not for write access, so you still have to do this: + +.. code-block:: diff + + -cell->type = "\\asdfghjk"; + +cell->type = design->twines().add("\\asdfghjk"); + +Checking the first character of an ``IdString`` for publicity can now get +expensive. Do this instead: + +.. code-block:: diff + + -if (wire->name[0] == '$') + +if (!wire->name.isPublic()) + +``ID(id)`` now accepts only names in ``kernel/constids.inc`` + +.. code-block:: diff + + -auto w = miter_module->addWire(ID(asdfghjk)); + +auto w = miter_module->addWire("\\asdfghjk"); + +``IdString`` is valid only in its own ``Design``: cross-design use requires +``TwinePool::copy_from``, ``TwinePool::find_from``, ``Module::clone(Design *)``, +``RTLIL::copy_attr_dict`` + +``RTLIL::sort_by_id_str`` takes a ``TwinePool`` reference. This is a good time +to rethink whether you really want to sort stuff by string contents! + +.. code-block:: diff + + -modules_.sort(sort_by_id_str()); + +modules_.sort(sort_by_id_str(design->twines())); + +``NEW_ID``, ``NEW_ID_SUFFIX(suffix)`` change type from ``IdString`` to +``TwineSpec``. + +But as long as you use them in the construction of RTLIL objects, magic happens: + +.. code-block:: cpp + + SigSpec s = module->And(NEW_ID, lhs, rhs); + +``RTLIL::unescape_id(IdString)`` and ``log_id`` have been removed, together with +other things that have relied on the old design. + +If you are experiencing bugs while working multiple ``Design``s, +enable extra checks with the ``YOSYS_ENABLE_TWINE_PROVENANCE`` CMake variable. + +Attribute and parameter dictionaries copied between objects of different +``Design``s need to be done via ``copy_attr_dict`` to safetly re-intern twines. + +Python helpers +^^^^^^^^^^^^^^ + +``pyosys`` lies to you - ``PooledName`` is what you're actually getting when you +get an ``IdString`` in Python. This is because we expect Python users to value +convenience and simplicity more than unnecessary bytes here. This is different +from what we need for our core optimization passes in C++. + +Strings still work as names in methods of ``Design``, ``Module``, ``Cell``, +``Wire``, ``Memory`` and ``Process``, and as keys of their ``attributes``, +``parameters``, ``parameter_default_values``, ``connections_``, ``wires_``, +``cells_``, ``memories``, ``processes`` and ``modules_``, since those know their +design. + +Elsewhere only static names (``"\\A"``, ``"$add"``) convert from strings. You +may otherwise need to get an ``IdString`` from the design: + +.. code-block:: diff + + my_idict = ys.IdstringIdict() + -my_idict("\\hello") + -print(my_idict[0]) + +my_idict(design.id_add("\\hello")) + +print(design.str(my_idict[0])) + +Use ``id_find`` instead of ``id_add`` to only look a name up, it returns +``None`` if absent: + +.. code-block:: diff + + -sel.selected_module("\\top") + +sel.selected_module(design.id_find("\\top")) + +``connections_``, ``wires_``, ``cells_``, ``memories``, ``processes`` and +``modules_`` can't be assigned as a whole anymore, use methods instead: + +.. code-block:: diff + + -cell.connections_ = {"\\A": sig} + +cell.setPort("\\A", sig) + +Using a name after its design was deleted now raises ``RuntimeError``, so +convert it with ``str()`` while the design is still alive if you want that. + +RTLIL +^^^^^ + +There is a new ``metadata`` section in the RTLIL textual format, holding a +``twines`` section. Older RTLIL versions can still be read in, but older Yosys +versions won't be able to read this format. + +To write out RTLIL in a format compatible with older +Yosys versions, use ``write_rtlil -readable``. This will discards only +prefix node structure, not string content. To remove human-readable comments +to save file size, use ``write_rtlil -small``. diff --git a/chips/yosys/docs/source/yosys_internals/index.rst b/chips/yosys/docs/source/yosys_internals/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..422a1bb100b8ea4e8ab57aa3e514d81171418249 --- /dev/null +++ b/chips/yosys/docs/source/yosys_internals/index.rst @@ -0,0 +1,42 @@ +.. _chapter:overview: + +Yosys internals +=============== + +.. todo:: less academic + +Yosys is an extensible open source hardware synthesis tool. It is aimed at +designers who are looking for an easily accessible, universal, and +vendor-independent synthesis tool, as well as scientists who do research in +electronic design automation (EDA) and are looking for an open synthesis +framework that can be used to test algorithms on complex real-world designs. + +Yosys can synthesize a large subset of Verilog 2005 and has been tested with a +wide range of real-world designs, including the `OpenRISC 1200 CPU`_, the +`openMSP430 CPU`_, the `OpenCores I2C master`_, and the `k68 CPU`_. + +.. todo:: add RISC-V core example + +.. _OpenRISC 1200 CPU: https://github.com/openrisc/or1200 + +.. _openMSP430 CPU: http://opencores.org/projects/openmsp430 + +.. _OpenCores I2C master: http://opencores.org/projects/i2c + +.. _k68 CPU: http://opencores.org/projects/k68 + +Yosys is written in C++, targeting C++20 at minimum. This chapter describes some +of the fundamental Yosys data structures. For the sake of simplicity the C++ +type names used in the Yosys implementation are used in this chapter, even +though the chapter only explains the conceptual idea behind it and can be used +as reference to implement a similar system in any language. + +.. toctree:: + :maxdepth: 3 + + flow/index + formats/index + extending_yosys/index + techmap + hashing + idstring diff --git a/chips/yosys/docs/source/yosys_internals/techmap.rst b/chips/yosys/docs/source/yosys_internals/techmap.rst new file mode 100644 index 0000000000000000000000000000000000000000..21b09c9032b6bfdfd502fc98c1d564b8110f3c3b --- /dev/null +++ b/chips/yosys/docs/source/yosys_internals/techmap.rst @@ -0,0 +1,191 @@ +Techmap by example +------------------ + +As a quick recap, the `techmap` command replaces cells in the design with +implementations given as Verilog code (called "map files"). It can replace +Yosys' internal cell types (such as `$or`) as well as user-defined cell types. + +- Verilog parameters are used extensively to customize the internal cell types. +- Additional special parameters are used by techmap to communicate meta-data to + the map files. +- Special wires are used to instruct techmap how to handle a module in the map + file. +- Generate blocks and recursion are powerful tools for writing map files. + +Code examples used in this document are included in the Yosys code base under +|code_examples/techmap|_. + +.. |code_examples/techmap| replace:: :file:`docs/source/code_examples/techmap` +.. _code_examples/techmap: https://github.com/YosysHQ/yosys/tree/main/docs/source/code_examples/techmap + + +Mapping OR3X1 +~~~~~~~~~~~~~ + +.. todo:: add/expand supporting text + +.. note:: + + This is a simple example for demonstration only. Techmap shouldn't be used + to implement basic logic optimization. + +.. literalinclude:: /code_examples/techmap/red_or3x1_map.v + :language: verilog + :caption: :file:`red_or3x1_map.v` + +.. figure:: /_images/code_examples/techmap/red_or3x1.* + :class: width-helper invert-helper + +.. literalinclude:: /code_examples/techmap/red_or3x1_test.ys + :language: yoscrypt + :caption: :file:`red_or3x1_test.ys` + +.. literalinclude:: /code_examples/techmap/red_or3x1_test.v + :language: verilog + :caption: :file:`red_or3x1_test.v` + +Conditional techmap +~~~~~~~~~~~~~~~~~~~ + +- In some cases only cells with certain properties should be substituted. +- The special wire ``_TECHMAP_FAIL_`` can be used to disable a module in the map + file for a certain set of parameters. +- The wire ``_TECHMAP_FAIL_`` must be set to a constant value. If it is non-zero + then the module is disabled for this set of parameters. +- Example use-cases: + + - coarse-grain cell types that only operate on certain bit widths + - memory resources for different memory geometries (width, depth, ports, + etc.) + +Example: + +.. figure:: /_images/code_examples/techmap/sym_mul.* + :class: width-helper invert-helper + +.. literalinclude:: /code_examples/techmap/sym_mul_map.v + :language: verilog + :caption: :file:`sym_mul_map.v` + +.. literalinclude:: /code_examples/techmap/sym_mul_test.v + :language: verilog + :caption: :file:`sym_mul_test.v` + +.. literalinclude:: /code_examples/techmap/sym_mul_test.ys + :language: yoscrypt + :caption: :file:`sym_mul_test.ys` + + +Scripting in map modules +~~~~~~~~~~~~~~~~~~~~~~~~ + +- The special wires ``_TECHMAP_DO_*`` can be used to run Yosys scripts in the + context of the replacement module. +- The wire that comes first in alphabetical oder is interpreted as string (must + be connected to constants) that is executed as script. Then the wire is + removed. Repeat. +- You can even call techmap recursively! +- Example use-cases: + + - Using always blocks in map module: call `proc` + - Perform expensive optimizations (such as `freduce`) on cells + where this is known to work well. + - Interacting with custom commands. + +.. note:: PROTIP: + + Commands such as `shell`, ``show -pause``, and `dump` can be used in the + ``_TECHMAP_DO_*`` scripts for debugging map modules. + +Example: + +.. figure:: /_images/code_examples/techmap/mymul.* + :class: width-helper invert-helper + +.. literalinclude:: /code_examples/techmap/mymul_map.v + :language: verilog + :caption: :file:`mymul_map.v` + +.. literalinclude:: /code_examples/techmap/mymul_test.v + :language: verilog + :caption: :file:`mymul_test.v` + +.. literalinclude:: /code_examples/techmap/mymul_test.ys + :language: yoscrypt + :caption: :file:`mymul_test.ys` + +Handling constant inputs +~~~~~~~~~~~~~~~~~~~~~~~~ + +- The special parameters ``_TECHMAP_CONSTMSK__`` and + ``_TECHMAP_CONSTVAL__`` can be used to handle constant input values + to cells. +- The former contains 1-bits for all constant input bits on the port. +- The latter contains the constant bits or undef (x) for non-constant bits. +- Example use-cases: + + - Converting arithmetic (for example multiply to shift). + - Identify constant addresses or enable bits in memory interfaces. + +Example: + +.. figure:: /_images/code_examples/techmap/mulshift.* + :class: width-helper invert-helper + +.. literalinclude:: /code_examples/techmap/mulshift_map.v + :language: verilog + :caption: :file:`mulshift_map.v` + +.. literalinclude:: /code_examples/techmap/mulshift_test.v + :language: verilog + :caption: :file:`mulshift_test.v` + +.. literalinclude:: /code_examples/techmap/mulshift_test.ys + :language: yoscrypt + :caption: :file:`mulshift_test.ys` + +Handling shorted inputs +~~~~~~~~~~~~~~~~~~~~~~~ + +- The special parameters ``_TECHMAP_BITS_CONNMAP_`` and + ``_TECHMAP_CONNMAP__`` can be used to handle shorted inputs. +- Each bit of the port correlates to an ``_TECHMAP_BITS_CONNMAP_`` bits wide + number in ``_TECHMAP_CONNMAP__``. +- Each unique signal bit is assigned its own number. Identical fields in the + ``_TECHMAP_CONNMAP__`` parameters mean shorted signal bits. +- The numbers 0-3 are reserved for ``0``, ``1``, ``x``, and ``z`` respectively. +- Example use-cases: + + - Detecting shared clock or control signals in memory interfaces. + - In some cases this can be used for for optimization. + +Example: + +.. figure:: /_images/code_examples/techmap/addshift.* + :class: width-helper invert-helper + +.. literalinclude:: /code_examples/techmap/addshift_map.v + :language: verilog + :caption: :file:`addshift_map.v` + +.. literalinclude:: /code_examples/techmap/addshift_test.v + :language: verilog + :caption: :file:`addshift_test.v` + +.. literalinclude:: /code_examples/techmap/addshift_test.ys + :language: yoscrypt + :caption: :file:`addshift_test.ys` + +Notes on using techmap +~~~~~~~~~~~~~~~~~~~~~~ + +- Don't use positional cell parameters in map modules. +- You can use the ``$__``-prefix for internal cell types to avoid collisions + with the user-namespace. But always use two underscores or the internal + consistency checker will trigger on these cells. +- Techmap has two major use cases: + + - Creating good logic-level representation of arithmetic functions. This + also means using dedicated hardware resources such as half- and full-adder + cells in ASICS or dedicated carry logic in FPGAs. + - Mapping of coarse-grain resources such as block memory or DSP cells. diff --git a/chips/yosys/docs/tests/macro_commands.py b/chips/yosys/docs/tests/macro_commands.py new file mode 100644 index 0000000000000000000000000000000000000000..cded283b3c8041b2fc16f4e2bbfc27b31c04be15 --- /dev/null +++ b/chips/yosys/docs/tests/macro_commands.py @@ -0,0 +1,102 @@ +#!/usr/bin/env python3 + +import logging +from pathlib import Path +import re +import subprocess +import sys +import os + +# basic logging setup +logging.basicConfig(level=logging.INFO) + +# expects __file__ = yosys/docs/tests/macro_commands.py +TESTS_DIR = Path(__file__).parent.absolute() +ROOT_DIR = TESTS_DIR.parent.parent +logging.log(logging.INFO, f"Using {ROOT_DIR} as root directory") +THIS_FILE = (TESTS_DIR / "macro_commands.py").relative_to(ROOT_DIR) +MACRO_SOURCE = TESTS_DIR.parent / "source" / "code_examples" / "macro_commands" +assert MACRO_SOURCE.exists(), f"can't find macro_commands in {MACRO_SOURCE}" + +YOSYS = Path(os.environ.get("YOSYS", ROOT_DIR / "yosys")) +assert YOSYS.exists(), f"can't find yosys executable in {YOSYS}" + +raise_error = False +# get all macro commands being used +for macro in MACRO_SOURCE.glob("*.ys"): + # log current test + relative_path = macro.relative_to(ROOT_DIR) + logging.log(logging.INFO, f"Checking {relative_path}") + # files in macros_commands should be named {command}.ys + command = macro.stem + # run `yosys -h {command}` to capture current sub-commands + proc = subprocess.run([YOSYS, "-QTh", command], capture_output=True, text=True) + with open(macro) as f: + # {command.ys} starts with two commented lines, the first is the text + # immediately prior to the macro body. The second is the text + # immediately after. + start = f.readline() + end = f.readline() + file_content = f.readlines() + expected_content = [] + for line in file_content: + line = line.split("#")[0].strip() + if line: + expected_content.append(line) + # parse {command.ys} + if "#start:" not in start or "#end:" not in end: + logging.error(f"Missing start and/or end string in {relative_path}, see {THIS_FILE}") + raise_error = True + continue + start = start.replace("#start:", "").strip() + end = end.replace("#end:", "").strip() + # attempt to find macro body in help output + match = re.fullmatch(f".*{start}(.*){end}.*", proc.stdout, re.DOTALL) + if not match: + logging.error(f"Couldn't find {start!r} and/or {end!r} in `yosys -h {command}` output") + raise_error = True + continue + match_content = match.group(1).strip().splitlines() + actual_content = [] + for line in match_content: + if line: + actual_content.append(line) + # iterate over and compare expected v actual + for (expected, actual) in zip(expected_content, actual_content): + expected = expected.strip() + actual = actual.strip() + # raw match + if expected == actual: + continue + + # rip apart formatting to match line parts + pattern = r"(?P\S+)(?P \[.*\])?(?P.*?)(?P\s+\(.*\))?" + try: + expected_dict = re.fullmatch(pattern, expected).groupdict() + except AttributeError: + logging.error(f"Bad formatting in {relative_path}: {expected!r}") + raise_error = True + continue + + try: + actual_dict = re.fullmatch(pattern, actual).groupdict() + except AttributeError: + logging.error(f"Unexpected formatting in `yosys -h {command}` output, {actual!r}") + raise_error = True + continue + + does_match = expected_dict["cmd"] == actual_dict["cmd"] + + #todo: check expected_dict["pass"] is a subset of actual_dict["pass"] + # only check opt and cond match if they're in {command}.ys + match_keys = ["opt", "cond"] + for key in match_keys: + if expected_dict[key] and expected_dict[key] != actual_dict[key]: + does_match = False + + # raise error on mismatch + if not does_match: + logging.error(f"Expected {expected!r}, got {actual!r}") + raise_error = True + +sys.exit(raise_error) diff --git a/chips/yosys/docs/util/RtlilLexer.py b/chips/yosys/docs/util/RtlilLexer.py new file mode 100644 index 0000000000000000000000000000000000000000..93a4015159a1176bc50c0e25360881fc04550c00 --- /dev/null +++ b/chips/yosys/docs/util/RtlilLexer.py @@ -0,0 +1,45 @@ +from pygments.lexer import RegexLexer, bygroups, include +from pygments.token import Comment, Keyword, Name, Number, String, Whitespace + +__all__ = ['RtlilLexer'] + +class RtlilLexer(RegexLexer): + name = 'RTLIL' + aliases = ['rtlil'] + filenames = ['*.il'] + + keyword_re = r'(always|assign|attribute|autoidx|case|cell|connect|edge|end|global|high|init|inout|input|low|memory|module|negedge|offset|output|parameter|posedge|process|real|signed|size|switch|sync|update|upto|width|wire)' + + tokens = { + 'common': [ + (r'\s+', Whitespace), + (r'#.*', Comment.Single), + (keyword_re, Keyword), + (r'([\\\$][^ \t\r\n]+|\.[0-9]+)', Name.Variable), + (r"[0-9]+'[01xzm-]*", Number), + (r'-?[0-9]+', Number.Integer), + (r'"', String, 'string'), + ], + 'root': [ + (r'cell', Keyword, 'cell_definition'), + (r'(module|wire|memory|process)', Keyword, 'definition'), + include('common'), + ], + 'definition': [ + (r'([\\\$][^ \t\r\n]+|\.[0-9]+)', Name.Entity, '#pop'), + include('common') + ], + 'cell_definition': [ + (r'(\$[^ \t\r\n]+)\b', Name.Function), + (r'(\\[^ \t\r\n]+|\.[0-9]+)', Name.Variable), + (r'$', Whitespace, '#pop'), + include('common'), + ], + 'string': [ + (r'"', String, '#pop'), + (r'\\([\\abfnrtv"\']|x[a-fA-F0-9]{2,4}|[0-7]{1,3})', String.Escape), + (r'[^\\"\n]+', String), # all other characters + (r'(\\)(\n)', bygroups(String.Escape, Whitespace)), # line continuation + (r'\\', String), # stray backslash + ] + } diff --git a/chips/yosys/docs/util/__init__.py b/chips/yosys/docs/util/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/chips/yosys/docs/util/cell_documenter.py b/chips/yosys/docs/util/cell_documenter.py new file mode 100644 index 0000000000000000000000000000000000000000..296ae1bfd6c64935730b29ea01034a9b94bf44b0 --- /dev/null +++ b/chips/yosys/docs/util/cell_documenter.py @@ -0,0 +1,415 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +from dataclasses import dataclass +import json +from pathlib import Path, PosixPath, WindowsPath +import re + +from typing import Any +from sphinx.application import Sphinx +from sphinx.ext import autodoc +from sphinx.ext.autodoc import Documenter +from sphinx.util import logging + +logger = logging.getLogger(__name__) + +# cell signature +cell_ext_sig_re = re.compile( + r'''^ ([^:\s]+::)? # optional group or file name + ([\w$._]+?) # module name + (?:\.([\w_]+))? # optional: thing name + (::[\w_]+)? # attribute + \s* $ # and nothing more + ''', re.VERBOSE) + +@dataclass +class YosysCell: + name: str + title: str + ports: str + source: str + desc: str + code: str + inputs: list[str] + outputs: list[str] + properties: list[str] + +class YosysCellGroupDocumenter(Documenter): + objtype = 'cellgroup' + priority = 10 + object: tuple[str, list[str]] + lib_key = 'groups' + + option_spec = { + 'caption': autodoc.annotation_option, + 'members': autodoc.members_option, + 'source': autodoc.bool_option, + 'linenos': autodoc.bool_option, + } + + __cell_lib: dict[str, list[str] | dict[str]] | None = None + @property + def cell_lib(self) -> dict[str, list[str] | dict[str]]: + if not self.__cell_lib: + self.__cell_lib = {} + cells_obj: dict[str, dict[str, list[str] | dict[str]]] + try: + with open(self.config.cells_json, "r") as f: + cells_obj = json.loads(f.read()) + except FileNotFoundError: + logger.warning( + f"unable to find cell lib at {self.config.cells_json}", + type = 'cellref', + subtype = 'cell_lib' + ) + else: + for (name, obj) in cells_obj.get(self.lib_key, {}).items(): + self.__cell_lib[name] = obj + return self.__cell_lib + + @classmethod + def can_document_member( + cls, + member: Any, + membername: str, + isattr: bool, + parent: Any + ) -> bool: + return False + + def parse_name(self) -> bool: + if not self.options.caption: + self.content_indent = '' + self.fullname = self.modname = self.name + return True + + def import_object(self, raiseerror: bool = False) -> bool: + # get cell + try: + self.object = (self.modname, self.cell_lib[self.modname]) + except KeyError: + if raiseerror: + raise + return False + + self.real_modname = self.modname + return True + + def get_sourcename(self) -> str: + return self.env.doc2path(self.env.docname) + + def format_name(self) -> str: + return self.options.caption or '' + + def format_signature(self, **kwargs: Any) -> str: + return self.modname + + def add_directive_header(self, sig: str) -> None: + domain = getattr(self, 'domain', 'cell') + directive = getattr(self, 'directivetype', 'group') + name = self.format_name() + sourcename = self.get_sourcename() + cell_list = self.object + + # cell definition + self.add_line(f'.. {domain}:{directive}:: {sig}', sourcename) + self.add_line(f' :caption: {name}', sourcename) + + if self.options.noindex: + self.add_line(' :noindex:', sourcename) + + def add_content(self, more_content: Any | None) -> None: + # groups have no native content + # add additional content (e.g. from document), if present + if more_content: + for line, src in zip(more_content.data, more_content.items): + self.add_line(line, src[0], src[1]) + + def filter_members( + self, + members: list[tuple[str, Any]], + want_all: bool + ) -> list[tuple[str, Any, bool]]: + return [(x[0], x[1], False) for x in members] + + def get_object_members( + self, + want_all: bool + ) -> tuple[bool, list[tuple[str, Any]]]: + ret: list[tuple[str, str]] = [] + + if want_all: + for member in self.object[1]: + ret.append((member, self.modname)) + else: + memberlist = self.options.members or [] + for name in memberlist: + if name in self.object: + ret.append((name, self.modname)) + else: + logger.warning(('unknown module mentioned in :members: option: ' + f'group {self.modname}, module {name}'), + type='cellref') + + return False, ret + + def document_members(self, all_members: bool = False) -> None: + want_all = (all_members or + self.options.inherited_members or + self.options.members is autodoc.ALL) + # find out which members are documentable + members_check_module, members = self.get_object_members(want_all) + + # document non-skipped members + memberdocumenters: list[tuple[Documenter, bool]] = [] + for (mname, member, isattr) in self.filter_members(members, want_all): + classes = [cls for cls in self.documenters.values() + if cls.can_document_member(member, mname, isattr, self)] + if not classes: + # don't know how to document this member + continue + # prefer the documenter with the highest priority + classes.sort(key=lambda cls: cls.priority) + # give explicitly separated module name, so that members + # of inner classes can be documented + full_mname = self.format_signature() + '::' + mname + documenter = classes[-1](self.directive, full_mname, self.indent) + memberdocumenters.append((documenter, isattr)) + + member_order = self.options.member_order or self.config.autodoc_member_order + memberdocumenters = self.sort_members(memberdocumenters, member_order) + + for documenter, isattr in memberdocumenters: + documenter.generate( + all_members=True, real_modname=self.real_modname, + check_module=members_check_module and not isattr) + + def generate( + self, + more_content: Any | None = None, + real_modname: str | None = None, + check_module: bool = False, + all_members: bool = False + ) -> None: + if not self.parse_name(): + # need a cell lib to import from + logger.warning( + f"don't know which cell lib to import for autodocumenting {self.name}", + type = 'cellref' + ) + return + + if not self.import_object(): + logger.warning( + f"unable to load {self.name}", + type = 'cellref' + ) + return + + # check __module__ of object (for members not given explicitly) + # if check_module: + # if not self.check_module(): + # return + + sourcename = self.get_sourcename() + self.add_line('', sourcename) + + # format the object's signature, if any + try: + sig = self.format_signature() + except Exception as exc: + logger.warning(('error while formatting signature for %s: %s'), + self.fullname, exc, type='cellref') + return + + # generate the directive header and options, if applicable + self.add_directive_header(sig) + self.add_line('', sourcename) + + # e.g. the module directive doesn't have content + self.indent += self.content_indent + + # add all content (from docstrings, attribute docs etc.) + self.add_content(more_content) + + # document members, if possible + self.document_members(all_members) + +class YosysCellDocumenter(YosysCellGroupDocumenter): + objtype = 'cell' + priority = 15 + object: YosysCell + lib_key = 'cells' + + @classmethod + def can_document_member( + cls, + member: Any, + membername: str, + isattr: bool, + parent: Any + ) -> bool: + if membername == "__source": + return False + if not membername.startswith('$'): + return False + return isinstance(parent, YosysCellGroupDocumenter) + + def parse_name(self) -> bool: + try: + matched = cell_ext_sig_re.match(self.name) + group, modname, thing, attribute = matched.groups() + except AttributeError: + logger.warning(('invalid signature for auto%s (%r)') % (self.objtype, self.name), + type='cellref') + return False + + self.modname = modname + self.groupname = group or '' + self.attribute = attribute or '' + self.fullname = ((self.modname) + (thing or '')) + + return True + + def import_object(self, raiseerror: bool = False) -> bool: + if super().import_object(raiseerror): + self.object = YosysCell(self.modname, **self.object[1]) + return True + return False + + def get_sourcename(self) -> str: + return self.object.source.split(":")[0] + + def format_name(self) -> str: + return self.object.name + + def format_signature(self, **kwargs: Any) -> str: + return self.groupname + self.fullname + self.attribute + + def add_directive_header(self, sig: str) -> None: + domain = getattr(self, 'domain', self.objtype) + directive = getattr(self, 'directivetype', 'def') + name = self.format_name() + sourcename = self.get_sourcename() + cell = self.object + + # cell definition + self.add_line(f'.. {domain}:{directive}:: {sig}', sourcename) + + # options + opt_attrs = ["title", "properties", ] + for attr in opt_attrs: + val = getattr(cell, attr, None) + if isinstance(val, list): + val = ' '.join(val) + if val: + self.add_line(f' :{attr}: {val}', sourcename) + + self.add_line('\n', sourcename) + + if self.options.noindex: + self.add_line(' :noindex:', sourcename) + + def add_content(self, more_content: Any | None) -> None: + # set sourcename and add content from attribute documentation + sourcename = self.get_sourcename() + startline = int(self.object.source.split(":")[1]) + + for i, line in enumerate(self.object.desc.splitlines(), startline): + self.add_line(line, sourcename, i) + + # add additional content (e.g. from document), if present + if more_content: + for line, src in zip(more_content.data, more_content.items): + self.add_line(line, src[0], src[1]) + + # fields + self.add_line('\n', sourcename) + field_attrs = ["properties", ] + for field in field_attrs: + attr = getattr(self.object, field, []) + for val in attr: + self.add_line(f':{field} {val}:', sourcename) + + def get_object_members( + self, + want_all: bool + ) -> tuple[bool, list[tuple[str, Any]]]: + ret: list[tuple[str, str]] = [] + + if self.options.source: + ret.append(('__source', self.real_modname)) + + return False, ret + +class YosysCellSourceDocumenter(YosysCellDocumenter): + objtype = 'cellsource' + priority = 20 + + @classmethod + def can_document_member( + cls, + member: Any, + membername: str, + isattr: bool, + parent: Any + ) -> bool: + if membername != "__source": + return False + if isinstance(parent, YosysCellDocumenter): + return True + return False + + def add_directive_header(self, sig: str) -> None: + domain = getattr(self, 'domain', 'cell') + directive = getattr(self, 'directivetype', 'source') + name = self.format_name() + sourcename = self.get_sourcename() + cell = self.object + + # cell definition + self.add_line(f'.. {domain}:{directive}:: {sig}', sourcename) + + if self.options.linenos: + self.add_line(f' :source: {cell.source.split(":")[0]}', sourcename) + else: + self.add_line(f' :source: {cell.source}', sourcename) + self.add_line(f' :language: verilog', sourcename) + + if self.options.linenos: + startline = int(self.object.source.split(":")[1]) + self.add_line(f' :lineno-start: {startline}', sourcename) + + if self.options.noindex: + self.add_line(' :noindex:', sourcename) + + def add_content(self, more_content: Any | None) -> None: + # set sourcename and add content from attribute documentation + sourcename = self.get_sourcename() + startline = int(self.object.source.split(":")[1]) + + for i, line in enumerate(self.object.code.splitlines(), startline-1): + self.add_line(line, sourcename, i) + + # add additional content (e.g. from document), if present + if more_content: + for line, src in zip(more_content.data, more_content.items): + self.add_line(line, src[0], src[1]) + + def get_object_members( + self, + want_all: bool + ) -> tuple[bool, list[tuple[str, Any]]]: + return False, [] + +def setup(app: Sphinx) -> dict[str, Any]: + app.add_config_value('cells_json', False, 'html', [Path, PosixPath, WindowsPath]) + app.setup_extension('sphinx.ext.autodoc') + app.add_autodocumenter(YosysCellDocumenter) + app.add_autodocumenter(YosysCellSourceDocumenter) + app.add_autodocumenter(YosysCellGroupDocumenter) + return { + 'version': '1', + 'parallel_read_safe': True, + } diff --git a/chips/yosys/docs/util/cmd_documenter.py b/chips/yosys/docs/util/cmd_documenter.py new file mode 100644 index 0000000000000000000000000000000000000000..2c9384cca96ea5c638c360d95e072a5736e4c92e --- /dev/null +++ b/chips/yosys/docs/util/cmd_documenter.py @@ -0,0 +1,443 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +from dataclasses import dataclass +import json +from pathlib import Path, PosixPath, WindowsPath +import re + +from typing import Any +from sphinx.application import Sphinx +from sphinx.ext import autodoc +from sphinx.ext.autodoc import Documenter +from sphinx.util import logging + +logger = logging.getLogger(__name__) + +# cmd signature +cmd_ext_sig_re = re.compile( + r'''^ ([\w/]+::)? # optional group + ([\w$._]+?) # module name + (?:\.([\w_]+))? # optional: thing name + (::[\w_]+)? # attribute + \s* $ # and nothing more + ''', re.VERBOSE) + +class YosysCmdContentListing: + type: str + body: str + source_file: str + source_line: int + options: dict[str, str] + content: list[YosysCmdContentListing] + + def __init__( + self, + type: str = "", + body: str = "", + source_file: str = "unknown", + source_line: int = 0, + options: dict[str, str] = {}, + content: list[dict[str]] = [], + ): + self.type = type + self.body = body + self.source_file = source_file + self.source_line = source_line + self.options = options + self.content = [YosysCmdContentListing(**c) for c in content] + +class YosysCmd: + name: str + title: str + content: list[YosysCmdContentListing] + group: str + source_file: str + source_line: int + source_func: str + experimental_flag: bool + internal_flag: bool + + def __init__( + self, + name:str = "", title:str = "", + content: list[dict[str]] = [], + group: str = 'unknown', + source_file: str = "", + source_line: int = 0, + source_func: str = "", + experimental_flag: bool = False, + internal_flag: bool = False, + ) -> None: + self.name = name + self.title = title + self.content = [YosysCmdContentListing(**c) for c in content] + self.group = group + self.source_file = source_file + self.source_line = source_line + self.source_func = source_func + self.experimental_flag = experimental_flag + self.internal_flag = internal_flag + +class YosysCmdGroupDocumenter(Documenter): + objtype = 'cmdgroup' + priority = 10 + object: tuple[str, list[str]] + lib_key = 'groups' + + option_spec = Documenter.option_spec.copy() + option_spec.update({ + 'caption': autodoc.annotation_option, + 'members': autodoc.members_option, + 'source': autodoc.bool_option, + 'linenos': autodoc.bool_option, + }) + + __cmd_lib: dict[str, list[str] | dict[str]] | None = None + @property + def cmd_lib(self) -> dict[str, list[str] | dict[str]]: + if not self.__cmd_lib: + self.__cmd_lib = {} + cmds_obj: dict[str, dict[str, dict[str]]] + try: + with open(self.config.cmds_json, "r") as f: + cmds_obj = json.loads(f.read()) + except FileNotFoundError: + logger.warning( + f"unable to find cmd lib at {self.config.cmds_json}", + type = 'cmdref', + subtype = 'cmd_lib' + ) + cmds_obj = {} + for (name, obj) in cmds_obj.get(self.lib_key, {}).items(): + self.__cmd_lib[name] = obj + return self.__cmd_lib + + @classmethod + def can_document_member( + cls, + member: Any, + membername: str, + isattr: bool, + parent: Any + ) -> bool: + return False + + def parse_name(self) -> bool: + if not self.options.caption: + self.content_indent = '' + self.fullname = self.modname = self.name + return True + + def import_object(self, raiseerror: bool = False) -> bool: + # get cmd + try: + self.object = (self.modname, self.cmd_lib[self.modname]) + except KeyError: + if raiseerror: + raise + return False + + self.real_modname = self.modname + return True + + def get_sourcename(self) -> str: + return self.env.doc2path(self.env.docname) + + def format_name(self) -> str: + return self.options.caption or '' + + def format_signature(self, **kwargs: Any) -> str: + return self.modname + + def add_directive_header(self, sig: str) -> None: + pass + + def add_content(self, more_content: Any | None) -> None: + pass + + def filter_members( + self, + members: list[tuple[str, Any]], + want_all: bool + ) -> list[tuple[str, Any, bool]]: + return [(x[0], x[1], False) for x in members] + + def get_object_members( + self, + want_all: bool + ) -> tuple[bool, list[tuple[str, Any]]]: + ret: list[tuple[str, str]] = [] + + if want_all: + for member in self.object[1]: + ret.append((member, self.modname)) + else: + memberlist = self.options.members or [] + for name in memberlist: + if name in self.object: + ret.append((name, self.modname)) + else: + logger.warning(('unknown module mentioned in :members: option: ' + f'group {self.modname}, module {name}'), + type='cmdref') + + return False, ret + + def document_members(self, all_members: bool = False) -> None: + want_all = (all_members or + self.options.inherited_members or + self.options.members is autodoc.ALL) + # find out which members are documentable + members_check_module, members = self.get_object_members(want_all) + + # document non-skipped members + memberdocumenters: list[tuple[Documenter, bool]] = [] + for (mname, member, isattr) in self.filter_members(members, want_all): + classes = [cls for cls in self.documenters.values() + if cls.can_document_member(member, mname, isattr, self)] + if not classes: + # don't know how to document this member + continue + # prefer the documenter with the highest priority + classes.sort(key=lambda cls: cls.priority) + # give explicitly separated module name, so that members + # of inner classes can be documented + full_mname = self.format_signature() + '::' + mname + documenter = classes[-1](self.directive, full_mname, self.indent) + memberdocumenters.append((documenter, isattr)) + + member_order = self.options.member_order or self.config.autodoc_member_order + memberdocumenters = self.sort_members(memberdocumenters, member_order) + + for documenter, isattr in memberdocumenters: + documenter.generate( + all_members=True, real_modname=self.real_modname, + check_module=members_check_module and not isattr) + + def generate( + self, + more_content: Any | None = None, + real_modname: str | None = None, + check_module: bool = False, + all_members: bool = False + ) -> None: + if not self.parse_name(): + # need a cmd lib to import from + logger.warning( + f"don't know which cmd lib to import for autodocumenting {self.name}", + type = 'cmdref' + ) + return + + sourcename = self.get_sourcename() + + imported_object = self.import_object(); + if self.lib_key == 'groups' and self.name == 'unknown': + if imported_object: + logger.warning(f"Found commands assigned to group {self.name}: {[x[0] for x in self.object]}", type='cmdref') + else: + return + elif not imported_object: + log_msg = f"unable to load {self.name} with {type(self)}" + if self.lib_key == 'groups': + logger.info(log_msg, type = 'cmdref') + self.add_line(f'.. warning:: No commands found for group {self.name!r}', sourcename) + self.add_line('', sourcename) + self.add_line(' Documentation may have been built without ``source_location`` support.', sourcename) + self.add_line(' Try check :doc:`/cmd/index_other`.', sourcename) + else: + logger.warning(log_msg, type = 'cmdref') + return + + # check __module__ of object (for members not given explicitly) + # if check_module: + # if not self.check_module(): + # return + + self.add_line('', sourcename) + + # format the object's signature, if any + try: + sig = self.format_signature() + except Exception as exc: + logger.warning(('error while formatting signature for %s: %s'), + self.fullname, exc, type='cmdref') + return + + # generate the directive header and options, if applicable + self.add_directive_header(sig) + self.add_line('', sourcename) + + # e.g. the module directive doesn't have content + self.indent += self.content_indent + + # add all content (from docstrings, attribute docs etc.) + self.add_content(more_content) + + # document members, if possible + self.document_members(all_members) + +class YosysCmdDocumenter(YosysCmdGroupDocumenter): + objtype = 'cmd' + priority = 15 + object: YosysCmd + lib_key = 'cmds' + + @classmethod + def can_document_member( + cls, + member: Any, + membername: str, + isattr: bool, + parent: Any + ) -> bool: + if membername.startswith('$'): + return False + return isinstance(parent, YosysCmdGroupDocumenter) + + def parse_name(self) -> bool: + try: + matched = cmd_ext_sig_re.match(self.name) + group, modname, thing, attribute = matched.groups() + except AttributeError: + logger.warning(('invalid signature for auto%s (%r)') % (self.objtype, self.name), + type='cmdref') + return False + + self.modname = modname + self.groupname = group or '' + self.attribute = attribute or '' + self.fullname = ((self.modname) + (thing or '')) + + return True + + def import_object(self, raiseerror: bool = False) -> bool: + if super().import_object(raiseerror): + self.object = YosysCmd(self.modname, **self.object[1]) + return True + return False + + def get_sourcename(self) -> str: + try: + return self.object.source_file + except AttributeError: + return super().get_sourcename() + + def format_name(self) -> str: + return self.object.name + + def format_signature(self, **kwargs: Any) -> str: + return self.fullname + self.attribute + + def add_directive_header(self, sig: str) -> None: + domain = getattr(self, 'domain', self.objtype) + directive = getattr(self, 'directivetype', 'def') + source_name = self.object.source_file + source_line = self.object.source_line + + title = f'{self.object.name} - {self.object.title}' + self.add_line(title, source_name, source_line) + self.add_line('#' * len(title), source_name, source_line) + + # cmd definition + self.add_line(f'.. {domain}:{directive}:: {sig}', source_name, source_line) + if self.object.title: + self.add_line(f' :title: {self.object.title}', source_name, source_line) + + if self.options.noindex: + self.add_line(' :noindex:', source_name) + + def add_content(self, more_content: Any | None) -> None: + # set sourcename and add content from attribute documentation + domain = getattr(self, 'domain', self.objtype) + source_name = self.object.source_file + source_line = self.object.source_line + + if self.object.experimental_flag: + self.add_line(f'.. warning:: This command is experimental', source_name, source_line) + self.add_line('\n', source_name) + + if self.object.internal_flag: + self.add_line(f'.. warning:: This command is intended for internal developer use only', source_name, source_line) + self.add_line('\n', source_name) + + def render(content_list: YosysCmdContentListing, indent: int=0): + content_source = content_list.source_file or source_name + indent_str = ' '*indent + if content_list.type == 'usage': + if content_list.body: + self.add_line(f'{indent_str}.. {domain}:{content_list.type}:: {self.name}::{content_list.body}', content_source) + else: + self.add_line(f'{indent_str}.. {domain}:{content_list.type}:: {self.name}::', content_source) + self.add_line(f'{indent_str} :noindex:', source_name) + self.add_line('', source_name) + elif content_list.type == 'option': + self.add_line(f'{indent_str}:{content_list.type} {content_list.body}:', content_source) + elif content_list.type == 'text': + self.add_line(f'{indent_str}{content_list.body}', content_source) + self.add_line('', source_name) + elif content_list.type == 'code': + language_str = content_list.options.get('language', '') + self.add_line(f'{indent_str}.. code-block:: {language_str}', source_name) + self.add_line('', source_name) + for body_line in content_list.body.splitlines(): + self.add_line(f'{indent_str} {body_line}', content_source) + self.add_line('', source_name) + else: + logger.warning(f"unknown content type '{content_list.type}'") + for content in content_list.content: + render(content, indent+1) + + for content in self.object.content: + render(content) + + if self.get_sourcename() != 'unknown': + self.add_line('\n', source_name) + self.add_line(f'.. note:: Help text automatically generated from :file:`{source_name}:{source_line}`', source_name) + + # add additional content (e.g. from document), if present + if more_content: + for line, src in zip(more_content.data, more_content.items): + self.add_line(line, src[0], src[1]) + + def get_object_members( + self, + want_all: bool + ) -> tuple[bool, list[tuple[str, Any]]]: + + return False, [] + +class YosysCmdRstDocumenter(YosysCmdDocumenter): + objtype = 'cmd_rst' + priority = 0 + + @classmethod + def can_document_member(cls, *args) -> bool: + return False + + def add_directive_header(self, sig): + source_name = self.object.source_file + cmd = self.object.name + self.add_line(f'.. code-block:: rst', source_name) + self.add_line(f' :caption: Generated rst for ``.. autocmd:: {cmd}``', source_name) + + def add_content(self, more_content): + source_name = self.object.source_file + cmd = self.object.name + self.domain = 'cmd' + super().add_directive_header(cmd) + self.add_line('', source_name) + self.indent += self.content_indent + super().add_content(more_content) + +def setup(app: Sphinx) -> dict[str, Any]: + app.add_config_value('cmds_json', False, 'html', [Path, PosixPath, WindowsPath]) + app.setup_extension('sphinx.ext.autodoc') + app.add_autodocumenter(YosysCmdGroupDocumenter) + app.add_autodocumenter(YosysCmdDocumenter) + app.add_autodocumenter(YosysCmdRstDocumenter) + return { + 'version': '2', + 'parallel_read_safe': True, + } diff --git a/chips/yosys/docs/util/custom_directives.py b/chips/yosys/docs/util/custom_directives.py new file mode 100644 index 0000000000000000000000000000000000000000..7072fa1db4cc2d33940a1ab5698eedd055a55b3c --- /dev/null +++ b/chips/yosys/docs/util/custom_directives.py @@ -0,0 +1,737 @@ +# based on https://github.com/ofosos/sphinxrecipes/blob/master/sphinxrecipes/sphinxrecipes.py + +from __future__ import annotations + +import re +from typing import cast +import warnings + +from docutils import nodes +from docutils.nodes import Node, Element, Text +from docutils.parsers.rst import directives +from docutils.parsers.rst.states import Inliner +from sphinx.application import Sphinx +from sphinx.domains import Domain, Index +from sphinx.domains.std import StandardDomain +from sphinx.environment import BuildEnvironment +from sphinx.roles import XRefRole, SphinxRole +from sphinx.directives import ObjectDescription +from sphinx.directives.code import container_wrapper +from sphinx.util.nodes import make_refnode +from sphinx.util.docfields import Field, GroupedField +from sphinx import addnodes + +class TocNode(ObjectDescription): + def add_target_and_index( + self, + name: str, + sig: str, + signode: addnodes.desc_signature + ) -> None: + idx = ".".join(name.split("::")) + signode['ids'].append(idx) + + def _object_hierarchy_parts(self, sig_node: addnodes.desc_signature) -> tuple[str, ...]: + if 'tocname' not in sig_node: + return () + + modname = sig_node.get('module') + fullname = sig_node['fullname'] + + if modname: + return (modname, *fullname.split('::')) + else: + return tuple(fullname.split('::')) + + def _toc_entry_name(self, sig_node: addnodes.desc_signature) -> str: + if not sig_node.get('_toc_parts'): + return '' + + config = self.env.app.config + objtype = sig_node.parent.get('objtype') + *parents, name = sig_node['_toc_parts'] + if config.toc_object_entries_show_parents == 'domain': + return sig_node.get('tocname', name) + if config.toc_object_entries_show_parents == 'hide': + return name + if config.toc_object_entries_show_parents == 'all': + return '.'.join(parents + [name]) + return '' + +class NodeWithOptions(TocNode): + """A custom node with options.""" + + doc_field_types = [ + GroupedField('opts', label='Options', names=('option', 'options', 'opt', 'opts')), + ] + + def transform_content(self, contentnode: addnodes.desc_content) -> None: + """hack `:option -thing: desc` into a proper option list with yoscrypt highlighting""" + newchildren = [] + for node in contentnode: + newnode = node + if isinstance(node, nodes.field_list): + newnode = nodes.option_list() + for field in node: + is_option = False + option_list_item = nodes.option_list_item() + for child in field: + if isinstance(child, nodes.field_name): + option_group = nodes.option_group() + option_list_item += option_group + option = nodes.option() + option_group += option + name, text = child.rawsource.split(' ', 1) + is_option = name == 'option' + literal = nodes.literal(text=text) + literal['classes'] += ['code', 'highlight', 'yoscrypt'] + literal['language'] = 'yoscrypt' + option += literal + if not is_option: warnings.warn(f'unexpected option \'{name}\' in {field.source}') + elif isinstance(child, nodes.field_body): + description = nodes.description() + description += child.children + option_list_item += description + if is_option: + newnode += option_list_item + newchildren.append(newnode) + contentnode.children = newchildren + +class CommandNode(NodeWithOptions): + """A custom node that describes a command.""" + + name = 'cmd' + required_arguments = 1 + + option_spec = NodeWithOptions.option_spec.copy() + option_spec.update({ + 'title': directives.unchanged, + 'tags': directives.unchanged + }) + + def handle_signature(self, sig, signode: addnodes.desc_signature): + signode['fullname'] = sig + signode += addnodes.desc_addname(text="yosys> help ") + signode += addnodes.desc_name(text=sig) + return signode['fullname'] + + def add_target_and_index(self, name_cls, sig, signode): + idx = type(self).name + '-' + sig + signode['ids'].append(idx) + if 'noindex' not in self.options: + name = "{}.{}.{}".format(self.name, type(self).__name__, sig) + tagmap = self.env.domaindata[type(self).name]['obj2tag'] + tagmap[name] = list(self.options.get('tags', '').split(' ')) + title = self.options.get('title', sig) + titlemap = self.env.domaindata[type(self).name]['obj2title'] + titlemap[name] = title + objs = self.env.domaindata[type(self).name]['objects'] + # (name, sig, typ, docname, anchor, prio) + objs.append((name, + sig, + type(self).name, + self.env.docname, + idx, + 0)) + +class CommandUsageNode(NodeWithOptions): + """A custom node that describes command usages""" + + name = 'cmdusage' + + option_spec = NodeWithOptions.option_spec + option_spec.update({ + 'usage': directives.unchanged, + }) + + def handle_signature(self, sig: str, signode: addnodes.desc_signature): + parts = sig.split('::') + if len(parts) > 2: parts.pop(0) + use = parts[-1] + signode['fullname'] = '::'.join(parts) + usage = self.options.get('usage', use) + if usage: + signode['tocname'] = usage + signode += addnodes.desc_name(text=usage) + return signode['fullname'] + + def add_target_and_index( + self, + name: str, + sig: str, + signode: addnodes.desc_signature + ) -> None: + idx = ".".join(name.split("::")) + signode['ids'].append(idx) + if 'noindex' not in self.options: + tocname: str = signode.get('tocname', name) + objs = self.env.domaindata[self.domain]['objects'] + # (name, sig, typ, docname, anchor, prio) + objs.append((name, + tocname, + type(self).name, + self.env.docname, + idx, + 1)) + +class PropNode(TocNode): + name = 'prop' + fieldname = 'props' + + def handle_signature(self, sig: str, signode: addnodes.desc_signature): + signode['fullname'] = sig + signode['tocname'] = tocname = sig.split('::')[-1] + signode += addnodes.desc_name(text=tocname) + return signode['fullname'] + + def add_target_and_index( + self, + name: str, + sig: str, + signode: addnodes.desc_signature + ) -> None: + idx = ".".join(name.split("::")) + signode['ids'].append(idx) + if 'noindex' not in self.options: + tocname: str = signode.get('tocname', name) + objs = self.env.domaindata[self.domain]['objects'] + # (name, sig, typ, docname, anchor, prio) + objs.append((name, + tocname, + type(self).name, + self.env.docname, + idx, + 1)) + +class CellGroupedField(Field): + """Custom version of GroupedField which doesn't require content.""" + is_grouped = True + list_type = nodes.bullet_list + + def __init__(self, name: str, names: tuple[str, ...] = (), label: str = None, + rolename: str = None, can_collapse: bool = False) -> None: + super().__init__(name, names, label, True, rolename) + self.can_collapse = can_collapse + + def make_field(self, types: dict[str, list[Node]], domain: str, + items: tuple, env: BuildEnvironment = None, + inliner: Inliner = None, location: Node = None) -> nodes.field: + fieldname = nodes.field_name('', self.label) + listnode = self.list_type() + for fieldarg, content in items: + par = nodes.paragraph() + if fieldarg: + par.extend(self.make_xrefs(self.rolename, domain, + fieldarg, nodes.Text, + env=env, inliner=inliner, location=location)) + + if len(content) == 1 and ( + isinstance(content[0], nodes.Text) or + (isinstance(content[0], nodes.inline) and len(content[0]) == 1 and + isinstance(content[0][0], nodes.Text))): + par += nodes.Text(' -- ') + par += content + listnode += nodes.list_item('', par) + + if len(items) == 1 and self.can_collapse: + list_item = cast(nodes.list_item, listnode[0]) + fieldbody = nodes.field_body('', list_item[0]) + return nodes.field('', fieldname, fieldbody) + + fieldbody = nodes.field_body('', listnode) + return nodes.field('', fieldname, fieldbody) + +class CellNode(TocNode): + """A custom node that describes an internal cell.""" + + name = 'cell' + + option_spec = { + 'title': directives.unchanged, + 'ports': directives.unchanged, + 'properties': directives.unchanged, + } + + doc_field_types = [ + CellGroupedField('props', label='Properties', rolename='prop', + names=('properties', 'property', 'tag', 'tags'), + can_collapse=True), + ] + + def handle_signature(self, sig: str, signode: addnodes.desc_signature): + signode['fullname'] = sig + signode['tocname'] = tocname = sig.split('::')[-1] + signode += addnodes.desc_addname(text="yosys> help ") + signode += addnodes.desc_name(text=tocname) + return signode['fullname'] + + def add_target_and_index( + self, + name: str, + sig: str, + signode: addnodes.desc_signature + ) -> None: + idx = ".".join(name.split("::")) + signode['ids'].append(idx) + if 'noindex' not in self.options: + tocname: str = signode.get('tocname', name) + title: str = self.options.get('title', sig) + titlemap = self.env.domaindata[self.domain]['obj2title'] + titlemap[name] = title + props = self.options.get('properties', '') + if props: + propmap = self.env.domaindata[self.domain]['obj2prop'] + propmap[name] = props.split(' ') + objs = self.env.domaindata[self.domain]['objects'] + # (name, sig, typ, docname, anchor, prio) + objs.append((name, + tocname, + type(self).name, + self.env.docname, + idx, + 0)) + + def transform_content(self, contentnode: addnodes.desc_content) -> None: + # Add the cell title to the body + if 'title' in self.options: + titlenode = nodes.paragraph() + titlenode += nodes.strong() + titlenode[-1] += nodes.Text(self.options['title']) + contentnode.insert(0, titlenode) + +class CellSourceNode(TocNode): + """A custom code block for including cell source.""" + + name = 'cellsource' + + option_spec = { + "source": directives.unchanged_required, + "language": directives.unchanged_required, + 'lineno-start': int, + } + + def handle_signature( + self, + sig, + signode: addnodes.desc_signature + ) -> str: + language = self.options.get('language') + signode['fullname'] = sig + signode['tocname'] = f"{sig.split('::')[-2]} {language}" + signode += addnodes.desc_name(text="Simulation model") + signode += addnodes.desc_sig_space() + signode += addnodes.desc_addname(text=f'({language})') + return signode['fullname'] + + def run(self) -> list[Node]: + """Override run to parse content as a code block""" + if ':' in self.name: + self.domain, self.objtype = self.name.split(':', 1) + else: + self.domain, self.objtype = '', self.name + self.indexnode = addnodes.index(entries=[]) + + node = addnodes.desc() + node.document = self.state.document + source, line = self.get_source_info() + if line is not None: + line -= 1 + self.state.document.note_source(source, line) + node['domain'] = self.domain + # 'desctype' is a backwards compatible attribute + node['objtype'] = node['desctype'] = self.objtype + node['noindex'] = noindex = ('noindex' in self.options) + node['noindexentry'] = ('noindexentry' in self.options) + node['nocontentsentry'] = ('nocontentsentry' in self.options) + if self.domain: + node['classes'].append(self.domain) + node['classes'].append(node['objtype']) + + self.names = [] + signatures = self.get_signatures() + for sig in signatures: + # add a signature node for each signature in the current unit + # and add a reference target for it + signode = addnodes.desc_signature(sig, '') + self.set_source_info(signode) + node.append(signode) + try: + # name can also be a tuple, e.g. (classname, objname); + # this is strictly domain-specific (i.e. no assumptions may + # be made in this base class) + name = self.handle_signature(sig, signode) + except ValueError: + # signature parsing failed + signode.clear() + signode += addnodes.desc_name(sig, sig) + continue # we don't want an index entry here + finally: + # Private attributes for ToC generation. Will be modified or removed + # without notice. + if self.env.app.config.toc_object_entries: + signode['_toc_parts'] = self._object_hierarchy_parts(signode) + signode['_toc_name'] = self._toc_entry_name(signode) + else: + signode['_toc_parts'] = () + signode['_toc_name'] = '' + if name not in self.names: + self.names.append(name) + if not noindex: + # only add target and index entry if this is the first + # description of the object with this name in this desc block + self.add_target_and_index(name, sig, signode) + + # handle code + code = '\n'.join(self.content) + literal: Element = nodes.literal_block(code, code) + if 'lineno-start' in self.options: + literal['linenos'] = True + literal['highlight_args'] = { + 'linenostart': self.options['lineno-start'] + } + literal['classes'] += self.options.get('class', []) + literal['language'] = self.options.get('language') + literal = container_wrapper(self, literal, self.options.get('source')) + + return [self.indexnode, node, literal] + +class CellGroupNode(TocNode): + name = 'cellgroup' + + option_spec = { + 'caption': directives.unchanged, + } + + def add_target_and_index(self, name: str, sig: str, signode: addnodes.desc_signature) -> None: + if self.options.get('caption', ''): + super().add_target_and_index(name, sig, signode) + + def handle_signature( + self, + sig, + signode: addnodes.desc_signature + ) -> str: + signode['fullname'] = fullname = sig + caption = self.options.get("caption", fullname) + if caption: + signode['tocname'] = caption + signode += addnodes.desc_name(text=caption) + return fullname + +class TagIndex(Index): + """A custom directive that creates a tag matrix.""" + + name = 'tag' + localname = 'Tag Index' + shortname = 'Tag' + + def __init__(self, *args, **kwargs): + super(TagIndex, self).__init__(*args, **kwargs) + + def generate(self, docnames=None): + """Return entries for the index given by *name*. If *docnames* is + given, restrict to entries referring to these docnames. + The return value is a tuple of ``(content, collapse)``, where + * collapse* is a boolean that determines if sub-entries should + start collapsed (for output formats that support collapsing + sub-entries). + *content* is a sequence of ``(letter, entries)`` tuples, where *letter* + is the "heading" for the given *entries*, usually the starting letter. + *entries* is a sequence of single entries, where a single entry is a + sequence ``[name, subtype, docname, anchor, extra, qualifier, descr]``. + The items in this sequence have the following meaning: + - `name` -- the name of the index entry to be displayed + - `subtype` -- sub-entry related type: + 0 -- normal entry + 1 -- entry with sub-entries + 2 -- sub-entry + - `docname` -- docname where the entry is located + - `anchor` -- anchor for the entry within `docname` + - `extra` -- extra info for the entry + - `qualifier` -- qualifier for the description + - `descr` -- description for the entry + Qualifier and description are not rendered e.g. in LaTeX output. + """ + + content = {} + + objs = {name: (dispname, typ, docname, anchor) + for name, dispname, typ, docname, anchor, prio + in self.domain.get_objects()} + + tmap = {} + tags = self.domain.data[f'obj2{self.name}'] + for name, tags in tags.items(): + for tag in tags: + tmap.setdefault(tag,[]) + tmap[tag].append(name) + + for tag in tmap.keys(): + lis = content.setdefault(tag, []) + objlis = tmap[tag] + for objname in objlis: + dispname, typ, docname, anchor = objs[objname] + lis.append(( + dispname, 0, docname, + anchor, + '', '', '' + )) + ret = [(k, v) for k, v in sorted(content.items())] + + return (ret, True) + +class CommandIndex(Index): + name = 'cmd' + localname = 'Command Reference' + shortname = 'Command' + + def __init__(self, *args, **kwargs): + super(CommandIndex, self).__init__(*args, **kwargs) + + def generate(self, docnames=None): + """Return entries for the index given by *name*. If *docnames* is + given, restrict to entries referring to these docnames. + The return value is a tuple of ``(content, collapse)``, where + * collapse* is a boolean that determines if sub-entries should + start collapsed (for output formats that support collapsing + sub-entries). + *content* is a sequence of ``(letter, entries)`` tuples, where *letter* + is the "heading" for the given *entries*, usually the starting letter. + *entries* is a sequence of single entries, where a single entry is a + sequence ``[name, subtype, docname, anchor, extra, qualifier, descr]``. + The items in this sequence have the following meaning: + - `name` -- the name of the index entry to be displayed + - `subtype` -- sub-entry related type: + 0 -- normal entry + 1 -- entry with sub-entries + 2 -- sub-entry + - `docname` -- docname where the entry is located + - `anchor` -- anchor for the entry within `docname` + - `extra` -- extra info for the entry + - `qualifier` -- qualifier for the description + - `descr` -- description for the entry + Qualifier and description are not rendered e.g. in LaTeX output. + """ + + content: dict[str, list[tuple]] = {} + items = ((name, dispname, typ, docname, anchor) + for name, dispname, typ, docname, anchor, prio + in self.domain.get_objects() + if typ == self.name) + items = sorted(items, key=lambda item: item[0]) + for name, dispname, typ, docname, anchor in items: + title = self.domain.data['obj2title'].get(name) + lis = content.setdefault(self.shortname, []) + lis.append(( + dispname, 0, docname, + anchor, + '', '', title + )) + ret = [(k, v) for k, v in sorted(content.items())] + + return (ret, True) + +class CellIndex(CommandIndex): + name = 'cell' + localname = 'Internal cell reference' + shortname = 'Internal cell' + +class PropIndex(TagIndex): + """A custom directive that creates a properties matrix.""" + + name = 'prop' + localname = 'Property Index' + shortname = 'Prop' + fieldname = 'props' + + def generate(self, docnames=None): + content = {} + + cells = {name: (dispname, docname, anchor) + for name, dispname, typ, docname, anchor, _ + in self.domain.get_objects() + if typ == 'cell'} + props = {name: (dispname, docname, anchor) + for name, dispname, typ, docname, anchor, _ + in self.domain.get_objects() + if typ == 'prop'} + + tmap: dict[str, list[str]] = {} + tags: dict[str, list[str]] = self.domain.data[f'obj2{self.name}'] + for name, tags in tags.items(): + for tag in tags: + tmap.setdefault(tag,[]) + tmap[tag].append(name) + + for tag in sorted(tmap.keys()): + test = re.match(r'^(\w+[_-])', tag) + tag_prefix = test.group(1) + lis = content.setdefault(tag_prefix, []) + try: + dispname, docname, anchor = props[tag] + except KeyError: + dispname = tag + docname = anchor = '' + lis.append(( + dispname, 1, docname, + anchor, + '', '', docname or 'unavailable' + )) + objlis = tmap[tag] + for objname in sorted(objlis): + dispname, docname, anchor = cells[objname] + lis.append(( + dispname, 2, docname, + anchor, + '', '', docname + )) + ret = [(k, v) for k, v in sorted(content.items())] + + return (ret, True) + +class TitleRefRole(XRefRole): + """XRefRole used which has the cmd title as the displayed text.""" + pass + +class OptionRole(SphinxRole): + def run(self) -> tuple[list[Node], list]: + return self.inliner.interpreted(self.rawtext, self.text, 'yoscrypt', self.lineno) + +class CommandDomain(Domain): + name = 'cmd' + label = 'Yosys commands' + + roles = { + 'ref': XRefRole(), + 'title': TitleRefRole(), + 'option': OptionRole(), + } + + directives = { + 'def': CommandNode, + 'usage': CommandUsageNode, + } + + indices = { + CommandIndex, + TagIndex + } + + initial_data = { + 'objects': [], # object list + 'obj2tag': {}, # name -> tags + 'obj2title': {}, # name -> title + } + + def get_full_qualified_name(self, node): + """Return full qualified name for a given node""" + return "{}.{}.{}".format(type(self).name, + type(node).__name__, + node.arguments[0]) + + def get_objects(self): + for obj in self.data['objects']: + yield(obj) + + def resolve_xref(self, env, fromdocname, builder, typ, + target, node, contnode): + + match = [(docname, anchor, name) + for name, sig, typ, docname, anchor, prio + in self.get_objects() if sig == target] + + if match: + todocname = match[0][0] + targ = match[0][1] + qual_name = match[0][2] + title = self.data['obj2title'].get(qual_name, targ) + + if typ == 'title': + # caller wants the title in the content of the node + cmd = contnode.astext() + contnode = Text(f'{cmd} - {title}') + return make_refnode(builder, fromdocname, todocname, + targ, contnode) + else: + # cmd title as hover text + return make_refnode(builder, fromdocname, todocname, + targ, contnode, title) + else: + print(f"Missing ref for {target} in {fromdocname} ") + return None + +class CellDomain(CommandDomain): + name = 'cell' + label = 'Yosys internal cells' + + roles = CommandDomain.roles.copy() + roles.update({ + 'prop': XRefRole() + }) + + directives = { + 'def': CellNode, + 'defprop': PropNode, + 'source': CellSourceNode, + 'group': CellGroupNode, + } + + indices = { + CellIndex, + PropIndex + } + + initial_data = { + 'objects': [], # object list + 'obj2prop': {}, # name -> properties + 'obj2title': {}, # name -> title + } + + def get_objects(self): + for obj in self.data['objects']: + yield(obj) + +def autoref(name, rawtext: str, text: str, lineno, inliner: Inliner, + options=None, content=None): + words = text.split(' ') + if len(words) == 2 and words[0] == "help": + IsLinkable = True + thing = words[1] + else: + IsLinkable = len(words) == 1 and words[0][0] != '-' + thing = words[0] + if IsLinkable: + role = 'cell:ref' if thing[0] == '$' else 'cmd:ref' + text = f'{text} <{thing}>' + else: + role = 'yoscrypt' + return inliner.interpreted(rawtext, text, role, lineno) + +def setup(app: Sphinx): + app.add_domain(CommandDomain) + app.add_domain(CellDomain) + + StandardDomain.initial_data['labels']['commandindex'] =\ + ('cmd-cmd', '', 'Command Reference') + StandardDomain.initial_data['labels']['tagindex'] =\ + ('cmd-tag', '', 'Tag Index') + StandardDomain.initial_data['labels']['cellindex'] =\ + ('cell-cell', '', 'Internal cell reference') + StandardDomain.initial_data['labels']['propindex'] =\ + ('cell-prop', '', 'Property Index') + + StandardDomain.initial_data['anonlabels']['commandindex'] =\ + ('cmd-cmd', '') + StandardDomain.initial_data['anonlabels']['tagindex'] =\ + ('cmd-tag', '') + StandardDomain.initial_data['anonlabels']['cellindex'] =\ + ('cell-cell', '') + StandardDomain.initial_data['anonlabels']['propindex'] =\ + ('cell-prop', '') + + app.add_role('autoref', autoref) + + return { + 'version': '0.3', + 'parallel_read_safe': False, + } diff --git a/chips/yosys/examples/aiger/.gitignore b/chips/yosys/examples/aiger/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..3524e93629a5c355c4b383fc44804cf6c4a1e453 --- /dev/null +++ b/chips/yosys/examples/aiger/.gitignore @@ -0,0 +1,5 @@ +demo.aig +demo.aim +demo.aiw +demo.smt2 +demo.vcd diff --git a/chips/yosys/examples/aiger/README b/chips/yosys/examples/aiger/README new file mode 100644 index 0000000000000000000000000000000000000000..13dce2035670dad95d743fee079a63fc941137bf --- /dev/null +++ b/chips/yosys/examples/aiger/README @@ -0,0 +1,22 @@ +AIGER is a format for And-Inverter Graphs (AIGs). +See http://fmv.jku.at/aiger/ for details. + +AIGER is used in the Hardware Model Checking Competition (HWMCC), +therefore all solvers competing in the competition have to support +the format. + +The example in this directory is using super_prove as solver. Check +http://downloads.bvsrc.org/super_prove/ for the lates release. (See +https://bitbucket.org/sterin/super_prove_build for sources.) + +The "demo.sh" script in this directory expects a "super_prove" executable +in the PATH. E.g. extract the release to /usr/local/libexec/super_prove +and then create a /usr/local/bin/super_prove file with the following +contents (and "chmod +x" that file): + + #!/usr/bin/env bash + exec /usr/local/libexec/super_prove/bin/super_prove.sh "$@" + +The "demo.sh" script also expects the "z3" SMT2 solver in the PATH for +converting the witness file generated by super_prove to VCD using +yosys-smtbmc. See https://github.com/Z3Prover/z3 for install notes. diff --git a/chips/yosys/examples/aiger/demo.sh b/chips/yosys/examples/aiger/demo.sh new file mode 100644 index 0000000000000000000000000000000000000000..a1217bbd2853c15edf322006f93893f5063864ef --- /dev/null +++ b/chips/yosys/examples/aiger/demo.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +set -ex +yosys -p ' + read_verilog -formal demo.v + prep -flatten -nordff -top demo + write_smt2 -wires demo.smt2 + flatten demo; delete -output + memory_map; opt -full + techmap; opt -fast + abc -fast -g AND; opt_clean + write_aiger -map demo.aim demo.aig +' +super_prove demo.aig > demo.aiw +yosys-smtbmc --dump-vcd demo.vcd --aig demo demo.smt2 diff --git a/chips/yosys/examples/aiger/demo.v b/chips/yosys/examples/aiger/demo.v new file mode 100644 index 0000000000000000000000000000000000000000..b98287424ea2e73e0793cc254f86f1cc10de03d4 --- /dev/null +++ b/chips/yosys/examples/aiger/demo.v @@ -0,0 +1,12 @@ +module demo(input clk, reset, ctrl); + localparam NBITS = 10; + reg [NBITS-1:0] counter; + initial counter[NBITS-2] = 0; + initial counter[0] = 1; + always @(posedge clk) begin + counter <= reset ? 1 : ctrl ? counter + 1 : counter - 1; + assume(counter != 0); + assume(counter != 1 << (NBITS-1)); + assert(counter != (1 << NBITS)-1); + end +endmodule diff --git a/chips/yosys/examples/anlogic/.gitignore b/chips/yosys/examples/anlogic/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..97c978a15053d6e4070e9976462ae7fee374de3d --- /dev/null +++ b/chips/yosys/examples/anlogic/.gitignore @@ -0,0 +1,7 @@ +demo.bit +demo_phy.area +full.v +*.log +*.h +*.tde +*.svf diff --git a/chips/yosys/examples/anlogic/README b/chips/yosys/examples/anlogic/README new file mode 100644 index 0000000000000000000000000000000000000000..35d8e9cb16ebb2e96e195063a9d692e765145778 --- /dev/null +++ b/chips/yosys/examples/anlogic/README @@ -0,0 +1,12 @@ +LED Blink project for Anlogic Lichee Tang board. + +Follow the install instructions for the Tang Dynasty IDE from given link below. + +https://tang.sipeed.com/en/getting-started/installing-td-ide/linux/ + + +set TD_HOME env variable to the full path to the TD as follow. + +export TD_HOME= + +then run "bash build.sh" in this directory. diff --git a/chips/yosys/examples/anlogic/build.sh b/chips/yosys/examples/anlogic/build.sh new file mode 100644 index 0000000000000000000000000000000000000000..9b6e8c4791533adfd9e2d6deda06b0f55a464eb3 --- /dev/null +++ b/chips/yosys/examples/anlogic/build.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +set -ex +yosys demo.ys +$TD_HOME/bin/td build.tcl diff --git a/chips/yosys/examples/anlogic/build.tcl b/chips/yosys/examples/anlogic/build.tcl new file mode 100644 index 0000000000000000000000000000000000000000..06db525c9a1136e76d6c296e87f57b3a39334953 --- /dev/null +++ b/chips/yosys/examples/anlogic/build.tcl @@ -0,0 +1,11 @@ +import_device eagle_s20.db -package BG256 +read_verilog full.v -top demo +read_adc demo.adc +optimize_rtl +map_macro +map +pack +place +route +report_area -io_info -file demo_phy.area +bitgen -bit demo.bit -version 0X0000 -svf demo.svf -svf_comment_on -g ucode:00000000000000000000000000000000 diff --git a/chips/yosys/examples/anlogic/demo.adc b/chips/yosys/examples/anlogic/demo.adc new file mode 100644 index 0000000000000000000000000000000000000000..ec802502e811cf38dae9fdc3472c732f779bbb3f --- /dev/null +++ b/chips/yosys/examples/anlogic/demo.adc @@ -0,0 +1,2 @@ +set_pin_assignment {CLK_IN} { LOCATION = K14; } ##24MHZ +set_pin_assignment {R_LED} { LOCATION = R3; } ##R_LED diff --git a/chips/yosys/examples/anlogic/demo.v b/chips/yosys/examples/anlogic/demo.v new file mode 100644 index 0000000000000000000000000000000000000000..e17db771ea047113621efd27882fc514de2c4904 --- /dev/null +++ b/chips/yosys/examples/anlogic/demo.v @@ -0,0 +1,18 @@ +module demo ( + input wire CLK_IN, + output wire R_LED +); + parameter time1 = 30'd12_000_000; + reg led_state; + reg [29:0] count; + + always @(posedge CLK_IN)begin + if(count == time1)begin + count<= 30'd0; + led_state <= ~led_state; + end + else + count <= count + 1'b1; + end + assign R_LED = led_state; +endmodule diff --git a/chips/yosys/examples/anlogic/demo.ys b/chips/yosys/examples/anlogic/demo.ys new file mode 100644 index 0000000000000000000000000000000000000000..cb396cc2b04d4ef3abb861c2ea67de3b16b5f808 --- /dev/null +++ b/chips/yosys/examples/anlogic/demo.ys @@ -0,0 +1,3 @@ +read_verilog demo.v +synth_anlogic -top demo +write_verilog full.v diff --git a/chips/yosys/examples/basys3/README b/chips/yosys/examples/basys3/README new file mode 100644 index 0000000000000000000000000000000000000000..77fbef15c17d314343ea0100e58c330fcb7bc491 --- /dev/null +++ b/chips/yosys/examples/basys3/README @@ -0,0 +1,18 @@ + +A simple example design, based on the Digilent BASYS3 board +=========================================================== + +This example uses Yosys for synthesis and Xilinx Vivado +for place&route and bit-stream creation. + +Running Yosys: + yosys run_yosys.ys + +Running Vivado: + vivado -nolog -nojournal -mode batch -source run_vivado.tcl + +Programming board: + vivado -nolog -nojournal -mode batch -source run_prog.tcl + +All of the above: + bash run.sh diff --git a/chips/yosys/examples/basys3/example.v b/chips/yosys/examples/basys3/example.v new file mode 100644 index 0000000000000000000000000000000000000000..2b01a22a82ec3bfd15b7f0ffc08f5171827807e0 --- /dev/null +++ b/chips/yosys/examples/basys3/example.v @@ -0,0 +1,21 @@ +module example(CLK, LD); + input CLK; + output [15:0] LD; + + wire clock; + reg [15:0] leds; + + BUFG CLK_BUF (.I(CLK), .O(clock)); + OBUF LD_BUF[15:0] (.I(leds), .O(LD)); + + parameter COUNTBITS = 26; + reg [COUNTBITS-1:0] counter; + + always @(posedge CLK) begin + counter <= counter + 1; + if (counter[COUNTBITS-1]) + leds <= 16'h8000 >> counter[COUNTBITS-2:COUNTBITS-5]; + else + leds <= 16'h0001 << counter[COUNTBITS-2:COUNTBITS-5]; + end +endmodule diff --git a/chips/yosys/examples/basys3/example.xdc b/chips/yosys/examples/basys3/example.xdc new file mode 100644 index 0000000000000000000000000000000000000000..7b6736588fdfbdfcc14c19204bada1508acde098 --- /dev/null +++ b/chips/yosys/examples/basys3/example.xdc @@ -0,0 +1,23 @@ + +set_property -dict { IOSTANDARD LVCMOS33 PACKAGE_PIN W5 } [get_ports CLK] +set_property -dict { IOSTANDARD LVCMOS33 PACKAGE_PIN U16 } [get_ports {LD[0]}] +set_property -dict { IOSTANDARD LVCMOS33 PACKAGE_PIN E19 } [get_ports {LD[1]}] +set_property -dict { IOSTANDARD LVCMOS33 PACKAGE_PIN U19 } [get_ports {LD[2]}] +set_property -dict { IOSTANDARD LVCMOS33 PACKAGE_PIN V19 } [get_ports {LD[3]}] +set_property -dict { IOSTANDARD LVCMOS33 PACKAGE_PIN W18 } [get_ports {LD[4]}] +set_property -dict { IOSTANDARD LVCMOS33 PACKAGE_PIN U15 } [get_ports {LD[5]}] +set_property -dict { IOSTANDARD LVCMOS33 PACKAGE_PIN U14 } [get_ports {LD[6]}] +set_property -dict { IOSTANDARD LVCMOS33 PACKAGE_PIN V14 } [get_ports {LD[7]}] +set_property -dict { IOSTANDARD LVCMOS33 PACKAGE_PIN V13 } [get_ports {LD[8]}] +set_property -dict { IOSTANDARD LVCMOS33 PACKAGE_PIN V3 } [get_ports {LD[9]}] +set_property -dict { IOSTANDARD LVCMOS33 PACKAGE_PIN W3 } [get_ports {LD[10]}] +set_property -dict { IOSTANDARD LVCMOS33 PACKAGE_PIN U3 } [get_ports {LD[11]}] +set_property -dict { IOSTANDARD LVCMOS33 PACKAGE_PIN P3 } [get_ports {LD[12]}] +set_property -dict { IOSTANDARD LVCMOS33 PACKAGE_PIN N3 } [get_ports {LD[13]}] +set_property -dict { IOSTANDARD LVCMOS33 PACKAGE_PIN P1 } [get_ports {LD[14]}] +set_property -dict { IOSTANDARD LVCMOS33 PACKAGE_PIN L1 } [get_ports {LD[15]}] + +create_clock -add -name sys_clk_pin -period 10.00 -waveform {0 5} [get_ports CLK] + +set_property CONFIG_VOLTAGE 3.3 [current_design] +set_property CFGBVS VCCO [current_design] diff --git a/chips/yosys/examples/basys3/run.sh b/chips/yosys/examples/basys3/run.sh new file mode 100644 index 0000000000000000000000000000000000000000..deb68d432555203df27950364a77047403af248a --- /dev/null +++ b/chips/yosys/examples/basys3/run.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +yosys run_yosys.ys +vivado -nolog -nojournal -mode batch -source run_vivado.tcl +vivado -nolog -nojournal -mode batch -source run_prog.tcl diff --git a/chips/yosys/examples/basys3/run_prog.tcl b/chips/yosys/examples/basys3/run_prog.tcl new file mode 100644 index 0000000000000000000000000000000000000000..b078ad511131dcb1bc643f3b330370e29e8d0ba6 --- /dev/null +++ b/chips/yosys/examples/basys3/run_prog.tcl @@ -0,0 +1,5 @@ +open_hw +connect_hw_server +open_hw_target [lindex [get_hw_targets] 0] +set_property PROGRAM.FILE example.bit [lindex [get_hw_devices] 0] +program_hw_devices [lindex [get_hw_devices] 0] diff --git a/chips/yosys/examples/basys3/run_vivado.tcl b/chips/yosys/examples/basys3/run_vivado.tcl new file mode 100644 index 0000000000000000000000000000000000000000..c3b6a610e77cb35a9e314cc40be57f941403cb6c --- /dev/null +++ b/chips/yosys/examples/basys3/run_vivado.tcl @@ -0,0 +1,9 @@ +read_xdc example.xdc +read_edif example.edif +link_design -part xc7a35tcpg236-1 -top example +opt_design +place_design +route_design +report_utilization +report_timing +write_bitstream -force example.bit diff --git a/chips/yosys/examples/basys3/run_yosys.ys b/chips/yosys/examples/basys3/run_yosys.ys new file mode 100644 index 0000000000000000000000000000000000000000..4541826d32e10d40f8327606ae73ed0d9746cf61 --- /dev/null +++ b/chips/yosys/examples/basys3/run_yosys.ys @@ -0,0 +1,2 @@ +read_verilog example.v +synth_xilinx -edif example.edif -top example diff --git a/chips/yosys/examples/cmos/.gitignore b/chips/yosys/examples/cmos/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..f58d95018195c18063ecdb4037d142bec565fa59 --- /dev/null +++ b/chips/yosys/examples/cmos/.gitignore @@ -0,0 +1,4 @@ +counter_tb +counter_tb.vcd +synth.sp +synth.v diff --git a/chips/yosys/examples/cmos/README b/chips/yosys/examples/cmos/README new file mode 100644 index 0000000000000000000000000000000000000000..7033c9b8277a00c759282a980bc7126841d2c12c --- /dev/null +++ b/chips/yosys/examples/cmos/README @@ -0,0 +1,12 @@ + +In this directory contains an example for generating a spice output using two +different spice modes, normal analog transient simulation and event-driven +digital simulation as supported by ngspice xspice sub-module. + +Each test bench can be run separately by either running: + +- testbench.sh, to start analog simulation or +- testbench_digital.sh for mixed-signal digital simulation. + +The later case also includes pure verilog simulation using the iverilog +and gtkwave for comparison. diff --git a/chips/yosys/examples/cmos/cmos_cells.lib b/chips/yosys/examples/cmos/cmos_cells.lib new file mode 100644 index 0000000000000000000000000000000000000000..1b0bf8457d0a70b6d3b0c6f1eff15c62c5d4c20b --- /dev/null +++ b/chips/yosys/examples/cmos/cmos_cells.lib @@ -0,0 +1,55 @@ +// test comment +/* test comment */ +library(demo) { + cell(BUF) { + area: 6; + pin(A) { direction: input; } + pin(Y) { direction: output; + function: "A"; } + } + cell(NOT) { + area: 3; + pin(A) { direction: input; } + pin(Y) { direction: output; + function: "A'"; } + } + cell(NAND) { + area: 4; + pin(A) { direction: input; } + pin(B) { direction: input; } + pin(Y) { direction: output; + function: "(A*B)'"; } + } + cell(NOR) { + area: 4; + pin(A) { direction: input; } + pin(B) { direction: input; } + pin(Y) { direction: output; + function: "(A+B)'"; } + } + cell(DFF) { + area: 18; + ff(IQ, IQN) { clocked_on: C; + next_state: D; } + pin(C) { direction: input; + clock: true; } + pin(D) { direction: input; } + pin(Q) { direction: output; + function: "IQ"; } + } + cell(DFFSR) { + area: 18; + ff("IQ", "IQN") { clocked_on: C; + next_state: D; + preset: S; + clear: R; } + pin(C) { direction: input; + clock: true; } + pin(D) { direction: input; } + pin(Q) { direction: output; + function: "IQ"; } + pin(S) { direction: input; } + pin(R) { direction: input; } + ; // empty statement + } +} diff --git a/chips/yosys/examples/cmos/cmos_cells.sp b/chips/yosys/examples/cmos/cmos_cells.sp new file mode 100644 index 0000000000000000000000000000000000000000..f23d978cb11bab4e9a550cdd072cd5fce9ab913e --- /dev/null +++ b/chips/yosys/examples/cmos/cmos_cells.sp @@ -0,0 +1,38 @@ + +.SUBCKT BUF A Y +X1 A B NOT +X2 B Y NOT +.ENDS NOT + +.SUBCKT NOT A Y +M1 Y A Vdd Vdd cmosp L=1u W=10u +M2 Y A Vss Vss cmosn L=1u W=10u +.ENDS NOT + +.SUBCKT NAND A B Y +M1 Y A Vdd Vdd cmosp L=1u W=10u +M2 Y B Vdd Vdd cmosp L=1u W=10u +M3 Y A M34 Vss cmosn L=1u W=10u +M4 M34 B Vss Vss cmosn L=1u W=10u +.ENDS NAND + +.SUBCKT NOR A B Y +M1 Y A M12 Vdd cmosp L=1u W=10u +M2 M12 B Vdd Vdd cmosp L=1u W=10u +M3 Y A Vss Vss cmosn L=1u W=10u +M4 Y B Vss Vss cmosn L=1u W=10u +.ENDS NOR + +.SUBCKT DLATCH E D Q +X1 D E S NAND +X2 nD E R NAND +X3 S nQ Q NAND +X4 Q R nQ NAND +X5 D nD NOT +.ENDS DLATCH + +.SUBCKT DFF C D Q +X1 nC D t DLATCH +X2 C t Q DLATCH +X3 C nC NOT +.ENDS DFF diff --git a/chips/yosys/examples/cmos/cmos_cells.v b/chips/yosys/examples/cmos/cmos_cells.v new file mode 100644 index 0000000000000000000000000000000000000000..9a855ab8c12b14505595c0cdd28209b719ed04eb --- /dev/null +++ b/chips/yosys/examples/cmos/cmos_cells.v @@ -0,0 +1,43 @@ + +module BUF(A, Y); +input A; +output Y; +assign Y = A; +endmodule + +module NOT(A, Y); +input A; +output Y; +assign Y = ~A; +endmodule + +module NAND(A, B, Y); +input A, B; +output Y; +assign Y = ~(A & B); +endmodule + +module NOR(A, B, Y); +input A, B; +output Y; +assign Y = ~(A | B); +endmodule + +module DFF(C, D, Q); +input C, D; +output reg Q; +always @(posedge C) + Q <= D; +endmodule + +module DFFSR(C, D, Q, S, R); +input C, D, S, R; +output reg Q; +always @(posedge C, posedge S, posedge R) + if (S) + Q <= 1'b1; + else if (R) + Q <= 1'b0; + else + Q <= D; +endmodule diff --git a/chips/yosys/examples/cmos/cmos_cells_digital.sp b/chips/yosys/examples/cmos/cmos_cells_digital.sp new file mode 100644 index 0000000000000000000000000000000000000000..89f844094e3150f0f8cd7b3f1ffe5709f8e9211d --- /dev/null +++ b/chips/yosys/examples/cmos/cmos_cells_digital.sp @@ -0,0 +1,30 @@ + +.SUBCKT BUF A Y +.model buffer1 d_buffer +Abuf A Y buffer1 +.ENDS NOT + +.SUBCKT NOT A Y +.model not1 d_inverter +Anot A Y not1 +.ENDS NOT + +.SUBCKT NAND A B Y +.model nand1 d_nand +Anand [A B] Y nand1 +.ENDS NAND + +.SUBCKT NOR A B Y +.model nor1 d_nor +Anand [A B] Y nor1 +.ENDS NOR + +.SUBCKT DLATCH E D Q +.model latch1 d_latch +Alatch D E null null Q nQ latch1 +.ENDS DLATCH + +.SUBCKT DFF C D Q +.model dff1 d_dff +Adff D C null null Q nQ dff1 +.ENDS DFF diff --git a/chips/yosys/examples/cmos/counter.v b/chips/yosys/examples/cmos/counter.v new file mode 100644 index 0000000000000000000000000000000000000000..f21658724f641e05fb5b0a3c0e7845da9044a3e6 --- /dev/null +++ b/chips/yosys/examples/cmos/counter.v @@ -0,0 +1,12 @@ +module counter (clk, rst, en, count); + + input clk, rst, en; + output reg [2:0] count; + + always @(posedge clk) + if (rst) + count <= 3'd0; + else if (en) + count <= count + 3'd1; + +endmodule diff --git a/chips/yosys/examples/cmos/counter.ys b/chips/yosys/examples/cmos/counter.ys new file mode 100644 index 0000000000000000000000000000000000000000..d0b093667ea96dff0b2c00b110a79539b31d3c18 --- /dev/null +++ b/chips/yosys/examples/cmos/counter.ys @@ -0,0 +1,16 @@ +read_verilog counter.v +read_verilog -lib cmos_cells.v + +synth +dfflibmap -liberty cmos_cells.lib +abc -liberty cmos_cells.lib +opt_clean + +stat -liberty cmos_cells.lib + +# http://vlsiarch.ecen.okstate.edu/flows/MOSIS_SCMOS/latest/cadence/lib/tsmc025/signalstorm/osu025_stdcells.lib +# dfflibmap -liberty osu025_stdcells.lib +# abc -liberty osu025_stdcells.lib;; + +write_verilog synth.v +write_spice synth.sp diff --git a/chips/yosys/examples/cmos/counter_digital.ys b/chips/yosys/examples/cmos/counter_digital.ys new file mode 100644 index 0000000000000000000000000000000000000000..eef353e9815588ba1e070087d56a2961bfe6b65b --- /dev/null +++ b/chips/yosys/examples/cmos/counter_digital.ys @@ -0,0 +1,15 @@ + +read_verilog counter.v +read_verilog -lib cmos_cells.v + +proc;; memory;; techmap;; + +dfflibmap -liberty cmos_cells.lib +abc -liberty cmos_cells.lib;; + +# http://vlsiarch.ecen.okstate.edu/flows/MOSIS_SCMOS/latest/cadence/lib/tsmc025/signalstorm/osu025_stdcells.lib +# dfflibmap -liberty osu025_stdcells.lib +# abc -liberty osu025_stdcells.lib;; + +write_verilog synth.v +write_spice -neg 0s -pos 1s synth.sp diff --git a/chips/yosys/examples/cmos/counter_tb.gtkw b/chips/yosys/examples/cmos/counter_tb.gtkw new file mode 100644 index 0000000000000000000000000000000000000000..4a2eac400579cbe796c6436f8073b24907bf8ee7 --- /dev/null +++ b/chips/yosys/examples/cmos/counter_tb.gtkw @@ -0,0 +1,5 @@ +[dumpfile] "counter_tb.vcd" +counter_tb.clk +counter_tb.count[2:0] +counter_tb.en +counter_tb.reset diff --git a/chips/yosys/examples/cmos/counter_tb.v b/chips/yosys/examples/cmos/counter_tb.v new file mode 100644 index 0000000000000000000000000000000000000000..11e82507ea60409e2d3e015def7fc74eed0a8a81 --- /dev/null +++ b/chips/yosys/examples/cmos/counter_tb.v @@ -0,0 +1,33 @@ +module counter_tb; + + /* Make a reset pulse and specify dump file */ + reg reset = 0; + initial begin + $dumpfile("counter_tb.vcd"); + $dumpvars(0,counter_tb); + + # 0 reset = 1; + # 4 reset = 0; + # 36 reset = 1; + # 4 reset = 0; + # 6 $finish; + end + + /* Make enable with period of 8 and 6,7 low */ + reg en = 1; + always begin + en = 1; + #6; + en = 0; + #2; + end + + /* Make a regular pulsing clock. */ + reg clk = 0; + always #1 clk = !clk; + + /* UUT */ + wire [2:0] count; + counter c1 (clk, reset, en, count); + +endmodule diff --git a/chips/yosys/examples/cmos/testbench.sh b/chips/yosys/examples/cmos/testbench.sh new file mode 100644 index 0000000000000000000000000000000000000000..6928b71a23927ac9de6138d4df7891ba6c51083f --- /dev/null +++ b/chips/yosys/examples/cmos/testbench.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash + +set -ex + +../../yosys counter.ys +ngspice testbench.sp diff --git a/chips/yosys/examples/cmos/testbench.sp b/chips/yosys/examples/cmos/testbench.sp new file mode 100644 index 0000000000000000000000000000000000000000..e571d2815e5405383bdeaa2b81a73b4c81155f36 --- /dev/null +++ b/chips/yosys/examples/cmos/testbench.sp @@ -0,0 +1,29 @@ + +* supply voltages +.global Vss Vdd +Vss Vss 0 DC 0 +Vdd Vdd 0 DC 3 + +* simple transistor model +.MODEL cmosn NMOS LEVEL=1 VT0=0.7 KP=110U GAMMA=0.4 LAMBDA=0.04 PHI=0.7 +.MODEL cmosp PMOS LEVEL=1 VT0=-0.7 KP=50U GAMMA=0.57 LAMBDA=0.05 PHI=0.8 + +* load design and library +.include cmos_cells.sp +.include synth.sp + +* input signals +Vclk clk 0 PULSE(0 3 1 0.1 0.1 0.8 2) +Vrst rst 0 PULSE(0 3 0.5 0.1 0.1 2.9 40) +Ven en 0 PULSE(0 3 0.5 0.1 0.1 5.9 8) + +Xuut clk rst en out0 out1 out2 COUNTER + +.tran 0.01 50 + +.control +run +plot v(clk) v(rst)+5 v(en)+10 v(out0)+20 v(out1)+25 v(out2)+30 +.endc + +.end diff --git a/chips/yosys/examples/cmos/testbench_digital.sh b/chips/yosys/examples/cmos/testbench_digital.sh new file mode 100644 index 0000000000000000000000000000000000000000..1a27925b161d4cd6c1b833cd59db073e2466446d --- /dev/null +++ b/chips/yosys/examples/cmos/testbench_digital.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash + +set -ex + +# iverlog simulation +echo "Doing Verilog simulation with iverilog" +iverilog -o counter_tb counter.v counter_tb.v +./counter_tb; gtkwave counter_tb.gtkw & + +# yosys synthesis +../../yosys counter_digital.ys + +# requires ngspice with xspice support enabled: +ngspice testbench_digital.sp diff --git a/chips/yosys/examples/cmos/testbench_digital.sp b/chips/yosys/examples/cmos/testbench_digital.sp new file mode 100644 index 0000000000000000000000000000000000000000..c5f9d598700e8fb79b964f94509e9cb85fe19a54 --- /dev/null +++ b/chips/yosys/examples/cmos/testbench_digital.sp @@ -0,0 +1,26 @@ + +* load design and library +.include cmos_cells_digital.sp +.include synth.sp + +* input signals +Vclk clk 0 PULSE(0 3 1 0.1 0.1 0.8 2) +Vrst rst 0 PULSE(0 3 0.5 0.1 0.1 2.9 40) +Ven en 0 PULSE(0 3 0.5 0.1 0.1 5.9 8) + +Xuut dclk drst den dout0 dout1 dout2 counter +* Bridge to digital +.model adc_buff adc_bridge(in_low = 0.8 in_high=2) +.model dac_buff dac_bridge(out_high = 3.5) +Aad [clk rst en] [dclk drst den] adc_buff +Ada [dout0 dout1 dout2] [out0 out1 out2] dac_buff + + +.tran 0.01 50 + +.control +run +plot v(clk) v(rst)+5 v(en)+10 v(out0)+20 v(out1)+25 v(out2)+30 +.endc + +.end diff --git a/chips/yosys/examples/cxx-api/demomain.cc b/chips/yosys/examples/cxx-api/demomain.cc new file mode 100644 index 0000000000000000000000000000000000000000..5f87a768a19914bfe8d27d8a5d5d842742acaa39 --- /dev/null +++ b/chips/yosys/examples/cxx-api/demomain.cc @@ -0,0 +1,20 @@ +// Note: Use `cmake -DYOSYS_INSTALL_LIBRARY=1` or build the `libyosys` target first +// yosys-config --exec --cxx -o demomain --cxxflags --ldflags demomain.cc -lyosys + +#include + +int main() +{ + Yosys::logger().add_sink(); + + Yosys::yosys_setup(); + Yosys::yosys_banner(); + + Yosys::run_pass("read_verilog example.v"); + Yosys::run_pass("synth -noabc"); + Yosys::run_pass("clean -purge"); + Yosys::run_pass("write_blif example.blif"); + + Yosys::yosys_shutdown(); + return 0; +} diff --git a/chips/yosys/examples/cxx-api/evaldemo.cc b/chips/yosys/examples/cxx-api/evaldemo.cc new file mode 100644 index 0000000000000000000000000000000000000000..cfe0c080428b35a9c4553aee797e593070cec186 --- /dev/null +++ b/chips/yosys/examples/cxx-api/evaldemo.cc @@ -0,0 +1,55 @@ +/* A simple Yosys plugin. (Copy&paste from http://stackoverflow.com/questions/32093541/how-does-the-yosys-consteval-api-work) + +Usage example: + +$ cat > evaldemo.v <, Design *design) override + { + Module *module = design->top_module(); + + if (module == nullptr) + log_error("No top module found!\n"); + + Wire *wire_a = module->wire(ID::A); + Wire *wire_y = module->wire(ID::Y); + + if (wire_a == nullptr) + log_error("No wire A found!\n"); + + if (wire_y == nullptr) + log_error("No wire Y found!\n"); + + ConstEval ce(module); + for (int v = 0; v < 4; v++) { + ce.push(); + ce.set(wire_a, Const(v, GetSize(wire_a))); + SigSpec sig_y = wire_y, sig_undef; + if (ce.eval(sig_y, sig_undef)) + log("Eval results for A=%d: Y=%s\n", v, log_signal(sig_y)); + else + log("Eval failed for A=%d: Missing value for %s\n", v, log_signal(sig_undef)); + ce.pop(); + } + } +} EvalDemoPass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/examples/cxx-api/scopeinfo_example.cc b/chips/yosys/examples/cxx-api/scopeinfo_example.cc new file mode 100644 index 0000000000000000000000000000000000000000..f3097d49626be8929b73eafd5c6adca563f91046 --- /dev/null +++ b/chips/yosys/examples/cxx-api/scopeinfo_example.cc @@ -0,0 +1,147 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2023 Jannis Harder + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +// build: yosys-config --build scopeinfo_example.so scopeinfo_example.cc +// use: yosys -m scopeinfo_example.so + +#include "backends/rtlil/rtlil_backend.h" +#include "kernel/scopeinfo.h" +#include "kernel/yosys.h" + +USING_YOSYS_NAMESPACE +PRIVATE_NAMESPACE_BEGIN + +struct ScopeinfoExamplePass : public Pass { + ScopeinfoExamplePass() : Pass("scopeinfo_example", "dump scopeinfo") {} + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" scopeinfo_example [options] [selection]\n"); + log("\n"); + } + + void execute(std::vector args, RTLIL::Design *design) override + { + log_header(design, "Executing SCOPEINFO_EXAMPLE pass.\n"); + + bool do_wires = false; + bool do_common = false; + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) { + if (args[argidx] == "-wires") { + do_wires = true; + continue; + } + if (args[argidx] == "-common") { + do_common = true; + continue; + } + break; + } + extra_args(args, argidx, design); + + + if (do_wires) { + for (auto module : design->selected_modules()) { + log("Source hierarchy for all selected wires within %s:\n", module); + ModuleHdlnameIndex index(module); + + index.index_scopeinfo_cells(); + + for (auto wire : module->selected_wires()) { + if (!wire->name.isPublic()) + continue; + + auto wire_scope = index.containing_scope(wire); + + if (!wire_scope.first.valid()) { + log_warning("Couldn't find containing scope for %s in index\n", wire); + continue; + } + + log("%s %s\n", wire_scope.first.path_str(design), + design->twines().unescaped_str(wire_scope.second)); + for (auto src : index.sources(wire)) + log(" - %s\n", src); + } + } + } + + if (do_common) { + for (auto module : design->selected_modules()) { + std::vector wires = module->selected_wires(); + + // Shuffle wires so this example produces more interesting outputs + std::sort(wires.begin(), wires.end(), [](Wire *a, Wire *b) { + return mkhash_xorshift(run_hash(a->name) * 0x2c9277b5) < mkhash_xorshift(run_hash(b->name) * 0x2c9277b5); + }); + + ModuleHdlnameIndex index(module); + + index.index_scopeinfo_cells(); + + for (auto wire_i = wires.begin(), wire_end = wires.end(); wire_i != wire_end; ++wire_i) { + if (!(*wire_i)->name.isPublic()) + continue; + + std::pair scope_i = index.containing_scope(*wire_i); + if (!scope_i.first.valid()) + continue; + + int limit = 0; + + for (auto wire_j = wire_i + 1; wire_j != wire_end; ++wire_j) { + if (!(*wire_j)->name.isPublic()) + continue; + + std::pair scope_j = index.containing_scope(*wire_j); + if (!scope_j.first.valid()) + continue; + + // Skip wires in the same hierarchy level + if (scope_i.first == scope_j.first) + continue; + + + ModuleHdlnameIndex::Cursor common = scope_i.first.common_ancestor(scope_j.first); + + // Try to show at least some non-root common ancestors + if (common.is_root() && limit > 5) + continue; + + log("common_ancestor(%s %s%s%s, %s %s%s%s) = %s %s\n", + module, scope_i.first.path_str(design), scope_i.first.is_root() ? "" : " ", + design->twines().unescaped_str(scope_i.second), + module, scope_j.first.path_str(design), scope_j.first.is_root() ? "" : " ", + design->twines().unescaped_str(scope_j.second), + module, common.path_str(design) + ); + + if (++limit == 10) + break; + } + } + } + } + } +} ScopeinfoExamplePass; + +PRIVATE_NAMESPACE_END diff --git a/chips/yosys/examples/gowin/.gitignore b/chips/yosys/examples/gowin/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..71030bdb805fc0817a061d6e17d62a67600d073a --- /dev/null +++ b/chips/yosys/examples/gowin/.gitignore @@ -0,0 +1,8 @@ +demo.bit +demo.out +demo.rpt +demo_syn.v +demo_out.v +demo_tr.html +testbench +testbench.vcd diff --git a/chips/yosys/examples/gowin/README b/chips/yosys/examples/gowin/README new file mode 100644 index 0000000000000000000000000000000000000000..75076fde52fa55ab68773433235245ca74d45c93 --- /dev/null +++ b/chips/yosys/examples/gowin/README @@ -0,0 +1,16 @@ +Simple test project for Gowinsemi GW2A-55K Eval Board Mini. + +Follow the install instructions for the Gowinsemi tools below, +then run "bash run.sh" in this directory. + + +Install instructions for gowinTool_linux +---------------------------------------- + +1.) extract gowinTool_linux.zip + +2.) set GOWIN_HOME env variable to the full path to the +gowinTool_linux directory + +3.) edit gowinTool_linux/bin/gwlicense.ini. Set lic="..." to +the full path to the license file. diff --git a/chips/yosys/examples/gowin/demo.cst b/chips/yosys/examples/gowin/demo.cst new file mode 100644 index 0000000000000000000000000000000000000000..2be79f694e964d134b89bb49ac38ad9e03678805 --- /dev/null +++ b/chips/yosys/examples/gowin/demo.cst @@ -0,0 +1,10 @@ +IO_LOC "clk" 35; +//IO_LOC "rst_n" 77; +IO_LOC "leds[0]" 79; +IO_LOC "leds[1]" 80; +IO_LOC "leds[2]" 81; +IO_LOC "leds[3]" 82; +IO_LOC "leds[4]" 83; +IO_LOC "leds[5]" 84; +IO_LOC "leds[6]" 85; +IO_LOC "leds[7]" 86; diff --git a/chips/yosys/examples/gowin/demo.sdc b/chips/yosys/examples/gowin/demo.sdc new file mode 100644 index 0000000000000000000000000000000000000000..6c90325fac688aa5687272983c0df7649b51797a --- /dev/null +++ b/chips/yosys/examples/gowin/demo.sdc @@ -0,0 +1 @@ +create_clock -name clk -period 20 -waveform {0 10} [get_ports {clk}] diff --git a/chips/yosys/examples/gowin/demo.v b/chips/yosys/examples/gowin/demo.v new file mode 100644 index 0000000000000000000000000000000000000000..485fec97f4932038e22821c9724c14afe3200b10 --- /dev/null +++ b/chips/yosys/examples/gowin/demo.v @@ -0,0 +1,10 @@ +module demo ( + input clk, + output [15:0] leds, + output unused +); + localparam PRESCALE = 20; + reg [PRESCALE+3:0] counter = 0; + always @(posedge clk) counter <= counter + 1; + assign leds = 1 << counter[PRESCALE +: 4]; +endmodule diff --git a/chips/yosys/examples/gowin/device.cfg b/chips/yosys/examples/gowin/device.cfg new file mode 100644 index 0000000000000000000000000000000000000000..f6ab8215954cf253c373f7f3a9cc46eb859cd9ce --- /dev/null +++ b/chips/yosys/examples/gowin/device.cfg @@ -0,0 +1,16 @@ +set JTAG regular_io = false +set SSPI regular_io = false +set MSPI regular_io = false +set READY regular_io = false +set DONE regular_io = false +set RECONFIG_N regular_io = false +set MODE regular_io = false +set CRC_check = true +set compress = false +set encryption = false +set security_bit_enable = true +set bsram_init_fuse_print = true +set download_speed = 250/100 +set spi_flash_address = 0x00FFF000 +set format = txt +set background_programming = false diff --git a/chips/yosys/examples/gowin/pnr.cfg b/chips/yosys/examples/gowin/pnr.cfg new file mode 100644 index 0000000000000000000000000000000000000000..a1b43cc3b07d3cdc6c8b92ad799101117764eb77 --- /dev/null +++ b/chips/yosys/examples/gowin/pnr.cfg @@ -0,0 +1,8 @@ +-sdf +-oc +-ibs +-posp +-o +-warning_all +-tt +-timing diff --git a/chips/yosys/examples/gowin/run.sh b/chips/yosys/examples/gowin/run.sh new file mode 100644 index 0000000000000000000000000000000000000000..96062446404051fdc203a3f85bb40d385da2769c --- /dev/null +++ b/chips/yosys/examples/gowin/run.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +set -ex +yosys -p "synth_gowin -top demo -vout demo_syn.v" demo.v +$GOWIN_HOME/bin/gowin -d demo_syn.v -cst demo.cst -sdc demo.sdc -p GW1NR-9-QFN88-6 -pn GW1NR-LV9QN88C6/I5 -cfg device.cfg -bit -tr -ph -timing -gpa -rpt -warning_all + +# post place&route simulation (icarus verilog) +if false; then + iverilog -D POST_IMPL -o testbench -s testbench testbench.v \ + demo_out.v $(yosys-config --datdir/gowin/cells_sim.v) + vvp -N testbench +fi diff --git a/chips/yosys/examples/gowin/run.tcl b/chips/yosys/examples/gowin/run.tcl new file mode 100644 index 0000000000000000000000000000000000000000..39da11cee248fca0eb5f606d272413bea7c4e4ab --- /dev/null +++ b/chips/yosys/examples/gowin/run.tcl @@ -0,0 +1,9 @@ +# gw_sh run.tcl +exec yosys -p "synth_gowin -top demo -vout demo_syn.v" demo.v +add_file -cst demo.cst +add_file -sdc demo.sdc +add_file -vm demo_syn.v +add_file -cfg device.cfg +set_option -device GW1NR-9-QFN88-6 +set_option -pn GW1NR-LV9QN88C6/I5 +run_pnr -opt pnr.cfg diff --git a/chips/yosys/examples/gowin/testbench.v b/chips/yosys/examples/gowin/testbench.v new file mode 100644 index 0000000000000000000000000000000000000000..6d206381e4937424e3ca0119a682c1531f8929ad --- /dev/null +++ b/chips/yosys/examples/gowin/testbench.v @@ -0,0 +1,40 @@ +module testbench; + reg clk; + + initial begin + #5 clk = 0; + forever #5 clk = ~clk; + end + + wire [15:0] leds; + + initial begin + // $dumpfile("testbench.vcd"); + // $dumpvars(0, testbench); + $monitor("%b", leds); + end + + demo uut ( + .clk (clk ), +`ifdef POST_IMPL + .\leds[0] (leds[0]), + .\leds[1] (leds[1]), + .\leds[2] (leds[2]), + .\leds[3] (leds[3]), + .\leds[4] (leds[4]), + .\leds[5] (leds[5]), + .\leds[6] (leds[6]), + .\leds[7] (leds[7]), + .\leds[8] (leds[8]), + .\leds[9] (leds[9]), + .\leds[10] (leds[10]), + .\leds[11] (leds[11]), + .\leds[12] (leds[12]), + .\leds[13] (leds[13]), + .\leds[14] (leds[14]), + .\leds[15] (leds[15]) +`else + .leds(leds) +`endif + ); +endmodule diff --git a/chips/yosys/examples/igloo2/.gitignore b/chips/yosys/examples/igloo2/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..33b7182d38dc527330c9da57c99f75fdd6ac775a --- /dev/null +++ b/chips/yosys/examples/igloo2/.gitignore @@ -0,0 +1,4 @@ +/netlist.edn +/netlist.vm +/example.stp +/proj diff --git a/chips/yosys/examples/igloo2/example.pdc b/chips/yosys/examples/igloo2/example.pdc new file mode 100644 index 0000000000000000000000000000000000000000..298d9e934bdc8dc785da5cacceefed74dd18c66a --- /dev/null +++ b/chips/yosys/examples/igloo2/example.pdc @@ -0,0 +1,20 @@ +# Add placement constraints here + +set_io clk -pinname H16 -fixed yes -DIRECTION INPUT + +set_io SW1 -pinname H12 -fixed yes -DIRECTION INPUT +set_io SW2 -pinname H13 -fixed yes -DIRECTION INPUT + +set_io LED1 -pinname J16 -fixed yes -DIRECTION OUTPUT +set_io LED2 -pinname M16 -fixed yes -DIRECTION OUTPUT +set_io LED3 -pinname K16 -fixed yes -DIRECTION OUTPUT +set_io LED4 -pinname N16 -fixed yes -DIRECTION OUTPUT + +set_io AA -pinname L12 -fixed yes -DIRECTION OUTPUT +set_io AB -pinname L13 -fixed yes -DIRECTION OUTPUT +set_io AC -pinname M13 -fixed yes -DIRECTION OUTPUT +set_io AD -pinname N15 -fixed yes -DIRECTION OUTPUT +set_io AE -pinname L11 -fixed yes -DIRECTION OUTPUT +set_io AF -pinname L14 -fixed yes -DIRECTION OUTPUT +set_io AG -pinname N14 -fixed yes -DIRECTION OUTPUT +set_io CA -pinname M15 -fixed yes -DIRECTION OUTPUT diff --git a/chips/yosys/examples/igloo2/example.sdc b/chips/yosys/examples/igloo2/example.sdc new file mode 100644 index 0000000000000000000000000000000000000000..f8b487316adc3d3106ad57afb5cef2bf45cd291f --- /dev/null +++ b/chips/yosys/examples/igloo2/example.sdc @@ -0,0 +1,2 @@ +# Add timing constraints here +create_clock -period 10.000 -waveform {0.000 5.000} [get_ports {clk}] diff --git a/chips/yosys/examples/igloo2/example.v b/chips/yosys/examples/igloo2/example.v new file mode 100644 index 0000000000000000000000000000000000000000..4a9486e50f6b185e09544e19d5b42112cba70db9 --- /dev/null +++ b/chips/yosys/examples/igloo2/example.v @@ -0,0 +1,64 @@ +module example ( + input clk, + input SW1, + input SW2, + output LED1, + output LED2, + output LED3, + output LED4, + + output AA, AB, AC, AD, + output AE, AF, AG, CA +); + + localparam BITS = 8; + localparam LOG2DELAY = 22; + + reg [BITS+LOG2DELAY-1:0] counter = 0; + reg [BITS-1:0] outcnt; + + always @(posedge clk) begin + counter <= counter + SW1 + SW2 + 1; + outcnt <= counter >> LOG2DELAY; + end + + assign {LED1, LED2, LED3, LED4} = outcnt ^ (outcnt >> 1); + + // assign CA = counter[10]; + // seg7enc seg7encinst ( + // .seg({AA, AB, AC, AD, AE, AF, AG}), + // .dat(CA ? outcnt[3:0] : outcnt[7:4]) + // ); + + assign {AA, AB, AC, AD, AE, AF, AG} = ~(7'b 100_0000 >> outcnt[6:4]); + assign CA = outcnt[7]; +endmodule + +module seg7enc ( + input [3:0] dat, + output [6:0] seg +); + reg [6:0] seg_inv; + always @* begin + seg_inv = 0; + case (dat) + 4'h0: seg_inv = 7'b 0111111; + 4'h1: seg_inv = 7'b 0000110; + 4'h2: seg_inv = 7'b 1011011; + 4'h3: seg_inv = 7'b 1001111; + 4'h4: seg_inv = 7'b 1100110; + 4'h5: seg_inv = 7'b 1101101; + 4'h6: seg_inv = 7'b 1111101; + 4'h7: seg_inv = 7'b 0000111; + 4'h8: seg_inv = 7'b 1111111; + 4'h9: seg_inv = 7'b 1101111; + 4'hA: seg_inv = 7'b 1110111; + 4'hB: seg_inv = 7'b 1111100; + 4'hC: seg_inv = 7'b 0111001; + 4'hD: seg_inv = 7'b 1011110; + 4'hE: seg_inv = 7'b 1111001; + 4'hF: seg_inv = 7'b 1110001; + endcase + end + assign seg = ~seg_inv; +endmodule diff --git a/chips/yosys/examples/igloo2/libero.tcl b/chips/yosys/examples/igloo2/libero.tcl new file mode 100644 index 0000000000000000000000000000000000000000..abc94e479543033c65b784d80811782653ffcb59 --- /dev/null +++ b/chips/yosys/examples/igloo2/libero.tcl @@ -0,0 +1,57 @@ +# Run with "libero SCRIPT:libero.tcl" + +file delete -force proj + +new_project \ + -name example \ + -location proj \ + -block_mode 0 \ + -hdl "VERILOG" \ + -family IGLOO2 \ + -die PA4MGL2500 \ + -package vf256 \ + -speed -1 + +import_files -hdl_source {netlist.vm} +import_files -sdc {example.sdc} +import_files -io_pdc {example.pdc} +build_design_hierarchy +set_option -synth 0 + +organize_tool_files -tool PLACEROUTE \ + -file {proj/constraint/example.sdc} \ + -file {proj/constraint/io/example.pdc} \ + -input_type constraint + +organize_tool_files -tool VERIFYTIMING \ + -file {proj/constraint/example.sdc} \ + -input_type constraint + +configure_tool -name PLACEROUTE \ + -params TDPR:true \ + -params PDPR:false \ + -params EFFORT_LEVEL:false \ + -params REPAIR_MIN_DELAY:false + +puts "" +puts "**> COMPILE" +run_tool -name {COMPILE} +puts "<** COMPILE" + +puts "" +puts "**> PLACEROUTE" +run_tool -name {PLACEROUTE} +puts "<** PLACEROUTE" + +puts "" +puts "**> VERIFYTIMING" +run_tool -name {VERIFYTIMING} +puts "<** VERIFYTIMING" + +puts "" +puts "**> BITSTREAM" +export_bitstream_file -trusted_facility_file 1 -trusted_facility_file_components {FABRIC} +puts "<** BITSTREAM" + +puts "" +exit 0 diff --git a/chips/yosys/examples/igloo2/runme.sh b/chips/yosys/examples/igloo2/runme.sh new file mode 100644 index 0000000000000000000000000000000000000000..3c39c481440fb4da4f7b559299a8b5dacf39827c --- /dev/null +++ b/chips/yosys/examples/igloo2/runme.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +set -ex +yosys -p 'synth_sf2 -discard-ffinit -top example -edif netlist.edn -vlog netlist.vm' example.v +export LM_LICENSE_FILE=${LM_LICENSE_FILE:-1702@localhost} +/opt/microsemi/Libero_SoC_v12.0/Libero/bin/libero SCRIPT:libero.tcl +cp proj/designer/example/export/example.stp . diff --git a/chips/yosys/examples/intel/DE2i-150/quartus_compile/de2i.qpf b/chips/yosys/examples/intel/DE2i-150/quartus_compile/de2i.qpf new file mode 100644 index 0000000000000000000000000000000000000000..9fc734eb3961a64eca9e4b3e357f7e6ce1e14f79 --- /dev/null +++ b/chips/yosys/examples/intel/DE2i-150/quartus_compile/de2i.qpf @@ -0,0 +1,4 @@ +QUARTUS_VERSION = "16.1" +# Revisions + +PROJECT_REVISION = "de2i" diff --git a/chips/yosys/examples/intel/DE2i-150/quartus_compile/de2i.qsf b/chips/yosys/examples/intel/DE2i-150/quartus_compile/de2i.qsf new file mode 100644 index 0000000000000000000000000000000000000000..99245b607d9b7c13806a28867268e1cf06d5fd33 --- /dev/null +++ b/chips/yosys/examples/intel/DE2i-150/quartus_compile/de2i.qsf @@ -0,0 +1,1099 @@ +set_global_assignment -name FAMILY "Cyclone IV GX" +set_global_assignment -name DEVICE EP4CGX150DF31C7 +set_global_assignment -name TOP_LEVEL_ENTITY "top" +set_global_assignment -name DEVICE_FILTER_PACKAGE FBGA + + +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to CLOCK2_50 +set_instance_assignment -name IO_STANDARD "2.5 V" -to CLOCK3_50 +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to CLOCK_50 + +#============================================================ +# DRAM +#============================================================ +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_ADDR[0] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_ADDR[1] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_ADDR[2] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_ADDR[3] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_ADDR[4] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_ADDR[5] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_ADDR[6] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_ADDR[7] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_ADDR[8] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_ADDR[9] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_ADDR[10] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_ADDR[11] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_ADDR[12] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_BA[0] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_BA[1] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_CAS_N +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_CKE +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_CLK +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_CS_N +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_DQ[0] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_DQ[1] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_DQ[2] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_DQ[3] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_DQ[4] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_DQ[5] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_DQ[6] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_DQ[7] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_DQ[8] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_DQ[9] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_DQ[10] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_DQ[11] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_DQ[12] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_DQ[13] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_DQ[14] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_DQ[15] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_DQ[16] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_DQ[17] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_DQ[18] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_DQ[19] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_DQ[20] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_DQ[21] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_DQ[22] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_DQ[23] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_DQ[24] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_DQ[25] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_DQ[26] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_DQ[27] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_DQ[28] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_DQ[29] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_DQ[30] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_DQ[31] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_DQM[0] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_DQM[1] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_DQM[2] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_DQM[3] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_RAS_N +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to DRAM_WE_N + +#============================================================ +# EEP +#============================================================ +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to EEP_I2C_SCLK +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to EEP_I2C_SDAT + +#============================================================ +# ENET +#============================================================ +set_instance_assignment -name IO_STANDARD "2.5 V" -to ENET_GTX_CLK +set_instance_assignment -name IO_STANDARD "2.5 V" -to ENET_INT_N +set_instance_assignment -name IO_STANDARD "2.5 V" -to ENET_LINK100 +set_instance_assignment -name IO_STANDARD "2.5 V" -to ENET_MDC +set_instance_assignment -name IO_STANDARD "2.5 V" -to ENET_MDIO +set_instance_assignment -name IO_STANDARD "2.5 V" -to ENET_RST_N +set_instance_assignment -name IO_STANDARD "2.5 V" -to ENET_RX_CLK +set_instance_assignment -name IO_STANDARD "2.5 V" -to ENET_RX_COL +set_instance_assignment -name IO_STANDARD "2.5 V" -to ENET_RX_CRS +set_instance_assignment -name IO_STANDARD "2.5 V" -to ENET_RX_DATA[0] +set_instance_assignment -name IO_STANDARD "2.5 V" -to ENET_RX_DATA[1] +set_instance_assignment -name IO_STANDARD "2.5 V" -to ENET_RX_DATA[2] +set_instance_assignment -name IO_STANDARD "2.5 V" -to ENET_RX_DATA[3] +set_instance_assignment -name IO_STANDARD "2.5 V" -to ENET_RX_DV +set_instance_assignment -name IO_STANDARD "2.5 V" -to ENET_RX_ER +set_instance_assignment -name IO_STANDARD "2.5 V" -to ENET_TX_CLK +set_instance_assignment -name IO_STANDARD "2.5 V" -to ENET_TX_DATA[0] +set_instance_assignment -name IO_STANDARD "2.5 V" -to ENET_TX_DATA[1] +set_instance_assignment -name IO_STANDARD "2.5 V" -to ENET_TX_DATA[2] +set_instance_assignment -name IO_STANDARD "2.5 V" -to ENET_TX_DATA[3] +set_instance_assignment -name IO_STANDARD "2.5 V" -to ENET_TX_EN +set_instance_assignment -name IO_STANDARD "2.5 V" -to ENET_TX_ER + +#============================================================ +# FAN +#============================================================ +set_instance_assignment -name IO_STANDARD "2.5 V" -to FAN_CTRL + +#============================================================ +# FLASH +#============================================================ +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FL_RESET_N + +#============================================================ +# FS +#============================================================ +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_ADDR[1] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_ADDR[2] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_ADDR[3] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_ADDR[4] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_ADDR[5] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_ADDR[6] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_ADDR[7] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_ADDR[8] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_ADDR[9] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_ADDR[10] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_ADDR[11] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_ADDR[12] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_ADDR[13] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_ADDR[14] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_ADDR[15] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_ADDR[16] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_ADDR[17] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_ADDR[18] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_ADDR[19] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_ADDR[20] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_ADDR[21] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_ADDR[22] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_ADDR[23] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_ADDR[24] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_ADDR[25] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_ADDR[26] + +#============================================================ +# FL +#============================================================ +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FL_CE_N +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FL_OE_N +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FL_RY +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FL_WE_N +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FL_WP_N + +#============================================================ +# FS +#============================================================ +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_DQ[0] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_DQ[1] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_DQ[2] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_DQ[3] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_DQ[4] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_DQ[5] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_DQ[6] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_DQ[7] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_DQ[8] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_DQ[9] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_DQ[10] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_DQ[11] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_DQ[12] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_DQ[13] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_DQ[14] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_DQ[15] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_DQ[16] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_DQ[17] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_DQ[18] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_DQ[19] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_DQ[20] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_DQ[21] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_DQ[22] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_DQ[23] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_DQ[24] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_DQ[25] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_DQ[26] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_DQ[27] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_DQ[28] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_DQ[29] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_DQ[30] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to FS_DQ[31] + +#============================================================ +# GPIO +#============================================================ +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to GPIO[0] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to GPIO[1] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to GPIO[2] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to GPIO[3] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to GPIO[4] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to GPIO[5] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to GPIO[6] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to GPIO[7] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to GPIO[8] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to GPIO[9] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to GPIO[10] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to GPIO[11] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to GPIO[12] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to GPIO[13] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to GPIO[14] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to GPIO[15] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to GPIO[16] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to GPIO[17] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to GPIO[18] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to GPIO[19] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to GPIO[20] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to GPIO[21] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to GPIO[22] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to GPIO[23] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to GPIO[24] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to GPIO[25] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to GPIO[26] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to GPIO[27] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to GPIO[28] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to GPIO[29] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to GPIO[30] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to GPIO[31] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to GPIO[32] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to GPIO[33] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to GPIO[34] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to GPIO[35] + +#============================================================ +# G +#============================================================ +set_instance_assignment -name IO_STANDARD "2.5 V" -to G_SENSOR_INT1 +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to G_SENSOR_SCLK +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to G_SENSOR_SDAT + +#============================================================ +# HEX0 +#============================================================ +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX0[0] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX0[1] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX0[2] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX0[3] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX0[4] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX0[5] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX0[6] + +#============================================================ +# HEX1 +#============================================================ +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX1[0] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX1[1] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX1[2] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX1[3] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX1[4] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX1[5] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX1[6] + +#============================================================ +# HEX2 +#============================================================ +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX2[0] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX2[1] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX2[2] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX2[3] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX2[4] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX2[5] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX2[6] + +#============================================================ +# HEX3 +#============================================================ +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX3[0] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX3[1] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX3[2] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX3[3] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX3[4] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX3[5] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX3[6] + +#============================================================ +# HEX4 +#============================================================ +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX4[0] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX4[1] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX4[2] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX4[3] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX4[4] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX4[5] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX4[6] + +#============================================================ +# HEX5 +#============================================================ +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX5[0] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX5[1] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX5[2] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX5[3] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX5[4] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX5[5] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX5[6] + +#============================================================ +# HEX6 +#============================================================ +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX6[0] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX6[1] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX6[2] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX6[3] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX6[4] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX6[5] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX6[6] + +#============================================================ +# HEX7 +#============================================================ +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX7[0] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX7[1] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX7[2] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX7[3] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX7[4] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX7[5] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HEX7[6] + +#============================================================ +# HSMC +#============================================================ +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_CLKIN0 +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_CLKIN_N1 +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_CLKIN_N2 +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_CLKIN_P1 +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_CLKIN_P2 +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_CLKOUT0 +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_CLKOUT_N1 +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_CLKOUT_N2 +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_CLKOUT_P1 +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_CLKOUT_P2 +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_D[0] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_D[1] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_D[2] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_D[3] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_I2C_SCLK +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_I2C_SDAT +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_RX_D_N[0] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_RX_D_N[1] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_RX_D_N[2] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_RX_D_N[3] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_RX_D_N[4] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_RX_D_N[5] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_RX_D_N[6] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_RX_D_N[7] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_RX_D_N[8] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_RX_D_N[9] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_RX_D_N[10] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_RX_D_N[11] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_RX_D_N[12] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_RX_D_N[13] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_RX_D_N[14] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_RX_D_N[15] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_RX_D_N[16] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_RX_D_P[0] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_RX_D_P[1] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_RX_D_P[2] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_RX_D_P[3] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_RX_D_P[4] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_RX_D_P[5] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_RX_D_P[6] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_RX_D_P[7] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_RX_D_P[8] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_RX_D_P[9] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_RX_D_P[10] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_RX_D_P[11] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_RX_D_P[12] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_RX_D_P[13] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_RX_D_P[14] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_RX_D_P[15] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_RX_D_P[16] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_TX_D_N[0] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_TX_D_N[1] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_TX_D_N[2] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_TX_D_N[3] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_TX_D_N[4] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_TX_D_N[5] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_TX_D_N[6] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_TX_D_N[7] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_TX_D_N[8] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_TX_D_N[9] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_TX_D_N[10] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_TX_D_N[11] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_TX_D_N[12] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_TX_D_N[13] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_TX_D_N[14] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_TX_D_N[15] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_TX_D_N[16] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_TX_D_P[0] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_TX_D_P[1] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_TX_D_P[2] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_TX_D_P[3] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_TX_D_P[4] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_TX_D_P[5] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_TX_D_P[6] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_TX_D_P[7] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_TX_D_P[8] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_TX_D_P[9] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_TX_D_P[10] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_TX_D_P[11] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_TX_D_P[12] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_TX_D_P[13] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_TX_D_P[14] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_TX_D_P[15] +set_instance_assignment -name IO_STANDARD "2.5 V" -to HSMC_TX_D_P[16] + +#============================================================ +# I2C +#============================================================ +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to I2C_SCLK +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to I2C_SDAT + +#============================================================ +# IRDA +#============================================================ +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to IRDA_RXD + +#============================================================ +# KEY +#============================================================ +set_instance_assignment -name IO_STANDARD "2.5 V" -to KEY[0] +set_instance_assignment -name IO_STANDARD "2.5 V" -to KEY[1] +set_instance_assignment -name IO_STANDARD "2.5 V" -to KEY[2] +set_instance_assignment -name IO_STANDARD "2.5 V" -to KEY[3] + +#============================================================ +# LCD +#============================================================ +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to LCD_DATA[0] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to LCD_DATA[1] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to LCD_DATA[2] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to LCD_DATA[3] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to LCD_DATA[4] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to LCD_DATA[5] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to LCD_DATA[6] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to LCD_DATA[7] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to LCD_EN +set_instance_assignment -name IO_STANDARD "2.5 V" -to LCD_ON +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to LCD_RS +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to LCD_RW + +#============================================================ +# LEDG +#============================================================ +set_instance_assignment -name IO_STANDARD "2.5 V" -to LEDG[0] +set_instance_assignment -name IO_STANDARD "2.5 V" -to LEDG[1] +set_instance_assignment -name IO_STANDARD "2.5 V" -to LEDG[2] +set_instance_assignment -name IO_STANDARD "2.5 V" -to LEDG[3] +set_instance_assignment -name IO_STANDARD "2.5 V" -to LEDG[4] +set_instance_assignment -name IO_STANDARD "2.5 V" -to LEDG[5] +set_instance_assignment -name IO_STANDARD "2.5 V" -to LEDG[6] +set_instance_assignment -name IO_STANDARD "2.5 V" -to LEDG[7] +set_instance_assignment -name IO_STANDARD "2.5 V" -to LEDG[8] + +#============================================================ +# LEDR +#============================================================ +set_instance_assignment -name IO_STANDARD "2.5 V" -to LEDR[0] +set_instance_assignment -name IO_STANDARD "2.5 V" -to LEDR[1] +set_instance_assignment -name IO_STANDARD "2.5 V" -to LEDR[2] +set_instance_assignment -name IO_STANDARD "2.5 V" -to LEDR[3] +set_instance_assignment -name IO_STANDARD "2.5 V" -to LEDR[4] +set_instance_assignment -name IO_STANDARD "2.5 V" -to LEDR[5] +set_instance_assignment -name IO_STANDARD "2.5 V" -to LEDR[6] +set_instance_assignment -name IO_STANDARD "2.5 V" -to LEDR[7] +set_instance_assignment -name IO_STANDARD "2.5 V" -to LEDR[8] +set_instance_assignment -name IO_STANDARD "2.5 V" -to LEDR[9] +set_instance_assignment -name IO_STANDARD "2.5 V" -to LEDR[10] +set_instance_assignment -name IO_STANDARD "2.5 V" -to LEDR[11] +set_instance_assignment -name IO_STANDARD "2.5 V" -to LEDR[12] +set_instance_assignment -name IO_STANDARD "2.5 V" -to LEDR[13] +set_instance_assignment -name IO_STANDARD "2.5 V" -to LEDR[14] +set_instance_assignment -name IO_STANDARD "2.5 V" -to LEDR[15] +set_instance_assignment -name IO_STANDARD "2.5 V" -to LEDR[16] +set_instance_assignment -name IO_STANDARD "2.5 V" -to LEDR[17] + +#============================================================ +# PCIE +#============================================================ +set_instance_assignment -name IO_STANDARD "2.5 V" -to PCIE_PERST_N +set_instance_assignment -name IO_STANDARD HCSL -to PCIE_REFCLK_P +set_instance_assignment -name IO_STANDARD "1.5-V PCML" -to PCIE_RX_P[0] +set_instance_assignment -name IO_STANDARD "1.5-V PCML" -to PCIE_RX_P[1] +set_instance_assignment -name IO_STANDARD "1.5-V PCML" -to PCIE_TX_P[0] +set_instance_assignment -name IO_STANDARD "1.5-V PCML" -to PCIE_TX_P[1] +set_instance_assignment -name IO_STANDARD "2.5 V" -to PCIE_WAKE_N + +#============================================================ +# SD +#============================================================ +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to SD_CLK +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to SD_CMD +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to SD_DAT[0] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to SD_DAT[1] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to SD_DAT[2] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to SD_DAT[3] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to SD_WP_N + +#============================================================ +# SMA +#============================================================ +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to SMA_CLKIN +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to SMA_CLKOUT + +#============================================================ +# SSRAM0 +#============================================================ +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to SSRAM0_CE_N + +#============================================================ +# SSRAM1 +#============================================================ +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to SSRAM1_CE_N + +#============================================================ +# SSRAM +#============================================================ +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to SSRAM_ADSC_N +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to SSRAM_ADSP_N +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to SSRAM_ADV_N +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to SSRAM_BE[0] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to SSRAM_BE[1] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to SSRAM_BE[2] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to SSRAM_BE[3] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to SSRAM_CLK +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to SSRAM_GW_N +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to SSRAM_OE_N +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to SSRAM_WE_N + +#============================================================ +# SW +#============================================================ +set_instance_assignment -name IO_STANDARD "2.5 V" -to SW[0] +set_instance_assignment -name IO_STANDARD "2.5 V" -to SW[1] +set_instance_assignment -name IO_STANDARD "2.5 V" -to SW[2] +set_instance_assignment -name IO_STANDARD "2.5 V" -to SW[3] +set_instance_assignment -name IO_STANDARD "2.5 V" -to SW[4] +set_instance_assignment -name IO_STANDARD "2.5 V" -to SW[5] +set_instance_assignment -name IO_STANDARD "2.5 V" -to SW[6] +set_instance_assignment -name IO_STANDARD "2.5 V" -to SW[7] +set_instance_assignment -name IO_STANDARD "2.5 V" -to SW[8] +set_instance_assignment -name IO_STANDARD "2.5 V" -to SW[9] +set_instance_assignment -name IO_STANDARD "2.5 V" -to SW[10] +set_instance_assignment -name IO_STANDARD "2.5 V" -to SW[11] +set_instance_assignment -name IO_STANDARD "2.5 V" -to SW[12] +set_instance_assignment -name IO_STANDARD "2.5 V" -to SW[13] +set_instance_assignment -name IO_STANDARD "2.5 V" -to SW[14] +set_instance_assignment -name IO_STANDARD "2.5 V" -to SW[15] +set_instance_assignment -name IO_STANDARD "2.5 V" -to SW[16] +set_instance_assignment -name IO_STANDARD "2.5 V" -to SW[17] + +#============================================================ +# TD +#============================================================ +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to TD_CLK27 +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to TD_DATA[0] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to TD_DATA[1] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to TD_DATA[2] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to TD_DATA[3] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to TD_DATA[4] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to TD_DATA[5] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to TD_DATA[6] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to TD_DATA[7] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to TD_HS +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to TD_RESET_N +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to TD_VS + +#============================================================ +# UART +#============================================================ +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to UART_CTS +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to UART_RTS +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to UART_RXD +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to UART_TXD + +#============================================================ +# VGA +#============================================================ +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to VGA_B[0] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to VGA_B[1] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to VGA_B[2] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to VGA_B[3] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to VGA_B[4] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to VGA_B[5] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to VGA_B[6] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to VGA_B[7] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to VGA_BLANK_N +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to VGA_CLK +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to VGA_G[0] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to VGA_G[1] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to VGA_G[2] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to VGA_G[3] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to VGA_G[4] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to VGA_G[5] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to VGA_G[6] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to VGA_G[7] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to VGA_HS +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to VGA_R[0] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to VGA_R[1] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to VGA_R[2] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to VGA_R[3] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to VGA_R[4] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to VGA_R[5] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to VGA_R[6] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to VGA_R[7] +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to VGA_SYNC_N +set_instance_assignment -name IO_STANDARD "3.3-V LVTTL" -to VGA_VS + +#============================================================ +# End of pin assignments by Terasic System Builder +#============================================================ + + + +set_global_assignment -name CYCLONEII_RESERVE_NCEO_AFTER_CONFIGURATION "USE AS REGULAR IO" +set_location_assignment PIN_A15 -to CLOCK2_50 +set_location_assignment PIN_V11 -to CLOCK3_50 +set_location_assignment PIN_AJ16 -to CLOCK_50 +set_location_assignment PIN_AG7 -to DRAM_ADDR[0] +set_location_assignment PIN_AJ7 -to DRAM_ADDR[1] +set_location_assignment PIN_AG8 -to DRAM_ADDR[2] +set_location_assignment PIN_AH8 -to DRAM_ADDR[3] +set_location_assignment PIN_AE16 -to DRAM_ADDR[4] +set_location_assignment PIN_AF16 -to DRAM_ADDR[5] +set_location_assignment PIN_AE14 -to DRAM_ADDR[6] +set_location_assignment PIN_AE15 -to DRAM_ADDR[7] +set_location_assignment PIN_AE13 -to DRAM_ADDR[8] +set_location_assignment PIN_AE12 -to DRAM_ADDR[9] +set_location_assignment PIN_AH6 -to DRAM_ADDR[10] +set_location_assignment PIN_AE11 -to DRAM_ADDR[11] +set_location_assignment PIN_AE10 -to DRAM_ADDR[12] +set_location_assignment PIN_AH5 -to DRAM_BA[0] +set_location_assignment PIN_AG6 -to DRAM_BA[1] +set_location_assignment PIN_AJ4 -to DRAM_CAS_N +set_location_assignment PIN_AD6 -to DRAM_CKE +set_location_assignment PIN_AE6 -to DRAM_CLK +set_location_assignment PIN_AG5 -to DRAM_CS_N +set_location_assignment PIN_AD10 -to DRAM_DQ[0] +set_location_assignment PIN_AD9 -to DRAM_DQ[1] +set_location_assignment PIN_AE9 -to DRAM_DQ[2] +set_location_assignment PIN_AE8 -to DRAM_DQ[3] +set_location_assignment PIN_AE7 -to DRAM_DQ[4] +set_location_assignment PIN_AF7 -to DRAM_DQ[5] +set_location_assignment PIN_AF6 -to DRAM_DQ[6] +set_location_assignment PIN_AF9 -to DRAM_DQ[7] +set_location_assignment PIN_AB13 -to DRAM_DQ[8] +set_location_assignment PIN_AF13 -to DRAM_DQ[9] +set_location_assignment PIN_AF12 -to DRAM_DQ[10] +set_location_assignment PIN_AG9 -to DRAM_DQ[11] +set_location_assignment PIN_AA13 -to DRAM_DQ[12] +set_location_assignment PIN_AB11 -to DRAM_DQ[13] +set_location_assignment PIN_AA12 -to DRAM_DQ[14] +set_location_assignment PIN_AA15 -to DRAM_DQ[15] +set_location_assignment PIN_AH11 -to DRAM_DQ[16] +set_location_assignment PIN_AG11 -to DRAM_DQ[17] +set_location_assignment PIN_AH12 -to DRAM_DQ[18] +set_location_assignment PIN_AG12 -to DRAM_DQ[19] +set_location_assignment PIN_AH13 -to DRAM_DQ[20] +set_location_assignment PIN_AG13 -to DRAM_DQ[21] +set_location_assignment PIN_AG14 -to DRAM_DQ[22] +set_location_assignment PIN_AH14 -to DRAM_DQ[23] +set_location_assignment PIN_AH9 -to DRAM_DQ[24] +set_location_assignment PIN_AK8 -to DRAM_DQ[25] +set_location_assignment PIN_AG10 -to DRAM_DQ[26] +set_location_assignment PIN_AK7 -to DRAM_DQ[27] +set_location_assignment PIN_AH7 -to DRAM_DQ[28] +set_location_assignment PIN_AK6 -to DRAM_DQ[29] +set_location_assignment PIN_AJ6 -to DRAM_DQ[30] +set_location_assignment PIN_AK5 -to DRAM_DQ[31] +set_location_assignment PIN_AF10 -to DRAM_DQM[0] +set_location_assignment PIN_AB14 -to DRAM_DQM[1] +set_location_assignment PIN_AH15 -to DRAM_DQM[2] +set_location_assignment PIN_AH10 -to DRAM_DQM[3] +set_location_assignment PIN_AK4 -to DRAM_RAS_N +set_location_assignment PIN_AK3 -to DRAM_WE_N +set_location_assignment PIN_AG27 -to EEP_I2C_SCLK +set_location_assignment PIN_AG25 -to EEP_I2C_SDAT +set_location_assignment PIN_A12 -to ENET_GTX_CLK +set_location_assignment PIN_E16 -to ENET_INT_N +set_location_assignment PIN_F5 -to ENET_LINK100 +set_location_assignment PIN_C16 -to ENET_MDC +set_location_assignment PIN_C15 -to ENET_MDIO +set_location_assignment PIN_C14 -to ENET_RST_N +set_location_assignment PIN_L15 -to ENET_RX_CLK +set_location_assignment PIN_G15 -to ENET_RX_COL +set_location_assignment PIN_D6 -to ENET_RX_CRS +set_location_assignment PIN_F15 -to ENET_RX_DATA[0] +set_location_assignment PIN_E13 -to ENET_RX_DATA[1] +set_location_assignment PIN_A5 -to ENET_RX_DATA[2] +set_location_assignment PIN_B7 -to ENET_RX_DATA[3] +set_location_assignment PIN_A8 -to ENET_RX_DV +set_location_assignment PIN_D11 -to ENET_RX_ER +set_location_assignment PIN_F13 -to ENET_TX_CLK +set_location_assignment PIN_B12 -to ENET_TX_DATA[0] +set_location_assignment PIN_E7 -to ENET_TX_DATA[1] +set_location_assignment PIN_C13 -to ENET_TX_DATA[2] +set_location_assignment PIN_D15 -to ENET_TX_DATA[3] +set_location_assignment PIN_D14 -to ENET_TX_EN +set_location_assignment PIN_D13 -to ENET_TX_ER +set_location_assignment PIN_AF28 -to FAN_CTRL +set_location_assignment PIN_AG18 -to FL_RESET_N +set_location_assignment PIN_AB22 -to FS_ADDR[1] +set_location_assignment PIN_AH19 -to FS_ADDR[2] +set_location_assignment PIN_AK19 -to FS_ADDR[3] +set_location_assignment PIN_AJ18 -to FS_ADDR[4] +set_location_assignment PIN_AA18 -to FS_ADDR[5] +set_location_assignment PIN_AH18 -to FS_ADDR[6] +set_location_assignment PIN_AK17 -to FS_ADDR[7] +set_location_assignment PIN_Y20 -to FS_ADDR[8] +set_location_assignment PIN_AK21 -to FS_ADDR[9] +set_location_assignment PIN_AH21 -to FS_ADDR[10] +set_location_assignment PIN_AG21 -to FS_ADDR[11] +set_location_assignment PIN_AG22 -to FS_ADDR[12] +set_location_assignment PIN_AD22 -to FS_ADDR[13] +set_location_assignment PIN_AE24 -to FS_ADDR[14] +set_location_assignment PIN_AD23 -to FS_ADDR[15] +set_location_assignment PIN_AB21 -to FS_ADDR[16] +set_location_assignment PIN_AH17 -to FS_ADDR[17] +set_location_assignment PIN_AE17 -to FS_ADDR[18] +set_location_assignment PIN_AG20 -to FS_ADDR[19] +set_location_assignment PIN_AK20 -to FS_ADDR[20] +set_location_assignment PIN_AE19 -to FS_ADDR[21] +set_location_assignment PIN_AA16 -to FS_ADDR[22] +set_location_assignment PIN_AF15 -to FS_ADDR[23] +set_location_assignment PIN_AG15 -to FS_ADDR[24] +set_location_assignment PIN_Y17 -to FS_ADDR[25] +set_location_assignment PIN_AB16 -to FS_ADDR[26] +set_location_assignment PIN_AG19 -to FL_CE_N +set_location_assignment PIN_AJ19 -to FL_OE_N +set_location_assignment PIN_AF19 -to FL_RY +set_location_assignment PIN_AG17 -to FL_WE_N +set_location_assignment PIN_AK18 -to FL_WP_N +set_location_assignment PIN_AK29 -to FS_DQ[0] +set_location_assignment PIN_AE23 -to FS_DQ[1] +set_location_assignment PIN_AH24 -to FS_DQ[2] +set_location_assignment PIN_AH23 -to FS_DQ[3] +set_location_assignment PIN_AA21 -to FS_DQ[4] +set_location_assignment PIN_AE20 -to FS_DQ[5] +set_location_assignment PIN_Y19 -to FS_DQ[6] +set_location_assignment PIN_AA17 -to FS_DQ[7] +set_location_assignment PIN_AB17 -to FS_DQ[8] +set_location_assignment PIN_Y18 -to FS_DQ[9] +set_location_assignment PIN_AA20 -to FS_DQ[10] +set_location_assignment PIN_AE21 -to FS_DQ[11] +set_location_assignment PIN_AH22 -to FS_DQ[12] +set_location_assignment PIN_AJ24 -to FS_DQ[13] +set_location_assignment PIN_AE22 -to FS_DQ[14] +set_location_assignment PIN_AK28 -to FS_DQ[15] +set_location_assignment PIN_AK9 -to FS_DQ[16] +set_location_assignment PIN_AJ10 -to FS_DQ[17] +set_location_assignment PIN_AK11 -to FS_DQ[18] +set_location_assignment PIN_AK12 -to FS_DQ[19] +set_location_assignment PIN_AJ13 -to FS_DQ[20] +set_location_assignment PIN_AK15 -to FS_DQ[21] +set_location_assignment PIN_AC16 -to FS_DQ[22] +set_location_assignment PIN_AH16 -to FS_DQ[23] +set_location_assignment PIN_AG16 -to FS_DQ[24] +set_location_assignment PIN_AD16 -to FS_DQ[25] +set_location_assignment PIN_AJ15 -to FS_DQ[26] +set_location_assignment PIN_AK14 -to FS_DQ[27] +set_location_assignment PIN_AK13 -to FS_DQ[28] +set_location_assignment PIN_AJ12 -to FS_DQ[29] +set_location_assignment PIN_AK10 -to FS_DQ[30] +set_location_assignment PIN_AJ9 -to FS_DQ[31] +set_location_assignment PIN_G16 -to GPIO[0] +set_location_assignment PIN_F17 -to GPIO[1] +set_location_assignment PIN_D18 -to GPIO[2] +set_location_assignment PIN_F18 -to GPIO[3] +set_location_assignment PIN_D19 -to GPIO[4] +set_location_assignment PIN_K21 -to GPIO[5] +set_location_assignment PIN_F19 -to GPIO[6] +set_location_assignment PIN_K22 -to GPIO[7] +set_location_assignment PIN_B21 -to GPIO[8] +set_location_assignment PIN_C21 -to GPIO[9] +set_location_assignment PIN_D22 -to GPIO[10] +set_location_assignment PIN_D21 -to GPIO[11] +set_location_assignment PIN_D23 -to GPIO[12] +set_location_assignment PIN_D24 -to GPIO[13] +set_location_assignment PIN_B28 -to GPIO[14] +set_location_assignment PIN_C25 -to GPIO[15] +set_location_assignment PIN_C26 -to GPIO[16] +set_location_assignment PIN_D28 -to GPIO[17] +set_location_assignment PIN_D25 -to GPIO[18] +set_location_assignment PIN_F20 -to GPIO[19] +set_location_assignment PIN_E21 -to GPIO[20] +set_location_assignment PIN_F23 -to GPIO[21] +set_location_assignment PIN_G20 -to GPIO[22] +set_location_assignment PIN_F22 -to GPIO[23] +set_location_assignment PIN_G22 -to GPIO[24] +set_location_assignment PIN_G24 -to GPIO[25] +set_location_assignment PIN_G23 -to GPIO[26] +set_location_assignment PIN_A25 -to GPIO[27] +set_location_assignment PIN_A26 -to GPIO[28] +set_location_assignment PIN_A19 -to GPIO[29] +set_location_assignment PIN_A28 -to GPIO[30] +set_location_assignment PIN_A27 -to GPIO[31] +set_location_assignment PIN_B30 -to GPIO[32] +set_location_assignment PIN_AG28 -to GPIO[33] +set_location_assignment PIN_AG26 -to GPIO[34] +set_location_assignment PIN_Y21 -to GPIO[35] +set_location_assignment PIN_AC30 -to G_SENSOR_INT1 +set_location_assignment PIN_AK27 -to G_SENSOR_SCLK +set_location_assignment PIN_AK26 -to G_SENSOR_SDAT +set_location_assignment PIN_E15 -to HEX0[0] +set_location_assignment PIN_E12 -to HEX0[1] +set_location_assignment PIN_G11 -to HEX0[2] +set_location_assignment PIN_F11 -to HEX0[3] +set_location_assignment PIN_F16 -to HEX0[4] +set_location_assignment PIN_D16 -to HEX0[5] +set_location_assignment PIN_F14 -to HEX0[6] +set_location_assignment PIN_G14 -to HEX1[0] +set_location_assignment PIN_B13 -to HEX1[1] +set_location_assignment PIN_G13 -to HEX1[2] +set_location_assignment PIN_F12 -to HEX1[3] +set_location_assignment PIN_G12 -to HEX1[4] +set_location_assignment PIN_J9 -to HEX1[5] +set_location_assignment PIN_G10 -to HEX1[6] +set_location_assignment PIN_G8 -to HEX2[0] +set_location_assignment PIN_G7 -to HEX2[1] +set_location_assignment PIN_F7 -to HEX2[2] +set_location_assignment PIN_AG30 -to HEX2[3] +set_location_assignment PIN_F6 -to HEX2[4] +set_location_assignment PIN_F4 -to HEX2[5] +set_location_assignment PIN_F10 -to HEX2[6] +set_location_assignment PIN_D10 -to HEX3[0] +set_location_assignment PIN_D7 -to HEX3[1] +set_location_assignment PIN_E6 -to HEX3[2] +set_location_assignment PIN_E4 -to HEX3[3] +set_location_assignment PIN_E3 -to HEX3[4] +set_location_assignment PIN_D5 -to HEX3[5] +set_location_assignment PIN_D4 -to HEX3[6] +set_location_assignment PIN_A14 -to HEX4[0] +set_location_assignment PIN_A13 -to HEX4[1] +set_location_assignment PIN_C7 -to HEX4[2] +set_location_assignment PIN_C6 -to HEX4[3] +set_location_assignment PIN_C5 -to HEX4[4] +set_location_assignment PIN_C4 -to HEX4[5] +set_location_assignment PIN_C3 -to HEX4[6] +set_location_assignment PIN_D3 -to HEX5[0] +set_location_assignment PIN_A10 -to HEX5[1] +set_location_assignment PIN_A9 -to HEX5[2] +set_location_assignment PIN_A7 -to HEX5[3] +set_location_assignment PIN_A6 -to HEX5[4] +set_location_assignment PIN_A11 -to HEX5[5] +set_location_assignment PIN_B6 -to HEX5[6] +set_location_assignment PIN_B9 -to HEX6[0] +set_location_assignment PIN_B10 -to HEX6[1] +set_location_assignment PIN_C8 -to HEX6[2] +set_location_assignment PIN_C9 -to HEX6[3] +set_location_assignment PIN_D8 -to HEX6[4] +set_location_assignment PIN_D9 -to HEX6[5] +set_location_assignment PIN_E9 -to HEX6[6] +set_location_assignment PIN_E10 -to HEX7[0] +set_location_assignment PIN_F8 -to HEX7[1] +set_location_assignment PIN_F9 -to HEX7[2] +set_location_assignment PIN_C10 -to HEX7[3] +set_location_assignment PIN_C11 -to HEX7[4] +set_location_assignment PIN_C12 -to HEX7[5] +set_location_assignment PIN_D12 -to HEX7[6] +set_location_assignment PIN_K15 -to HSMC_CLKIN0 +set_location_assignment PIN_V30 -to HSMC_CLKIN_N1 +set_location_assignment PIN_T30 -to HSMC_CLKIN_N2 +set_location_assignment PIN_V29 -to HSMC_CLKIN_P1 +set_location_assignment PIN_T29 -to HSMC_CLKIN_P2 +set_location_assignment PIN_G6 -to HSMC_CLKOUT0 +set_location_assignment PIN_AB28 -to HSMC_CLKOUT_N1 +set_location_assignment PIN_Y28 -to HSMC_CLKOUT_N2 +set_location_assignment PIN_AB27 -to HSMC_CLKOUT_P1 +set_location_assignment PIN_AA28 -to HSMC_CLKOUT_P2 +set_location_assignment PIN_AC25 -to HSMC_D[0] +set_location_assignment PIN_E27 -to HSMC_D[1] +set_location_assignment PIN_AB26 -to HSMC_D[2] +set_location_assignment PIN_E28 -to HSMC_D[3] +set_location_assignment PIN_AD26 -to HSMC_I2C_SCLK +set_location_assignment PIN_AD25 -to HSMC_I2C_SDAT +set_location_assignment PIN_G27 -to HSMC_RX_D_N[0] +set_location_assignment PIN_G29 -to HSMC_RX_D_N[1] +set_location_assignment PIN_H27 -to HSMC_RX_D_N[2] +set_location_assignment PIN_K29 -to HSMC_RX_D_N[3] +set_location_assignment PIN_L28 -to HSMC_RX_D_N[4] +set_location_assignment PIN_M28 -to HSMC_RX_D_N[5] +set_location_assignment PIN_N30 -to HSMC_RX_D_N[6] +set_location_assignment PIN_P28 -to HSMC_RX_D_N[7] +set_location_assignment PIN_R28 -to HSMC_RX_D_N[8] +set_location_assignment PIN_U28 -to HSMC_RX_D_N[9] +set_location_assignment PIN_W28 -to HSMC_RX_D_N[10] +set_location_assignment PIN_W30 -to HSMC_RX_D_N[11] +set_location_assignment PIN_M30 -to HSMC_RX_D_N[12] +set_location_assignment PIN_Y27 -to HSMC_RX_D_N[13] +set_location_assignment PIN_AA29 -to HSMC_RX_D_N[14] +set_location_assignment PIN_AD28 -to HSMC_RX_D_N[15] +set_location_assignment PIN_AE28 -to HSMC_RX_D_N[16] +set_location_assignment PIN_G26 -to HSMC_RX_D_P[0] +set_location_assignment PIN_G28 -to HSMC_RX_D_P[1] +set_location_assignment PIN_J27 -to HSMC_RX_D_P[2] +set_location_assignment PIN_K28 -to HSMC_RX_D_P[3] +set_location_assignment PIN_L27 -to HSMC_RX_D_P[4] +set_location_assignment PIN_M27 -to HSMC_RX_D_P[5] +set_location_assignment PIN_N29 -to HSMC_RX_D_P[6] +set_location_assignment PIN_P27 -to HSMC_RX_D_P[7] +set_location_assignment PIN_R27 -to HSMC_RX_D_P[8] +set_location_assignment PIN_U27 -to HSMC_RX_D_P[9] +set_location_assignment PIN_W27 -to HSMC_RX_D_P[10] +set_location_assignment PIN_W29 -to HSMC_RX_D_P[11] +set_location_assignment PIN_M29 -to HSMC_RX_D_P[12] +set_location_assignment PIN_AA27 -to HSMC_RX_D_P[13] +set_location_assignment PIN_AB29 -to HSMC_RX_D_P[14] +set_location_assignment PIN_AD27 -to HSMC_RX_D_P[15] +set_location_assignment PIN_AE27 -to HSMC_RX_D_P[16] +set_location_assignment PIN_H28 -to HSMC_TX_D_N[0] +set_location_assignment PIN_F29 -to HSMC_TX_D_N[1] +set_location_assignment PIN_D30 -to HSMC_TX_D_N[2] +set_location_assignment PIN_E30 -to HSMC_TX_D_N[3] +set_location_assignment PIN_G30 -to HSMC_TX_D_N[4] +set_location_assignment PIN_J30 -to HSMC_TX_D_N[5] +set_location_assignment PIN_K27 -to HSMC_TX_D_N[6] +set_location_assignment PIN_K30 -to HSMC_TX_D_N[7] +set_location_assignment PIN_T25 -to HSMC_TX_D_N[8] +set_location_assignment PIN_N28 -to HSMC_TX_D_N[9] +set_location_assignment PIN_V26 -to HSMC_TX_D_N[10] +set_location_assignment PIN_Y30 -to HSMC_TX_D_N[11] +set_location_assignment PIN_AC28 -to HSMC_TX_D_N[12] +set_location_assignment PIN_AD30 -to HSMC_TX_D_N[13] +set_location_assignment PIN_AE30 -to HSMC_TX_D_N[14] +set_location_assignment PIN_AH30 -to HSMC_TX_D_N[15] +set_location_assignment PIN_AG29 -to HSMC_TX_D_N[16] +set_location_assignment PIN_J28 -to HSMC_TX_D_P[0] +set_location_assignment PIN_F28 -to HSMC_TX_D_P[1] +set_location_assignment PIN_D29 -to HSMC_TX_D_P[2] +set_location_assignment PIN_F30 -to HSMC_TX_D_P[3] +set_location_assignment PIN_H30 -to HSMC_TX_D_P[4] +set_location_assignment PIN_J29 -to HSMC_TX_D_P[5] +set_location_assignment PIN_K26 -to HSMC_TX_D_P[6] +set_location_assignment PIN_L30 -to HSMC_TX_D_P[7] +set_location_assignment PIN_U25 -to HSMC_TX_D_P[8] +set_location_assignment PIN_N27 -to HSMC_TX_D_P[9] +set_location_assignment PIN_V25 -to HSMC_TX_D_P[10] +set_location_assignment PIN_AA30 -to HSMC_TX_D_P[11] +set_location_assignment PIN_AC27 -to HSMC_TX_D_P[12] +set_location_assignment PIN_AD29 -to HSMC_TX_D_P[13] +set_location_assignment PIN_AE29 -to HSMC_TX_D_P[14] +set_location_assignment PIN_AJ30 -to HSMC_TX_D_P[15] +set_location_assignment PIN_AH29 -to HSMC_TX_D_P[16] +set_location_assignment PIN_C27 -to I2C_SCLK +set_location_assignment PIN_G21 -to I2C_SDAT +set_location_assignment PIN_AH28 -to IRDA_RXD +set_location_assignment PIN_AA26 -to KEY[0] +set_location_assignment PIN_AE25 -to KEY[1] +set_location_assignment PIN_AF30 -to KEY[2] +set_location_assignment PIN_AE26 -to KEY[3] +set_location_assignment PIN_AG4 -to LCD_DATA[0] +set_location_assignment PIN_AF3 -to LCD_DATA[1] +set_location_assignment PIN_AH3 -to LCD_DATA[2] +set_location_assignment PIN_AE5 -to LCD_DATA[3] +set_location_assignment PIN_AH2 -to LCD_DATA[4] +set_location_assignment PIN_AE3 -to LCD_DATA[5] +set_location_assignment PIN_AH4 -to LCD_DATA[6] +set_location_assignment PIN_AE4 -to LCD_DATA[7] +set_location_assignment PIN_AF4 -to LCD_EN +set_location_assignment PIN_AF27 -to LCD_ON +set_location_assignment PIN_AG3 -to LCD_RS +set_location_assignment PIN_AJ3 -to LCD_RW +set_location_assignment PIN_AA25 -to LEDG[0] +set_location_assignment PIN_AB25 -to LEDG[1] +set_location_assignment PIN_F27 -to LEDG[2] +set_location_assignment PIN_F26 -to LEDG[3] +set_location_assignment PIN_W26 -to LEDG[4] +set_location_assignment PIN_Y22 -to LEDG[5] +set_location_assignment PIN_Y25 -to LEDG[6] +set_location_assignment PIN_AA22 -to LEDG[7] +set_location_assignment PIN_J25 -to LEDG[8] +set_location_assignment PIN_T23 -to LEDR[0] +set_location_assignment PIN_T24 -to LEDR[1] +set_location_assignment PIN_V27 -to LEDR[2] +set_location_assignment PIN_W25 -to LEDR[3] +set_location_assignment PIN_T21 -to LEDR[4] +set_location_assignment PIN_T26 -to LEDR[5] +set_location_assignment PIN_R25 -to LEDR[6] +set_location_assignment PIN_T27 -to LEDR[7] +set_location_assignment PIN_P25 -to LEDR[8] +set_location_assignment PIN_R24 -to LEDR[9] +set_location_assignment PIN_P21 -to LEDR[10] +set_location_assignment PIN_N24 -to LEDR[11] +set_location_assignment PIN_N21 -to LEDR[12] +set_location_assignment PIN_M25 -to LEDR[13] +set_location_assignment PIN_K24 -to LEDR[14] +set_location_assignment PIN_L25 -to LEDR[15] +set_location_assignment PIN_M21 -to LEDR[16] +set_location_assignment PIN_M22 -to LEDR[17] +set_location_assignment PIN_A4 -to PCIE_PERST_N +set_location_assignment PIN_V15 -to PCIE_REFCLK_P +set_location_assignment PIN_AC2 -to PCIE_RX_P[0] +set_location_assignment PIN_AA2 -to PCIE_RX_P[1] +set_location_assignment PIN_AB4 -to PCIE_TX_P[0] +set_location_assignment PIN_Y4 -to PCIE_TX_P[1] +set_location_assignment PIN_C29 -to PCIE_WAKE_N +set_location_assignment PIN_AH25 -to SD_CLK +set_location_assignment PIN_AF18 -to SD_CMD +set_location_assignment PIN_AH27 -to SD_DAT[0] +set_location_assignment PIN_AJ28 -to SD_DAT[1] +set_location_assignment PIN_AD24 -to SD_DAT[2] +set_location_assignment PIN_AE18 -to SD_DAT[3] +set_location_assignment PIN_AJ27 -to SD_WP_N +set_location_assignment PIN_AK16 -to SMA_CLKIN +set_location_assignment PIN_AF25 -to SMA_CLKOUT +set_location_assignment PIN_AJ21 -to SSRAM0_CE_N +set_location_assignment PIN_AG23 -to SSRAM1_CE_N +set_location_assignment PIN_AK25 -to SSRAM_ADSC_N +set_location_assignment PIN_AJ25 -to SSRAM_ADSP_N +set_location_assignment PIN_AH26 -to SSRAM_ADV_N +set_location_assignment PIN_AF22 -to SSRAM_BE[0] +set_location_assignment PIN_AK22 -to SSRAM_BE[1] +set_location_assignment PIN_AJ22 -to SSRAM_BE[2] +set_location_assignment PIN_AF21 -to SSRAM_BE[3] +set_location_assignment PIN_AF24 -to SSRAM_CLK +set_location_assignment PIN_AK23 -to SSRAM_GW_N +set_location_assignment PIN_AG24 -to SSRAM_OE_N +set_location_assignment PIN_AK24 -to SSRAM_WE_N +set_location_assignment PIN_V28 -to SW[0] +set_location_assignment PIN_U30 -to SW[1] +set_location_assignment PIN_V21 -to SW[2] +set_location_assignment PIN_C2 -to SW[3] +set_location_assignment PIN_AB30 -to SW[4] +set_location_assignment PIN_U21 -to SW[5] +set_location_assignment PIN_T28 -to SW[6] +set_location_assignment PIN_R30 -to SW[7] +set_location_assignment PIN_P30 -to SW[8] +set_location_assignment PIN_R29 -to SW[9] +set_location_assignment PIN_R26 -to SW[10] +set_location_assignment PIN_N26 -to SW[11] +set_location_assignment PIN_M26 -to SW[12] +set_location_assignment PIN_N25 -to SW[13] +set_location_assignment PIN_J26 -to SW[14] +set_location_assignment PIN_K25 -to SW[15] +set_location_assignment PIN_C30 -to SW[16] +set_location_assignment PIN_H25 -to SW[17] +set_location_assignment PIN_B15 -to TD_CLK27 +set_location_assignment PIN_C17 -to TD_DATA[0] +set_location_assignment PIN_D17 -to TD_DATA[1] +set_location_assignment PIN_A16 -to TD_DATA[2] +set_location_assignment PIN_B16 -to TD_DATA[3] +set_location_assignment PIN_G18 -to TD_DATA[4] +set_location_assignment PIN_G17 -to TD_DATA[5] +set_location_assignment PIN_K18 -to TD_DATA[6] +set_location_assignment PIN_K17 -to TD_DATA[7] +set_location_assignment PIN_C28 -to TD_HS +set_location_assignment PIN_E25 -to TD_RESET_N +set_location_assignment PIN_E22 -to TD_VS +set_location_assignment PIN_D26 -to UART_CTS +set_location_assignment PIN_A29 -to UART_RTS +set_location_assignment PIN_B27 -to UART_RXD +set_location_assignment PIN_H24 -to UART_TXD +set_location_assignment PIN_E24 -to VGA_B[0] +set_location_assignment PIN_C24 -to VGA_B[1] +set_location_assignment PIN_B25 -to VGA_B[2] +set_location_assignment PIN_C23 -to VGA_B[3] +set_location_assignment PIN_F24 -to VGA_B[4] +set_location_assignment PIN_A23 -to VGA_B[5] +set_location_assignment PIN_G25 -to VGA_B[6] +set_location_assignment PIN_C22 -to VGA_B[7] +set_location_assignment PIN_F25 -to VGA_BLANK_N +set_location_assignment PIN_D27 -to VGA_CLK +set_location_assignment PIN_D20 -to VGA_G[0] +set_location_assignment PIN_C20 -to VGA_G[1] +set_location_assignment PIN_A20 -to VGA_G[2] +set_location_assignment PIN_K19 -to VGA_G[3] +set_location_assignment PIN_A21 -to VGA_G[4] +set_location_assignment PIN_F21 -to VGA_G[5] +set_location_assignment PIN_A22 -to VGA_G[6] +set_location_assignment PIN_B22 -to VGA_G[7] +set_location_assignment PIN_B24 -to VGA_HS +set_location_assignment PIN_A17 -to VGA_R[0] +set_location_assignment PIN_C18 -to VGA_R[1] +set_location_assignment PIN_B18 -to VGA_R[2] +set_location_assignment PIN_A18 -to VGA_R[3] +set_location_assignment PIN_E18 -to VGA_R[4] +set_location_assignment PIN_E19 -to VGA_R[5] +set_location_assignment PIN_B19 -to VGA_R[6] +set_location_assignment PIN_C19 -to VGA_R[7] +set_location_assignment PIN_AH20 -to VGA_SYNC_N +set_location_assignment PIN_A24 -to VGA_VS +set_instance_assignment -name VIRTUAL_PIN ON -to FS_ADDR[0] +#============================================================ +set_global_assignment -name PARTITION_NETLIST_TYPE SOURCE -section_id Top +set_global_assignment -name PARTITION_FITTER_PRESERVATION_LEVEL PLACEMENT_AND_ROUTING -section_id Top +set_global_assignment -name PARTITION_COLOR 16764057 -section_id Top +set_global_assignment -name STRATIX_DEVICE_IO_STANDARD "2.5 V" +set_global_assignment -name VQM_FILE ../top.vqm +set_global_assignment -name SDC_FILE de2i_150_golden_top.sdc +set_global_assignment -name MIN_CORE_JUNCTION_TEMP 0 +set_global_assignment -name MAX_CORE_JUNCTION_TEMP 85 +set_global_assignment -name POWER_PRESET_COOLING_SOLUTION "23 MM HEAT SINK WITH 200 LFPM AIRFLOW" +set_global_assignment -name POWER_BOARD_THERMAL_MODEL "NONE (CONSERVATIVE)" +set_instance_assignment -name PARTITION_HIERARCHY root_partition -to | -section_id Top diff --git a/chips/yosys/examples/intel/DE2i-150/quartus_compile/runme_quartus b/chips/yosys/examples/intel/DE2i-150/quartus_compile/runme_quartus new file mode 100644 index 0000000000000000000000000000000000000000..2bc29582cc9f4d3a642ada7304823082836d31e7 --- /dev/null +++ b/chips/yosys/examples/intel/DE2i-150/quartus_compile/runme_quartus @@ -0,0 +1,7 @@ +#!/usr/bin/env bash + +export REV="de2i" + +quartus_map -c $REV top && \ + quartus_fit -c $REV top && \ + quartus_asm -c $REV top diff --git a/chips/yosys/examples/intel/DE2i-150/run_cycloneiv b/chips/yosys/examples/intel/DE2i-150/run_cycloneiv new file mode 100644 index 0000000000000000000000000000000000000000..518807b574bfcfb9750d1b99596aad44f8d6ebc3 --- /dev/null +++ b/chips/yosys/examples/intel/DE2i-150/run_cycloneiv @@ -0,0 +1,2 @@ +#/bin/env bash +yosys -p "synth_intel -family cycloneiv -top top -vqm top.vqm" top.v sevenseg.v diff --git a/chips/yosys/examples/intel/DE2i-150/sevenseg.v b/chips/yosys/examples/intel/DE2i-150/sevenseg.v new file mode 100644 index 0000000000000000000000000000000000000000..06cf7c146c550fa9446a70c7f340aed1f34ce5f8 --- /dev/null +++ b/chips/yosys/examples/intel/DE2i-150/sevenseg.v @@ -0,0 +1,25 @@ +module sevenseg ( output reg [6:0] HEX0, + input [3:0] SW ); + + always @(*) begin + case(SW) + 4'h1: HEX0 = 7'b1111001; + 4'h2: HEX0 = 7'b0100100; + 4'h3: HEX0 = 7'b0110000; + 4'h4: HEX0 = 7'b0011001; + 4'h5: HEX0 = 7'b0010010; + 4'h6: HEX0 = 7'b0000010; + 4'h7: HEX0 = 7'b1111000; + 4'h8: HEX0 = 7'b0000000; + 4'h9: HEX0 = 7'b0011000; + 4'ha: HEX0 = 7'b0001000; + 4'hb: HEX0 = 7'b0000011; + 4'hc: HEX0 = 7'b1000110; + 4'hd: HEX0 = 7'b0100001; + 4'he: HEX0 = 7'b0000110; + 4'hf: HEX0 = 7'b0001110; + 4'h0: HEX0 = 7'b1000000; + endcase // case (SW) + end + +endmodule diff --git a/chips/yosys/examples/intel/DE2i-150/top.v b/chips/yosys/examples/intel/DE2i-150/top.v new file mode 100644 index 0000000000000000000000000000000000000000..2bada0e21880ecba26551b1db7277aa2f608093c --- /dev/null +++ b/chips/yosys/examples/intel/DE2i-150/top.v @@ -0,0 +1,15 @@ +`default_nettype none +module top ( output wire [6:0] HEX0, HEX1, HEX2, HEX3, HEX4, HEX5, HEX6, HEX7, + input wire [15:0] SW ); + + + sevenseg UUD0 (.HEX0(HEX0), .SW(4'h7)); + sevenseg UUD1 (.HEX0(HEX1), .SW(4'h1)); + sevenseg UUD2 (.HEX0(HEX2), .SW(4'h0)); + sevenseg UUD3 (.HEX0(HEX3), .SW(4'h2)); + sevenseg UUD4 (.HEX0(HEX4), .SW(SW[3:0])); + sevenseg UUD5 (.HEX0(HEX5), .SW(SW[7:4])); + sevenseg UUD6 (.HEX0(HEX6), .SW(SW[11:8])); + sevenseg UUD7 (.HEX0(HEX7), .SW(SW[15:12])); + +endmodule diff --git a/chips/yosys/examples/intel/MAX10/run_max10 b/chips/yosys/examples/intel/MAX10/run_max10 new file mode 100644 index 0000000000000000000000000000000000000000..0378e4fa7fcc65d2fcad5c3706af9c399e05316b --- /dev/null +++ b/chips/yosys/examples/intel/MAX10/run_max10 @@ -0,0 +1 @@ +yosys -p "synth_intel -family max10 -top top -vqm top.vqm" top.v sevenseg.v diff --git a/chips/yosys/examples/intel/MAX10/runme_postsynth b/chips/yosys/examples/intel/MAX10/runme_postsynth new file mode 100644 index 0000000000000000000000000000000000000000..70bad061d8e9a2ce46f0254f9e039748cd007906 --- /dev/null +++ b/chips/yosys/examples/intel/MAX10/runme_postsynth @@ -0,0 +1,4 @@ +#!/usr/bin/env bash + +iverilog -D POST_IMPL -o verif_post -s tb_top tb_top.v top.vqm $(yosys-config --datdir/altera_intel/max10/cells_comb_max10.v) +vvp -N verif_post diff --git a/chips/yosys/examples/intel/MAX10/sevenseg.v b/chips/yosys/examples/intel/MAX10/sevenseg.v new file mode 100644 index 0000000000000000000000000000000000000000..06cf7c146c550fa9446a70c7f340aed1f34ce5f8 --- /dev/null +++ b/chips/yosys/examples/intel/MAX10/sevenseg.v @@ -0,0 +1,25 @@ +module sevenseg ( output reg [6:0] HEX0, + input [3:0] SW ); + + always @(*) begin + case(SW) + 4'h1: HEX0 = 7'b1111001; + 4'h2: HEX0 = 7'b0100100; + 4'h3: HEX0 = 7'b0110000; + 4'h4: HEX0 = 7'b0011001; + 4'h5: HEX0 = 7'b0010010; + 4'h6: HEX0 = 7'b0000010; + 4'h7: HEX0 = 7'b1111000; + 4'h8: HEX0 = 7'b0000000; + 4'h9: HEX0 = 7'b0011000; + 4'ha: HEX0 = 7'b0001000; + 4'hb: HEX0 = 7'b0000011; + 4'hc: HEX0 = 7'b1000110; + 4'hd: HEX0 = 7'b0100001; + 4'he: HEX0 = 7'b0000110; + 4'hf: HEX0 = 7'b0001110; + 4'h0: HEX0 = 7'b1000000; + endcase // case (SW) + end + +endmodule diff --git a/chips/yosys/examples/intel/MAX10/top.v b/chips/yosys/examples/intel/MAX10/top.v new file mode 100644 index 0000000000000000000000000000000000000000..2bada0e21880ecba26551b1db7277aa2f608093c --- /dev/null +++ b/chips/yosys/examples/intel/MAX10/top.v @@ -0,0 +1,15 @@ +`default_nettype none +module top ( output wire [6:0] HEX0, HEX1, HEX2, HEX3, HEX4, HEX5, HEX6, HEX7, + input wire [15:0] SW ); + + + sevenseg UUD0 (.HEX0(HEX0), .SW(4'h7)); + sevenseg UUD1 (.HEX0(HEX1), .SW(4'h1)); + sevenseg UUD2 (.HEX0(HEX2), .SW(4'h0)); + sevenseg UUD3 (.HEX0(HEX3), .SW(4'h2)); + sevenseg UUD4 (.HEX0(HEX4), .SW(SW[3:0])); + sevenseg UUD5 (.HEX0(HEX5), .SW(SW[7:4])); + sevenseg UUD6 (.HEX0(HEX6), .SW(SW[11:8])); + sevenseg UUD7 (.HEX0(HEX7), .SW(SW[15:12])); + +endmodule diff --git a/chips/yosys/examples/intel/asicworld_lfsr/README b/chips/yosys/examples/intel/asicworld_lfsr/README new file mode 100644 index 0000000000000000000000000000000000000000..ba365fabf8edb55fc9fa73bfad8011bb36d92910 --- /dev/null +++ b/chips/yosys/examples/intel/asicworld_lfsr/README @@ -0,0 +1,6 @@ +Source of the files: +http://www.asic-world.com/examples/verilog/lfsr.html + +Run first: runme_presynth +Generate output netlist with run_max10 or run_cycloneiv +Then, check with: runme_postsynth diff --git a/chips/yosys/examples/intel/asicworld_lfsr/lfsr_updown.v b/chips/yosys/examples/intel/asicworld_lfsr/lfsr_updown.v new file mode 100644 index 0000000000000000000000000000000000000000..e60012c999da22789cf0c3b076819a305ab8b4af --- /dev/null +++ b/chips/yosys/examples/intel/asicworld_lfsr/lfsr_updown.v @@ -0,0 +1,35 @@ +`default_nettype none +module lfsr_updown ( +clk , // Clock input +reset , // Reset input +enable , // Enable input +up_down , // Up Down input +count , // Count output +overflow // Overflow output +); + + input clk; + input reset; + input enable; + input up_down; + + output [7 : 0] count; + output overflow; + + reg [7 : 0] count; + + assign overflow = (up_down) ? (count == {{7{1'b0}}, 1'b1}) : + (count == {1'b1, {7{1'b0}}}) ; + + always @(posedge clk) + if (reset) + count <= {7{1'b0}}; + else if (enable) begin + if (up_down) begin + count <= {~(^(count & 8'b01100011)),count[7:1]}; + end else begin + count <= {count[5:0],~(^(count & 8'b10110001))}; + end + end + +endmodule diff --git a/chips/yosys/examples/intel/asicworld_lfsr/lfsr_updown_tb.v b/chips/yosys/examples/intel/asicworld_lfsr/lfsr_updown_tb.v new file mode 100644 index 0000000000000000000000000000000000000000..65681801ccc87cb3489078d3cd16f0fd8a2e7cb1 --- /dev/null +++ b/chips/yosys/examples/intel/asicworld_lfsr/lfsr_updown_tb.v @@ -0,0 +1,34 @@ +module tb(); + reg clk; + reg reset; + reg enable; + reg up_down; + + wire [7 : 0] count; + wire overflow; + +initial begin + $monitor("rst %b en %b updown %b cnt %b overflow %b", + reset,enable,up_down,count, overflow); + clk = 0; + reset = 1; + enable = 0; + up_down = 0; + #10 reset = 0; + #1 enable = 1; + #20 up_down = 1; + #30 $finish; +end + +always #1 clk = ~clk; + +lfsr_updown U( +.clk ( clk ), +.reset ( reset ), +.enable ( enable ), +.up_down ( up_down ), +.count ( count ), +.overflow ( overflow ) +); + +endmodule diff --git a/chips/yosys/examples/intel/asicworld_lfsr/run_cycloneiv b/chips/yosys/examples/intel/asicworld_lfsr/run_cycloneiv new file mode 100644 index 0000000000000000000000000000000000000000..077b7fbde150da725263c369e7b94ffd01d268ee --- /dev/null +++ b/chips/yosys/examples/intel/asicworld_lfsr/run_cycloneiv @@ -0,0 +1,2 @@ +#!/usr/bin/env bash +yosys -p "synth_intel -family cycloneiv -top lfsr_updown -vqm top.vqm" lfsr_updown.v diff --git a/chips/yosys/examples/intel/asicworld_lfsr/run_max10 b/chips/yosys/examples/intel/asicworld_lfsr/run_max10 new file mode 100644 index 0000000000000000000000000000000000000000..8fccb57f88f22ddb1468fe2467eb25ae42184624 --- /dev/null +++ b/chips/yosys/examples/intel/asicworld_lfsr/run_max10 @@ -0,0 +1,2 @@ +#!/usr/bin/env bash +yosys -p "synth_intel -family max10 -top lfsr_updown -vqm top.vqm" lfsr_updown.v diff --git a/chips/yosys/examples/intel/asicworld_lfsr/runme_postsynth b/chips/yosys/examples/intel/asicworld_lfsr/runme_postsynth new file mode 100644 index 0000000000000000000000000000000000000000..56a232eb30f208eae66766d1e032b8a8b166d015 --- /dev/null +++ b/chips/yosys/examples/intel/asicworld_lfsr/runme_postsynth @@ -0,0 +1,4 @@ +#!/usr/bin/env bash + +iverilog -D POST_IMPL -o verif_post -s tb lfsr_updown_tb.v top.vqm $(yosys-config --datdir/altera_intel/max10/cells_comb_max10.v) +vvp -N verif_post diff --git a/chips/yosys/examples/intel/asicworld_lfsr/runme_presynth b/chips/yosys/examples/intel/asicworld_lfsr/runme_presynth new file mode 100644 index 0000000000000000000000000000000000000000..9a83b1bbd09a1b9de4e30107b3a8f4e188156069 --- /dev/null +++ b/chips/yosys/examples/intel/asicworld_lfsr/runme_presynth @@ -0,0 +1,5 @@ +#!/usr/bin/env bash + +iverilog -o presynth lfsr_updown_tb.v lfsr_updown.v &&\ + +vvp -N presynth diff --git a/chips/yosys/examples/mimas2/README b/chips/yosys/examples/mimas2/README new file mode 100644 index 0000000000000000000000000000000000000000..b12875cbc6eee85f7646969196cc4fb24c388611 --- /dev/null +++ b/chips/yosys/examples/mimas2/README @@ -0,0 +1,8 @@ +A simple example design, based on the Numato Labs Mimas V2 board +================================================================ + +This example uses Yosys for synthesis and Xilinx ISE +for place&route and bit-stream creation. + +To synthesize: + bash run.sh diff --git a/chips/yosys/examples/mimas2/example.ucf b/chips/yosys/examples/mimas2/example.ucf new file mode 100644 index 0000000000000000000000000000000000000000..4e31b74abf1059b33e3342c1fbf37c5f3e05a495 --- /dev/null +++ b/chips/yosys/examples/mimas2/example.ucf @@ -0,0 +1,13 @@ +CONFIG VCCAUX = "3.3" ; + + +NET "CLK" LOC = D9 | IOSTANDARD = LVCMOS33 | PERIOD = 12MHz ; + +NET "LED[7]" LOC = P15 | IOSTANDARD = LVCMOS33 | DRIVE = 8 | SLEW = SLOW ; +NET "LED[6]" LOC = P16 | IOSTANDARD = LVCMOS33 | DRIVE = 8 | SLEW = SLOW ; +NET "LED[5]" LOC = N15 | IOSTANDARD = LVCMOS33 | DRIVE = 8 | SLEW = SLOW ; +NET "LED[4]" LOC = N16 | IOSTANDARD = LVCMOS33 | DRIVE = 8 | SLEW = SLOW ; +NET "LED[3]" LOC = U17 | IOSTANDARD = LVCMOS33 | DRIVE = 8 | SLEW = SLOW ; +NET "LED[2]" LOC = U18 | IOSTANDARD = LVCMOS33 | DRIVE = 8 | SLEW = SLOW ; +NET "LED[1]" LOC = T17 | IOSTANDARD = LVCMOS33 | DRIVE = 8 | SLEW = SLOW ; +NET "LED[0]" LOC = T18 | IOSTANDARD = LVCMOS33 | DRIVE = 8 | SLEW = SLOW ; diff --git a/chips/yosys/examples/mimas2/example.v b/chips/yosys/examples/mimas2/example.v new file mode 100644 index 0000000000000000000000000000000000000000..2a91173936aa7c3ffaff580999d9f420a39e6551 --- /dev/null +++ b/chips/yosys/examples/mimas2/example.v @@ -0,0 +1,14 @@ +module example( + input wire CLK, + output wire [7:0] LED +); + +reg [27:0] ctr; +initial ctr = 0; + +always @(posedge CLK) + ctr <= ctr + 1; + +assign LED = ctr[27:20]; + +endmodule diff --git a/chips/yosys/examples/mimas2/run.sh b/chips/yosys/examples/mimas2/run.sh new file mode 100644 index 0000000000000000000000000000000000000000..b16341eceb816bbc470bba8fadcde7727fddc953 --- /dev/null +++ b/chips/yosys/examples/mimas2/run.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env sh +set -e +yosys run_yosys.ys +edif2ngd example.edif +ngdbuild example -uc example.ucf -p xc6slx9csg324-3 +map -w example +par -w example.ncd example_par.ncd +bitgen -w example_par.ncd -g StartupClk:JTAGClk diff --git a/chips/yosys/examples/mimas2/run_yosys.ys b/chips/yosys/examples/mimas2/run_yosys.ys new file mode 100644 index 0000000000000000000000000000000000000000..b48877811cc32a8bbad7409d672a4aeb96ffccc1 --- /dev/null +++ b/chips/yosys/examples/mimas2/run_yosys.ys @@ -0,0 +1,3 @@ +read_verilog example.v +synth_xilinx -top example -family xc6s -ise +write_edif -pvector bra example.edif diff --git a/chips/yosys/examples/osu035/.gitignore b/chips/yosys/examples/osu035/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..3abf340bbe3da2c9b24805e09536347bf5fd7dca --- /dev/null +++ b/chips/yosys/examples/osu035/.gitignore @@ -0,0 +1,3 @@ +osu035_stdcells.lib +example.yslog +example.edif diff --git a/chips/yosys/examples/osu035/Makefile b/chips/yosys/examples/osu035/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..ce3c36269a3869f90a69a5926f658290a45e7412 --- /dev/null +++ b/chips/yosys/examples/osu035/Makefile @@ -0,0 +1,12 @@ + +example.edif: example.ys example.v example.constr osu035_stdcells.lib + yosys -l example.yslog -q example.ys + +osu035_stdcells.lib: + rm -f osu035_stdcells.lib.part osu035_stdcells.lib + wget -O osu035_stdcells.lib.part https://vlsiarch.ecen.okstate.edu/flows/MOSIS_SCMOS/latest/cadence/lib/ami035/signalstorm/osu035_stdcells.lib + mv osu035_stdcells.lib.part osu035_stdcells.lib + +clean: + rm -f osu035_stdcells.lib + rm -f example.yslog example.edif diff --git a/chips/yosys/examples/osu035/example.constr b/chips/yosys/examples/osu035/example.constr new file mode 100644 index 0000000000000000000000000000000000000000..eb2c6e8d519fb32079f49dfdfe7680cdd956541d --- /dev/null +++ b/chips/yosys/examples/osu035/example.constr @@ -0,0 +1,2 @@ +set_driving_cell INVX1 +set_load 0.015 diff --git a/chips/yosys/examples/osu035/example.v b/chips/yosys/examples/osu035/example.v new file mode 100644 index 0000000000000000000000000000000000000000..0f043e5fc1e3df4b779c59b80773f016d73a0dd1 --- /dev/null +++ b/chips/yosys/examples/osu035/example.v @@ -0,0 +1,3 @@ +module top (input clk, input [7:0] a, b, output reg [15:0] c); + always @(posedge clk) c <= a * b; +endmodule diff --git a/chips/yosys/examples/osu035/example.ys b/chips/yosys/examples/osu035/example.ys new file mode 100644 index 0000000000000000000000000000000000000000..6821ef42664aa900b41a6ff22d4d1800f147fa75 --- /dev/null +++ b/chips/yosys/examples/osu035/example.ys @@ -0,0 +1,11 @@ +read_verilog example.v +read_liberty -lib osu035_stdcells.lib + +synth -top top + +dfflibmap -liberty osu035_stdcells.lib +abc -D 10000 -constr example.constr -liberty osu035_stdcells.lib +opt_clean + +stat -liberty osu035_stdcells.lib +write_edif example.edif diff --git a/chips/yosys/examples/python-api/.gitignore b/chips/yosys/examples/python-api/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..758de11347f01d667738e0663d2fbb9daae04ef4 --- /dev/null +++ b/chips/yosys/examples/python-api/.gitignore @@ -0,0 +1 @@ +out/** diff --git a/chips/yosys/examples/python-api/pass.py b/chips/yosys/examples/python-api/pass.py new file mode 100644 index 0000000000000000000000000000000000000000..d5e5868b0dcc739c6e6da11427eb474bfa1b5b53 --- /dev/null +++ b/chips/yosys/examples/python-api/pass.py @@ -0,0 +1,42 @@ +#!/usr/bin/python3 + +from pyosys import libyosys as ys + +from pathlib import Path + +import matplotlib.pyplot as plt + +__file_dir__ = Path(__file__).absolute().parent + +class CellStatsPass(ys.Pass): + + def __init__(self): + super().__init__("cell_stats", "Shows cell stats as plot") + + def help(self): + ys.log("This pass uses the matplotlib library to display cell stats\n") + + def execute(self, args, design): + ys.log_header(design, "Plotting cell stats\n") + cell_stats = {} + for module in design.all_selected_whole_modules(): + for cell in module.selected_cells(): + if cell.type.str() in cell_stats: + cell_stats[cell.type.str()] += 1 + else: + cell_stats[cell.type.str()] = 1 + plt.bar(range(len(cell_stats)), height = list(cell_stats.values()),align='center') + plt.xticks(range(len(cell_stats)), list(cell_stats.keys())) + plt.show() + + def clear_flags(self): + ys.log("Clear Flags - CellStatsPass\n") + +p = CellStatsPass() # register + +if __name__ == "__main__": + design = ys.Design() + ys.run_pass(f"read_verilog {__file_dir__.parents[1] / 'tests' / 'simple' / 'fiedler-cooley.v'}", design) + ys.run_pass("prep", design) + ys.run_pass("opt -full", design) + ys.run_pass("cell_stats", design) diff --git a/chips/yosys/examples/python-api/script.py b/chips/yosys/examples/python-api/script.py new file mode 100644 index 0000000000000000000000000000000000000000..f0fa5a0b8f3142c78d2912372a926a828010098e --- /dev/null +++ b/chips/yosys/examples/python-api/script.py @@ -0,0 +1,22 @@ +#!/usr/bin/python3 + +from pyosys import libyosys as ys + +import matplotlib.pyplot as plt +import numpy as np + +design = ys.Design() +ys.run_pass("read_verilog ../../tests/simple/fiedler-cooley.v", design); +ys.run_pass("prep", design) +ys.run_pass("opt -full", design) + +cell_stats = {} +for module in design.selected_whole_modules_warn(): + for cell in module.selected_cells(): + if cell.type.str() in cell_stats: + cell_stats[cell.type.str()] += 1 + else: + cell_stats[cell.type.str()] = 1 +plt.bar(range(len(cell_stats)), height = list(cell_stats.values()),align='center') +plt.xticks(range(len(cell_stats)), list(cell_stats.keys())) +plt.show() diff --git a/chips/yosys/examples/smtbmc/.gitignore b/chips/yosys/examples/smtbmc/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..278f5ebf7dd802627c7e421374e6efd6b3c32143 --- /dev/null +++ b/chips/yosys/examples/smtbmc/.gitignore @@ -0,0 +1,24 @@ +demo1.smt2 +demo1.yslog +demo2.smt2 +demo2.smtc +demo2.vcd +demo2.yslog +demo2_tb +demo2_tb.v +demo2_tb.vcd +demo3.smt2 +demo3.vcd +demo3.yslog +demo4.smt2 +demo4.vcd +demo4.yslog +demo5.smt2 +demo5.vcd +demo5.yslog +demo6.smt2 +demo6.yslog +demo7.smt2 +demo7.yslog +demo8.smt2 +demo8.yslog diff --git a/chips/yosys/examples/smtbmc/Makefile b/chips/yosys/examples/smtbmc/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..54dd2dac49146a215da931c04b7cdd5618e0a2c7 --- /dev/null +++ b/chips/yosys/examples/smtbmc/Makefile @@ -0,0 +1,76 @@ + +all: demo1 demo2 demo3 demo4 demo5 demo6 demo7 demo8 demo9 glift_mux + +demo1: demo1.smt2 + yosys-smtbmc --dump-vcd demo1.vcd demo1.smt2 + yosys-smtbmc -i --dump-vcd demo1.vcd demo1.smt2 + +demo2: demo2.smt2 + yosys-smtbmc -g --dump-vcd demo2.vcd --dump-smtc demo2.smtc --dump-vlogtb demo2_tb.v demo2.smt2 + iverilog -g2012 -o demo2_tb demo2_tb.v demo2.v + vvp demo2_tb +vcd=demo2_tb.vcd + +demo3: demo3.smt2 + yosys-smtbmc --dump-vcd demo3.vcd --smtc demo3.smtc demo3.smt2 + +demo4: demo4.smt2 + yosys-smtbmc -s yices --dump-vcd demo4.vcd --smtc demo4.smtc demo4.smt2 + +demo5: demo5.smt2 + yosys-smtbmc -g -t 50 --dump-vcd demo5.vcd demo5.smt2 + +demo6: demo6.smt2 + yosys-smtbmc -t 1 demo6.smt2 + +demo7: demo7.smt2 + yosys-smtbmc -t 10 demo7.smt2 + +demo8: demo8.smt2 + yosys-smtbmc -s z3 -t 1 -g demo8.smt2 + +demo9: demo9.smt2 + yosys-smtbmc -s z3 -t 1 -g demo9.smt2 + +glift_mux: + yosys -ql glift_mux.yslog glift/mux2.ys + +demo1.smt2: demo1.v + yosys -ql demo1.yslog -p 'read_verilog -formal demo1.v; prep -top demo1 -nordff; write_smt2 -wires demo1.smt2' + +demo2.smt2: demo2.v + yosys -ql demo2.yslog -p 'read_verilog -formal demo2.v; prep -top demo2 -nordff; write_smt2 -wires demo2.smt2' + +demo3.smt2: demo3.v + yosys -ql demo3.yslog -p 'read_verilog -formal demo3.v; prep -top demo3 -nordff; write_smt2 -wires demo3.smt2' + +demo4.smt2: demo4.v + yosys -ql demo4.yslog -p 'read_verilog -formal demo4.v; prep -top demo4 -nordff; write_smt2 -wires demo4.smt2' + +demo5.smt2: demo5.v + yosys -ql demo5.yslog -p 'read_verilog -formal demo5.v; prep -top demo5 -nordff; write_smt2 -wires demo5.smt2' + +demo6.smt2: demo6.v + yosys -ql demo6.yslog -p 'read_verilog demo6.v; prep -top demo6 -nordff; assertpmux; opt -keepdc -fast; write_smt2 -wires demo6.smt2' + +demo7.smt2: demo7.v + yosys -ql demo7.yslog -p 'read_verilog -formal demo7.v; prep -top demo7 -nordff; write_smt2 -wires demo7.smt2' + +demo8.smt2: demo8.v + yosys -ql demo8.yslog -p 'read_verilog -formal demo8.v; prep -top demo8 -nordff; write_smt2 -stbv -wires demo8.smt2' + +demo9.smt2: demo9.v + yosys -ql demo9.yslog -p 'read_verilog -formal demo9.v; prep -top demo9 -nordff; write_smt2 -stbv -wires demo9.smt2' + +clean: + rm -f demo1.yslog demo1.smt2 demo1.vcd + rm -f demo2.yslog demo2.smt2 demo2.vcd demo2.smtc demo2_tb.v demo2_tb demo2_tb.vcd + rm -f demo3.yslog demo3.smt2 demo3.vcd + rm -f demo4.yslog demo4.smt2 demo4.vcd + rm -f demo5.yslog demo5.smt2 demo5.vcd + rm -f demo6.yslog demo6.smt2 + rm -f demo7.yslog demo7.smt2 + rm -f demo8.yslog demo8.smt2 + rm -f demo9.yslog demo9.smt2 + rm -f glift_mux.ys + +.PHONY: demo1 demo2 demo3 demo4 demo5 demo6 demo7 demo8 demo9 clean diff --git a/chips/yosys/examples/smtbmc/demo1.v b/chips/yosys/examples/smtbmc/demo1.v new file mode 100644 index 0000000000000000000000000000000000000000..567dde1483e9307cd188bbb31875c8045da9e294 --- /dev/null +++ b/chips/yosys/examples/smtbmc/demo1.v @@ -0,0 +1,19 @@ +module demo1(input clk, input addtwo, output iseven); + reg [3:0] cnt; + wire [3:0] next_cnt; + + inc inc_inst (addtwo, iseven, cnt, next_cnt); + + always @(posedge clk) + cnt = (iseven ? cnt == 10 : cnt == 11) ? 0 : next_cnt; + +`ifdef FORMAL + assert property (cnt != 15); + initial assume (!cnt[2]); +`endif +endmodule + +module inc(input addtwo, output iseven, input [3:0] a, output [3:0] y); + assign iseven = !a[0]; + assign y = a + (addtwo ? 2 : 1); +endmodule diff --git a/chips/yosys/examples/smtbmc/demo2.v b/chips/yosys/examples/smtbmc/demo2.v new file mode 100644 index 0000000000000000000000000000000000000000..0cf529a4298b5f0e8928e675c4b8ba92efd7f967 --- /dev/null +++ b/chips/yosys/examples/smtbmc/demo2.v @@ -0,0 +1,29 @@ +// Nothing to prove in this demo. +// Just an example for memories, vcd dumps and vlog testbench dumps. + +`ifdef FORMAL +`define assume(_expr_) assume(_expr_) +`else +`define assume(_expr_) +`endif + +module demo2(input clk, input [4:0] addr, output reg [31:0] data); + reg [31:0] mem [0:31]; + always @(negedge clk) + data <= mem[addr]; + + reg [31:0] used_addr = 0; + reg [31:0] used_dbits = 0; + reg initstate = 1; + + always @(posedge clk) begin + initstate <= 0; + `assume(!used_addr[addr]); + used_addr[addr] <= 1; + if (!initstate) begin + `assume(data != 0); + `assume((used_dbits & data) == 0); + used_dbits <= used_dbits | data; + end + end +endmodule diff --git a/chips/yosys/examples/smtbmc/demo3.smtc b/chips/yosys/examples/smtbmc/demo3.smtc new file mode 100644 index 0000000000000000000000000000000000000000..f5e017cf026671bc7d53945103415ca672a47ac7 --- /dev/null +++ b/chips/yosys/examples/smtbmc/demo3.smtc @@ -0,0 +1,5 @@ +initial +assume [rst] + +always -1 +assert (= [-1:mem] [mem]) diff --git a/chips/yosys/examples/smtbmc/demo3.v b/chips/yosys/examples/smtbmc/demo3.v new file mode 100644 index 0000000000000000000000000000000000000000..13b3a19700f66109c572b1cadde5566fd5f41daf --- /dev/null +++ b/chips/yosys/examples/smtbmc/demo3.v @@ -0,0 +1,18 @@ +// Whatever the initial content of this memory is at reset, it will never change +// see demo3.smtc for assumptions and assertions + +module demo3(input clk, rst, input [15:0] addr, output reg [31:0] data); + reg [31:0] mem [0:2**16-1]; + reg [15:0] addr_q; + + always @(posedge clk) begin + if (rst) begin + data <= mem[0] ^ 123456789; + addr_q <= 0; + end else begin + mem[addr_q] <= data ^ 123456789; + data <= mem[addr] ^ 123456789; + addr_q <= addr; + end + end +endmodule diff --git a/chips/yosys/examples/smtbmc/demo4.smtc b/chips/yosys/examples/smtbmc/demo4.smtc new file mode 100644 index 0000000000000000000000000000000000000000..2f91f8164a5b6ed7cfe3c78d0e783263a34445ab --- /dev/null +++ b/chips/yosys/examples/smtbmc/demo4.smtc @@ -0,0 +1,11 @@ +initial +assume [rst] + +always -1 +assume (not [rst]) +assume (=> [-1:inv2] [inv2]) + +final -2 +assume [-1:inv2] +assume (not [-2:inv2]) +assert (= [r1] [r2]) diff --git a/chips/yosys/examples/smtbmc/demo4.v b/chips/yosys/examples/smtbmc/demo4.v new file mode 100644 index 0000000000000000000000000000000000000000..3f1b47277dd11c0d882a30a9721e3ad9cf163df4 --- /dev/null +++ b/chips/yosys/examples/smtbmc/demo4.v @@ -0,0 +1,13 @@ +// Demo for "final" smtc constraints + +module demo4(input clk, rst, inv2, input [15:0] in, output reg [15:0] r1, r2); + always @(posedge clk) begin + if (rst) begin + r1 <= in; + r2 <= -in; + end else begin + r1 <= r1 + in; + r2 <= inv2 ? -(r2 - in) : (r2 - in); + end + end +endmodule diff --git a/chips/yosys/examples/smtbmc/demo5.v b/chips/yosys/examples/smtbmc/demo5.v new file mode 100644 index 0000000000000000000000000000000000000000..63ace307cf0f028090f225b08c3500bb033a9b52 --- /dev/null +++ b/chips/yosys/examples/smtbmc/demo5.v @@ -0,0 +1,18 @@ +// Demo for $anyconst + +module demo5 (input clk); + wire [7:0] step_size = $anyconst; + reg [7:0] state = 0, count = 0; + reg [31:0] hash = 0; + + always @(posedge clk) begin + count <= count + 1; + hash <= ((hash << 5) + hash) ^ state; + state <= state + step_size; + end + + always @* begin + if (count == 42) + assert(hash == 32'h A18FAC0A); + end +endmodule diff --git a/chips/yosys/examples/smtbmc/demo6.v b/chips/yosys/examples/smtbmc/demo6.v new file mode 100644 index 0000000000000000000000000000000000000000..62a72e2a85c69c823123ec89f8380605e3077b98 --- /dev/null +++ b/chips/yosys/examples/smtbmc/demo6.v @@ -0,0 +1,14 @@ +// Demo for assertpmux + +module demo6 (input A, B, C, D, E, output reg Y); + always @* begin + Y = 0; + if (A != B) begin + (* parallel_case *) + case (C) + A: Y = D; + B: Y = E; + endcase + end + end +endmodule diff --git a/chips/yosys/examples/smtbmc/demo7.v b/chips/yosys/examples/smtbmc/demo7.v new file mode 100644 index 0000000000000000000000000000000000000000..63f6272f16f46e82bb2c7309c805a4336983b343 --- /dev/null +++ b/chips/yosys/examples/smtbmc/demo7.v @@ -0,0 +1,19 @@ +// Demo for memory initialization + +module demo7; + wire [2:0] addr = $anyseq; + reg [15:0] memory [0:7]; + + initial begin + memory[0] = 1331; + memory[1] = 1331 + 1; + memory[2] = 1331 + 2; + memory[3] = 1331 + 4; + memory[4] = 1331 + 8; + memory[5] = 1331 + 16; + memory[6] = 1331 + 32; + memory[7] = 1331 + 64; + end + + assert property (1000 < memory[addr] && memory[addr] < 2000); +endmodule diff --git a/chips/yosys/examples/smtbmc/demo8.v b/chips/yosys/examples/smtbmc/demo8.v new file mode 100644 index 0000000000000000000000000000000000000000..c4c396cde3bafce6905972d0c9907d20b440425a --- /dev/null +++ b/chips/yosys/examples/smtbmc/demo8.v @@ -0,0 +1,12 @@ +// Simple exists-forall demo + +module demo8; + wire [7:0] prime = $anyconst; + wire [3:0] factor = $allconst; + + always @* begin + if (1 < factor && factor < prime) + assume((prime % factor) != 0); + assume(prime > 1); + end +endmodule diff --git a/chips/yosys/examples/smtbmc/demo9.v b/chips/yosys/examples/smtbmc/demo9.v new file mode 100644 index 0000000000000000000000000000000000000000..bbfbf11b8f3799d23256286ea8b8ad7a8df08b6f --- /dev/null +++ b/chips/yosys/examples/smtbmc/demo9.v @@ -0,0 +1,12 @@ +module demo9; + (* maximize *) wire[7:0] h = $anyconst; + wire [7:0] i = $allconst; + + wire [7:0] t0 = ((i << 8'b00000010) + 8'b00000011); + wire trigger = (t0 > h) && (h < 8'b00000100); + + always @* begin + assume(trigger == 1'b1); + cover(1); + end +endmodule diff --git a/chips/yosys/examples/smtbmc/glift/C7552.v b/chips/yosys/examples/smtbmc/glift/C7552.v new file mode 100644 index 0000000000000000000000000000000000000000..1dff5338e8c8de78ee72786b910d1fcc5d720fbb --- /dev/null +++ b/chips/yosys/examples/smtbmc/glift/C7552.v @@ -0,0 +1,4194 @@ +module C7552_lev2(pi000, pi001, pi002, pi003, pi004, pi005, pi006, pi007, pi008, pi009, + pi010, pi011, pi012, pi013, pi014, pi015, pi016, pi017, pi018, pi019, + pi020, pi021, pi022, pi023, pi024, pi025, pi026, pi027, pi028, pi029, + pi030, pi031, pi032, pi033, pi034, pi035, pi036, pi037, pi038, pi039, + pi040, pi041, pi042, pi043, pi044, pi045, pi046, pi047, pi048, pi049, + pi050, pi051, pi052, pi053, pi054, pi055, pi056, pi057, pi058, pi059, + pi060, pi061, pi062, pi063, pi064, pi065, pi066, pi067, pi068, pi069, + pi070, pi071, pi072, pi073, pi074, pi075, pi076, pi077, pi078, pi079, + pi080, pi081, pi082, pi083, pi084, pi085, pi086, pi087, pi088, pi089, + pi090, pi091, pi092, pi093, pi094, pi095, pi096, pi097, pi098, pi099, + pi100, pi101, pi102, pi103, pi104, pi105, pi106, pi107, pi108, pi109, + pi110, pi111, pi112, pi113, pi114, pi115, pi116, pi117, pi118, pi119, + pi120, pi121, pi122, pi123, pi124, pi125, pi126, pi127, pi128, pi129, + pi130, pi131, pi132, pi133, pi134, pi135, pi136, pi137, pi138, pi139, + pi140, pi141, pi142, pi143, pi144, pi145, pi146, pi147, pi148, pi149, + pi150, pi151, pi152, pi153, pi154, pi155, pi156, pi157, pi158, pi159, + pi160, pi161, pi162, pi163, pi164, pi165, pi166, pi167, pi168, pi169, + pi170, pi171, pi172, pi173, pi174, pi175, pi176, pi177, pi178, pi179, + pi180, pi181, pi182, pi183, pi184, pi185, pi186, pi187, pi188, pi189, + pi190, pi191, pi192, pi193, pi194, pi195, pi196, pi197, pi198, pi199, + pi200, pi201, pi202, pi203, pi204, pi205, pi206, po000, po001, po002, + po003, po004, po005, po006, po007, po008, po009, po010, po011, po012, + po013, po014, po015, po016, po017, po018, po019, po020, po021, po022, + po023, po024, po025, po026, po027, po028, po029, po030, po031, po032, + po033, po034, po035, po036, po037, po038, po039, po040, po041, po042, + po043, po044, po045, po046, po047, po048, po049, po050, po051, po052, + po053, po054, po055, po056, po057, po058, po059, po060, po061, po062, + po063, po064, po065, po066, po067, po068, po069, po070, po071, po072, + po073, po074, po075, po076, po077, po078, po079, po080, po081, po082, + po083, po084, po085, po086, po087, po088, po089, po090, po091, po092, + po093, po094, po095, po096, po097, po098, po099, po100, po101, po102, + po103, po104, po105, po106, po107); + +input pi000, pi001, pi002, pi003, pi004, pi005, pi006, pi007, pi008, pi009, + pi010, pi011, pi012, pi013, pi014, pi015, pi016, pi017, pi018, pi019, + pi020, pi021, pi022, pi023, pi024, pi025, pi026, pi027, pi028, pi029, + pi030, pi031, pi032, pi033, pi034, pi035, pi036, pi037, pi038, pi039, + pi040, pi041, pi042, pi043, pi044, pi045, pi046, pi047, pi048, pi049, + pi050, pi051, pi052, pi053, pi054, pi055, pi056, pi057, pi058, pi059, + pi060, pi061, pi062, pi063, pi064, pi065, pi066, pi067, pi068, pi069, + pi070, pi071, pi072, pi073, pi074, pi075, pi076, pi077, pi078, pi079, + pi080, pi081, pi082, pi083, pi084, pi085, pi086, pi087, pi088, pi089, + pi090, pi091, pi092, pi093, pi094, pi095, pi096, pi097, pi098, pi099, + pi100, pi101, pi102, pi103, pi104, pi105, pi106, pi107, pi108, pi109, + pi110, pi111, pi112, pi113, pi114, pi115, pi116, pi117, pi118, pi119, + pi120, pi121, pi122, pi123, pi124, pi125, pi126, pi127, pi128, pi129, + pi130, pi131, pi132, pi133, pi134, pi135, pi136, pi137, pi138, pi139, + pi140, pi141, pi142, pi143, pi144, pi145, pi146, pi147, pi148, pi149, + pi150, pi151, pi152, pi153, pi154, pi155, pi156, pi157, pi158, pi159, + pi160, pi161, pi162, pi163, pi164, pi165, pi166, pi167, pi168, pi169, + pi170, pi171, pi172, pi173, pi174, pi175, pi176, pi177, pi178, pi179, + pi180, pi181, pi182, pi183, pi184, pi185, pi186, pi187, pi188, pi189, + pi190, pi191, pi192, pi193, pi194, pi195, pi196, pi197, pi198, pi199, + pi200, pi201, pi202, pi203, pi204, pi205, pi206; + +output po000, po001, po002, po003, po004, po005, po006, po007, po008, po009, + po010, po011, po012, po013, po014, po015, po016, po017, po018, po019, + po020, po021, po022, po023, po024, po025, po026, po027, po028, po029, + po030, po031, po032, po033, po034, po035, po036, po037, po038, po039, + po040, po041, po042, po043, po044, po045, po046, po047, po048, po049, + po050, po051, po052, po053, po054, po055, po056, po057, po058, po059, + po060, po061, po062, po063, po064, po065, po066, po067, po068, po069, + po070, po071, po072, po073, po074, po075, po076, po077, po078, po079, + po080, po081, po082, po083, po084, po085, po086, po087, po088, po089, + po090, po091, po092, po093, po094, po095, po096, po097, po098, po099, + po100, po101, po102, po103, po104, po105, po106, po107; + +wire n2822, n2823, n2824, n2825, n2826, n2827, n2828, n2829, n2830, n2831, + n2832, n2833, n2834, n2835, n2836, n2837, n2838, n2839, n2840, n2841, + n2842, n2843, n2844, n2845, n2846, n2847, n2848, n2849, n2850, n2851, + n2852, n2853, n2854, n2855, n2856, n2857, n2858, n2859, n2860, n2861, + n2862, n2863, n2864, n2865, n2866, n2867, n2868, n2869, n2870, n2871, + n2872, n2873, n2874, n2875, n2876, n2877, n2878, n2879, n2880, n2881, + n2882, n2883, n2884, n2885, n2886, n2887, n2888, n2889, n2890, n2891, + n2892, n2893, n2894, n2895, n2896, n2897, n2898, n2899, n2900, n2901, + n2902, n2903, n2904, n2905, n2906, n2907, n2908, n2909, n2910, n2911, + n2912, n2913, n2914, n2915, n2916, n2917, n2918, n2919, n2920, n2921, + n2922, n2923, n2924, n2925, n2926, n2927, n2928, n2929, n2930, n2931, + n2932, n2933, n2934, n2935, n2936, n2937, n2938, n2939, n2940, n2941, + n2942, n2943, n2944, n2945, n2946, n2947, n2948, n2949, n2950, n2951, + n2952, n2953, n2954, n2955, n2956, n2957, n2958, n2959, n2960, n2961, + n2962, n2963, n2964, n2965, n2966, n2967, n2968, n2969, n2970, n2971, + n2972, n2973, n2974, n2975, n2976, n2977, n2978, n2979, n2980, n2981, + n2982, n2983, n2984, n2985, n2986, n2987, n2988, n2989, n2990, n2991, + n2992, n2993, n2994, n2995, n2996, n2997, n2998, n2999, n3000, n3001, + n3002, n3003, n3004, n3005, n3006, n3007, n3008, n3009, n3010, n3011, + n3012, n3013, n3014, n3015, n3016, n3017, n3018, n3019, n3020, n3021, + n3022, n3023, n3024, n3025, n3026, n3027, n3028, n3029, n3030, n3031, + n3032, n3033, n3034, n3035, n3036, n3037, n3038, n3039, n3040, n3041, + n3042, n3043, n3044, n3045, n3046, n3047, n3048, n3049, n3050, n3051, + n3052, n3053, n3054, n3055, n3056, n3057, n3058, n3059, n3060, n3061, + n3062, n3063, n3064, n3065, n3066, n3067, n3068, n3069, n3070, n3071, + n3072, n3073, n3074, n3075, n3076, n3077, n3078, n3079, n3080, n3081, + n3082, n3083, n3084, n3085, n3086, n3087, n3088, n3089, n3090, n3091, + n3092, n3093, n3094, n3095, n3096, n3097, n3098, n3099, n3100, n3101, + n3102, n3103, n3104, n3105, n3106, n3107, n3108, n3109, n3110, n3111, + n3112, n3113, n3114, n3115, n3116, n3117, n3118, n3119, n3120, n3121, + n3122, n3123, n3124, n3125, n3126, n3127, n3128, n3129, n3130, n3131, + n3132, n3133, n3134, n3135, n3136, n3137, n3138, n3139, n3140, n3141, + n3142, n3143, n3144, n3145, n3146, n3147, n3148, n3149, n3150, n3151, + n3152, n3153, n3154, n3155, n3156, n3157, n3158, n3159, n3160, n3161, + n3162, n3163, n3164, n3165, n3166, n3167, n3168, n3169, n3170, n3171, + n3172, n3173, n3174, n3175, n3176, n3177, n3178, n3179, n3180, n3181, + n3182, n3183, n3184, n3185, n3186, n3187, n3188, n3189, n3190, n3191, + n3192, n3193, n3194, n3195, n3196, n3197, n3198, n3199, n3200, n3201, + n3202, n3203, n3204, n3205, n3206, n3207, n3208, n3209, n3210, n3211, + n3212, n3213, n3214, n3215, n3216, n3217, n3218, n3219, n3220, n3221, + n3222, n3223, n3224, n3225, n3226, n3227, n3228, n3229, n3230, n3231, + n3232, n3233, n3234, n3235, n3236, n3237, n3238, n3239, n3240, n3241, + n3242, n3243, n3244, n3245, n3246, n3247, n3248, n3249, n3250, n3251, + n3252, n3253, n3254, n3255, n3256, n3257, n3258, n3259, n3260, n3261, + n3262, n3263, n3264, n3265, n3266, n3267, n3268, n3269, n3270, n3271, + n3272, n3273, n3274, n3275, n3276, n3277, n3278, n3279, n3280, n3281, + n3282, n3283, n3284, n3285, n3286, n3287, n3288, n3289, n3290, n3291, + n3292, n3293, n3294, n3295, n3296, n3297, n3298, n3299, n3300, n3301, + n3302, n3303, n3304, n3305, n3306, n3307, n3308, n3309, n3310, n3311, + n3312, n3313, n3314, n3315, n3316, n3317, n3318, n3319, n3320, n3321, + n3322, n3323, n3324, n3325, n3326, n3327, n3328, n3329, n3330, n3331, + n3332, n3333, n3334, n3335, n3336, n3337, n3338, n3339, n3340, n3341, + n3342, n3343, n3344, n3345, n3346, n3347, n3348, n3349, n3350, n3351, + n3352, n3353, n3354, n3355, n3356, n3357, n3358, n3359, n3360, n3361, + n3362, n3363, n3364, n3365, n3366, n3367, n3368, n3369, n3370, n3371, + n3372, n3373, n3374, n3375, n3376, n3377, n3378, n3379, n3380, n3381, + n3382, n3383, n3384, n3385, n3386, n3387, n3388, n3389, n3390, n3391, + n3392, n3393, n3394, n3395, n3396, n3397, n3398, n3399, n3400, n3401, + n3402, n3403, n3404, n3405, n3406, n3407, n3408, n3409, n3410, n3411, + n3412, n3413, n3414, n3415, n3416, n3417, n3418, n3419, n3420, n3421, + n3422, n3423, n3424, n3425, n3426, n3427, n3428, n3429, n3430, n3431, + n3432, n3433, n3434, n3435, n3436, n3437, n3438, n3439, n3440, n3441, + n3442, n3443, n3444, n3445, n3446, n3447, n3448, n3449, n3450, n3451, + n3452, n3453, n3454, n3455, n3456, n3457, n3458, n3459, n3460, n3461, + n3462, n3463, n3464, n3465, n3466, n3467, n3468, n3469, n3470, n3471, + n3472, n3473, n3474, n3475, n3476, n3477, n3478, n3479, n3480, n3481, + n3482, n3483, n3484, n3485, n3486, n3487, n3488, n3489, n3490, n3491, + n3492, n3493, n3494, n3495, n3496, n3497, n3498, n3499, n3500, n3501, + n3502, n3503, n3504, n3505, n3506, n3507, n3508, n3509, n3510, n3511, + n3512, n3513, n3514, n3515, n3516, n3517, n3518, n3519, n3520, n3521, + n3522, n3523, n3524, n3525, n3526, n3527, n3528, n3529, n3530, n3531, + n3532, n3533, n3534, n3535, n3536, n3537, n3538, n3539, n3540, n3541, + n3542, n3543, n3544, n3545, n3546, n3547, n3548, n3549, n3550, n3551, + n3552, n3553, n3554, n3555, n3556, n3557, n3558, n3559, n3560, n3561, + n3562, n3563, n3564, n3565, n3566, n3567, n3568, n3569, n3570, n3571, + n3572, n3573, n3574, n3575, n3576, n3577, n3578, n3579, n3580, n3581, + n3582, n3583, n3584, n3585, n3586, n3587, n3588, n3589, n3590, n3591, + n3592, n3593, n3594, n3595, n3596, n3597, n3598, n3599, n3600, n3601, + n3602, n3603, n3604, n3605, n3606, n3607, n3608, n3609, n3610, n3611, + n3612, n3613, n3614, n3615, n3616, n3617, n3618, n3619, n3620, n3621, + n3622, n3623, n3624, n3625, n3626, n3627, n3628, n3629, n3630, n3631, + n3632, n3633, n3634, n3635, n3636, n3637, n3638, n3639, n3640, n3641, + n3642, n3643, n3644, n3645, n3646, n3647, n3648, n3649, n3650, n3651, + n3652, n3653, n3654, n3655, n3656, n3657, n3658, n3659, n3660, n3661, + n3662, n3663, n3664, n3665, n3666, n3667, n3668, n3669, n3670, n3671, + n3672, n3673, n3674, n3675, n3676, n3677, n3678, n3679, n3680, n3681, + n3682, n3683, n3684, n3685, n3686, n3687, n3688, n3689, n3690, n3691, + n3692, n3693, n3694, n3695, n3696, n3697, n3698, n3699, n3700, n3701, + n3702, n3703, n3704, n3705, n3706, n3707, n3708, n3709, n3710, n3711, + n3712, n3713, n3714, n3715, n3716, n3717, n3718, n3719, n3720, n3721, + n3722, n3723, n3724, n3725, n3726, n3727, n3728, n3729, n3730, n3731, + n3732, n3733, n3734, n3735, n3736, n3737, n3738, n3739, n3740, n3741, + n3742, n3743, n3744, n3745, n3746, n3747, n3748, n3749, n3750, n3751, + n3752, n3753, n3754, n3755, n3756, n3757, n3758, n3759, n3760, n3761, + n3762, n3763, n3764, n3765, n3766, n3767, n3768, n3769, n3770, n3771, + n3772, n3773, n3774, n3775, n3776, n3777, n3778, n3779, n3780, n3781, + n3782, n3783, n3784, n3785, n3786, n3787, n3788, n3789, n3790, n3791, + n3792, n3793, n3794, n3795, n3796, n3797, n3798, n3799, n3800, n3801, + n3802, n3803, n3804, n3805, n3806, n3807, n3808, n3809, n3810, n3811, + n3812, n3813, n3814, n3815, n3816, n3817, n3818, n3819, n3820, n3821, + n3822, n3823, n3824, n3825, n3826, n3827, n3828, n3829, n3830, n3831, + n3832, n3833, n3834, n3835, n3836, n3837, n3838, n3839, n3840, n3841, + n3842, n3843, n3844, n3845, n3846, n3847, n3848, n3849, n3850, n3851, + n3852, n3853, n3854, n3855, n3856, n3857, n3858, n3859, n3860, n3861, + n3862, n3863, n3864, n3865, n3866, n3867, n3868, n3869, n3870, n3871, + n3872, n3873, n3874, n3875, n3876, n3877, n3878, n3879, n3880, n3881, + n3882, n3883, n3884, n3885, n3886, n3887, n3888, n3889, n3890, n3891, + n3892, n3893, n3894, n3895, n3896, n3897, n3898, n3899, n3900, n3901, + n3902, n3903, n3904, n3905, n3906, n3907, n3908, n3909, n3910, n3911, + n3912, n3913, n3914, n3915, n3916, n3917, n3918, n3919, n3920, n3921, + n3922, n3923, n3924, n3925, n3926, n3927, n3928, n3929, n3930, n3931, + n3932, n3933, n3934, n3935, n3936, n3937, n3938, n3939, n3940, n3941, + n3942, n3943, n3944, n3945, n3946, n3947, n3948, n3949, n3950, n3951, + n3952, n3953, n3954, n3955, n3956, n3957, n3958, n3959, n3960, n3961, + n3962, n3963, n3964, n3965, n3966, n3967, n3968, n3969, n3970, n3971, + n3972, n3973, n3974, n3975, n3976, n3977, n3978, n3979, n3980, n3981, + n3982, n3983, n3984, n3985, n3986, n3987, n3988, n3989, n3990, n3991, + n3992, n3993, n3994, n3995, n3996, n3997, n3998, n3999, n4000, n4001, + n4002, n4003, n4004, n4005, n4006, n4007, n4008, n4009, n4010, n4011, + n4012, n4013, n4014, n4015, n4016, n4017, n4018, n4019, n4020, n4021, + n4022, n4023, n4024, n4025, n4026, n4027, n4028, n4029, n4030, n4031, + n4032, n4033, n4034, n4035, n4036, n4037, n4038, n4039, n4040, n4041, + n4042, n4043, n4044, n4045, n4046, n4047, n4048, n4049, n4050, n4051, + n4052, n4053, n4054, n4055, n4056, n4057, n4058, n4059, n4060, n4061, + n4062, n4063, n4064, n4065, n4066, n4067, n4068, n4069, n4070, n4071, + n4072, n4073, n4074, n4075, n4076, n4077, n4078, n4079, n4080, n4081, + n4082, n4083, n4084, n4085, n4086, n4087, n4088, n4089, n4090, n4091, + n4092, n4093, n4094, n4095, n4096, n4097, n4098, n4099, n4100, n4101, + n4102, n4103, n4104, n4105, n4106, n4107, n4108, n4109, n4110, n4111, + n4112, n4113, n4114, n4115, n4116, n4117, n4118, n4119, n4120, n4121, + n4122, n4123, n4124, n4125, n4126, n4127, n4128, n4129, n4130, n4131, + n4132, n4133, n4134, n4135, n4136, n4137, n4138, n4139, n4140, n4141, + n4142, n4143, n4144, n4145, n4146, n4147, n4148, n4149, n4150, n4151, + n4152, n4153, n4154, n4155, n4156, n4157, n4158, n4159, n4160, n4161, + n4162, n4163, n4164, n4165, n4166, n4167, n4168, n4169, n4170, n4171, + n4172, n4173, n4174, n4175, n4176, n4177, n4178, n4179, n4180, n4181, + n4182, n4183, n4184, n4185, n4186, n4187, n4188, n4189, n4190, n4191, + n4192, n4193, n4194, n4195, n4196, n4197, n4198, n4199, n4200, n4201, + n4202, n4203, n4204, n4205, n4206, n4207, n4208, n4209, n4210, n4211, + n4212, n4213, n4214, n4215, n4216, n4217, n4218, n4219, n4220, n4221, + n4222, n4223, n4224, n4225, n4226, n4227, n4228, n4229, n4230, n4231, + n4232, n4233, n4234, n4235, n4236, n4237, n4238, n4239, n4240, n4241, + n4242, n4243, n4244, n4245, n4246, n4247, n4248, n4249, n4250, n4251, + n4252, n4253, n4254, n4255, n4256, n4257, n4258, n4259, n4260, n4261, + n4262, n4263, n4264, n4265, n4266, n4267, n4268, n4269, n4270, n4271, + n4272, n4273, n4274, n4275, n4276, n4277, n4278, n4279, n4280, n4281, + n4282, n4283, n4284, n4285, n4286, n4287, n4288, n4289, n4290, n4291, + n4292, n4293, n4294, n4295, n4296, n4297, n4298, n4299, n4300, n4301, + n4302, n4303, n4304, n4305, n4306, n4307, n4308, n4309, n4310, n4311, + n4312, n4313, n4314, n4315, n4316, n4317, n4318, n4319, n4320, n4321, + n4322, n4323, n4324, n4325, n4326, n4327, n4328, n4329, n4330, n4331, + n4332, n4333, n4334, n4335, n4336, n4337, n4338, n4339, n4340, n4341, + n4342, n4343, n4344, n4345, n4346, n4347, n4348, n4349, n4350, n4351, + n4352, n4353, n4354, n4355, n4356, n4357, n4358, n4359, n4360, n4361, + n4362, n4363, n4364, n4365, n4366, n4367, n4368, n4369, n4370, n4371, + n4372, n4373, n4374, n4375, n4376, n4377, n4378, n4379, n4380, n4381, + n4382, n4383, n4384, n4385, n4386, n4387, n4388, n4389, n4390, n4391, + n4392, n4393, n4394, n4395, n4396, n4397, n4398, n4399, n4400, n4401, + n4402, n4403, n4404, n4405, n4406, n4407, n4408, n4409, n4410, n4411, + n4412, n4413, n4414, n4415, n4416, n4417, n4418, n4419, n4420, n4421, + n4422, n4423, n4424, n4425, n4426, n4427, n4428, n4429, n4430, n4431, + n4432, n4433, n4434, n4435, n4436, n4437, n4438, n4439, n4440, n4441, + n4442, n4443, n4444, n4445, n4446, n4447, n4448, n4449, n4450, n4451, + n4452, n4453, n4454, n4455, n4456, n4457, n4458, n4459, n4460, n4461, + n4462, n4463, n4464, n4465, n4466, n4467, n4468, n4469, n4470, n4471, + n4472, n4473, n4474, n4475, n4476, n4477, n4478, n4479, n4480, n4481, + n4482, n4483, n4484, n4485, n4486, n4487, n4488, n4489, n4490, n4491, + n4492, n4493, n4494, n4495, n4496, n4497, n4498, n4499, n4500, n4501, + n4502, n4503, n4504, n4505, n4506, n4507, n4508, n4509, n4510, n4511, + n4512, n4513, n4514, n4515, n4516, n4517, n4518, n4519, n4520, n4521, + n4522, n4523, n4524, n4525, n4526, n4527, n4528, n4529, n4530, n4531, + n4532, n4533, n4534, n4535, n4536, n4537, n4538, n4539, n4540, n4541, + n4542, n4543, n4544, n4545, n4546, n4547, n4548, n4549, n4550, n4551, + n4552, n4553, n4554, n4555, n4556, n4557, n4558, n4559, n4560, n4561, + n4562, n4563, n4564, n4565, n4566, n4567, n4568, n4569, n4570, n4571, + n4572, n4573, n4574, n4575, n4576, n4577, n4578, n4579, n4580, n4581, + n4582, n4583, n4584, n4585, n4586, n4587, n4588, n4589, n4590, n4591, + n4592, n4593, n4594, n4595, n4596, n4597, n4598, n4599, n4600, n4601, + n4602, n4603, n4604, n4605, n4606, n4607, n4608, n4609, n4610, n4611, + n4612, n4613, n4614, n4615, n4616, n4617, n4618, n4619, n4620, n4621, + n4622, n4623, n4624, n4625, n4626, n4627, n4628, n4629, n4630, n4631, + n4632, n4633, n4634, n4635, n4636, n4637, n4638, n4639, n4640, n4641, + n4642, n4643, n4644, n4645, n4646, n4647, n4648, n4649, n4650, n4651, + n4652, n4653, n4654, n4655, n4656, n4657, n4658, n4659, n4660, n4661, + n4662, n4663, n4664, n4665, n4666, n4667, n4668, n4669, n4670, n4671, + n4672, n4673, n4674, n4675, n4676, n4677, n4678, n4679, n4680, n4681, + n4682, n4683, n4684, n4685, n4686, n4687, n4688, n4689, n4690, n4691, + n4692, n4693, n4694, n4695, n4696, n4697, n4698, n4699, n4700, n4701, + n4702, n4703, n4704, n4705, n4706, n4707, n4708, n4709, n4710, n4711, + n4712, n4713, n4714, n4715, n4716, n4717, n4718, n4719, n4720, n4721, + n4722, n4723, n4724, n4725, n4726, n4727, n4728, n4729, n4730, n4731, + n4732, n4733, n4734, n4735, n4736, n4737, n4738, n4739, n4740, n4741, + n4742, n4743, n4744, n4745, n4746, n4747, n4748, n4749, n4750, n4751, + n4752, n4753, n4754, n4755, n4756, n4757, n4758, n4759, n4760, n4761, + n4762, n4763, n4764, n4765, n4766, n4767, n4768, n4769, n4770, n4771, + n4772, n4773, n4774, n4775, n4776, n4777, n4778, n4779, n4780, n4781, + n4782, n4783, n4784, n4785, n4786, n4787, n4788, n4789, n4790, n4791, + n4792, n4793, n4794, n4795, n4796, n4797, n4798, n4799, n4800, n4801, + n4802, n4803, n4804, n4805, n4806, n4807, n4808, n4809, n4810, n4811, + n4812, n4813, n4814, n4815, n4816, n4817, n4818, n4819, n4820, n4821, + n4822, n4823, n4824, n4825, n4826, n4827, n4828, n4829, n4830, n4831, + n4832, n4833, n4834, n4835, n4836, n4837, n4838, n4839, n4840, n4841, + n4842, n4843, n4844, n4845, n4846, n4847, n4848, n4849, n4850, n4851, + n4852, n4853, n4854, n4855, n4856, n4857, n4858, n4859, n4860, n4861, + n4862, n4863, n4864, n4865, n4866, n4867, n4868, n4869, n4870, n4871, + n4872, n4873, n4874, n4875, n4876, n4877, n4878, n4879, n4880, n4881, + n4882, n4883, n4884, n4885, n4886, n4887, n4888, n4889, n4890, n4891, + n4892, n4893, n4894, n4895, n4896, n4897, n4898, n4899, n4900, n4901, + n4902, n4903, n4904, n4905, n4906, n4907, n4908, n4909, n4910, n4911, + n4912, n4913, n4914, n4915, n4916, n4917, n4918, n4919, n4920, n4921, + n4922, n4923, n4924, n4925, n4926, n4927, n4928, n4929, n4930, n4931, + n4932, n4933, n4934, n4935, n4936, n4937, n4938, n4939, n4940, n4941, + n4942, n4943, n4944, n4945, n4946, n4947, n4948, n4949, n4950, n4951, + n4952, n4953, n4954, n4955, n4956, n4957, n4958, n4959, n4960, n4961, + n4962, n4963, n4964, n4965, n4966, n4967, n4968, n4969, n4970, n4971, + n4972, n4973, n4974, n4975, n4976, n4977, n4978, n4979, n4980, n4981, + n4982, n4983, n4984, n4985, n4986, n4987, n4988, n4989, n4990, n4991, + n4992, n4993, n4994, n4995, n4996, n4997, n4998, n4999, n5000, n5001, + n5002, n5003, n5004, n5005, n5006, n5007, n5008, n5009, n5010, n5011, + n5012, n5013, n5014, n5015, n5016, n5017, n5018, n5019, n5020, n5021, + n5022, n5023, n5024, n5025, n5026, n5027, n5028, n5029, n5030, n5031, + n5032, n5033, n5034, n5035, n5036, n5037, n5038, n5039, n5040, n5041, + n5042, n5043, n5044, n5045, n5046, n5047, n5048, n5049, n5050, n5051, + n5052, n5053, n5054, n5055, n5056, n5057, n5058, n5059, n5060, n5061, + n5062, n5063, n5064, n5065, n5066, n5067, n5068, n5069, n5070, n5071, + n5072, n5073, n5074, n5075, n5076, n5077, n5078, n5079, n5080, n5081, + n5082, n5083, n5084, n5085, n5086, n5087, n5088, n5089, n5090, n5091, + n5092, n5093, n5094, n5095, n5096, n5097, n5098, n5099, n5100, n5101, + n5102, n5103, n5104, n5105, n5106, n5107, n5108, n5109, n5110, n5111, + n5112, n5113, n5114, n5115, n5116, n5117, n5118, n5119, n5120, n5121, + n5122, n5123, n5124, n5125, n5126, n5127, n5128, n5129, n5130, n5131, + n5132, n5133, n5134, n5135, n5136, n5137, n5138, n5139, n5140, n5141, + n5142, n5143, n5144, n5145, n5146, n5147, n5148, n5149, n5150, n5151, + n5152, n5153, n5154, n5155, n5156, n5157, n5158, n5159, n5160, n5161, + n5162, n5163, n5164, n5165, n5166, n5167, n5168, n5169, n5170, n5171, + n5172, n5173, n5174, n5175, n5176, n5177, n5178, n5179, n5180, n5181, + n5182, n5183, n5184, n5185, n5186, n5187, n5188, n5189, n5190, n5191, + n5192, n5193, n5194, n5195, n5196, n5197, n5198, n5199, n5200, n5201, + n5202, n5203, n5204, n5205, n5206, n5207, n5208, n5209, n5210, n5211, + n5212, n5213, n5214, n5215, n5216, n5217, n5218, n5219, n5220, n5221, + n5222, n5223, n5224, n5225, n5226, n5227, n5228, n5229, n5230, n5231, + n5232, n5233, n5234, n5235, n5236, n5237, n5238, n5239, n5240, n5241, + n5242, n5243, n5244, n5245, n5246, n5247, n5248, n5249, n5250, n5251, + n5252, n5253, n5254, n5255, n5256, n5257, n5258, n5259, n5260, n5261, + n5262, n5263, n5264, n5265, n5266, n5267, n5268, n5269, n5270, n5271, + n5272, n5273, n5274, n5275, n5276, n5277, n5278, n5279, n5280, n5281, + n5282, n5283, n5284, n5285, n5286, n5287, n5288, n5289, n5290, n5291, + n5292, n5293, n5294, n5295, n5296, n5297, n5298, n5299, n5300, n5301, + n5302, n5303, n5304, n5305, n5306, n5307, n5308, n5309, n5310, n5311, + n5312, n5313, n5314, n5315, n5316, n5317, n5318, n5319, n5320, n5321, + n5322, n5323, n5324, n5325, n5326, n5327, n5328, n5329, n5330, n5331, + n5332, n5333, n5334, n5335, n5336, n5337, n5338, n5339, n5340, n5341, + n5342, n5343, n5344, n5345, n5346, n5347, n5348, n5349, n5350, n5351, + n5352, n5353, n5354, n5355, n5356, n5357, n5358, n5359, n5360, n5361, + n5362, n5363, n5364, n5365, n5366, n5367, n5368, n5369, n5370, n5371, + n5372, n5373, n5374, n5375, n5376, n5377, n5378, n5379, n5380, n5381, + n5382, n5383, n5384, n5385, n5386, n5387, n5388, n5389, n5390, n5391, + n5392, n5393, n5394, n5395, n5396, n5397, n5398, n5399, n5400, n5401, + n5402, n5403, n5404, n5405, n5406, n5407, n5408, n5409, n5410, n5411, + n5412, n5413, n5414, n5415, n5416, n5417, n5418, n5419, n5420, n5421, + n5422, n5423, n5424, n5425, n5426, n5427, n5428, n5429, n5430, n5431, + n5432, n5433, n5434, n5435, n5436, n5437, n5438, n5439, n5440, n5441, + n5442, n5443, n5444, n5445, n5446, n5447, n5448, n5449, n5450, n5451, + n5452, n5453, n5454, n5455, n5456, n5457, n5458, n5459, n5460, n5461, + n5462, n5463, n5464, n5465, n5466, n5467, n5468, n5469, n5470, n5471, + n5472, n5473, n5474, n5475, n5476, n5477, n5478, n5479, n5480, n5481, + n5482, n5483, n5484, n5485, n5486, n5487, n5488, n5489, n5490, n5491, + n5492, n5493, n5494, n5495, n5496, n5497, n5498, n5499, n5500, n5501, + n5502, n5503, n5504, n5505, n5506, n5507, n5508, n5509, n5510, n5511, + n5512, n5513, n5514, n5515, n5516, n5517, n5518, n5519, n5520, n5521, + n5522, n5523, n5524, n5525, n5526, n5527, n5528, n5529, n5530, n5531, + n5532, n5533, n5534, n5535, n5536, n5537, n5538, n5539, n5540, n5541, + n5542, n5543, n5544, n5545, n5546, n5547, n5548, n5549, n5550, n5551, + n5552, n5553, n5554, n5555, n5556, n5557, n5558, n5559, n5560, n5561, + n5562, n5563, n5564, n5565, n5566, n5567, n5568, n5569, n5570, n5571, + n5572, n5573, n5574, n5575, n5576, n5577, n5578, n5579, n5580, n5581, + n5582, n5583, n5584, n5585, n5586, n5587, n5588, n5589, n5590, n5591, + n5592, n5593, n5594, n5595, n5596, n5597, n5598, n5599, n5600, n5601, + n5602, n5603, n5604, n5605, n5606, n5607, n5608, n5609, n5610, n5611, + n5612, n5613, n5614, n5615, n5616, n5617, n5618, n5619, n5620, n5621, + n5622, n5623, n5624, n5625, n5626, n5627, n5628, n5629, n5630, n5631, + n5632, n5633, n5634, n5635, n5636, n5637, n5638, n5639, n5640, n5641, + n5642, n5643, n5644, n5645, n5646, n5647, n5648, n5649, n5650, n5651, + n5652, n5653, n5654, n5655, n5656, n5657, n5658, n5659, n5660, n5661, + n5662, n5663, n5664, n5665, n5666, n5667, n5668, n5669, n5670, n5671, + n5672, n5673, n5674, n5675, n5676, n5677, n5678, n5679, n5680, n5681, + n5682, n5683, n5684, n5685, n5686, n5687, n5688, n5689, n5690, n5691, + n5692, n5693, n5694, n5695, n5696, n5697, n5698, n5699, n5700, n5701, + n5702, n5703, n5704, n5705, n5706, n5707, n5708, n5709, n5710, n5711, + n5712, n5713, n5714, n5715, n5716, n5717, n5718, n5719, n5720, n5721, + n5722, n5723, n5724, n5725, n5726, n5727, n5728, n5729, n5730, n5731, + n5732, n5733, n5734, n5735, n5736, n5737, n5738, n5739, n5740, n5741, + n5742, n5743, n5744, n5745, n5746, n5747, n5748, n5749, n5750, n5751, + n5752, n5753, n5754, n5755, n5756, n5757, n5758, n5759, n5760, n5761, + n5762, n5763, n5764, n5765, n5766, n5767, n5768, n5769, n5770, n5771, + n5772, n5773, n5774, n5775, n5776, n5777, n5778, n5779, n5780, n5781, + n5782, n5783, n5784, n5785, n5786, n5787, n5788, n5789, n5790, n5791, + n5792, n5793, n5794, n5795, n5796, n5797, n5798, n5799, n5800, n5801, + n5802, n5803, n5804, n5805, n5806, n5807, n5808, n5809, n5810, n5811, + n5812, n5813, n5814, n5815, n5816, n5817, n5818, n5819, n5820, n5821, + n5822, n5823, n5824, n5825, n5826, n5827, n5828, n5829, n5830, n5831, + n5832, n5833, n5834, n5835, n5836, n5837, n5838, n5839, n5840, n5841, + n5842, n5843, n5844, n5845, n5846, n5847, n5848, n5849, n5850, n5851, + n5852, n5853, n5854, n5855, n5856, n5857, n5858, n5859, n5860, n5861, + n5862, n5863, n5864, n5865, n5866, n5867, n5868, n5869, n5870, n5871, + n5872, n5873, n5874, n5875, n5876, n5877, n5878, n5879, n5880, n5881, + n5882, n5883, n5884, n5885, n5886, n5887, n5888, n5889, n5890, n5891, + n5892, n5893, n5894, n5895, n5896, n5897, n5898, n5899, n5900, n5901, + n5902, n5903, n5904, n5905, n5906, n5907, n5908, n5909, n5910, n5911, + n5912, n5913, n5914, n5915, n5916, n5917, n5918, n5919, n5920, n5921, + n5922, n5923, n5924, n5925, n5926, n5927, n5928, n5929, n5930, n5931, + n5932, n5933, n5934, n5935, n5936, n5937, n5938, n5939, n5940, n5941, + n5942, n5943, n5944, n5945, n5946, n5947, n5948, n5949, n5950, n5951, + n5952, n5953, n5954, n5955, n5956, n5957, n5958, n5959, n5960, n5961, + n5962, n5963, n5964, n5965, n5966, n5967, n5968, n5969, n5970, n5971, + n5972, n5973, n5974, n5975, n5976, n5977, n5978, n5979, n5980, n5981, + n5982, n5983, n5984, n5985, n5986, n5987, n5988, n5989, n5990, n5991, + n5992, n5993, n5994, n5995, n5996, n5997, n5998, n5999, n6000, n6001, + n6002, n6003, n6004, n6005, n6006, n6007, n6008, n6009, n6010, n6011, + n6012, n6013, n6014, n6015, n6016, n6017, n6018, n6019, n6020, n6021, + n6022, n6023, n6024, n6025, n6026, n6027, n6028, n6029, n6030, n6031, + n6032, n6033, n6034, n6035, n6036, n6037, n6038, n6039, n6040, n6041, + n6042, n6043, n6044, n6045, n6046, n6047, n6048, n6049, n6050, n6051, + n6052, n6053, n6054, n6055, n6056, n6057, n6058, n6059, n6060, n6061, + n6062, n6063, n6064, n6065, n6066, n6067, n6068, n6069, n6070, n6071, + n6072, n6073, n6074, n6075, n6076, n6077, n6078, n6079, n6080, n6081, + n6082, n6083, n6084, n6085, n6086, n6087, n6088, n6089, n6090, n6091, + n6092, n6093, n6094, n6095, n6096, n6097, n6098, n6099, n6100, n6101, + n6102, n6103, n6104, n6105, n6106, n6107, n6108, n6109, n6110, n6111, + n6112, n6113, n6114, n6115, n6116, n6117, n6118, n6119, n6120, n6121, + n6122, n6123, n6124, n6125, n6126, n6127, n6128, n6129, n6130, n6131, + n6132, n6133, n6134, n6135, n6136, n6137, n6138, n6139, n6140, n6141, + n6142, n6143, n6144, n6145, n6146, n6147, n6148, n6149, n6150, n6151, + n6152, n6153, n6154, n6155, n6156, n6157, n6158, n6159, n6160, n6161, + n6162, n6163, n6164, n6165, n6166, n6167, n6168, n6169, n6170, n6171, + n6172, n6173, n6174, n6175, n6176, n6177, n6178, n6179, n6180, n6181, + n6182, n6183, n6184, n6185, n6186, n6187, n6188, n6189, n6190, n6191, + n6192, n6193, n6194, n6195, n6196, n6197, n6198, n6199, n6200, n6201, + n6202, n6203, n6204, n6205, n6206, n6207, n6208, n6209, n6210, n6211, + n6212, n6213, n6214, n6215, n6216, n6217, n6218, n6219, n6220, n6221, + n6222, n6223, n6224, n6225, n6226, n6227, n6228, n6229, n6230, n6231, + n6232, n6233, n6234, n6235, n6236, n6237, n6238, n6239, n6240, n6241, + n6242, n6243, n6244, n6245, n6246, n6247, n6248, n6249, n6250, n6251, + n6252, n6253, n6254, n6255, n6256, n6257, n6258, n6259, n6260, n6261, + n6262, n6263, n6264, n6265, n6266, n6267, n6268, n6269, n6270, n6271, + n6272, n6273, n6274, n6275, n6276, n6277, n6278, n6279, n6280, n6281, + n6282, n6283, n6284, n6285, n6286, n6287, n6288, n6289, n6290, n6291, + n6292, n6293, n6294, n6295, n6296, n6297, n6298, n6299, n6300, n6301, + n6302, n6303, n6304, n6305, n6306, n6307, n6308, n6309, n6310, n6311, + n6312, n6313, n6314, n6315, n6316, n6317, n6318, n6319, n6320, n6321, + n6322, n6323, n6324, n6325, n6326, n6327, n6328, n6329, n6330, n6331, + n6332, n6333, n6334, n6335, n6336, n6337, n6338, n6339, n6340, n6341, + n6342, n6343, n6344, n6345, n6346, n6347, n6348, n6349, n6350, n6351, + n6352, n6353, n6354, n6355, n6356, n6357, n6358, n6359, n6360, n6361, + n6362, n6363, n6364, n6365, n6366, n6367, n6368, n6369, n6370, n6371, + n6372, n6373, n6374, n6375, n6376, n6377, n6378, n6379, n6380, n6381, + n6382, n6383, n6384, n6385, n6386, n6387, n6388, n6389, n6390, n6391, + n6392, n6393, n6394, n6395, n6396, n6397, n6398, n6399, n6400, n6401, + n6402, n6403, n6404, n6405; + +assign po001 = pi187; + +assign po015 = po003; + +assign po004 = pi106; + +assign po009 = pi136; + +assign po010 = pi022; + +assign po011 = pi112; + +assign po005 = po012; + +assign po013 = pi062; + +assign po014 = pi123; + +assign po101 = po023; + +assign po067 = po023; + +assign po066 = po023; + +assign po023 = pi119; + +assign po024 = pi152; + +assign po025 = pi125; + +assign po027 = pi102; + +assign po028 = pi031; + +assign po031 = pi155; + +assign po065 = po034; + +assign po035 = pi182; + +assign po036 = pi023; + +assign po038 = pi071; + +assign po039 = pi015; + +assign po040 = pi132; + +assign po044 = pi044; + +assign po052 = pi048; + +assign po057 = pi117; + +assign po059 = pi091; + +assign po063 = pi000; + +assign po064 = pi194; + +assign po069 = pi147; + +assign po070 = pi002; + +assign po071 = pi080; + +assign po072 = pi188; + +assign po018 = po074; + +assign po021 = po074; + +assign po079 = pi084; + +assign po082 = pi144; + +assign po084 = pi199; + +assign po085 = pi066; + +assign po091 = pi008; + +assign po092 = pi154; + +assign po099 = pi042; + +assign po102 = pi179; + +assign po103 = pi145; + +assign po104 = pi127; + +assign po106 = pi105; + +assign po107 = pi029; + +assign po020 = po041; + +assign po032 = po007; + +assign po089 = po076; + +assign po054 = po076; + + OR2 U2865 ( .A(n2822), .B(n2823), .Z(po100)); + AN2 U2866 ( .A(n2824), .B(pi192), .Z(n2823)); + OR2 U2867 ( .A(n2825), .B(n2826), .Z(n2824)); + AN2 U2868 ( .A(n2827), .B(n2828), .Z(n2826)); + IV2 U2869 ( .A(n2829), .Z(n2825)); + OR2 U2870 ( .A(n2828), .B(n2827), .Z(n2829)); + OR2 U2871 ( .A(n2830), .B(n2831), .Z(n2827)); + AN2 U2872 ( .A(n2832), .B(n2833), .Z(n2831)); + AN2 U2873 ( .A(n2834), .B(n2835), .Z(n2830)); + AN2 U2874 ( .A(n2836), .B(n2837), .Z(n2822)); + OR2 U2875 ( .A(n2838), .B(n2839), .Z(n2836)); + AN2 U2876 ( .A(n2840), .B(n2828), .Z(n2839)); + IV2 U2877 ( .A(n2841), .Z(n2838)); + OR2 U2878 ( .A(n2828), .B(n2840), .Z(n2841)); + OR2 U2879 ( .A(n2842), .B(n2843), .Z(n2840)); + AN2 U2880 ( .A(n2844), .B(n2845), .Z(n2843)); + AN2 U2881 ( .A(n2846), .B(n2847), .Z(n2842)); + AN2 U2882 ( .A(n2848), .B(n2849), .Z(n2828)); + IV2 U2883 ( .A(n2850), .Z(n2849)); + AN2 U2884 ( .A(n2851), .B(n2852), .Z(n2850)); + OR2 U2885 ( .A(n2852), .B(n2851), .Z(n2848)); + OR2 U2886 ( .A(n2853), .B(n2854), .Z(n2851)); + AN2 U2887 ( .A(n2855), .B(n2856), .Z(n2854)); + IV2 U2888 ( .A(n2857), .Z(n2853)); + OR2 U2889 ( .A(n2856), .B(n2855), .Z(n2857)); + IV2 U2890 ( .A(n2858), .Z(n2855)); + OR2 U2891 ( .A(n2859), .B(n2860), .Z(n2858)); + AN2 U2892 ( .A(n2861), .B(n2862), .Z(n2859)); + OR2 U2893 ( .A(n2863), .B(n2864), .Z(n2856)); + OR2 U2894 ( .A(n2865), .B(n2866), .Z(n2864)); + AN2 U2895 ( .A(pi192), .B(n2867), .Z(n2866)); + OR2 U2896 ( .A(n2868), .B(n2869), .Z(n2867)); + OR2 U2897 ( .A(n2870), .B(n2871), .Z(n2869)); + AN2 U2898 ( .A(n2872), .B(n2873), .Z(n2871)); + AN2 U2899 ( .A(n2862), .B(n2874), .Z(n2872)); + OR2 U2900 ( .A(n2875), .B(n2876), .Z(n2874)); + AN2 U2901 ( .A(n2877), .B(n2878), .Z(n2875)); + AN2 U2902 ( .A(n2879), .B(n2880), .Z(n2870)); + AN2 U2903 ( .A(n2881), .B(n2882), .Z(n2868)); + OR2 U2904 ( .A(n2883), .B(n2884), .Z(n2881)); + AN2 U2905 ( .A(n2885), .B(n2886), .Z(n2884)); + AN2 U2906 ( .A(n2879), .B(n2887), .Z(n2883)); + IV2 U2907 ( .A(n2873), .Z(n2879)); + OR2 U2908 ( .A(n2888), .B(n2889), .Z(n2873)); + AN2 U2909 ( .A(n2890), .B(n2891), .Z(n2889)); + AN2 U2910 ( .A(n2892), .B(n2886), .Z(n2888)); + AN2 U2911 ( .A(n2893), .B(n2837), .Z(n2865)); + OR2 U2912 ( .A(n2894), .B(n2895), .Z(n2893)); + OR2 U2913 ( .A(n2896), .B(n2897), .Z(n2895)); + OR2 U2914 ( .A(n2898), .B(n2899), .Z(n2897)); + AN2 U2915 ( .A(n2900), .B(n2901), .Z(n2899)); + AN2 U2916 ( .A(n2902), .B(n2903), .Z(n2900)); + OR2 U2917 ( .A(n2904), .B(n2905), .Z(n2903)); + OR2 U2918 ( .A(n2906), .B(n2907), .Z(n2905)); + AN2 U2919 ( .A(n2890), .B(n2908), .Z(n2907)); + AN2 U2920 ( .A(n2909), .B(n2886), .Z(n2906)); + AN2 U2921 ( .A(n2910), .B(pi082), .Z(n2909)); + AN2 U2922 ( .A(pi200), .B(n2911), .Z(n2898)); + OR2 U2923 ( .A(n2912), .B(n2913), .Z(n2911)); + OR2 U2924 ( .A(n2914), .B(n2915), .Z(n2913)); + AN2 U2925 ( .A(n2916), .B(n2890), .Z(n2915)); + AN2 U2926 ( .A(n2910), .B(n2917), .Z(n2916)); + OR2 U2927 ( .A(n2918), .B(n2919), .Z(n2917)); + AN2 U2928 ( .A(n2920), .B(n2886), .Z(n2914)); + OR2 U2929 ( .A(n2921), .B(n2922), .Z(n2920)); + OR2 U2930 ( .A(n2923), .B(n2924), .Z(n2922)); + AN2 U2931 ( .A(n2918), .B(n2860), .Z(n2924)); + AN2 U2932 ( .A(n2925), .B(n2926), .Z(n2923)); + OR2 U2933 ( .A(n2927), .B(n2928), .Z(n2926)); + AN2 U2934 ( .A(n2844), .B(n2929), .Z(n2928)); + AN2 U2935 ( .A(n2930), .B(n2931), .Z(n2927)); + OR2 U2936 ( .A(n2932), .B(n2933), .Z(n2921)); + AN2 U2937 ( .A(n2934), .B(n2935), .Z(n2933)); + AN2 U2938 ( .A(n2936), .B(n2910), .Z(n2934)); + AN2 U2939 ( .A(n2937), .B(n2938), .Z(n2932)); + AN2 U2940 ( .A(n2929), .B(n2939), .Z(n2937)); + AN2 U2941 ( .A(n2935), .B(n2940), .Z(n2912)); + OR2 U2942 ( .A(n2904), .B(n2941), .Z(n2940)); + AN2 U2943 ( .A(n2890), .B(n2942), .Z(n2941)); + AN2 U2944 ( .A(n2943), .B(n2944), .Z(n2942)); + OR2 U2945 ( .A(n2945), .B(n2946), .Z(n2944)); + IV2 U2946 ( .A(n2910), .Z(n2945)); + OR2 U2947 ( .A(n2936), .B(n2947), .Z(n2943)); + IV2 U2948 ( .A(n2948), .Z(n2904)); + OR2 U2949 ( .A(n2949), .B(n2939), .Z(n2948)); + AN2 U2950 ( .A(n2950), .B(n2951), .Z(n2949)); + OR2 U2951 ( .A(n2890), .B(n2947), .Z(n2951)); + OR2 U2952 ( .A(n2929), .B(n2886), .Z(n2950)); + AN2 U2953 ( .A(n2952), .B(n2953), .Z(n2896)); + AN2 U2954 ( .A(n2954), .B(n2955), .Z(n2953)); + OR2 U2955 ( .A(n2956), .B(n2957), .Z(n2955)); + AN2 U2956 ( .A(n2890), .B(n2958), .Z(n2956)); + OR2 U2957 ( .A(n2959), .B(n2960), .Z(n2958)); + OR2 U2958 ( .A(pi082), .B(n2961), .Z(n2954)); + AN2 U2959 ( .A(n2901), .B(n2886), .Z(n2961)); + AN2 U2960 ( .A(n2910), .B(n2962), .Z(n2952)); + AN2 U2961 ( .A(n2947), .B(n2862), .Z(n2910)); + OR2 U2962 ( .A(n2963), .B(n2964), .Z(n2894)); + AN2 U2963 ( .A(n2965), .B(n2890), .Z(n2964)); + AN2 U2964 ( .A(n2929), .B(n2966), .Z(n2965)); + OR2 U2965 ( .A(n2967), .B(n2968), .Z(n2966)); + AN2 U2966 ( .A(n2969), .B(n2901), .Z(n2967)); + OR2 U2967 ( .A(n2970), .B(n2971), .Z(n2969)); + OR2 U2968 ( .A(n2972), .B(n2973), .Z(n2971)); + AN2 U2969 ( .A(n2902), .B(n2962), .Z(n2973)); + AN2 U2970 ( .A(n2974), .B(n2957), .Z(n2972)); + AN2 U2971 ( .A(pi082), .B(po031), .Z(n2970)); + AN2 U2972 ( .A(n2975), .B(n2886), .Z(n2963)); + OR2 U2973 ( .A(n2976), .B(n2977), .Z(n2975)); + AN2 U2974 ( .A(n2968), .B(n2947), .Z(n2977)); + AN2 U2975 ( .A(n2978), .B(n2979), .Z(n2968)); + OR2 U2976 ( .A(n2980), .B(n2981), .Z(n2979)); + AN2 U2977 ( .A(n2982), .B(n2931), .Z(n2980)); + AN2 U2978 ( .A(n2983), .B(n2929), .Z(n2976)); + AN2 U2979 ( .A(n2984), .B(n2936), .Z(n2983)); + AN2 U2980 ( .A(n2974), .B(n2901), .Z(n2984)); + OR2 U2981 ( .A(n2985), .B(n2986), .Z(n2863)); + AN2 U2982 ( .A(n2987), .B(n2890), .Z(n2986)); + AN2 U2983 ( .A(n2988), .B(n2989), .Z(n2987)); + AN2 U2984 ( .A(n2990), .B(n2962), .Z(n2989)); + AN2 U2985 ( .A(n2862), .B(n2877), .Z(n2988)); + AN2 U2986 ( .A(n2991), .B(n2886), .Z(n2985)); + OR2 U2987 ( .A(n2992), .B(n2993), .Z(n2991)); + AN2 U2988 ( .A(n2994), .B(n2995), .Z(n2993)); + AN2 U2989 ( .A(n2990), .B(n2901), .Z(n2995)); + AN2 U2990 ( .A(n2996), .B(n2974), .Z(n2994)); + OR2 U2991 ( .A(po031), .B(n2930), .Z(n2996)); + AN2 U2992 ( .A(n2997), .B(n2860), .Z(n2992)); + AN2 U2993 ( .A(n2998), .B(n2930), .Z(n2860)); + AN2 U2994 ( .A(n2877), .B(n2999), .Z(n2997)); + IV2 U2995 ( .A(n2882), .Z(n2877)); + AN2 U2996 ( .A(n3000), .B(n3001), .Z(n2852)); + OR2 U2997 ( .A(n3002), .B(n2925), .Z(n3001)); + OR2 U2998 ( .A(n3003), .B(n3004), .Z(n3000)); + IV2 U2999 ( .A(n3002), .Z(n3004)); + OR2 U3000 ( .A(n3005), .B(n3006), .Z(n3002)); + AN2 U3001 ( .A(n3007), .B(n3008), .Z(n3006)); + OR2 U3002 ( .A(n3009), .B(n3010), .Z(n3008)); + AN2 U3003 ( .A(n3011), .B(n3012), .Z(n3009)); + AN2 U3004 ( .A(n3013), .B(n3014), .Z(n3007)); + OR2 U3005 ( .A(n3015), .B(n3016), .Z(n3014)); + IV2 U3006 ( .A(n3017), .Z(n3016)); + OR2 U3007 ( .A(n3017), .B(n3018), .Z(n3013)); + OR2 U3008 ( .A(n3019), .B(n3020), .Z(n3017)); + AN2 U3009 ( .A(n3021), .B(n3022), .Z(n3020)); + OR2 U3010 ( .A(n3023), .B(n3024), .Z(n3022)); + OR2 U3011 ( .A(n3025), .B(n3026), .Z(n3024)); + OR2 U3012 ( .A(n3027), .B(n3028), .Z(n3026)); + AN2 U3013 ( .A(po010), .B(n3029), .Z(n3028)); + AN2 U3014 ( .A(n3030), .B(pi192), .Z(n3027)); + AN2 U3015 ( .A(n3031), .B(n3032), .Z(n3030)); + OR2 U3016 ( .A(n3033), .B(n3034), .Z(n3032)); + AN2 U3017 ( .A(n3035), .B(n3036), .Z(n3034)); + AN2 U3018 ( .A(n3015), .B(n3037), .Z(n3035)); + OR2 U3019 ( .A(n3038), .B(n3039), .Z(n3031)); + OR2 U3020 ( .A(n3040), .B(n3041), .Z(n3039)); + AN2 U3021 ( .A(po010), .B(n3042), .Z(n3040)); + OR2 U3022 ( .A(n3043), .B(n3044), .Z(n3025)); + AN2 U3023 ( .A(n3015), .B(n3045), .Z(n3044)); + OR2 U3024 ( .A(n3046), .B(n3047), .Z(n3045)); + AN2 U3025 ( .A(n3048), .B(n3049), .Z(n3047)); + OR2 U3026 ( .A(n3050), .B(n3051), .Z(n3048)); + AN2 U3027 ( .A(n3052), .B(po070), .Z(n3051)); + AN2 U3028 ( .A(n3053), .B(po099), .Z(n3050)); + AN2 U3029 ( .A(n3054), .B(n3055), .Z(n3046)); + AN2 U3030 ( .A(n3018), .B(n3056), .Z(n3043)); + OR2 U3031 ( .A(n3057), .B(n3058), .Z(n3056)); + OR2 U3032 ( .A(n3059), .B(n3060), .Z(n3058)); + AN2 U3033 ( .A(n3061), .B(n3042), .Z(n3060)); + AN2 U3034 ( .A(n3062), .B(n3063), .Z(n3059)); + AN2 U3035 ( .A(n3064), .B(n3049), .Z(n3062)); + AN2 U3036 ( .A(n3065), .B(n3066), .Z(n3057)); + OR2 U3037 ( .A(n3067), .B(n3068), .Z(n3023)); + OR2 U3038 ( .A(n3069), .B(n3070), .Z(n3068)); + AN2 U3039 ( .A(n3071), .B(n3072), .Z(n3070)); + AN2 U3040 ( .A(n3053), .B(n3073), .Z(n3069)); + OR2 U3041 ( .A(n3074), .B(n3075), .Z(n3067)); + AN2 U3042 ( .A(n3076), .B(n3077), .Z(n3075)); + OR2 U3043 ( .A(n3078), .B(n3079), .Z(n3077)); + AN2 U3044 ( .A(n3080), .B(n3066), .Z(n3078)); + AN2 U3045 ( .A(n3081), .B(n3061), .Z(n3074)); + AN2 U3046 ( .A(n3082), .B(n3038), .Z(n3081)); + AN2 U3047 ( .A(n3083), .B(n3084), .Z(n3019)); + OR2 U3048 ( .A(n3085), .B(n3086), .Z(n3084)); + OR2 U3049 ( .A(n3087), .B(n3088), .Z(n3086)); + OR2 U3050 ( .A(n3089), .B(n3090), .Z(n3088)); + AN2 U3051 ( .A(n3091), .B(n3049), .Z(n3089)); + OR2 U3052 ( .A(n3092), .B(n3093), .Z(n3087)); + AN2 U3053 ( .A(n3015), .B(n3094), .Z(n3093)); + OR2 U3054 ( .A(n3095), .B(n3096), .Z(n3094)); + OR2 U3055 ( .A(n3097), .B(n3098), .Z(n3096)); + AN2 U3056 ( .A(n3099), .B(n3100), .Z(n3098)); + AN2 U3057 ( .A(po010), .B(po070), .Z(n3099)); + AN2 U3058 ( .A(n3101), .B(pi192), .Z(n3097)); + AN2 U3059 ( .A(n3041), .B(n3038), .Z(n3101)); + OR2 U3060 ( .A(n3102), .B(n3103), .Z(n3041)); + AN2 U3061 ( .A(n3104), .B(pi166), .Z(n3103)); + AN2 U3062 ( .A(n3037), .B(n3049), .Z(n3104)); + AN2 U3063 ( .A(n3105), .B(n3106), .Z(n3102)); + OR2 U3064 ( .A(n3107), .B(n3042), .Z(n3105)); + AN2 U3065 ( .A(po010), .B(n3108), .Z(n3107)); + AN2 U3066 ( .A(n3079), .B(n3109), .Z(n3095)); + OR2 U3067 ( .A(n3110), .B(n3111), .Z(n3079)); + AN2 U3068 ( .A(n3071), .B(n3112), .Z(n3111)); + AN2 U3069 ( .A(n3065), .B(n3113), .Z(n3110)); + OR2 U3070 ( .A(n3114), .B(n3066), .Z(n3113)); + AN2 U3071 ( .A(po010), .B(n3115), .Z(n3114)); + AN2 U3072 ( .A(n3018), .B(n3116), .Z(n3092)); + OR2 U3073 ( .A(n3117), .B(n3118), .Z(n3116)); + AN2 U3074 ( .A(n3065), .B(n3119), .Z(n3118)); + AN2 U3075 ( .A(n3063), .B(n3120), .Z(n3117)); + OR2 U3076 ( .A(n3121), .B(n3122), .Z(n3085)); + OR2 U3077 ( .A(n3123), .B(n3124), .Z(n3122)); + AN2 U3078 ( .A(n3125), .B(n3055), .Z(n3124)); + AN2 U3079 ( .A(n3076), .B(n3112), .Z(n3125)); + AN2 U3080 ( .A(n3126), .B(n3127), .Z(n3123)); + AN2 U3081 ( .A(n3033), .B(n3037), .Z(n3126)); + AN2 U3082 ( .A(n3080), .B(n3072), .Z(n3121)); + AN2 U3083 ( .A(n3119), .B(n3018), .Z(n3072)); + AN2 U3084 ( .A(n3128), .B(n3129), .Z(n3005)); + OR2 U3085 ( .A(n3130), .B(n3131), .Z(n3129)); + OR2 U3086 ( .A(n3132), .B(n3133), .Z(n3131)); + AN2 U3087 ( .A(n3134), .B(pi192), .Z(n3133)); + AN2 U3088 ( .A(n3135), .B(n3136), .Z(n3134)); + OR2 U3089 ( .A(n3137), .B(po044), .Z(n3135)); + AN2 U3090 ( .A(n3138), .B(n2886), .Z(n3137)); + AN2 U3091 ( .A(n3139), .B(n2837), .Z(n3132)); + AN2 U3092 ( .A(n3140), .B(n3141), .Z(n3139)); + OR2 U3093 ( .A(n3142), .B(po044), .Z(n3140)); + AN2 U3094 ( .A(n3143), .B(n2886), .Z(n3142)); + AN2 U3095 ( .A(n3144), .B(n3145), .Z(n3130)); + OR2 U3096 ( .A(n3146), .B(n3147), .Z(n3145)); + IV2 U3097 ( .A(n3012), .Z(n3144)); + AN2 U3098 ( .A(n3148), .B(n3149), .Z(n3128)); + OR2 U3099 ( .A(n3150), .B(n3018), .Z(n3149)); + OR2 U3100 ( .A(n3015), .B(n3151), .Z(n3148)); + IV2 U3101 ( .A(n3150), .Z(n3151)); + OR2 U3102 ( .A(n3152), .B(n3153), .Z(n3150)); + AN2 U3103 ( .A(n3021), .B(n3154), .Z(n3153)); + AN2 U3104 ( .A(n3155), .B(n3083), .Z(n3152)); + IV2 U3105 ( .A(n3154), .Z(n3155)); + OR2 U3106 ( .A(n3156), .B(n3157), .Z(n3154)); + OR2 U3107 ( .A(n3091), .B(n3158), .Z(n3157)); + OR2 U3108 ( .A(n3159), .B(n3160), .Z(n3158)); + AN2 U3109 ( .A(n3161), .B(n3049), .Z(n3160)); + OR2 U3110 ( .A(n3162), .B(n3029), .Z(n3161)); + OR2 U3111 ( .A(n3163), .B(n3164), .Z(n3029)); + AN2 U3112 ( .A(po099), .B(n3165), .Z(n3164)); + OR2 U3113 ( .A(n3166), .B(n3167), .Z(n3165)); + OR2 U3114 ( .A(n3168), .B(n3169), .Z(n3167)); + AN2 U3115 ( .A(n3170), .B(pi192), .Z(n3169)); + AN2 U3116 ( .A(n3038), .B(n3171), .Z(n3170)); + AN2 U3117 ( .A(n3054), .B(n2837), .Z(n3168)); + AN2 U3118 ( .A(n3172), .B(n3173), .Z(n3166)); + AN2 U3119 ( .A(n3015), .B(n3109), .Z(n3172)); + AN2 U3120 ( .A(n3100), .B(n3018), .Z(n3163)); + AN2 U3121 ( .A(n3015), .B(n3174), .Z(n3162)); + OR2 U3122 ( .A(n3175), .B(n3176), .Z(n3174)); + AN2 U3123 ( .A(n3054), .B(n3173), .Z(n3176)); + AN2 U3124 ( .A(n3177), .B(n3109), .Z(n3054)); + AN2 U3125 ( .A(n3178), .B(n3064), .Z(n3175)); + AN2 U3126 ( .A(n3038), .B(n3037), .Z(n3178)); + AN2 U3127 ( .A(po010), .B(n3179), .Z(n3159)); + OR2 U3128 ( .A(n3090), .B(n3180), .Z(n3179)); + OR2 U3129 ( .A(n3181), .B(n3182), .Z(n3180)); + AN2 U3130 ( .A(n3053), .B(n3183), .Z(n3182)); + OR2 U3131 ( .A(n3184), .B(n3119), .Z(n3183)); + AN2 U3132 ( .A(pi141), .B(n3015), .Z(n3184)); + AN2 U3133 ( .A(n3109), .B(n3065), .Z(n3053)); + AN2 U3134 ( .A(n3185), .B(n3061), .Z(n3181)); + AN2 U3135 ( .A(n3186), .B(n3038), .Z(n3185)); + OR2 U3136 ( .A(n3187), .B(n3063), .Z(n3186)); + AN2 U3137 ( .A(pi033), .B(n3015), .Z(n3187)); + OR2 U3138 ( .A(n3188), .B(n3189), .Z(n3090)); + AN2 U3139 ( .A(n3190), .B(n3065), .Z(n3189)); + AN2 U3140 ( .A(n3073), .B(n3076), .Z(n3190)); + AN2 U3141 ( .A(n3191), .B(n3061), .Z(n3188)); + AN2 U3142 ( .A(n3082), .B(n3033), .Z(n3191)); + OR2 U3143 ( .A(n3192), .B(n3193), .Z(n3091)); + OR2 U3144 ( .A(n3194), .B(n3195), .Z(n3193)); + AN2 U3145 ( .A(n3052), .B(n3018), .Z(n3195)); + AN2 U3146 ( .A(n3064), .B(n3196), .Z(n3194)); + OR2 U3147 ( .A(n3197), .B(n3198), .Z(n3196)); + AN2 U3148 ( .A(n3082), .B(n3199), .Z(n3198)); + AN2 U3149 ( .A(n3042), .B(n3033), .Z(n3197)); + OR2 U3150 ( .A(n3200), .B(n3201), .Z(n3192)); + AN2 U3151 ( .A(n3173), .B(n3202), .Z(n3201)); + OR2 U3152 ( .A(n3203), .B(n3204), .Z(n3202)); + AN2 U3153 ( .A(n3073), .B(n3205), .Z(n3204)); + AN2 U3154 ( .A(n3076), .B(n3066), .Z(n3203)); + AN2 U3155 ( .A(n3206), .B(po099), .Z(n3200)); + AN2 U3156 ( .A(po070), .B(n3207), .Z(n3206)); + OR2 U3157 ( .A(n3208), .B(n3209), .Z(n3156)); + AN2 U3158 ( .A(n3210), .B(n3055), .Z(n3209)); + AN2 U3159 ( .A(n3076), .B(n3115), .Z(n3210)); + AN2 U3160 ( .A(n3211), .B(n3127), .Z(n3208)); + AN2 U3161 ( .A(n3033), .B(n3108), .Z(n3211)); + OR2 U3162 ( .A(n3212), .B(n3213), .Z(po098)); + AN2 U3163 ( .A(n3214), .B(pi192), .Z(n3213)); + OR2 U3164 ( .A(n3215), .B(n3216), .Z(n3214)); + AN2 U3165 ( .A(n2832), .B(n2901), .Z(n3216)); + IV2 U3166 ( .A(n2835), .Z(n2832)); + AN2 U3167 ( .A(pi200), .B(n2835), .Z(n3215)); + OR2 U3168 ( .A(n2880), .B(n2876), .Z(n2835)); + AN2 U3169 ( .A(n3217), .B(n2837), .Z(n3212)); + OR2 U3170 ( .A(n3218), .B(n3219), .Z(n3217)); + AN2 U3171 ( .A(n3220), .B(n2847), .Z(n3219)); + OR2 U3172 ( .A(n3221), .B(n2902), .Z(n3220)); + AN2 U3173 ( .A(pi200), .B(n2938), .Z(n3221)); + AN2 U3174 ( .A(n2844), .B(n3222), .Z(n3218)); + IV2 U3175 ( .A(n2847), .Z(n2844)); + OR2 U3176 ( .A(n2936), .B(n2978), .Z(n2847)); + OR2 U3177 ( .A(n3223), .B(n3224), .Z(po097)); + AN2 U3178 ( .A(n3225), .B(n3226), .Z(n3224)); + OR2 U3179 ( .A(n3227), .B(n3228), .Z(n3226)); + OR2 U3180 ( .A(n3229), .B(n3230), .Z(n3228)); + OR2 U3181 ( .A(n3231), .B(n3232), .Z(n3230)); + AN2 U3182 ( .A(n3233), .B(n3234), .Z(n3232)); + AN2 U3183 ( .A(n3235), .B(n3236), .Z(n3231)); + OR2 U3184 ( .A(n3237), .B(n3238), .Z(n3227)); + OR2 U3185 ( .A(n3239), .B(n3240), .Z(n3238)); + AN2 U3186 ( .A(n3241), .B(n3242), .Z(n3240)); + AN2 U3187 ( .A(n3243), .B(n3244), .Z(n3239)); + AN2 U3188 ( .A(po082), .B(n3245), .Z(n3237)); + AN2 U3189 ( .A(n3246), .B(n3247), .Z(n3223)); + OR2 U3190 ( .A(n3248), .B(n3249), .Z(n3246)); + AN2 U3191 ( .A(n3250), .B(n3251), .Z(n3249)); + OR2 U3192 ( .A(n3252), .B(n3253), .Z(po096)); + AN2 U3193 ( .A(n3254), .B(n3255), .Z(n3252)); + OR2 U3194 ( .A(n3256), .B(n3257), .Z(n3254)); + AN2 U3195 ( .A(n3258), .B(n3259), .Z(n3256)); + AN2 U3196 ( .A(n3260), .B(n3261), .Z(n3258)); + OR2 U3197 ( .A(n3262), .B(n3263), .Z(n3260)); + AN2 U3198 ( .A(n3264), .B(n3265), .Z(n3262)); + OR2 U3199 ( .A(n3266), .B(n3267), .Z(po095)); + OR2 U3200 ( .A(n3268), .B(n3269), .Z(n3267)); + AN2 U3201 ( .A(n3270), .B(n3119), .Z(n3269)); + OR2 U3202 ( .A(n3271), .B(n3272), .Z(n3270)); + AN2 U3203 ( .A(n3273), .B(n2837), .Z(n3272)); + AN2 U3204 ( .A(n3065), .B(n3274), .Z(n3271)); + AN2 U3205 ( .A(n3063), .B(n3275), .Z(n3268)); + OR2 U3206 ( .A(n3276), .B(n3277), .Z(n3275)); + AN2 U3207 ( .A(n3273), .B(pi192), .Z(n3277)); + AN2 U3208 ( .A(n3061), .B(n3274), .Z(n3276)); + OR2 U3209 ( .A(n3278), .B(n3279), .Z(n3266)); + AN2 U3210 ( .A(n3280), .B(n3281), .Z(n3279)); + OR2 U3211 ( .A(n3282), .B(n3100), .Z(n3281)); + AN2 U3212 ( .A(n3283), .B(n3284), .Z(n3278)); + OR2 U3213 ( .A(n3285), .B(n3052), .Z(n3283)); + AN2 U3214 ( .A(n3286), .B(n3287), .Z(n3052)); + AN2 U3215 ( .A(po099), .B(n3207), .Z(n3285)); + AN2 U3216 ( .A(n3288), .B(n3289), .Z(po094)); + OR2 U3217 ( .A(n3290), .B(n3291), .Z(n3289)); + OR2 U3218 ( .A(n3234), .B(n3292), .Z(n3288)); + OR2 U3219 ( .A(n3293), .B(n3294), .Z(po093)); + AN2 U3220 ( .A(n3295), .B(n3296), .Z(n3294)); + OR2 U3221 ( .A(n3297), .B(n3298), .Z(n3296)); + AN2 U3222 ( .A(n3299), .B(n3300), .Z(n3297)); + AN2 U3223 ( .A(n3301), .B(n3302), .Z(n3293)); + IV2 U3224 ( .A(n3303), .Z(n3302)); + AN2 U3225 ( .A(n3304), .B(n3299), .Z(n3303)); + OR2 U3226 ( .A(n3305), .B(n3306), .Z(n3299)); + OR2 U3227 ( .A(n3300), .B(n3298), .Z(n3304)); + AN2 U3228 ( .A(n3305), .B(n3306), .Z(n3298)); + OR2 U3229 ( .A(n3307), .B(n3308), .Z(po090)); + OR2 U3230 ( .A(n3309), .B(n3310), .Z(n3308)); + AN2 U3231 ( .A(n3311), .B(n3312), .Z(n3310)); + AN2 U3232 ( .A(n3313), .B(n3314), .Z(n3309)); + OR2 U3233 ( .A(n3315), .B(n3316), .Z(n3313)); + OR2 U3234 ( .A(n3317), .B(n3318), .Z(n3316)); + AN2 U3235 ( .A(n3319), .B(n3320), .Z(n3315)); + OR2 U3236 ( .A(n3321), .B(n3322), .Z(n3319)); + OR2 U3237 ( .A(n3323), .B(n3324), .Z(n3307)); + AN2 U3238 ( .A(n3325), .B(n3326), .Z(n3324)); + AN2 U3239 ( .A(n3327), .B(n3328), .Z(n3323)); + OR2 U3240 ( .A(n3329), .B(n3330), .Z(n3327)); + OR2 U3241 ( .A(n3331), .B(n3332), .Z(po088)); + IV2 U3242 ( .A(n3333), .Z(n3332)); + OR2 U3243 ( .A(n3334), .B(n3335), .Z(n3333)); + AN2 U3244 ( .A(n3335), .B(n3334), .Z(n3331)); + AN2 U3245 ( .A(n3336), .B(n3337), .Z(n3334)); + OR2 U3246 ( .A(n3338), .B(n3339), .Z(n3337)); + IV2 U3247 ( .A(n3340), .Z(n3338)); + OR2 U3248 ( .A(n3341), .B(n3340), .Z(n3336)); + OR2 U3249 ( .A(n3342), .B(n3343), .Z(n3340)); + AN2 U3250 ( .A(n3291), .B(n3250), .Z(n3343)); + AN2 U3251 ( .A(n3344), .B(n3292), .Z(n3342)); + OR2 U3252 ( .A(n3345), .B(n3346), .Z(n3335)); + IV2 U3253 ( .A(n3347), .Z(n3346)); + OR2 U3254 ( .A(n3348), .B(n3349), .Z(n3347)); + AN2 U3255 ( .A(n3349), .B(n3348), .Z(n3345)); + AN2 U3256 ( .A(n3350), .B(n3351), .Z(n3348)); + OR2 U3257 ( .A(n3352), .B(n3353), .Z(n3351)); + IV2 U3258 ( .A(n3354), .Z(n3353)); + OR2 U3259 ( .A(n3354), .B(n3355), .Z(n3350)); + OR2 U3260 ( .A(n3356), .B(n3357), .Z(n3354)); + OR2 U3261 ( .A(n3358), .B(n3359), .Z(n3357)); + AN2 U3262 ( .A(n3360), .B(n3361), .Z(n3359)); + AN2 U3263 ( .A(n3362), .B(n3363), .Z(n3360)); + OR2 U3264 ( .A(n3364), .B(n3365), .Z(n3362)); + OR2 U3265 ( .A(n3366), .B(n3367), .Z(n3365)); + AN2 U3266 ( .A(n3368), .B(n3369), .Z(n3367)); + AN2 U3267 ( .A(n3370), .B(n3371), .Z(n3368)); + AN2 U3268 ( .A(n3372), .B(n3373), .Z(n3366)); + AN2 U3269 ( .A(n3374), .B(n3375), .Z(n3372)); + OR2 U3270 ( .A(n3376), .B(n3377), .Z(n3374)); + OR2 U3271 ( .A(n3378), .B(n3379), .Z(n3377)); + AN2 U3272 ( .A(n2837), .B(n3380), .Z(n3379)); + AN2 U3273 ( .A(pi060), .B(n3381), .Z(n3378)); + AN2 U3274 ( .A(n3382), .B(n3369), .Z(n3364)); + AN2 U3275 ( .A(n3369), .B(n3383), .Z(n3358)); + OR2 U3276 ( .A(n3384), .B(n3385), .Z(n3383)); + OR2 U3277 ( .A(n3386), .B(n3387), .Z(n3385)); + AN2 U3278 ( .A(n3370), .B(n3388), .Z(n3387)); + OR2 U3279 ( .A(n3389), .B(n3390), .Z(n3388)); + AN2 U3280 ( .A(n3391), .B(n3392), .Z(n3390)); + AN2 U3281 ( .A(n3393), .B(n3394), .Z(n3386)); + OR2 U3282 ( .A(n3395), .B(n3396), .Z(n3394)); + OR2 U3283 ( .A(n3321), .B(n3397), .Z(n3396)); + AN2 U3284 ( .A(n3398), .B(n3399), .Z(n3397)); + AN2 U3285 ( .A(n3400), .B(n3401), .Z(n3395)); + OR2 U3286 ( .A(n3402), .B(n3371), .Z(n3400)); + AN2 U3287 ( .A(n3403), .B(n3404), .Z(n3402)); + AN2 U3288 ( .A(pi060), .B(po071), .Z(n3403)); + OR2 U3289 ( .A(n3405), .B(n3406), .Z(n3384)); + AN2 U3290 ( .A(n3407), .B(n3363), .Z(n3406)); + AN2 U3291 ( .A(n3408), .B(n3401), .Z(n3407)); + OR2 U3292 ( .A(n3409), .B(n3410), .Z(n3408)); + AN2 U3293 ( .A(n3411), .B(n3412), .Z(n3409)); + OR2 U3294 ( .A(n3413), .B(n3414), .Z(n3411)); + AN2 U3295 ( .A(n3415), .B(n3370), .Z(n3414)); + OR2 U3296 ( .A(n3416), .B(n3417), .Z(n3415)); + AN2 U3297 ( .A(n3418), .B(n3381), .Z(n3413)); + AN2 U3298 ( .A(n3393), .B(n3419), .Z(n3418)); + AN2 U3299 ( .A(n3420), .B(po027), .Z(n3405)); + OR2 U3300 ( .A(n3421), .B(n3422), .Z(n3420)); + OR2 U3301 ( .A(n3423), .B(n3424), .Z(n3422)); + AN2 U3302 ( .A(n3410), .B(n3361), .Z(n3424)); + IV2 U3303 ( .A(n3425), .Z(n3410)); + AN2 U3304 ( .A(n3426), .B(n3401), .Z(n3423)); + OR2 U3305 ( .A(n3427), .B(n3382), .Z(n3426)); + IV2 U3306 ( .A(n3428), .Z(n3382)); + OR2 U3307 ( .A(n3429), .B(n3430), .Z(n3421)); + AN2 U3308 ( .A(n3431), .B(n3370), .Z(n3430)); + AN2 U3309 ( .A(n3393), .B(n3432), .Z(n3429)); + OR2 U3310 ( .A(n3433), .B(n3434), .Z(n3432)); + AN2 U3311 ( .A(po071), .B(n3419), .Z(n3434)); + IV2 U3312 ( .A(n3435), .Z(n3369)); + OR2 U3313 ( .A(n3436), .B(n3375), .Z(n3435)); + AN2 U3314 ( .A(n3437), .B(n3438), .Z(n3436)); + AN2 U3315 ( .A(n3439), .B(n3440), .Z(n3438)); + OR2 U3316 ( .A(n3361), .B(n3441), .Z(n3440)); + AN2 U3317 ( .A(n3442), .B(n3443), .Z(n3441)); + OR2 U3318 ( .A(n3444), .B(n3445), .Z(n3443)); + OR2 U3319 ( .A(n3370), .B(n3446), .Z(n3445)); + OR2 U3320 ( .A(n3371), .B(n3380), .Z(n3444)); + AN2 U3321 ( .A(n3447), .B(n3448), .Z(n3442)); + OR2 U3322 ( .A(po027), .B(n3449), .Z(n3448)); + AN2 U3323 ( .A(n3450), .B(n3428), .Z(n3449)); + OR2 U3324 ( .A(n3371), .B(n3451), .Z(n3428)); + OR2 U3325 ( .A(n3370), .B(n3412), .Z(n3450)); + OR2 U3326 ( .A(n3363), .B(n3425), .Z(n3447)); + OR2 U3327 ( .A(n3427), .B(n3452), .Z(n3425)); + AN2 U3328 ( .A(n3453), .B(n3412), .Z(n3452)); + AN2 U3329 ( .A(n3371), .B(n3451), .Z(n3427)); + OR2 U3330 ( .A(n3401), .B(n3454), .Z(n3439)); + IV2 U3331 ( .A(n3455), .Z(n3454)); + AN2 U3332 ( .A(n3412), .B(n3456), .Z(n3455)); + OR2 U3333 ( .A(n3457), .B(n3458), .Z(n3456)); + AN2 U3334 ( .A(n3392), .B(n3393), .Z(n3458)); + AN2 U3335 ( .A(n3459), .B(n3460), .Z(n3437)); + OR2 U3336 ( .A(n3457), .B(n3461), .Z(n3460)); + AN2 U3337 ( .A(n3462), .B(n3463), .Z(n3459)); + OR2 U3338 ( .A(n3464), .B(n3370), .Z(n3463)); + IV2 U3339 ( .A(n3465), .Z(n3464)); + OR2 U3340 ( .A(n3389), .B(n3431), .Z(n3465)); + AN2 U3341 ( .A(n3466), .B(n3419), .Z(n3431)); + AN2 U3342 ( .A(n3467), .B(n3468), .Z(n3389)); + IV2 U3343 ( .A(n3469), .Z(n3468)); + OR2 U3344 ( .A(n3417), .B(n3470), .Z(n3469)); + AN2 U3345 ( .A(n3471), .B(n3399), .Z(n3470)); + OR2 U3346 ( .A(n3371), .B(n3446), .Z(n3471)); + OR2 U3347 ( .A(n3472), .B(n3393), .Z(n3462)); + AN2 U3348 ( .A(n3473), .B(n3474), .Z(n3472)); + AN2 U3349 ( .A(n3475), .B(n3476), .Z(n3474)); + OR2 U3350 ( .A(n3412), .B(n3477), .Z(n3476)); + AN2 U3351 ( .A(n3478), .B(n3261), .Z(n3475)); + IV2 U3352 ( .A(n3479), .Z(n3478)); + AN2 U3353 ( .A(n3361), .B(n3480), .Z(n3479)); + AN2 U3354 ( .A(n3481), .B(n3482), .Z(n3473)); + OR2 U3355 ( .A(n3483), .B(n3380), .Z(n3482)); + AN2 U3356 ( .A(n3484), .B(n3461), .Z(n3483)); + OR2 U3357 ( .A(n3371), .B(n3485), .Z(n3484)); + IV2 U3358 ( .A(n3433), .Z(n3481)); + OR2 U3359 ( .A(n3486), .B(n3417), .Z(n3433)); + AN2 U3360 ( .A(n3404), .B(n3381), .Z(n3417)); + AN2 U3361 ( .A(n3487), .B(n3380), .Z(n3486)); + AN2 U3362 ( .A(n3488), .B(n3375), .Z(n3356)); + OR2 U3363 ( .A(n3489), .B(n3490), .Z(n3375)); + AN2 U3364 ( .A(n3225), .B(n3491), .Z(n3489)); + OR2 U3365 ( .A(n3492), .B(n3493), .Z(n3491)); + AN2 U3366 ( .A(n3494), .B(n3495), .Z(n3492)); + OR2 U3367 ( .A(n3496), .B(n3497), .Z(n3488)); + OR2 U3368 ( .A(n3498), .B(n3499), .Z(n3497)); + AN2 U3369 ( .A(n3371), .B(n3500), .Z(n3499)); + OR2 U3370 ( .A(n3501), .B(n3502), .Z(n3500)); + OR2 U3371 ( .A(n3503), .B(n3504), .Z(n3502)); + AN2 U3372 ( .A(n3505), .B(n3401), .Z(n3504)); + OR2 U3373 ( .A(n3506), .B(n3507), .Z(n3505)); + AN2 U3374 ( .A(n3508), .B(n3509), .Z(n3507)); + OR2 U3375 ( .A(n3510), .B(n3511), .Z(n3509)); + OR2 U3376 ( .A(n3398), .B(n3487), .Z(n3511)); + AN2 U3377 ( .A(n3512), .B(n2837), .Z(n3487)); + AN2 U3378 ( .A(n3404), .B(pi060), .Z(n3510)); + AN2 U3379 ( .A(n3513), .B(po027), .Z(n3506)); + AN2 U3380 ( .A(n3514), .B(n3515), .Z(n3513)); + OR2 U3381 ( .A(n3516), .B(n3517), .Z(n3515)); + OR2 U3382 ( .A(n3321), .B(n3373), .Z(n3514)); + AN2 U3383 ( .A(n3518), .B(n3467), .Z(n3503)); + AN2 U3384 ( .A(n3404), .B(n3519), .Z(n3518)); + OR2 U3385 ( .A(n3520), .B(n3521), .Z(n3501)); + AN2 U3386 ( .A(n3522), .B(n3517), .Z(n3521)); + AN2 U3387 ( .A(n3516), .B(n3363), .Z(n3522)); + AN2 U3388 ( .A(n3373), .B(n3523), .Z(n3520)); + OR2 U3389 ( .A(n3524), .B(n3525), .Z(n3523)); + AN2 U3390 ( .A(n3361), .B(n3526), .Z(n3524)); + OR2 U3391 ( .A(n3527), .B(n3321), .Z(n3526)); + AN2 U3392 ( .A(n3519), .B(n3528), .Z(n3498)); + OR2 U3393 ( .A(n3529), .B(n3530), .Z(n3528)); + OR2 U3394 ( .A(n3392), .B(n3531), .Z(n3530)); + AN2 U3395 ( .A(n3376), .B(n3412), .Z(n3531)); + OR2 U3396 ( .A(n3532), .B(n3321), .Z(n3376)); + AN2 U3397 ( .A(n3533), .B(n3399), .Z(n3532)); + AN2 U3398 ( .A(n3534), .B(n3381), .Z(n3529)); + OR2 U3399 ( .A(n3535), .B(n3536), .Z(n3519)); + AN2 U3400 ( .A(n3537), .B(po027), .Z(n3536)); + AN2 U3401 ( .A(n3538), .B(n3363), .Z(n3535)); + AN2 U3402 ( .A(n3517), .B(n3401), .Z(n3538)); + OR2 U3403 ( .A(n3539), .B(n3540), .Z(n3496)); + AN2 U3404 ( .A(n3541), .B(n3542), .Z(n3540)); + OR2 U3405 ( .A(n3543), .B(n3544), .Z(n3542)); + AN2 U3406 ( .A(n3453), .B(po071), .Z(n3544)); + AN2 U3407 ( .A(n3480), .B(n3534), .Z(n3543)); + AN2 U3408 ( .A(n3545), .B(n3546), .Z(n3541)); + OR2 U3409 ( .A(n3361), .B(n3547), .Z(n3546)); + AN2 U3410 ( .A(n3508), .B(n3412), .Z(n3547)); + OR2 U3411 ( .A(n3401), .B(n3548), .Z(n3545)); + IV2 U3412 ( .A(n3508), .Z(n3548)); + OR2 U3413 ( .A(n3549), .B(n3550), .Z(n3508)); + AN2 U3414 ( .A(n3373), .B(n3363), .Z(n3550)); + AN2 U3415 ( .A(n3517), .B(po027), .Z(n3549)); + AN2 U3416 ( .A(n3551), .B(n3467), .Z(n3539)); + AN2 U3417 ( .A(n3552), .B(n3381), .Z(n3551)); + OR2 U3418 ( .A(n3553), .B(n3554), .Z(n3552)); + AN2 U3419 ( .A(n3537), .B(n3363), .Z(n3554)); + AN2 U3420 ( .A(n3555), .B(po027), .Z(n3553)); + IV2 U3421 ( .A(n3537), .Z(n3555)); + OR2 U3422 ( .A(n3556), .B(n3557), .Z(n3537)); + AN2 U3423 ( .A(n3373), .B(n3401), .Z(n3557)); + AN2 U3424 ( .A(n3517), .B(n3361), .Z(n3556)); + IV2 U3425 ( .A(n3373), .Z(n3517)); + OR2 U3426 ( .A(n3558), .B(n3559), .Z(n3373)); + AN2 U3427 ( .A(n3370), .B(n3560), .Z(n3559)); + OR2 U3428 ( .A(n3561), .B(n3562), .Z(n3560)); + OR2 U3429 ( .A(n3361), .B(n3563), .Z(n3562)); + AN2 U3430 ( .A(n3321), .B(po027), .Z(n3563)); + OR2 U3431 ( .A(n3564), .B(n3565), .Z(n3561)); + OR2 U3432 ( .A(n3527), .B(n3566), .Z(n3565)); + AN2 U3433 ( .A(po027), .B(n3398), .Z(n3527)); + AN2 U3434 ( .A(n3404), .B(n3567), .Z(n3564)); + AN2 U3435 ( .A(n3393), .B(n3568), .Z(n3558)); + OR2 U3436 ( .A(n3569), .B(n3570), .Z(n3568)); + AN2 U3437 ( .A(n3571), .B(n3401), .Z(n3570)); + OR2 U3438 ( .A(n3516), .B(n3572), .Z(n3571)); + AN2 U3439 ( .A(n3419), .B(n3363), .Z(n3572)); + AN2 U3440 ( .A(po104), .B(n3453), .Z(n3516)); + AN2 U3441 ( .A(n3573), .B(n3467), .Z(n3569)); + AN2 U3442 ( .A(n3261), .B(n3533), .Z(n3467)); + AN2 U3443 ( .A(n3404), .B(po027), .Z(n3573)); + OR2 U3444 ( .A(n3574), .B(n3575), .Z(n3349)); + AN2 U3445 ( .A(n3576), .B(n3247), .Z(n3575)); + IV2 U3446 ( .A(n3577), .Z(n3576)); + AN2 U3447 ( .A(n3225), .B(n3577), .Z(n3574)); + OR2 U3448 ( .A(n3578), .B(n3579), .Z(n3577)); + OR2 U3449 ( .A(n3580), .B(n3581), .Z(n3579)); + OR2 U3450 ( .A(n3582), .B(n3583), .Z(n3581)); + AN2 U3451 ( .A(n3584), .B(n2837), .Z(n3583)); + OR2 U3452 ( .A(n3585), .B(n3586), .Z(n3584)); + OR2 U3453 ( .A(n3587), .B(n3588), .Z(n3586)); + AN2 U3454 ( .A(n3589), .B(n3590), .Z(n3588)); + AN2 U3455 ( .A(n3591), .B(n3592), .Z(n3589)); + OR2 U3456 ( .A(n3593), .B(n3355), .Z(n3592)); + AN2 U3457 ( .A(n3594), .B(n3595), .Z(n3591)); + OR2 U3458 ( .A(n3596), .B(n3597), .Z(n3595)); + OR2 U3459 ( .A(pi003), .B(n3598), .Z(n3594)); + AN2 U3460 ( .A(n3599), .B(n3600), .Z(n3587)); + OR2 U3461 ( .A(n3601), .B(n3602), .Z(n3600)); + OR2 U3462 ( .A(n3603), .B(n3604), .Z(n3602)); + AN2 U3463 ( .A(n3605), .B(n3593), .Z(n3604)); + AN2 U3464 ( .A(n3606), .B(n3607), .Z(n3603)); + OR2 U3465 ( .A(n3608), .B(n3609), .Z(n3601)); + AN2 U3466 ( .A(n3610), .B(pi003), .Z(n3609)); + AN2 U3467 ( .A(n3611), .B(n3612), .Z(n3610)); + AN2 U3468 ( .A(n3613), .B(n3597), .Z(n3608)); + OR2 U3469 ( .A(n3614), .B(n3615), .Z(n3613)); + AN2 U3470 ( .A(n3598), .B(n3616), .Z(n3615)); + AN2 U3471 ( .A(n3617), .B(n3593), .Z(n3614)); + AN2 U3472 ( .A(n3618), .B(n3619), .Z(n3585)); + AN2 U3473 ( .A(n3620), .B(n3590), .Z(n3618)); + OR2 U3474 ( .A(n3621), .B(n3622), .Z(n3620)); + OR2 U3475 ( .A(n3494), .B(n3606), .Z(n3622)); + AN2 U3476 ( .A(pi003), .B(n3623), .Z(n3606)); + AN2 U3477 ( .A(n3616), .B(po011), .Z(n3623)); + AN2 U3478 ( .A(n3624), .B(n3625), .Z(n3621)); + AN2 U3479 ( .A(n3616), .B(n3597), .Z(n3624)); + AN2 U3480 ( .A(pi192), .B(n3626), .Z(n3582)); + OR2 U3481 ( .A(n3627), .B(n3628), .Z(n3626)); + OR2 U3482 ( .A(n3629), .B(n3630), .Z(n3628)); + AN2 U3483 ( .A(n3631), .B(n3632), .Z(n3630)); + AN2 U3484 ( .A(n3633), .B(n3634), .Z(n3631)); + OR2 U3485 ( .A(n3635), .B(n3355), .Z(n3634)); + AN2 U3486 ( .A(n3636), .B(n3637), .Z(n3633)); + OR2 U3487 ( .A(n3596), .B(n3638), .Z(n3637)); + AN2 U3488 ( .A(n3639), .B(n3339), .Z(n3596)); + OR2 U3489 ( .A(pi098), .B(n3598), .Z(n3636)); + AN2 U3490 ( .A(n3640), .B(n3641), .Z(n3629)); + OR2 U3491 ( .A(n3642), .B(n3643), .Z(n3641)); + OR2 U3492 ( .A(n3644), .B(n3645), .Z(n3643)); + AN2 U3493 ( .A(n3605), .B(n3635), .Z(n3645)); + OR2 U3494 ( .A(n3646), .B(n3647), .Z(n3605)); + AN2 U3495 ( .A(n3648), .B(n3493), .Z(n3647)); + AN2 U3496 ( .A(n3341), .B(n3639), .Z(n3646)); + AN2 U3497 ( .A(n3649), .B(n3607), .Z(n3644)); + OR2 U3498 ( .A(n3650), .B(n3651), .Z(n3642)); + AN2 U3499 ( .A(n3652), .B(pi098), .Z(n3651)); + AN2 U3500 ( .A(n3653), .B(n3612), .Z(n3652)); + AN2 U3501 ( .A(n3654), .B(n3638), .Z(n3650)); + OR2 U3502 ( .A(n3655), .B(n3656), .Z(n3654)); + AN2 U3503 ( .A(n3598), .B(n3657), .Z(n3656)); + OR2 U3504 ( .A(n3658), .B(n3659), .Z(n3598)); + AN2 U3505 ( .A(n3660), .B(n3493), .Z(n3659)); + AN2 U3506 ( .A(po011), .B(n3612), .Z(n3660)); + AN2 U3507 ( .A(n3625), .B(n3661), .Z(n3658)); + AN2 U3508 ( .A(n3617), .B(n3635), .Z(n3655)); + AN2 U3509 ( .A(n3625), .B(n3493), .Z(n3617)); + AN2 U3510 ( .A(n3662), .B(n3619), .Z(n3627)); + AN2 U3511 ( .A(n3663), .B(n3632), .Z(n3662)); + OR2 U3512 ( .A(n3664), .B(n3665), .Z(n3663)); + OR2 U3513 ( .A(n3494), .B(n3649), .Z(n3665)); + AN2 U3514 ( .A(pi098), .B(n3666), .Z(n3649)); + AN2 U3515 ( .A(n3657), .B(po011), .Z(n3666)); + AN2 U3516 ( .A(n3612), .B(n3667), .Z(n3494)); + AN2 U3517 ( .A(n3668), .B(n3625), .Z(n3664)); + AN2 U3518 ( .A(n3657), .B(n3638), .Z(n3668)); + OR2 U3519 ( .A(n3669), .B(n3670), .Z(n3580)); + AN2 U3520 ( .A(n3671), .B(po011), .Z(n3670)); + AN2 U3521 ( .A(n3672), .B(n3612), .Z(n3671)); + AN2 U3522 ( .A(n3673), .B(n3674), .Z(n3672)); + OR2 U3523 ( .A(pi192), .B(n3675), .Z(n3674)); + AN2 U3524 ( .A(n3676), .B(n3597), .Z(n3675)); + OR2 U3525 ( .A(n3677), .B(n3678), .Z(n3676)); + AN2 U3526 ( .A(n3679), .B(n3680), .Z(n3677)); + AN2 U3527 ( .A(n3599), .B(n3661), .Z(n3679)); + OR2 U3528 ( .A(n2837), .B(n3681), .Z(n3673)); + AN2 U3529 ( .A(n3682), .B(n3638), .Z(n3681)); + OR2 U3530 ( .A(n3683), .B(n3684), .Z(n3682)); + AN2 U3531 ( .A(n3685), .B(n3686), .Z(n3683)); + AN2 U3532 ( .A(n3640), .B(n3661), .Z(n3685)); + AN2 U3533 ( .A(n3687), .B(n3688), .Z(n3669)); + OR2 U3534 ( .A(n3689), .B(n3690), .Z(n3687)); + OR2 U3535 ( .A(n3691), .B(n3692), .Z(n3690)); + AN2 U3536 ( .A(n3693), .B(n3612), .Z(n3692)); + AN2 U3537 ( .A(n3619), .B(n3694), .Z(n3693)); + OR2 U3538 ( .A(n3695), .B(n3696), .Z(n3694)); + OR2 U3539 ( .A(n3697), .B(n3698), .Z(n3696)); + AN2 U3540 ( .A(n3699), .B(n3616), .Z(n3698)); + AN2 U3541 ( .A(n3700), .B(n3657), .Z(n3697)); + AN2 U3542 ( .A(n3341), .B(n3701), .Z(n3695)); + AN2 U3543 ( .A(n3493), .B(n3352), .Z(n3619)); + AN2 U3544 ( .A(n3625), .B(n3702), .Z(n3691)); + OR2 U3545 ( .A(n3703), .B(n3704), .Z(n3702)); + AN2 U3546 ( .A(n3705), .B(n3706), .Z(n3704)); + OR2 U3547 ( .A(n3684), .B(n3707), .Z(n3706)); + OR2 U3548 ( .A(n3708), .B(n3709), .Z(n3707)); + AN2 U3549 ( .A(n3710), .B(n3640), .Z(n3709)); + OR2 U3550 ( .A(n3711), .B(n3712), .Z(n3710)); + AN2 U3551 ( .A(n3607), .B(n3686), .Z(n3712)); + AN2 U3552 ( .A(n3493), .B(n3713), .Z(n3711)); + IV2 U3553 ( .A(n3686), .Z(n3713)); + AN2 U3554 ( .A(n3653), .B(n3632), .Z(n3708)); + OR2 U3555 ( .A(n3714), .B(n3715), .Z(n3653)); + AN2 U3556 ( .A(n3686), .B(n3493), .Z(n3714)); + AN2 U3557 ( .A(n3635), .B(n3339), .Z(n3686)); + AN2 U3558 ( .A(n3607), .B(n3716), .Z(n3684)); + AN2 U3559 ( .A(n3632), .B(n3657), .Z(n3716)); + AN2 U3560 ( .A(n3717), .B(n3718), .Z(n3703)); + OR2 U3561 ( .A(n3678), .B(n3719), .Z(n3718)); + OR2 U3562 ( .A(n3720), .B(n3721), .Z(n3719)); + AN2 U3563 ( .A(n3722), .B(n3599), .Z(n3721)); + OR2 U3564 ( .A(n3723), .B(n3724), .Z(n3722)); + AN2 U3565 ( .A(n3680), .B(n3607), .Z(n3724)); + AN2 U3566 ( .A(n3493), .B(n3725), .Z(n3723)); + IV2 U3567 ( .A(n3680), .Z(n3725)); + AN2 U3568 ( .A(n3611), .B(n3590), .Z(n3720)); + OR2 U3569 ( .A(n3726), .B(n3715), .Z(n3611)); + AN2 U3570 ( .A(n3341), .B(n3607), .Z(n3715)); + AN2 U3571 ( .A(n3680), .B(n3493), .Z(n3726)); + AN2 U3572 ( .A(n3593), .B(n3339), .Z(n3680)); + AN2 U3573 ( .A(n3607), .B(n3727), .Z(n3678)); + AN2 U3574 ( .A(n3590), .B(n3616), .Z(n3727)); + AN2 U3575 ( .A(n3661), .B(n3352), .Z(n3607)); + AN2 U3576 ( .A(n3639), .B(n3728), .Z(n3689)); + OR2 U3577 ( .A(n3729), .B(n3730), .Z(n3728)); + OR2 U3578 ( .A(n3731), .B(n3732), .Z(n3730)); + AN2 U3579 ( .A(n3733), .B(pi192), .Z(n3732)); + AN2 U3580 ( .A(n3640), .B(n3657), .Z(n3733)); + AN2 U3581 ( .A(n3734), .B(n2837), .Z(n3731)); + AN2 U3582 ( .A(n3599), .B(n3616), .Z(n3734)); + IV2 U3583 ( .A(n3590), .Z(n3599)); + AN2 U3584 ( .A(n3735), .B(n3355), .Z(n3729)); + OR2 U3585 ( .A(n3339), .B(n3736), .Z(n3735)); + OR2 U3586 ( .A(n3737), .B(n3738), .Z(n3578)); + AN2 U3587 ( .A(n3355), .B(n3739), .Z(n3738)); + OR2 U3588 ( .A(n3740), .B(n3741), .Z(n3739)); + AN2 U3589 ( .A(n3742), .B(n3625), .Z(n3741)); + AN2 U3590 ( .A(n3743), .B(n3744), .Z(n3742)); + OR2 U3591 ( .A(n3661), .B(n3688), .Z(n3744)); + OR2 U3592 ( .A(po011), .B(n3745), .Z(n3743)); + AN2 U3593 ( .A(n3493), .B(n3746), .Z(n3745)); + AN2 U3594 ( .A(n3747), .B(n3639), .Z(n3740)); + AN2 U3595 ( .A(n3661), .B(n3612), .Z(n3639)); + AN2 U3596 ( .A(n3736), .B(n3746), .Z(n3747)); + OR2 U3597 ( .A(n3292), .B(n3344), .Z(n3736)); + IV2 U3598 ( .A(n3291), .Z(n3292)); + AN2 U3599 ( .A(n3748), .B(n3648), .Z(n3737)); + OR2 U3600 ( .A(n3749), .B(n3750), .Z(n3648)); + AN2 U3601 ( .A(n3625), .B(po011), .Z(n3750)); + IV2 U3602 ( .A(n3612), .Z(n3625)); + AN2 U3603 ( .A(n3751), .B(n3688), .Z(n3749)); + AN2 U3604 ( .A(n3339), .B(n3612), .Z(n3751)); + OR2 U3605 ( .A(n3752), .B(n3753), .Z(n3612)); + OR2 U3606 ( .A(n3754), .B(n3755), .Z(n3753)); + AN2 U3607 ( .A(n3756), .B(n3757), .Z(n3755)); + OR2 U3608 ( .A(n3758), .B(n3759), .Z(n3752)); + AN2 U3609 ( .A(n3760), .B(n3761), .Z(n3759)); + AN2 U3610 ( .A(n3661), .B(n3762), .Z(n3748)); + OR2 U3611 ( .A(n3763), .B(n3764), .Z(po087)); + OR2 U3612 ( .A(po042), .B(n3765), .Z(n3764)); + OR2 U3613 ( .A(po029), .B(po022), .Z(n3765)); + OR2 U3614 ( .A(n3766), .B(n3767), .Z(n3763)); + OR2 U3615 ( .A(po080), .B(po056), .Z(n3767)); + OR2 U3616 ( .A(po105), .B(po083), .Z(n3766)); + IV2 U3617 ( .A(n3768), .Z(po105)); + AN2 U3618 ( .A(n3769), .B(n3770), .Z(n3768)); + AN2 U3619 ( .A(pi034), .B(pi007), .Z(n3770)); + AN2 U3620 ( .A(pi139), .B(pi120), .Z(n3769)); + OR2 U3621 ( .A(n3771), .B(n3772), .Z(po086)); + AN2 U3622 ( .A(n3773), .B(n3774), .Z(n3772)); + OR2 U3623 ( .A(n3775), .B(n3776), .Z(n3774)); + AN2 U3624 ( .A(n3777), .B(n3778), .Z(n3771)); + AN2 U3625 ( .A(n3779), .B(n3780), .Z(n3777)); + OR2 U3626 ( .A(po025), .B(n3781), .Z(n3779)); + IV2 U3627 ( .A(n3782), .Z(po083)); + AN2 U3628 ( .A(n3783), .B(n3784), .Z(n3782)); + AN2 U3629 ( .A(pi067), .B(pi041), .Z(n3784)); + AN2 U3630 ( .A(pi104), .B(pi070), .Z(n3783)); + OR2 U3631 ( .A(n3785), .B(n3786), .Z(po081)); + AN2 U3632 ( .A(n2862), .B(n3787), .Z(n3786)); + AN2 U3633 ( .A(n2930), .B(n3788), .Z(n3785)); + OR2 U3634 ( .A(n3146), .B(n3789), .Z(n3788)); + OR2 U3635 ( .A(n3790), .B(n3791), .Z(n3789)); + AN2 U3636 ( .A(n3792), .B(n2901), .Z(n3791)); + OR2 U3637 ( .A(n3793), .B(n3794), .Z(n3792)); + AN2 U3638 ( .A(pi192), .B(n2887), .Z(n3794)); + AN2 U3639 ( .A(n3795), .B(n2974), .Z(n3793)); + OR2 U3640 ( .A(n3796), .B(po031), .Z(n3795)); + AN2 U3641 ( .A(n2957), .B(n2837), .Z(n3796)); + AN2 U3642 ( .A(n3797), .B(n2935), .Z(n3790)); + AN2 U3643 ( .A(n2946), .B(n2837), .Z(n3797)); + OR2 U3644 ( .A(n3798), .B(n3799), .Z(po080)); + OR2 U3645 ( .A(n3800), .B(n3801), .Z(n3799)); + OR2 U3646 ( .A(n3802), .B(n3803), .Z(n3801)); + AN2 U3647 ( .A(n3804), .B(n2837), .Z(n3803)); + OR2 U3648 ( .A(n3805), .B(n3806), .Z(n3804)); + OR2 U3649 ( .A(n3807), .B(n3808), .Z(n3806)); + AN2 U3650 ( .A(n3809), .B(n3810), .Z(n3808)); + AN2 U3651 ( .A(n3811), .B(n3812), .Z(n3807)); + AN2 U3652 ( .A(n3813), .B(n3814), .Z(n3805)); + OR2 U3653 ( .A(n3815), .B(n3816), .Z(n3814)); + OR2 U3654 ( .A(n3817), .B(n3818), .Z(n3813)); + AN2 U3655 ( .A(pi192), .B(n3819), .Z(n3802)); + OR2 U3656 ( .A(n3820), .B(n3821), .Z(n3819)); + OR2 U3657 ( .A(n3822), .B(n3823), .Z(n3821)); + AN2 U3658 ( .A(n3824), .B(n3825), .Z(n3823)); + OR2 U3659 ( .A(n3826), .B(n3827), .Z(n3825)); + IV2 U3660 ( .A(n3828), .Z(n3824)); + AN2 U3661 ( .A(n3827), .B(n3826), .Z(n3828)); + OR2 U3662 ( .A(n3829), .B(n3830), .Z(n3826)); + AN2 U3663 ( .A(n3817), .B(n3171), .Z(n3830)); + AN2 U3664 ( .A(n3816), .B(pi033), .Z(n3829)); + IV2 U3665 ( .A(n3817), .Z(n3816)); + OR2 U3666 ( .A(n3831), .B(n3832), .Z(n3817)); + AN2 U3667 ( .A(n3833), .B(pi192), .Z(n3832)); + OR2 U3668 ( .A(n3834), .B(n3835), .Z(n3833)); + IV2 U3669 ( .A(n3836), .Z(n3835)); + OR2 U3670 ( .A(n3837), .B(n3838), .Z(n3836)); + AN2 U3671 ( .A(n3838), .B(n3837), .Z(n3834)); + AN2 U3672 ( .A(n3839), .B(n3840), .Z(n3837)); + OR2 U3673 ( .A(n3841), .B(pi013), .Z(n3840)); + IV2 U3674 ( .A(n3842), .Z(n3841)); + OR2 U3675 ( .A(n3843), .B(n3842), .Z(n3839)); + OR2 U3676 ( .A(n3844), .B(n3845), .Z(n3842)); + AN2 U3677 ( .A(pi026), .B(n3846), .Z(n3845)); + AN2 U3678 ( .A(pi077), .B(n3847), .Z(n3844)); + IV2 U3679 ( .A(pi013), .Z(n3843)); + OR2 U3680 ( .A(n3848), .B(n3849), .Z(n3838)); + AN2 U3681 ( .A(n3850), .B(n3136), .Z(n3849)); + AN2 U3682 ( .A(n3851), .B(pi088), .Z(n3848)); + IV2 U3683 ( .A(n3850), .Z(n3851)); + OR2 U3684 ( .A(n3852), .B(n3853), .Z(n3850)); + IV2 U3685 ( .A(n3854), .Z(n3853)); + OR2 U3686 ( .A(n3855), .B(pi157), .Z(n3854)); + AN2 U3687 ( .A(pi157), .B(n3855), .Z(n3852)); + IV2 U3688 ( .A(pi137), .Z(n3855)); + AN2 U3689 ( .A(n3856), .B(n3857), .Z(n3827)); + OR2 U3690 ( .A(n3858), .B(pi096), .Z(n3857)); + IV2 U3691 ( .A(n3859), .Z(n3858)); + OR2 U3692 ( .A(n3859), .B(n3199), .Z(n3856)); + OR2 U3693 ( .A(n3860), .B(n3861), .Z(n3859)); + AN2 U3694 ( .A(pi166), .B(n3862), .Z(n3861)); + IV2 U3695 ( .A(pi175), .Z(n3862)); + AN2 U3696 ( .A(pi175), .B(n3106), .Z(n3860)); + OR2 U3697 ( .A(n3863), .B(n3864), .Z(n3822)); + AN2 U3698 ( .A(n3865), .B(n3866), .Z(n3864)); + IV2 U3699 ( .A(n3867), .Z(n3863)); + OR2 U3700 ( .A(n3866), .B(n3865), .Z(n3867)); + OR2 U3701 ( .A(n3868), .B(n3869), .Z(n3865)); + AN2 U3702 ( .A(n3811), .B(n3870), .Z(n3869)); + IV2 U3703 ( .A(n3810), .Z(n3811)); + AN2 U3704 ( .A(pi016), .B(n3810), .Z(n3868)); + OR2 U3705 ( .A(n3871), .B(n3872), .Z(n3810)); + OR2 U3706 ( .A(n3873), .B(n3874), .Z(n3872)); + AN2 U3707 ( .A(n3875), .B(pi148), .Z(n3874)); + OR2 U3708 ( .A(n3876), .B(n3877), .Z(n3875)); + AN2 U3709 ( .A(n3878), .B(pi135), .Z(n3877)); + AN2 U3710 ( .A(n3879), .B(n3880), .Z(n3876)); + AN2 U3711 ( .A(n3881), .B(n3882), .Z(n3873)); + IV2 U3712 ( .A(pi148), .Z(n3882)); + OR2 U3713 ( .A(n3883), .B(n3884), .Z(n3881)); + AN2 U3714 ( .A(n3879), .B(pi135), .Z(n3884)); + OR2 U3715 ( .A(n3885), .B(n3886), .Z(n3879)); + AN2 U3716 ( .A(n3887), .B(n3888), .Z(n3886)); + AN2 U3717 ( .A(n3889), .B(n3890), .Z(n3885)); + AN2 U3718 ( .A(n3878), .B(n3880), .Z(n3883)); + OR2 U3719 ( .A(n3891), .B(n3892), .Z(n3878)); + AN2 U3720 ( .A(n3887), .B(n3890), .Z(n3892)); + AN2 U3721 ( .A(n3889), .B(n3888), .Z(n3891)); + IV2 U3722 ( .A(n3887), .Z(n3889)); + OR2 U3723 ( .A(n3893), .B(n3894), .Z(n3887)); + AN2 U3724 ( .A(n3895), .B(n3896), .Z(n3894)); + AN2 U3725 ( .A(n3897), .B(pi005), .Z(n3893)); + IV2 U3726 ( .A(n3895), .Z(n3897)); + OR2 U3727 ( .A(n3898), .B(n3899), .Z(n3895)); + AN2 U3728 ( .A(pi069), .B(n3900), .Z(n3899)); + IV2 U3729 ( .A(pi072), .Z(n3900)); + AN2 U3730 ( .A(pi072), .B(n3901), .Z(n3898)); + AN2 U3731 ( .A(n3902), .B(n3903), .Z(n3866)); + OR2 U3732 ( .A(n3904), .B(pi045), .Z(n3903)); + IV2 U3733 ( .A(n3905), .Z(n3902)); + AN2 U3734 ( .A(n3904), .B(pi045), .Z(n3905)); + AN2 U3735 ( .A(n3906), .B(n3907), .Z(n3904)); + OR2 U3736 ( .A(n3908), .B(pi158), .Z(n3907)); + OR2 U3737 ( .A(n3909), .B(pi079), .Z(n3906)); + OR2 U3738 ( .A(n3910), .B(n3911), .Z(n3820)); + AN2 U3739 ( .A(n3912), .B(n3913), .Z(n3911)); + AN2 U3740 ( .A(n3534), .B(n3914), .Z(n3912)); + AN2 U3741 ( .A(pi118), .B(n3915), .Z(n3910)); + OR2 U3742 ( .A(n3916), .B(n3917), .Z(n3915)); + AN2 U3743 ( .A(n3918), .B(pi060), .Z(n3917)); + AN2 U3744 ( .A(n3919), .B(n3534), .Z(n3916)); + AN2 U3745 ( .A(n3920), .B(n3921), .Z(n3919)); + AN2 U3746 ( .A(n3922), .B(n3923), .Z(n3800)); + OR2 U3747 ( .A(n3924), .B(n3925), .Z(n3923)); + OR2 U3748 ( .A(n3321), .B(n3926), .Z(n3925)); + AN2 U3749 ( .A(n3927), .B(n3928), .Z(n3924)); + AN2 U3750 ( .A(pi050), .B(pi118), .Z(n3928)); + AN2 U3751 ( .A(pi196), .B(n3534), .Z(n3927)); + OR2 U3752 ( .A(n3929), .B(n3930), .Z(n3798)); + OR2 U3753 ( .A(n3931), .B(n3932), .Z(n3930)); + AN2 U3754 ( .A(n3933), .B(n3533), .Z(n3932)); + AN2 U3755 ( .A(n3934), .B(n3913), .Z(n3933)); + OR2 U3756 ( .A(n3918), .B(n3935), .Z(n3934)); + OR2 U3757 ( .A(n3936), .B(n3937), .Z(n3935)); + AN2 U3758 ( .A(n3938), .B(n3921), .Z(n3937)); + AN2 U3759 ( .A(n3920), .B(n3261), .Z(n3938)); + AN2 U3760 ( .A(n3939), .B(n3922), .Z(n3936)); + AN2 U3761 ( .A(pi196), .B(n3940), .Z(n3939)); + AN2 U3762 ( .A(n3922), .B(n3941), .Z(n3918)); + AN2 U3763 ( .A(n3942), .B(n3943), .Z(n3941)); + AN2 U3764 ( .A(n3944), .B(n3945), .Z(n3931)); + AN2 U3765 ( .A(pi204), .B(n3946), .Z(n3944)); + IV2 U3766 ( .A(n3947), .Z(n3946)); + AN2 U3767 ( .A(n3948), .B(n3261), .Z(n3929)); + OR2 U3768 ( .A(n3949), .B(n3950), .Z(n3948)); + AN2 U3769 ( .A(n3947), .B(n3951), .Z(n3950)); + AN2 U3770 ( .A(n3952), .B(n3953), .Z(n3947)); + IV2 U3771 ( .A(n3954), .Z(n3953)); + AN2 U3772 ( .A(n3955), .B(n3956), .Z(n3954)); + OR2 U3773 ( .A(n3956), .B(n3955), .Z(n3952)); + OR2 U3774 ( .A(n3957), .B(n3958), .Z(n3955)); + AN2 U3775 ( .A(n3959), .B(n3960), .Z(n3958)); + IV2 U3776 ( .A(pi009), .Z(n3960)); + AN2 U3777 ( .A(pi009), .B(n3961), .Z(n3957)); + AN2 U3778 ( .A(n3962), .B(n3963), .Z(n3956)); + OR2 U3779 ( .A(n3964), .B(pi129), .Z(n3963)); + IV2 U3780 ( .A(n3965), .Z(n3964)); + OR2 U3781 ( .A(n3965), .B(n3966), .Z(n3962)); + OR2 U3782 ( .A(n3967), .B(n3968), .Z(n3965)); + AN2 U3783 ( .A(pi138), .B(n3969), .Z(n3968)); + AN2 U3784 ( .A(pi169), .B(n3970), .Z(n3967)); + IV2 U3785 ( .A(pi138), .Z(n3970)); + AN2 U3786 ( .A(n3971), .B(n3533), .Z(n3949)); + AN2 U3787 ( .A(n3914), .B(pi118), .Z(n3971)); + OR2 U3788 ( .A(n3972), .B(n3973), .Z(n3914)); + AN2 U3789 ( .A(n3920), .B(n3922), .Z(n3973)); + IV2 U3790 ( .A(n3921), .Z(n3922)); + AN2 U3791 ( .A(n3921), .B(n3974), .Z(n3972)); + IV2 U3792 ( .A(n3920), .Z(n3974)); + OR2 U3793 ( .A(n3975), .B(n3976), .Z(n3920)); + AN2 U3794 ( .A(pi050), .B(n3942), .Z(n3976)); + AN2 U3795 ( .A(pi196), .B(n3943), .Z(n3975)); + OR2 U3796 ( .A(n3977), .B(n3978), .Z(n3921)); + AN2 U3797 ( .A(n3979), .B(pi192), .Z(n3978)); + OR2 U3798 ( .A(n3980), .B(n3981), .Z(n3979)); + AN2 U3799 ( .A(n3982), .B(n3983), .Z(n3981)); + IV2 U3800 ( .A(n3984), .Z(n3980)); + OR2 U3801 ( .A(n3983), .B(n3982), .Z(n3984)); + OR2 U3802 ( .A(n3985), .B(n3986), .Z(n3982)); + IV2 U3803 ( .A(n3987), .Z(n3986)); + OR2 U3804 ( .A(n3988), .B(n3989), .Z(n3987)); + AN2 U3805 ( .A(n3988), .B(n3989), .Z(n3985)); + AN2 U3806 ( .A(n3990), .B(n3991), .Z(n3988)); + OR2 U3807 ( .A(n3992), .B(pi039), .Z(n3991)); + OR2 U3808 ( .A(n3993), .B(pi004), .Z(n3990)); + IV2 U3809 ( .A(pi039), .Z(n3993)); + AN2 U3810 ( .A(n3994), .B(n3995), .Z(n3983)); + OR2 U3811 ( .A(n3996), .B(pi068), .Z(n3995)); + IV2 U3812 ( .A(n3997), .Z(n3996)); + OR2 U3813 ( .A(n3997), .B(n3998), .Z(n3994)); + OR2 U3814 ( .A(n3999), .B(n4000), .Z(n3997)); + AN2 U3815 ( .A(pi098), .B(n4001), .Z(n4000)); + AN2 U3816 ( .A(pi171), .B(n3638), .Z(n3999)); + OR2 U3817 ( .A(pi037), .B(pi043), .Z(po078)); + OR2 U3818 ( .A(n4002), .B(n4003), .Z(po077)); + AN2 U3819 ( .A(n4004), .B(n4005), .Z(n4003)); + AN2 U3820 ( .A(n4006), .B(n4007), .Z(n4002)); + OR2 U3821 ( .A(n4008), .B(n4009), .Z(n4007)); + IV2 U3822 ( .A(pi090), .Z(po076)); + OR2 U3823 ( .A(n4010), .B(n4011), .Z(po075)); + AN2 U3824 ( .A(n4012), .B(n4013), .Z(n4011)); + OR2 U3825 ( .A(n4014), .B(n4015), .Z(n4012)); + OR2 U3826 ( .A(n4016), .B(n4017), .Z(n4015)); + OR2 U3827 ( .A(n4018), .B(n4019), .Z(n4014)); + AN2 U3828 ( .A(n4020), .B(n3314), .Z(n4019)); + OR2 U3829 ( .A(n4021), .B(n4022), .Z(n4020)); + AN2 U3830 ( .A(n3926), .B(n3328), .Z(n4022)); + OR2 U3831 ( .A(n3265), .B(n3326), .Z(n3328)); + AN2 U3832 ( .A(n4023), .B(pi204), .Z(n4021)); + AN2 U3833 ( .A(n3312), .B(n3261), .Z(n4023)); + OR2 U3834 ( .A(n4024), .B(n4025), .Z(n3312)); + AN2 U3835 ( .A(n3326), .B(n4026), .Z(n4024)); + AN2 U3836 ( .A(n4027), .B(n3320), .Z(n4018)); + OR2 U3837 ( .A(n4028), .B(n3321), .Z(n4027)); + AN2 U3838 ( .A(po040), .B(n4029), .Z(n4010)); + OR2 U3839 ( .A(n4030), .B(n4031), .Z(n4029)); + OR2 U3840 ( .A(n4032), .B(n4033), .Z(n4031)); + AN2 U3841 ( .A(n4034), .B(n3261), .Z(n4032)); + OR2 U3842 ( .A(n4035), .B(n4036), .Z(n4034)); + OR2 U3843 ( .A(n4037), .B(n4038), .Z(n4036)); + AN2 U3844 ( .A(n4039), .B(n3951), .Z(n4038)); + AN2 U3845 ( .A(n4025), .B(n3314), .Z(n4039)); + AN2 U3846 ( .A(n4040), .B(n4041), .Z(n4037)); + AN2 U3847 ( .A(n4042), .B(n3320), .Z(n4035)); + OR2 U3848 ( .A(n4043), .B(n4044), .Z(n4042)); + AN2 U3849 ( .A(pi204), .B(n4045), .Z(n4044)); + AN2 U3850 ( .A(n4046), .B(n4041), .Z(n4043)); + OR2 U3851 ( .A(n4047), .B(n4048), .Z(n4030)); + AN2 U3852 ( .A(n4049), .B(n4050), .Z(n4048)); + OR2 U3853 ( .A(n4051), .B(n4052), .Z(n4050)); + AN2 U3854 ( .A(n3321), .B(n3265), .Z(n4052)); + AN2 U3855 ( .A(n3951), .B(n4053), .Z(n4051)); + AN2 U3856 ( .A(n3326), .B(n3314), .Z(n4049)); + AN2 U3857 ( .A(n4054), .B(n4055), .Z(n4047)); + AN2 U3858 ( .A(n4056), .B(n4057), .Z(n4055)); + AN2 U3859 ( .A(n3945), .B(pi204), .Z(n4054)); + OR2 U3860 ( .A(n4058), .B(n4059), .Z(po073)); + AN2 U3861 ( .A(n4060), .B(n4061), .Z(n4059)); + AN2 U3862 ( .A(n3457), .B(n4062), .Z(n4058)); + OR2 U3863 ( .A(n4063), .B(n4064), .Z(po068)); + AN2 U3864 ( .A(n4065), .B(n4066), .Z(n4064)); + OR2 U3865 ( .A(n4067), .B(n4068), .Z(n4065)); + OR2 U3866 ( .A(n4069), .B(n4070), .Z(n4068)); + AN2 U3867 ( .A(n4071), .B(n4072), .Z(n4070)); + OR2 U3868 ( .A(n4073), .B(po059), .Z(n4071)); + AN2 U3869 ( .A(n4074), .B(n2837), .Z(n4073)); + AN2 U3870 ( .A(n4075), .B(n4076), .Z(n4069)); + AN2 U3871 ( .A(n3780), .B(n4077), .Z(n4075)); + AN2 U3872 ( .A(n4078), .B(n4079), .Z(n4063)); + OR2 U3873 ( .A(n4080), .B(n4081), .Z(n4079)); + OR2 U3874 ( .A(n4082), .B(n4083), .Z(n4081)); + AN2 U3875 ( .A(n4084), .B(n2837), .Z(n4083)); + AN2 U3876 ( .A(n4085), .B(pi192), .Z(n4082)); + AN2 U3877 ( .A(n3778), .B(n3776), .Z(n4080)); + OR2 U3878 ( .A(n4086), .B(n4087), .Z(n3776)); + OR2 U3879 ( .A(n4088), .B(n4089), .Z(po061)); + AN2 U3880 ( .A(n2861), .B(n4090), .Z(n4089)); + OR2 U3881 ( .A(n4091), .B(n4092), .Z(n4090)); + OR2 U3882 ( .A(n4093), .B(n4094), .Z(n4092)); + AN2 U3883 ( .A(n4095), .B(n2901), .Z(n4094)); + AN2 U3884 ( .A(n2862), .B(n2990), .Z(n4093)); + OR2 U3885 ( .A(n4096), .B(n4097), .Z(n4091)); + AN2 U3886 ( .A(n2880), .B(n4098), .Z(n4097)); + AN2 U3887 ( .A(n4099), .B(n4100), .Z(n4096)); + OR2 U3888 ( .A(n4101), .B(n4102), .Z(n4100)); + OR2 U3889 ( .A(n2978), .B(n4103), .Z(n4102)); + AN2 U3890 ( .A(n3222), .B(n2957), .Z(n4103)); + AN2 U3891 ( .A(n2935), .B(po031), .Z(n4101)); + IV2 U3892 ( .A(n2938), .Z(n2935)); + AN2 U3893 ( .A(n4104), .B(n2998), .Z(n4088)); + OR2 U3894 ( .A(n4105), .B(n4106), .Z(n4104)); + OR2 U3895 ( .A(n4107), .B(n4108), .Z(n4106)); + AN2 U3896 ( .A(n2892), .B(pi192), .Z(n4108)); + AN2 U3897 ( .A(n2929), .B(n2837), .Z(n4107)); + AN2 U3898 ( .A(n2930), .B(n3787), .Z(n4105)); + OR2 U3899 ( .A(n4109), .B(n4110), .Z(n3787)); + OR2 U3900 ( .A(n4111), .B(n4112), .Z(n4110)); + AN2 U3901 ( .A(n4113), .B(n2837), .Z(n4112)); + AN2 U3902 ( .A(n2876), .B(pi192), .Z(n4111)); + AN2 U3903 ( .A(pi200), .B(n4114), .Z(n4109)); + OR2 U3904 ( .A(n4115), .B(n2999), .Z(n4114)); + OR2 U3905 ( .A(n4116), .B(n4117), .Z(n2999)); + AN2 U3906 ( .A(n2938), .B(n2962), .Z(n4117)); + AN2 U3907 ( .A(pi192), .B(n2878), .Z(n4116)); + AN2 U3908 ( .A(n2918), .B(n2837), .Z(n4115)); + AN2 U3909 ( .A(n2938), .B(pi082), .Z(n2918)); + OR2 U3910 ( .A(n4118), .B(n4119), .Z(po060)); + OR2 U3911 ( .A(n4120), .B(n4121), .Z(n4119)); + AN2 U3912 ( .A(n4122), .B(n4123), .Z(n4121)); + OR2 U3913 ( .A(n4124), .B(n4125), .Z(n4123)); + AN2 U3914 ( .A(n4126), .B(n4127), .Z(n4124)); + OR2 U3915 ( .A(n4128), .B(n4129), .Z(n4126)); + AN2 U3916 ( .A(n4130), .B(n4131), .Z(n4122)); + OR2 U3917 ( .A(n4132), .B(n4133), .Z(n4131)); + AN2 U3918 ( .A(pi052), .B(n4134), .Z(n4132)); + OR2 U3919 ( .A(po064), .B(n4135), .Z(n4130)); + AN2 U3920 ( .A(n4136), .B(n4137), .Z(n4120)); + OR2 U3921 ( .A(n4138), .B(n4139), .Z(n4137)); + AN2 U3922 ( .A(n4140), .B(n4141), .Z(n4139)); + OR2 U3923 ( .A(n4142), .B(n4143), .Z(n4140)); + OR2 U3924 ( .A(n4144), .B(n4145), .Z(n4143)); + AN2 U3925 ( .A(po040), .B(n3321), .Z(n4145)); + AN2 U3926 ( .A(po103), .B(n4146), .Z(n4144)); + OR2 U3927 ( .A(n4147), .B(n3321), .Z(n4146)); + AN2 U3928 ( .A(n4148), .B(n4149), .Z(n4147)); + OR2 U3929 ( .A(po004), .B(n4150), .Z(n4149)); + OR2 U3930 ( .A(n4151), .B(n4152), .Z(n4142)); + OR2 U3931 ( .A(n4153), .B(n4154), .Z(n4152)); + IV2 U3932 ( .A(n4155), .Z(n4154)); + OR2 U3933 ( .A(n4156), .B(n4157), .Z(n4155)); + AN2 U3934 ( .A(n4158), .B(n4159), .Z(n4153)); + AN2 U3935 ( .A(n4160), .B(po004), .Z(n4151)); + AN2 U3936 ( .A(n3951), .B(po040), .Z(n4160)); + AN2 U3937 ( .A(po004), .B(n4161), .Z(n4138)); + AN2 U3938 ( .A(n4162), .B(n4163), .Z(n4136)); + OR2 U3939 ( .A(n4164), .B(n4134), .Z(n4163)); + AN2 U3940 ( .A(n4165), .B(po064), .Z(n4164)); + IV2 U3941 ( .A(n4166), .Z(n4165)); + OR2 U3942 ( .A(n4167), .B(n4125), .Z(n4166)); + OR2 U3943 ( .A(n4135), .B(n4168), .Z(n4162)); + OR2 U3944 ( .A(n4169), .B(n4170), .Z(n4168)); + AN2 U3945 ( .A(pi054), .B(n4167), .Z(n4170)); + AN2 U3946 ( .A(n4171), .B(n4133), .Z(n4169)); + IV2 U3947 ( .A(n4172), .Z(n4171)); + OR2 U3948 ( .A(n4173), .B(n4174), .Z(n4118)); + AN2 U3949 ( .A(n4175), .B(pi054), .Z(n4174)); + AN2 U3950 ( .A(n4176), .B(n4177), .Z(n4175)); + OR2 U3951 ( .A(n4178), .B(n4179), .Z(n4176)); + AN2 U3952 ( .A(n4134), .B(n4133), .Z(n4179)); + AN2 U3953 ( .A(n4135), .B(po064), .Z(n4178)); + AN2 U3954 ( .A(n4180), .B(n4135), .Z(n4173)); + IV2 U3955 ( .A(n4134), .Z(n4135)); + OR2 U3956 ( .A(n4181), .B(n4182), .Z(n4134)); + AN2 U3957 ( .A(n4183), .B(n4184), .Z(n4182)); + OR2 U3958 ( .A(n4185), .B(n4186), .Z(n4183)); + AN2 U3959 ( .A(n4187), .B(n4188), .Z(n4186)); + IV2 U3960 ( .A(n4189), .Z(n4188)); + OR2 U3961 ( .A(n4190), .B(n4191), .Z(n4187)); + AN2 U3962 ( .A(n4192), .B(n4193), .Z(n4191)); + OR2 U3963 ( .A(n4194), .B(n4195), .Z(n4193)); + AN2 U3964 ( .A(n4196), .B(n3261), .Z(n4195)); + OR2 U3965 ( .A(n4197), .B(n4198), .Z(n4196)); + AN2 U3966 ( .A(n4199), .B(po103), .Z(n4198)); + AN2 U3967 ( .A(n4200), .B(n4201), .Z(n4199)); + AN2 U3968 ( .A(n4202), .B(n4025), .Z(n4197)); + AN2 U3969 ( .A(n4203), .B(po091), .Z(n4202)); + AN2 U3970 ( .A(n4204), .B(n4205), .Z(n4190)); + OR2 U3971 ( .A(n3317), .B(n4206), .Z(n4204)); + OR2 U3972 ( .A(n4207), .B(n4208), .Z(n4206)); + AN2 U3973 ( .A(n4209), .B(n3314), .Z(n4208)); + IV2 U3974 ( .A(n4210), .Z(n4209)); + AN2 U3975 ( .A(n4210), .B(n4057), .Z(n4207)); + AN2 U3976 ( .A(po103), .B(n4148), .Z(n4210)); + AN2 U3977 ( .A(n4189), .B(n4211), .Z(n4185)); + OR2 U3978 ( .A(n4212), .B(n4213), .Z(n4211)); + AN2 U3979 ( .A(n4214), .B(n4205), .Z(n4213)); + OR2 U3980 ( .A(n3325), .B(n4215), .Z(n4214)); + OR2 U3981 ( .A(n4216), .B(n3329), .Z(n4215)); + AN2 U3982 ( .A(n4040), .B(n4217), .Z(n3329)); + AN2 U3983 ( .A(n4192), .B(n4218), .Z(n4212)); + OR2 U3984 ( .A(n4219), .B(n4220), .Z(n4218)); + OR2 U3985 ( .A(n4221), .B(n4222), .Z(n4220)); + AN2 U3986 ( .A(n4025), .B(n4201), .Z(n4222)); + IV2 U3987 ( .A(n4223), .Z(n4025)); + AN2 U3988 ( .A(po091), .B(n4200), .Z(n4221)); + OR2 U3989 ( .A(n4224), .B(n4225), .Z(n4189)); + AN2 U3990 ( .A(n4226), .B(n4227), .Z(n4225)); + IV2 U3991 ( .A(n4228), .Z(n4224)); + OR2 U3992 ( .A(n4227), .B(n4226), .Z(n4228)); + AN2 U3993 ( .A(n4229), .B(n4230), .Z(n4181)); + OR2 U3994 ( .A(n4231), .B(n4232), .Z(n4230)); + OR2 U3995 ( .A(n4233), .B(n4234), .Z(n4232)); + AN2 U3996 ( .A(n4235), .B(n4236), .Z(n4234)); + OR2 U3997 ( .A(n4237), .B(n4238), .Z(n4235)); + AN2 U3998 ( .A(n4239), .B(n4240), .Z(n4238)); + OR2 U3999 ( .A(n3325), .B(n4216), .Z(n4240)); + AN2 U4000 ( .A(po103), .B(n4194), .Z(n4216)); + AN2 U4001 ( .A(n3265), .B(n4040), .Z(n3325)); + AN2 U4002 ( .A(n4241), .B(n4242), .Z(n4237)); + OR2 U4003 ( .A(n4243), .B(n4219), .Z(n4241)); + OR2 U4004 ( .A(n4244), .B(n3321), .Z(n4219)); + AN2 U4005 ( .A(n4203), .B(n4223), .Z(n4244)); + AN2 U4006 ( .A(n4245), .B(n3314), .Z(n4243)); + OR2 U4007 ( .A(n4246), .B(po091), .Z(n4245)); + AN2 U4008 ( .A(n4247), .B(n3265), .Z(n4246)); + AN2 U4009 ( .A(n4248), .B(n4249), .Z(n4233)); + OR2 U4010 ( .A(n4250), .B(n4251), .Z(n4249)); + OR2 U4011 ( .A(n4252), .B(n4253), .Z(n4251)); + AN2 U4012 ( .A(po103), .B(n4254), .Z(n4253)); + OR2 U4013 ( .A(n4255), .B(n3330), .Z(n4254)); + AN2 U4014 ( .A(n3311), .B(n4242), .Z(n4255)); + AN2 U4015 ( .A(n4194), .B(n3265), .Z(n4252)); + AN2 U4016 ( .A(n4148), .B(n3311), .Z(n4194)); + AN2 U4017 ( .A(n4239), .B(n4256), .Z(n4250)); + OR2 U4018 ( .A(n4257), .B(n4258), .Z(n4256)); + OR2 U4019 ( .A(n3926), .B(n4259), .Z(n4258)); + AN2 U4020 ( .A(n4260), .B(n3314), .Z(n4259)); + OR2 U4021 ( .A(n4261), .B(n4262), .Z(n4257)); + AN2 U4022 ( .A(pi058), .B(pi129), .Z(n4262)); + AN2 U4023 ( .A(n4056), .B(n3966), .Z(n4261)); + AN2 U4024 ( .A(n4263), .B(n4264), .Z(n4231)); + AN2 U4025 ( .A(n4265), .B(n4266), .Z(n4264)); + OR2 U4026 ( .A(n4267), .B(n4236), .Z(n4266)); + AN2 U4027 ( .A(n4268), .B(pi058), .Z(n4267)); + AN2 U4028 ( .A(n4242), .B(n3265), .Z(n4268)); + OR2 U4029 ( .A(n4269), .B(n4248), .Z(n4265)); + IV2 U4030 ( .A(n4236), .Z(n4248)); + AN2 U4031 ( .A(n4270), .B(n4271), .Z(n4236)); + IV2 U4032 ( .A(n4272), .Z(n4271)); + AN2 U4033 ( .A(n4226), .B(n4141), .Z(n4272)); + OR2 U4034 ( .A(n4226), .B(n4141), .Z(n4270)); + OR2 U4035 ( .A(n4273), .B(n4274), .Z(n4226)); + IV2 U4036 ( .A(n4275), .Z(n4274)); + OR2 U4037 ( .A(n4276), .B(n4277), .Z(n4275)); + AN2 U4038 ( .A(n4277), .B(n4276), .Z(n4273)); + AN2 U4039 ( .A(n4278), .B(n4279), .Z(n4276)); + OR2 U4040 ( .A(n4280), .B(n4281), .Z(n4279)); + IV2 U4041 ( .A(n4282), .Z(n4280)); + OR2 U4042 ( .A(n4283), .B(n4282), .Z(n4278)); + OR2 U4043 ( .A(n4284), .B(n4285), .Z(n4282)); + AN2 U4044 ( .A(po040), .B(n4286), .Z(n4285)); + OR2 U4045 ( .A(n4017), .B(n4287), .Z(n4286)); + OR2 U4046 ( .A(n4288), .B(n4289), .Z(n4287)); + AN2 U4047 ( .A(n4290), .B(n3314), .Z(n4289)); + OR2 U4048 ( .A(n4291), .B(n3321), .Z(n4290)); + IV2 U4049 ( .A(n4292), .Z(n4288)); + OR2 U4050 ( .A(n4293), .B(n3314), .Z(n4292)); + OR2 U4051 ( .A(n4294), .B(n3330), .Z(n4017)); + AN2 U4052 ( .A(n4201), .B(n3926), .Z(n3330)); + AN2 U4053 ( .A(n3311), .B(pi204), .Z(n4294)); + AN2 U4054 ( .A(n4295), .B(n4013), .Z(n4284)); + OR2 U4055 ( .A(n4033), .B(n4296), .Z(n4295)); + OR2 U4056 ( .A(n4297), .B(n4298), .Z(n4296)); + AN2 U4057 ( .A(n4299), .B(n3314), .Z(n4298)); + AN2 U4058 ( .A(n4300), .B(n3261), .Z(n4299)); + OR2 U4059 ( .A(n4301), .B(n4302), .Z(n4300)); + AN2 U4060 ( .A(pi204), .B(n4203), .Z(n4302)); + AN2 U4061 ( .A(po091), .B(n4041), .Z(n4301)); + AN2 U4062 ( .A(n4040), .B(n4293), .Z(n4297)); + AN2 U4063 ( .A(n3311), .B(n3951), .Z(n4033)); + IV2 U4064 ( .A(n4260), .Z(n3311)); + OR2 U4065 ( .A(n3321), .B(n4057), .Z(n4260)); + IV2 U4066 ( .A(n4281), .Z(n4283)); + OR2 U4067 ( .A(n4303), .B(n4304), .Z(n4281)); + AN2 U4068 ( .A(n4305), .B(n4306), .Z(n4304)); + AN2 U4069 ( .A(n4307), .B(n3261), .Z(n4305)); + OR2 U4070 ( .A(n4308), .B(n4309), .Z(n4307)); + AN2 U4071 ( .A(pi065), .B(n4148), .Z(n4309)); + AN2 U4072 ( .A(n4310), .B(pi058), .Z(n4308)); + AN2 U4073 ( .A(n4311), .B(n4312), .Z(n4303)); + OR2 U4074 ( .A(n3961), .B(n4313), .Z(n4311)); + IV2 U4075 ( .A(n3959), .Z(n3961)); + OR2 U4076 ( .A(n4314), .B(n4315), .Z(n3959)); + AN2 U4077 ( .A(pi058), .B(n4150), .Z(n4315)); + AN2 U4078 ( .A(pi065), .B(n4316), .Z(n4314)); + OR2 U4079 ( .A(n4317), .B(n4318), .Z(n4277)); + AN2 U4080 ( .A(po004), .B(n3265), .Z(n4318)); + AN2 U4081 ( .A(po103), .B(n4319), .Z(n4317)); + AN2 U4082 ( .A(n4239), .B(pi058), .Z(n4269)); + AN2 U4083 ( .A(n4040), .B(n3261), .Z(n4263)); + AN2 U4084 ( .A(n4320), .B(n4167), .Z(n4180)); + OR2 U4085 ( .A(n4129), .B(n4127), .Z(n4320)); + AN2 U4086 ( .A(po023), .B(pi183), .Z(po058)); + IV2 U4087 ( .A(n4321), .Z(po056)); + AN2 U4088 ( .A(n4322), .B(n4323), .Z(n4321)); + AN2 U4089 ( .A(pi063), .B(pi010), .Z(n4323)); + AN2 U4090 ( .A(pi203), .B(pi073), .Z(n4322)); + OR2 U4091 ( .A(n4324), .B(n4325), .Z(po055)); + AN2 U4092 ( .A(n3015), .B(n4326), .Z(n4325)); + AN2 U4093 ( .A(n3018), .B(n4327), .Z(n4324)); + AN2 U4094 ( .A(n4328), .B(n4329), .Z(po053)); + OR2 U4095 ( .A(n4306), .B(n4330), .Z(n4329)); + IV2 U4096 ( .A(n4312), .Z(n4306)); + OR2 U4097 ( .A(n4331), .B(n4312), .Z(n4328)); + AN2 U4098 ( .A(n4332), .B(n3780), .Z(po051)); + OR2 U4099 ( .A(n4333), .B(n4334), .Z(n4332)); + OR2 U4100 ( .A(n4335), .B(n4336), .Z(po050)); + AN2 U4101 ( .A(n4337), .B(n4338), .Z(n4336)); + OR2 U4102 ( .A(n4339), .B(n4340), .Z(n4338)); + AN2 U4103 ( .A(n4087), .B(n4341), .Z(n4339)); + AN2 U4104 ( .A(n4342), .B(n4343), .Z(n4335)); + OR2 U4105 ( .A(n4344), .B(n4345), .Z(n4343)); + OR2 U4106 ( .A(n4346), .B(n4347), .Z(n4345)); + AN2 U4107 ( .A(n4067), .B(n4348), .Z(n4346)); + OR2 U4108 ( .A(n4349), .B(n4350), .Z(n4067)); + AN2 U4109 ( .A(n4351), .B(pi192), .Z(n4350)); + AN2 U4110 ( .A(n4072), .B(n3880), .Z(n4351)); + AN2 U4111 ( .A(n4352), .B(n3890), .Z(n4349)); + AN2 U4112 ( .A(n4353), .B(n3780), .Z(n4352)); + OR2 U4113 ( .A(n4354), .B(n4355), .Z(n4344)); + AN2 U4114 ( .A(n4356), .B(n3780), .Z(n4355)); + AN2 U4115 ( .A(n4357), .B(n4076), .Z(n4354)); + AN2 U4116 ( .A(n4072), .B(n4358), .Z(n4357)); + OR2 U4117 ( .A(n4359), .B(n4360), .Z(po049)); + AN2 U4118 ( .A(n3361), .B(n4361), .Z(n4360)); + OR2 U4119 ( .A(n4362), .B(n4363), .Z(n4361)); + AN2 U4120 ( .A(n4364), .B(n3451), .Z(n4362)); + IV2 U4121 ( .A(n3401), .Z(n3361)); + AN2 U4122 ( .A(n4365), .B(n3401), .Z(n4359)); + OR2 U4123 ( .A(n4366), .B(n4367), .Z(n4365)); + AN2 U4124 ( .A(n3453), .B(n4368), .Z(n4366)); + OR2 U4125 ( .A(n4369), .B(n3253), .Z(po048)); + AN2 U4126 ( .A(n4370), .B(n3255), .Z(n4369)); + OR2 U4127 ( .A(n4371), .B(n4372), .Z(n4370)); + AN2 U4128 ( .A(n4373), .B(n3259), .Z(n4371)); + AN2 U4129 ( .A(n4374), .B(n4242), .Z(n4373)); + OR2 U4130 ( .A(n4375), .B(n4376), .Z(po047)); + OR2 U4131 ( .A(n4377), .B(n4378), .Z(n4376)); + AN2 U4132 ( .A(n4379), .B(n4380), .Z(n4378)); + AN2 U4133 ( .A(n4381), .B(n3259), .Z(n4377)); + AN2 U4134 ( .A(n4382), .B(n4383), .Z(n4381)); + OR2 U4135 ( .A(po004), .B(n4384), .Z(n4383)); + OR2 U4136 ( .A(n3926), .B(n4385), .Z(n4384)); + AN2 U4137 ( .A(n4386), .B(pi065), .Z(n4385)); + AN2 U4138 ( .A(n4387), .B(n4157), .Z(n4386)); + OR2 U4139 ( .A(n4319), .B(n4388), .Z(n4382)); + OR2 U4140 ( .A(n4389), .B(n4390), .Z(n4388)); + AN2 U4141 ( .A(n4391), .B(n3321), .Z(n4390)); + AN2 U4142 ( .A(n4392), .B(n4310), .Z(n4389)); + AN2 U4143 ( .A(pi204), .B(n4387), .Z(n4392)); + OR2 U4144 ( .A(n4393), .B(n4394), .Z(n4375)); + AN2 U4145 ( .A(n4395), .B(n4319), .Z(n4394)); + OR2 U4146 ( .A(n4396), .B(n4397), .Z(n4395)); + AN2 U4147 ( .A(n4227), .B(n4161), .Z(n4397)); + AN2 U4148 ( .A(po004), .B(n4398), .Z(n4393)); + OR2 U4149 ( .A(n4399), .B(n4400), .Z(n4398)); + OR2 U4150 ( .A(n4401), .B(n4402), .Z(n4400)); + AN2 U4151 ( .A(n4310), .B(n4403), .Z(n4402)); + AN2 U4152 ( .A(n4404), .B(n4227), .Z(n4401)); + AN2 U4153 ( .A(n4405), .B(n4406), .Z(n4399)); + AN2 U4154 ( .A(n4407), .B(n3261), .Z(n4405)); + OR2 U4155 ( .A(n4408), .B(n4409), .Z(n4407)); + AN2 U4156 ( .A(n4028), .B(pi065), .Z(n4409)); + AN2 U4157 ( .A(po040), .B(n4410), .Z(n4408)); + OR2 U4158 ( .A(n4411), .B(n4412), .Z(n4410)); + AN2 U4159 ( .A(pi065), .B(n4045), .Z(n4412)); + AN2 U4160 ( .A(n4046), .B(n4156), .Z(n4411)); + OR2 U4161 ( .A(n4413), .B(n4414), .Z(po046)); + OR2 U4162 ( .A(n4415), .B(n4416), .Z(n4414)); + AN2 U4163 ( .A(n3339), .B(n4417), .Z(n4416)); + AN2 U4164 ( .A(n3341), .B(n4418), .Z(n4415)); + OR2 U4165 ( .A(n4419), .B(n4420), .Z(n4413)); + AN2 U4166 ( .A(n4421), .B(pi192), .Z(n4420)); + OR2 U4167 ( .A(n4422), .B(n4423), .Z(n4421)); + AN2 U4168 ( .A(n4424), .B(pi098), .Z(n4423)); + AN2 U4169 ( .A(n4425), .B(n4426), .Z(n4424)); + OR2 U4170 ( .A(n3242), .B(n3657), .Z(n4425)); + IV2 U4171 ( .A(n3635), .Z(n3657)); + AN2 U4172 ( .A(n4427), .B(n3638), .Z(n4422)); + OR2 U4173 ( .A(n4428), .B(n4429), .Z(n4427)); + AN2 U4174 ( .A(n4430), .B(pi171), .Z(n4429)); + AN2 U4175 ( .A(n4431), .B(n4001), .Z(n4428)); + AN2 U4176 ( .A(n4432), .B(n2837), .Z(n4419)); + OR2 U4177 ( .A(n4433), .B(n4434), .Z(n4432)); + AN2 U4178 ( .A(n4435), .B(pi003), .Z(n4434)); + AN2 U4179 ( .A(n4436), .B(n4426), .Z(n4435)); + OR2 U4180 ( .A(n3244), .B(n3616), .Z(n4436)); + IV2 U4181 ( .A(n3593), .Z(n3616)); + AN2 U4182 ( .A(n4437), .B(n3597), .Z(n4433)); + OR2 U4183 ( .A(n4438), .B(n4439), .Z(n4437)); + AN2 U4184 ( .A(n4430), .B(pi142), .Z(n4439)); + AN2 U4185 ( .A(n4431), .B(n4440), .Z(n4438)); + AN2 U4186 ( .A(n3236), .B(n4441), .Z(n4431)); + OR2 U4187 ( .A(n4442), .B(n4443), .Z(po045)); + AN2 U4188 ( .A(n4444), .B(n4445), .Z(n4443)); + OR2 U4189 ( .A(n4446), .B(n3756), .Z(n4445)); + AN2 U4190 ( .A(n4006), .B(n4005), .Z(n4446)); + OR2 U4191 ( .A(n4447), .B(n4448), .Z(n4005)); + AN2 U4192 ( .A(n4449), .B(n3301), .Z(n4447)); + AN2 U4193 ( .A(n4450), .B(n3306), .Z(n4449)); + AN2 U4194 ( .A(n3757), .B(n4451), .Z(n4442)); + OR2 U4195 ( .A(n4452), .B(n4453), .Z(n4451)); + OR2 U4196 ( .A(n4454), .B(n4455), .Z(n4453)); + AN2 U4197 ( .A(po092), .B(n4456), .Z(n4455)); + OR2 U4198 ( .A(n4008), .B(n4004), .Z(n4456)); + AN2 U4199 ( .A(n4457), .B(n4458), .Z(n4008)); + AN2 U4200 ( .A(n4458), .B(n4459), .Z(n4454)); + OR2 U4201 ( .A(n4460), .B(n4461), .Z(n4459)); + AN2 U4202 ( .A(n4462), .B(n4463), .Z(n4461)); + AN2 U4203 ( .A(n4464), .B(n4465), .Z(n4462)); + AN2 U4204 ( .A(n4466), .B(n4467), .Z(n4460)); + AN2 U4205 ( .A(n4468), .B(n4469), .Z(n4466)); + OR2 U4206 ( .A(n4470), .B(n4471), .Z(po043)); + OR2 U4207 ( .A(n4472), .B(n4473), .Z(n4471)); + AN2 U4208 ( .A(n4474), .B(n4475), .Z(n4473)); + AN2 U4209 ( .A(n4476), .B(n4337), .Z(n4474)); + AN2 U4210 ( .A(n4477), .B(n4478), .Z(n4472)); + OR2 U4211 ( .A(n4479), .B(n4480), .Z(n4477)); + AN2 U4212 ( .A(n4337), .B(n4481), .Z(n4480)); + IV2 U4213 ( .A(n4342), .Z(n4337)); + AN2 U4214 ( .A(n4342), .B(n4476), .Z(n4479)); + IV2 U4215 ( .A(n4481), .Z(n4476)); + AN2 U4216 ( .A(n4482), .B(n4481), .Z(n4470)); + OR2 U4217 ( .A(n4483), .B(n4484), .Z(n4481)); + OR2 U4218 ( .A(n4485), .B(n4486), .Z(n4484)); + AN2 U4219 ( .A(n4487), .B(n4078), .Z(n4486)); + OR2 U4220 ( .A(n4488), .B(n4489), .Z(n4487)); + AN2 U4221 ( .A(n4490), .B(n3778), .Z(n4489)); + AN2 U4222 ( .A(n3773), .B(n4491), .Z(n4488)); + AN2 U4223 ( .A(n4492), .B(n4066), .Z(n4485)); + AN2 U4224 ( .A(n4490), .B(n3773), .Z(n4492)); + AN2 U4225 ( .A(n4491), .B(n4341), .Z(n4483)); + IV2 U4226 ( .A(n4490), .Z(n4491)); + OR2 U4227 ( .A(n4493), .B(n4494), .Z(n4490)); + IV2 U4228 ( .A(n4495), .Z(n4494)); + OR2 U4229 ( .A(n4496), .B(n4497), .Z(n4495)); + AN2 U4230 ( .A(n4497), .B(n4496), .Z(n4493)); + AN2 U4231 ( .A(n4498), .B(n4499), .Z(n4496)); + IV2 U4232 ( .A(n4500), .Z(n4499)); + AN2 U4233 ( .A(n4333), .B(n4501), .Z(n4500)); + OR2 U4234 ( .A(n4501), .B(n4333), .Z(n4498)); + OR2 U4235 ( .A(n4502), .B(n4503), .Z(n4501)); + OR2 U4236 ( .A(n4504), .B(n4505), .Z(n4503)); + OR2 U4237 ( .A(n4506), .B(n4507), .Z(n4505)); + AN2 U4238 ( .A(n4508), .B(n4509), .Z(n4507)); + AN2 U4239 ( .A(n4510), .B(n4511), .Z(n4506)); + AN2 U4240 ( .A(n4512), .B(n4513), .Z(n4504)); + OR2 U4241 ( .A(n4514), .B(n4515), .Z(n4502)); + AN2 U4242 ( .A(n4516), .B(n4517), .Z(n4515)); + AN2 U4243 ( .A(po102), .B(n4518), .Z(n4514)); + OR2 U4244 ( .A(n4519), .B(n4520), .Z(n4518)); + AN2 U4245 ( .A(n4513), .B(n4521), .Z(n4520)); + OR2 U4246 ( .A(n4522), .B(n4523), .Z(n4513)); + AN2 U4247 ( .A(n4508), .B(n3773), .Z(n4523)); + AN2 U4248 ( .A(po025), .B(n4516), .Z(n4522)); + AN2 U4249 ( .A(n4508), .B(n4524), .Z(n4519)); + IV2 U4250 ( .A(n4510), .Z(n4508)); + OR2 U4251 ( .A(n4525), .B(n4526), .Z(n4510)); + AN2 U4252 ( .A(n4527), .B(n4528), .Z(n4526)); + OR2 U4253 ( .A(n4529), .B(n4530), .Z(n4527)); + OR2 U4254 ( .A(n4531), .B(n4532), .Z(n4530)); + AN2 U4255 ( .A(po025), .B(n4533), .Z(n4532)); + OR2 U4256 ( .A(n4534), .B(n4535), .Z(n4533)); + OR2 U4257 ( .A(n4356), .B(n4536), .Z(n4535)); + AN2 U4258 ( .A(n4537), .B(n4538), .Z(n4536)); + AN2 U4259 ( .A(n4539), .B(n4540), .Z(n4537)); + AN2 U4260 ( .A(n3890), .B(n4541), .Z(n4534)); + OR2 U4261 ( .A(n4542), .B(n4543), .Z(n4541)); + AN2 U4262 ( .A(n4085), .B(n4544), .Z(n4542)); + AN2 U4263 ( .A(n3778), .B(n4545), .Z(n4531)); + OR2 U4264 ( .A(n4546), .B(n4547), .Z(n4545)); + OR2 U4265 ( .A(n4548), .B(n4549), .Z(n4547)); + AN2 U4266 ( .A(n3775), .B(n4550), .Z(n4549)); + AN2 U4267 ( .A(n4524), .B(n4333), .Z(n4548)); + AN2 U4268 ( .A(n4086), .B(n4551), .Z(n4546)); + OR2 U4269 ( .A(n4552), .B(n4553), .Z(n4529)); + AN2 U4270 ( .A(n4554), .B(n4555), .Z(n4553)); + OR2 U4271 ( .A(n4556), .B(n3888), .Z(n4555)); + AN2 U4272 ( .A(pi192), .B(n4557), .Z(n4556)); + AN2 U4273 ( .A(n4558), .B(n4559), .Z(n4554)); + OR2 U4274 ( .A(n4085), .B(n4560), .Z(n4558)); + AN2 U4275 ( .A(n4561), .B(n3773), .Z(n4560)); + AN2 U4276 ( .A(n4562), .B(n4563), .Z(n4552)); + OR2 U4277 ( .A(n4564), .B(n4565), .Z(n4563)); + AN2 U4278 ( .A(n4566), .B(n4567), .Z(n4564)); + AN2 U4279 ( .A(n3773), .B(n4076), .Z(n4566)); + OR2 U4280 ( .A(pi076), .B(n4557), .Z(n4562)); + AN2 U4281 ( .A(n4516), .B(n4568), .Z(n4525)); + OR2 U4282 ( .A(n4569), .B(n4570), .Z(n4568)); + OR2 U4283 ( .A(n4571), .B(n4572), .Z(n4570)); + OR2 U4284 ( .A(n4573), .B(n4574), .Z(n4572)); + AN2 U4285 ( .A(n4575), .B(n4576), .Z(n4574)); + AN2 U4286 ( .A(n4577), .B(n4076), .Z(n4575)); + AN2 U4287 ( .A(n3773), .B(n4578), .Z(n4577)); + AN2 U4288 ( .A(n4579), .B(n4580), .Z(n4573)); + OR2 U4289 ( .A(n4581), .B(n4565), .Z(n4579)); + AN2 U4290 ( .A(n4539), .B(n4582), .Z(n4565)); + AN2 U4291 ( .A(n2837), .B(n4550), .Z(n4582)); + IV2 U4292 ( .A(n4540), .Z(n4550)); + AN2 U4293 ( .A(n4567), .B(n4076), .Z(n4581)); + AN2 U4294 ( .A(n4086), .B(n4583), .Z(n4571)); + OR2 U4295 ( .A(n4584), .B(n4585), .Z(n4583)); + AN2 U4296 ( .A(n4543), .B(n3773), .Z(n4585)); + AN2 U4297 ( .A(n4586), .B(n4544), .Z(n4584)); + OR2 U4298 ( .A(n4085), .B(n3778), .Z(n4586)); + AN2 U4299 ( .A(n4557), .B(n3888), .Z(n4086)); + OR2 U4300 ( .A(n4587), .B(n4588), .Z(n4569)); + AN2 U4301 ( .A(n4589), .B(n4590), .Z(n4588)); + OR2 U4302 ( .A(n4591), .B(n3890), .Z(n4590)); + AN2 U4303 ( .A(po025), .B(pi192), .Z(n4591)); + AN2 U4304 ( .A(n4559), .B(n4592), .Z(n4589)); + OR2 U4305 ( .A(n4561), .B(n4085), .Z(n4592)); + OR2 U4306 ( .A(n4551), .B(n4353), .Z(n4559)); + AN2 U4307 ( .A(n4593), .B(n3775), .Z(n4587)); + AN2 U4308 ( .A(n2837), .B(n4576), .Z(n3775)); + AN2 U4309 ( .A(n4594), .B(n4540), .Z(n4593)); + OR2 U4310 ( .A(n4567), .B(n4066), .Z(n4540)); + OR2 U4311 ( .A(n4539), .B(n3778), .Z(n4594)); + IV2 U4312 ( .A(n4528), .Z(n4516)); + OR2 U4313 ( .A(n4595), .B(n4596), .Z(n4497)); + AN2 U4314 ( .A(n4597), .B(n4598), .Z(n4596)); + OR2 U4315 ( .A(n4599), .B(n4600), .Z(n4598)); + AN2 U4316 ( .A(n4601), .B(n4602), .Z(n4600)); + IV2 U4317 ( .A(n4603), .Z(n4599)); + OR2 U4318 ( .A(n4602), .B(n4601), .Z(n4603)); + OR2 U4319 ( .A(n4604), .B(n4605), .Z(n4601)); + AN2 U4320 ( .A(n3295), .B(n4606), .Z(n4605)); + AN2 U4321 ( .A(n4450), .B(n3301), .Z(n4604)); + AN2 U4322 ( .A(n4607), .B(n4608), .Z(n4602)); + OR2 U4323 ( .A(n4609), .B(n4610), .Z(n4608)); + IV2 U4324 ( .A(n4611), .Z(n4610)); + OR2 U4325 ( .A(n4611), .B(n4612), .Z(n4607)); + IV2 U4326 ( .A(n4609), .Z(n4612)); + OR2 U4327 ( .A(n4613), .B(n4614), .Z(n4609)); + OR2 U4328 ( .A(n4615), .B(n4616), .Z(n4614)); + AN2 U4329 ( .A(n4004), .B(n4617), .Z(n4616)); + OR2 U4330 ( .A(n4618), .B(n4619), .Z(n4617)); + AN2 U4331 ( .A(n4620), .B(n4463), .Z(n4619)); + AN2 U4332 ( .A(n4621), .B(n4464), .Z(n4620)); + AN2 U4333 ( .A(n4622), .B(n4467), .Z(n4618)); + AN2 U4334 ( .A(n4623), .B(n4468), .Z(n4622)); + AN2 U4335 ( .A(n4006), .B(n4624), .Z(n4615)); + OR2 U4336 ( .A(n4625), .B(n4626), .Z(n4613)); + AN2 U4337 ( .A(n4627), .B(n4628), .Z(n4626)); + OR2 U4338 ( .A(n4629), .B(n4630), .Z(n4627)); + AN2 U4339 ( .A(n4631), .B(pi192), .Z(n4630)); + AN2 U4340 ( .A(n4632), .B(pi158), .Z(n4631)); + AN2 U4341 ( .A(n4633), .B(n4634), .Z(n4632)); + OR2 U4342 ( .A(n4635), .B(n4465), .Z(n4634)); + OR2 U4343 ( .A(n4464), .B(n4636), .Z(n4633)); + OR2 U4344 ( .A(n4621), .B(n3301), .Z(n4636)); + AN2 U4345 ( .A(n4637), .B(n2837), .Z(n4629)); + AN2 U4346 ( .A(n4638), .B(pi151), .Z(n4637)); + AN2 U4347 ( .A(n4639), .B(n4640), .Z(n4638)); + OR2 U4348 ( .A(n4641), .B(n4469), .Z(n4640)); + OR2 U4349 ( .A(n4468), .B(n4642), .Z(n4639)); + OR2 U4350 ( .A(n4623), .B(n3301), .Z(n4642)); + AN2 U4351 ( .A(n4643), .B(po092), .Z(n4625)); + AN2 U4352 ( .A(n4644), .B(n3295), .Z(n4643)); + AN2 U4353 ( .A(n4645), .B(n4646), .Z(n4644)); + OR2 U4354 ( .A(pi192), .B(n4647), .Z(n4646)); + AN2 U4355 ( .A(n4641), .B(n4648), .Z(n4647)); + OR2 U4356 ( .A(n2837), .B(n4649), .Z(n4645)); + AN2 U4357 ( .A(n4635), .B(n3908), .Z(n4649)); + IV2 U4358 ( .A(n3761), .Z(n4597)); + AN2 U4359 ( .A(n4650), .B(n3761), .Z(n4595)); + OR2 U4360 ( .A(n4651), .B(n4652), .Z(n3761)); + AN2 U4361 ( .A(n4653), .B(n4654), .Z(n4651)); + AN2 U4362 ( .A(n4333), .B(n4528), .Z(n4654)); + OR2 U4363 ( .A(n4655), .B(n4656), .Z(n4528)); + AN2 U4364 ( .A(n4657), .B(n3083), .Z(n4655)); + AN2 U4365 ( .A(n3018), .B(n4658), .Z(n4657)); + OR2 U4366 ( .A(n4659), .B(n4660), .Z(n4658)); + OR2 U4367 ( .A(n4661), .B(n4662), .Z(n4660)); + AN2 U4368 ( .A(n4663), .B(n3010), .Z(n4662)); + AN2 U4369 ( .A(n4664), .B(n3049), .Z(n4661)); + OR2 U4370 ( .A(n4665), .B(n4663), .Z(n4664)); + AN2 U4371 ( .A(n4666), .B(n3010), .Z(n4665)); + OR2 U4372 ( .A(n3100), .B(n4667), .Z(n4659)); + AN2 U4373 ( .A(n4668), .B(n3012), .Z(n4667)); + OR2 U4374 ( .A(n4669), .B(n4670), .Z(n4668)); + AN2 U4375 ( .A(n4671), .B(pi201), .Z(n4670)); + AN2 U4376 ( .A(n4672), .B(n3115), .Z(n4671)); + OR2 U4377 ( .A(n4673), .B(n3173), .Z(n4672)); + AN2 U4378 ( .A(n2837), .B(n3049), .Z(n4673)); + AN2 U4379 ( .A(n4674), .B(pi088), .Z(n4669)); + AN2 U4380 ( .A(n4675), .B(n3108), .Z(n4674)); + OR2 U4381 ( .A(n4676), .B(n3064), .Z(n4675)); + AN2 U4382 ( .A(pi192), .B(n3049), .Z(n4676)); + AN2 U4383 ( .A(n4341), .B(n4482), .Z(n4653)); + OR2 U4384 ( .A(n4677), .B(n4678), .Z(n4650)); + OR2 U4385 ( .A(n4679), .B(n4680), .Z(n4678)); + OR2 U4386 ( .A(n4681), .B(n4682), .Z(n4680)); + AN2 U4387 ( .A(n4683), .B(n4684), .Z(n4682)); + AN2 U4388 ( .A(n4685), .B(n4648), .Z(n4683)); + AN2 U4389 ( .A(n4686), .B(n4687), .Z(n4681)); + OR2 U4390 ( .A(n4688), .B(n4689), .Z(n4687)); + OR2 U4391 ( .A(n4690), .B(n4691), .Z(n4689)); + AN2 U4392 ( .A(n4692), .B(n4621), .Z(n4691)); + AN2 U4393 ( .A(n4685), .B(n4623), .Z(n4690)); + AN2 U4394 ( .A(n4693), .B(n3300), .Z(n4688)); + IV2 U4395 ( .A(n4684), .Z(n4686)); + OR2 U4396 ( .A(n4694), .B(n4695), .Z(n4679)); + AN2 U4397 ( .A(n4696), .B(n3300), .Z(n4695)); + AN2 U4398 ( .A(po014), .B(n4684), .Z(n4696)); + OR2 U4399 ( .A(n4697), .B(n4698), .Z(n4684)); + AN2 U4400 ( .A(n4699), .B(n4450), .Z(n4697)); + AN2 U4401 ( .A(po039), .B(n4700), .Z(n4694)); + OR2 U4402 ( .A(n4701), .B(n4702), .Z(n4700)); + AN2 U4403 ( .A(n4698), .B(n4703), .Z(n4702)); + AN2 U4404 ( .A(n4704), .B(n4606), .Z(n4698)); + AN2 U4405 ( .A(n4705), .B(n4706), .Z(n4701)); + AN2 U4406 ( .A(n4707), .B(n4708), .Z(n4705)); + OR2 U4407 ( .A(n4704), .B(n3295), .Z(n4708)); + OR2 U4408 ( .A(n4699), .B(n3301), .Z(n4707)); + OR2 U4409 ( .A(n4709), .B(n4710), .Z(n4677)); + AN2 U4410 ( .A(n4711), .B(n4699), .Z(n4710)); + IV2 U4411 ( .A(n4704), .Z(n4699)); + AN2 U4412 ( .A(n4450), .B(n4712), .Z(n4711)); + OR2 U4413 ( .A(po014), .B(n3301), .Z(n4712)); + AN2 U4414 ( .A(n4713), .B(n4704), .Z(n4709)); + OR2 U4415 ( .A(n4714), .B(n4715), .Z(n4704)); + OR2 U4416 ( .A(n4716), .B(n4717), .Z(n4715)); + OR2 U4417 ( .A(n4718), .B(n4719), .Z(n4717)); + IV2 U4418 ( .A(n4720), .Z(n4719)); + OR2 U4419 ( .A(n4721), .B(n4006), .Z(n4720)); + OR2 U4420 ( .A(n4444), .B(n3756), .Z(n4721)); + AN2 U4421 ( .A(n4722), .B(n4006), .Z(n4718)); + AN2 U4422 ( .A(n4444), .B(n4452), .Z(n4722)); + OR2 U4423 ( .A(n4723), .B(n4724), .Z(n4452)); + OR2 U4424 ( .A(n4725), .B(n4726), .Z(n4724)); + AN2 U4425 ( .A(po092), .B(n4009), .Z(n4726)); + OR2 U4426 ( .A(n4727), .B(n4728), .Z(n4009)); + AN2 U4427 ( .A(n3295), .B(n4729), .Z(n4728)); + AN2 U4428 ( .A(n4606), .B(n4457), .Z(n4727)); + OR2 U4429 ( .A(n4730), .B(n4706), .Z(n4457)); + OR2 U4430 ( .A(n4731), .B(n4732), .Z(n4706)); + AN2 U4431 ( .A(n4733), .B(pi192), .Z(n4732)); + AN2 U4432 ( .A(n4465), .B(n3870), .Z(n4733)); + AN2 U4433 ( .A(n4734), .B(n2837), .Z(n4731)); + AN2 U4434 ( .A(n4469), .B(n4735), .Z(n4734)); + AN2 U4435 ( .A(po039), .B(n4729), .Z(n4730)); + OR2 U4436 ( .A(po014), .B(n4736), .Z(n4729)); + AN2 U4437 ( .A(n4737), .B(n4606), .Z(n4725)); + AN2 U4438 ( .A(po014), .B(n4738), .Z(n4737)); + OR2 U4439 ( .A(n4739), .B(n4740), .Z(n4738)); + AN2 U4440 ( .A(n4463), .B(n4464), .Z(n4740)); + AN2 U4441 ( .A(n4467), .B(n4468), .Z(n4739)); + OR2 U4442 ( .A(n4741), .B(n4742), .Z(n4723)); + AN2 U4443 ( .A(n4743), .B(n4463), .Z(n4742)); + AN2 U4444 ( .A(n3909), .B(pi192), .Z(n4463)); + IV2 U4445 ( .A(pi158), .Z(n3909)); + AN2 U4446 ( .A(n4744), .B(n3908), .Z(n4743)); + OR2 U4447 ( .A(n4745), .B(n3295), .Z(n4744)); + AN2 U4448 ( .A(n4606), .B(n4464), .Z(n4745)); + AN2 U4449 ( .A(n4746), .B(n4467), .Z(n4741)); + AN2 U4450 ( .A(n2837), .B(n4747), .Z(n4467)); + AN2 U4451 ( .A(n4748), .B(n4648), .Z(n4746)); + OR2 U4452 ( .A(n4749), .B(n3295), .Z(n4748)); + AN2 U4453 ( .A(n4606), .B(n4468), .Z(n4749)); + AN2 U4454 ( .A(n3756), .B(n4611), .Z(n4716)); + OR2 U4455 ( .A(n4750), .B(n4751), .Z(n4611)); + AN2 U4456 ( .A(n4004), .B(n4444), .Z(n4750)); + IV2 U4457 ( .A(n4006), .Z(n4004)); + AN2 U4458 ( .A(n4628), .B(n4752), .Z(n3756)); + OR2 U4459 ( .A(n3758), .B(n3760), .Z(n4714)); + AN2 U4460 ( .A(n4448), .B(n4751), .Z(n3758)); + OR2 U4461 ( .A(n4713), .B(n4693), .Z(n4448)); + OR2 U4462 ( .A(n4753), .B(n4754), .Z(n4693)); + AN2 U4463 ( .A(n4621), .B(pi192), .Z(n4754)); + AN2 U4464 ( .A(n4623), .B(n2837), .Z(n4753)); + AN2 U4465 ( .A(n3301), .B(n4624), .Z(n4713)); + OR2 U4466 ( .A(n4755), .B(n4756), .Z(po042)); + AN2 U4467 ( .A(n4757), .B(n2837), .Z(n4756)); + OR2 U4468 ( .A(n4758), .B(n4759), .Z(n4757)); + OR2 U4469 ( .A(n4760), .B(n4761), .Z(n4759)); + AN2 U4470 ( .A(n4762), .B(n4763), .Z(n4761)); + OR2 U4471 ( .A(n4764), .B(n4765), .Z(n4763)); + IV2 U4472 ( .A(n4766), .Z(n4762)); + AN2 U4473 ( .A(n4765), .B(n4764), .Z(n4766)); + OR2 U4474 ( .A(n4767), .B(n4768), .Z(n4764)); + AN2 U4475 ( .A(n4769), .B(n4770), .Z(n4768)); + AN2 U4476 ( .A(n4771), .B(pi028), .Z(n4767)); + AN2 U4477 ( .A(n4772), .B(n4773), .Z(n4765)); + OR2 U4478 ( .A(n4774), .B(pi094), .Z(n4773)); + IV2 U4479 ( .A(n4775), .Z(n4772)); + AN2 U4480 ( .A(n4774), .B(pi094), .Z(n4775)); + AN2 U4481 ( .A(n4776), .B(n4777), .Z(n4774)); + OR2 U4482 ( .A(n4778), .B(pi173), .Z(n4777)); + OR2 U4483 ( .A(n4779), .B(pi163), .Z(n4776)); + IV2 U4484 ( .A(pi173), .Z(n4779)); + AN2 U4485 ( .A(n4780), .B(n4781), .Z(n4760)); + IV2 U4486 ( .A(n4782), .Z(n4781)); + AN2 U4487 ( .A(n4783), .B(n4784), .Z(n4782)); + OR2 U4488 ( .A(n4784), .B(n4783), .Z(n4780)); + AN2 U4489 ( .A(n4785), .B(n4786), .Z(n4783)); + IV2 U4490 ( .A(n4787), .Z(n4786)); + AN2 U4491 ( .A(n4788), .B(n4789), .Z(n4787)); + OR2 U4492 ( .A(n4789), .B(n4788), .Z(n4785)); + OR2 U4493 ( .A(n4790), .B(n4791), .Z(n4788)); + AN2 U4494 ( .A(pi025), .B(n4792), .Z(n4791)); + IV2 U4495 ( .A(n4793), .Z(n4790)); + OR2 U4496 ( .A(n4792), .B(pi025), .Z(n4793)); + IV2 U4497 ( .A(pi035), .Z(n4792)); + AN2 U4498 ( .A(n4794), .B(n4795), .Z(n4789)); + IV2 U4499 ( .A(n4796), .Z(n4795)); + AN2 U4500 ( .A(pi056), .B(n4797), .Z(n4796)); + OR2 U4501 ( .A(n4797), .B(pi056), .Z(n4794)); + IV2 U4502 ( .A(pi100), .Z(n4797)); + OR2 U4503 ( .A(n4798), .B(n4799), .Z(n4784)); + IV2 U4504 ( .A(n4800), .Z(n4799)); + OR2 U4505 ( .A(n4801), .B(n4802), .Z(n4800)); + AN2 U4506 ( .A(n4802), .B(n4801), .Z(n4798)); + AN2 U4507 ( .A(n4803), .B(n4804), .Z(n4801)); + IV2 U4508 ( .A(n4805), .Z(n4804)); + AN2 U4509 ( .A(pi126), .B(n4806), .Z(n4805)); + OR2 U4510 ( .A(n4806), .B(pi126), .Z(n4803)); + IV2 U4511 ( .A(pi146), .Z(n4806)); + OR2 U4512 ( .A(n4807), .B(n4808), .Z(n4802)); + AN2 U4513 ( .A(pi190), .B(n4809), .Z(n4808)); + IV2 U4514 ( .A(pi202), .Z(n4809)); + AN2 U4515 ( .A(pi202), .B(n4810), .Z(n4807)); + IV2 U4516 ( .A(pi190), .Z(n4810)); + OR2 U4517 ( .A(n4811), .B(n4812), .Z(n4758)); + AN2 U4518 ( .A(n4813), .B(n4814), .Z(n4812)); + IV2 U4519 ( .A(n4815), .Z(n4814)); + AN2 U4520 ( .A(n4816), .B(n4817), .Z(n4815)); + OR2 U4521 ( .A(n4817), .B(n4816), .Z(n4813)); + AN2 U4522 ( .A(n4818), .B(n4819), .Z(n4816)); + OR2 U4523 ( .A(n4820), .B(pi019), .Z(n4819)); + OR2 U4524 ( .A(n4821), .B(n4822), .Z(n4818)); + IV2 U4525 ( .A(pi019), .Z(n4822)); + OR2 U4526 ( .A(n4823), .B(n4824), .Z(n4817)); + IV2 U4527 ( .A(n4825), .Z(n4824)); + OR2 U4528 ( .A(n4826), .B(pi085), .Z(n4825)); + AN2 U4529 ( .A(n4826), .B(pi085), .Z(n4823)); + AN2 U4530 ( .A(n4827), .B(n4828), .Z(n4826)); + OR2 U4531 ( .A(n4829), .B(pi167), .Z(n4828)); + IV2 U4532 ( .A(pi110), .Z(n4829)); + OR2 U4533 ( .A(n4830), .B(pi110), .Z(n4827)); + IV2 U4534 ( .A(pi167), .Z(n4830)); + AN2 U4535 ( .A(n4831), .B(n4832), .Z(n4811)); + IV2 U4536 ( .A(n4833), .Z(n4832)); + AN2 U4537 ( .A(n4834), .B(n4835), .Z(n4833)); + OR2 U4538 ( .A(n4835), .B(n4834), .Z(n4831)); + AN2 U4539 ( .A(n4836), .B(n4837), .Z(n4834)); + OR2 U4540 ( .A(n4838), .B(pi020), .Z(n4837)); + OR2 U4541 ( .A(n4839), .B(n4840), .Z(n4836)); + IV2 U4542 ( .A(pi020), .Z(n4840)); + OR2 U4543 ( .A(n4841), .B(n4842), .Z(n4835)); + IV2 U4544 ( .A(n4843), .Z(n4842)); + OR2 U4545 ( .A(n4844), .B(pi047), .Z(n4843)); + AN2 U4546 ( .A(n4844), .B(pi047), .Z(n4841)); + AN2 U4547 ( .A(n4845), .B(n4846), .Z(n4844)); + OR2 U4548 ( .A(n4847), .B(pi153), .Z(n4846)); + IV2 U4549 ( .A(pi075), .Z(n4847)); + OR2 U4550 ( .A(n4848), .B(pi075), .Z(n4845)); + IV2 U4551 ( .A(pi153), .Z(n4848)); + AN2 U4552 ( .A(pi192), .B(n4849), .Z(n4755)); + OR2 U4553 ( .A(n4850), .B(n4851), .Z(n4849)); + OR2 U4554 ( .A(n4852), .B(n4853), .Z(n4851)); + AN2 U4555 ( .A(n4854), .B(n4855), .Z(n4853)); + OR2 U4556 ( .A(n4856), .B(n4857), .Z(n4855)); + IV2 U4557 ( .A(n4858), .Z(n4854)); + AN2 U4558 ( .A(n4857), .B(n4856), .Z(n4858)); + OR2 U4559 ( .A(n4859), .B(n4860), .Z(n4856)); + AN2 U4560 ( .A(n4839), .B(n4861), .Z(n4860)); + AN2 U4561 ( .A(n4838), .B(po014), .Z(n4859)); + IV2 U4562 ( .A(n4839), .Z(n4838)); + OR2 U4563 ( .A(n4862), .B(n4863), .Z(n4839)); + AN2 U4564 ( .A(n4864), .B(pi192), .Z(n4863)); + OR2 U4565 ( .A(n4865), .B(n4866), .Z(n4864)); + IV2 U4566 ( .A(n4867), .Z(n4866)); + OR2 U4567 ( .A(n4868), .B(n4869), .Z(n4867)); + AN2 U4568 ( .A(n4869), .B(n4868), .Z(n4865)); + AN2 U4569 ( .A(n4870), .B(n4871), .Z(n4868)); + OR2 U4570 ( .A(n4872), .B(po024), .Z(n4871)); + IV2 U4571 ( .A(n4873), .Z(n4872)); + OR2 U4572 ( .A(n4873), .B(n4874), .Z(n4870)); + OR2 U4573 ( .A(n4875), .B(n4876), .Z(n4873)); + AN2 U4574 ( .A(po025), .B(n4877), .Z(n4876)); + AN2 U4575 ( .A(po059), .B(n4557), .Z(n4875)); + OR2 U4576 ( .A(n4878), .B(n4879), .Z(n4869)); + AN2 U4577 ( .A(n4880), .B(n4881), .Z(n4879)); + AN2 U4578 ( .A(n4882), .B(po072), .Z(n4878)); + IV2 U4579 ( .A(n4880), .Z(n4882)); + OR2 U4580 ( .A(n4883), .B(n4884), .Z(n4880)); + AN2 U4581 ( .A(po084), .B(n4885), .Z(n4884)); + AN2 U4582 ( .A(po102), .B(n4886), .Z(n4883)); + IV2 U4583 ( .A(po084), .Z(n4886)); + AN2 U4584 ( .A(n4887), .B(n2837), .Z(n4862)); + OR2 U4585 ( .A(n4888), .B(n4889), .Z(n4887)); + AN2 U4586 ( .A(n4890), .B(n4891), .Z(n4889)); + IV2 U4587 ( .A(n4892), .Z(n4888)); + OR2 U4588 ( .A(n4891), .B(n4890), .Z(n4892)); + OR2 U4589 ( .A(n4893), .B(n4894), .Z(n4890)); + IV2 U4590 ( .A(n4895), .Z(n4894)); + OR2 U4591 ( .A(n4896), .B(pi014), .Z(n4895)); + AN2 U4592 ( .A(n4896), .B(pi014), .Z(n4893)); + AN2 U4593 ( .A(n4897), .B(n4898), .Z(n4896)); + OR2 U4594 ( .A(n4899), .B(pi111), .Z(n4898)); + OR2 U4595 ( .A(n4900), .B(pi097), .Z(n4897)); + IV2 U4596 ( .A(pi111), .Z(n4900)); + AN2 U4597 ( .A(n4901), .B(n4902), .Z(n4891)); + OR2 U4598 ( .A(n4903), .B(pi143), .Z(n4902)); + IV2 U4599 ( .A(n4904), .Z(n4901)); + AN2 U4600 ( .A(n4903), .B(pi143), .Z(n4904)); + AN2 U4601 ( .A(n4905), .B(n4906), .Z(n4903)); + OR2 U4602 ( .A(n4907), .B(pi189), .Z(n4906)); + IV2 U4603 ( .A(n4908), .Z(n4905)); + AN2 U4604 ( .A(pi189), .B(n4907), .Z(n4908)); + IV2 U4605 ( .A(pi176), .Z(n4907)); + AN2 U4606 ( .A(n4909), .B(n4910), .Z(n4857)); + OR2 U4607 ( .A(n4911), .B(po039), .Z(n4910)); + IV2 U4608 ( .A(n4912), .Z(n4911)); + OR2 U4609 ( .A(n4912), .B(n3300), .Z(n4909)); + OR2 U4610 ( .A(n4913), .B(n4914), .Z(n4912)); + AN2 U4611 ( .A(po063), .B(n4628), .Z(n4914)); + AN2 U4612 ( .A(po092), .B(n4915), .Z(n4913)); + AN2 U4613 ( .A(n4916), .B(n4917), .Z(n4852)); + IV2 U4614 ( .A(n4918), .Z(n4917)); + AN2 U4615 ( .A(n4919), .B(n4920), .Z(n4918)); + OR2 U4616 ( .A(n4920), .B(n4919), .Z(n4916)); + IV2 U4617 ( .A(n4921), .Z(n4919)); + OR2 U4618 ( .A(n4922), .B(n4923), .Z(n4921)); + AN2 U4619 ( .A(n4821), .B(n3391), .Z(n4923)); + IV2 U4620 ( .A(n4924), .Z(n3391)); + AN2 U4621 ( .A(n4924), .B(n4820), .Z(n4922)); + IV2 U4622 ( .A(n4821), .Z(n4820)); + OR2 U4623 ( .A(n4925), .B(n4926), .Z(n4821)); + AN2 U4624 ( .A(n4927), .B(pi192), .Z(n4926)); + OR2 U4625 ( .A(n4928), .B(n4929), .Z(n4927)); + IV2 U4626 ( .A(n4930), .Z(n4929)); + OR2 U4627 ( .A(n4931), .B(n4932), .Z(n4930)); + AN2 U4628 ( .A(n4932), .B(n4931), .Z(n4928)); + AN2 U4629 ( .A(n4933), .B(n4934), .Z(n4931)); + OR2 U4630 ( .A(n4935), .B(po001), .Z(n4934)); + IV2 U4631 ( .A(n4936), .Z(n4935)); + OR2 U4632 ( .A(n4936), .B(n4937), .Z(n4933)); + OR2 U4633 ( .A(n4938), .B(n4939), .Z(n4936)); + AN2 U4634 ( .A(po011), .B(n4441), .Z(n4939)); + AN2 U4635 ( .A(po036), .B(n3688), .Z(n4938)); + OR2 U4636 ( .A(n4940), .B(n4941), .Z(n4932)); + AN2 U4637 ( .A(n4942), .B(n4943), .Z(n4941)); + AN2 U4638 ( .A(n4944), .B(po057), .Z(n4940)); + IV2 U4639 ( .A(n4942), .Z(n4944)); + OR2 U4640 ( .A(n4945), .B(n4946), .Z(n4942)); + AN2 U4641 ( .A(po069), .B(n4947), .Z(n4946)); + AN2 U4642 ( .A(po082), .B(n4948), .Z(n4945)); + IV2 U4643 ( .A(po069), .Z(n4948)); + AN2 U4644 ( .A(n4949), .B(n2837), .Z(n4925)); + OR2 U4645 ( .A(n4950), .B(n4951), .Z(n4949)); + AN2 U4646 ( .A(n4952), .B(n4953), .Z(n4951)); + IV2 U4647 ( .A(n4954), .Z(n4950)); + OR2 U4648 ( .A(n4953), .B(n4952), .Z(n4954)); + OR2 U4649 ( .A(n4955), .B(n4956), .Z(n4952)); + IV2 U4650 ( .A(n4957), .Z(n4956)); + OR2 U4651 ( .A(n4958), .B(pi024), .Z(n4957)); + AN2 U4652 ( .A(n4958), .B(pi024), .Z(n4955)); + AN2 U4653 ( .A(n4959), .B(n4960), .Z(n4958)); + OR2 U4654 ( .A(n4961), .B(pi078), .Z(n4960)); + OR2 U4655 ( .A(n4962), .B(pi030), .Z(n4959)); + IV2 U4656 ( .A(pi078), .Z(n4962)); + AN2 U4657 ( .A(n4963), .B(n4964), .Z(n4953)); + OR2 U4658 ( .A(n4965), .B(pi087), .Z(n4964)); + IV2 U4659 ( .A(n4966), .Z(n4963)); + AN2 U4660 ( .A(n4965), .B(pi087), .Z(n4966)); + AN2 U4661 ( .A(n4967), .B(n4968), .Z(n4965)); + OR2 U4662 ( .A(n4969), .B(pi164), .Z(n4968)); + OR2 U4663 ( .A(n4970), .B(pi159), .Z(n4967)); + IV2 U4664 ( .A(pi164), .Z(n4970)); + OR2 U4665 ( .A(n4971), .B(n4972), .Z(n4924)); + AN2 U4666 ( .A(po027), .B(n3512), .Z(n4972)); + AN2 U4667 ( .A(po104), .B(n3363), .Z(n4971)); + OR2 U4668 ( .A(n4973), .B(n4974), .Z(n4920)); + AN2 U4669 ( .A(po038), .B(n3380), .Z(n4974)); + AN2 U4670 ( .A(po071), .B(n4975), .Z(n4973)); + OR2 U4671 ( .A(n4976), .B(n4977), .Z(n4850)); + AN2 U4672 ( .A(n4978), .B(n4979), .Z(n4977)); + OR2 U4673 ( .A(n4980), .B(n4981), .Z(n4979)); + IV2 U4674 ( .A(n4982), .Z(n4978)); + AN2 U4675 ( .A(n4981), .B(n4980), .Z(n4982)); + OR2 U4676 ( .A(n4983), .B(n4984), .Z(n4980)); + AN2 U4677 ( .A(n4769), .B(n3049), .Z(n4984)); + AN2 U4678 ( .A(n4771), .B(po010), .Z(n4983)); + IV2 U4679 ( .A(n4769), .Z(n4771)); + OR2 U4680 ( .A(n4985), .B(n4986), .Z(n4769)); + AN2 U4681 ( .A(n4987), .B(pi192), .Z(n4986)); + OR2 U4682 ( .A(n4988), .B(n4989), .Z(n4987)); + IV2 U4683 ( .A(n4990), .Z(n4989)); + OR2 U4684 ( .A(n4991), .B(n4992), .Z(n4990)); + AN2 U4685 ( .A(n4992), .B(n4991), .Z(n4988)); + AN2 U4686 ( .A(n4993), .B(n4994), .Z(n4991)); + OR2 U4687 ( .A(n4995), .B(po031), .Z(n4994)); + IV2 U4688 ( .A(n4996), .Z(n4995)); + OR2 U4689 ( .A(n4996), .B(n2962), .Z(n4993)); + OR2 U4690 ( .A(n4997), .B(n4998), .Z(n4996)); + AN2 U4691 ( .A(po044), .B(n4999), .Z(n4998)); + IV2 U4692 ( .A(po052), .Z(n4999)); + AN2 U4693 ( .A(po052), .B(n5000), .Z(n4997)); + OR2 U4694 ( .A(n5001), .B(n5002), .Z(n4992)); + AN2 U4695 ( .A(n5003), .B(n5004), .Z(n5002)); + AN2 U4696 ( .A(n5005), .B(po079), .Z(n5001)); + IV2 U4697 ( .A(n5003), .Z(n5005)); + OR2 U4698 ( .A(n5006), .B(n5007), .Z(n5003)); + AN2 U4699 ( .A(po106), .B(n2931), .Z(n5007)); + AN2 U4700 ( .A(po107), .B(n5008), .Z(n5006)); + AN2 U4701 ( .A(n5009), .B(n2837), .Z(n4985)); + OR2 U4702 ( .A(n5010), .B(n5011), .Z(n5009)); + IV2 U4703 ( .A(n5012), .Z(n5011)); + OR2 U4704 ( .A(n5013), .B(n5014), .Z(n5012)); + AN2 U4705 ( .A(n5014), .B(n5013), .Z(n5010)); + AN2 U4706 ( .A(n5015), .B(n5016), .Z(n5013)); + OR2 U4707 ( .A(n5017), .B(pi011), .Z(n5016)); + IV2 U4708 ( .A(n5018), .Z(n5017)); + OR2 U4709 ( .A(n5018), .B(n5019), .Z(n5015)); + OR2 U4710 ( .A(n5020), .B(n5021), .Z(n5018)); + AN2 U4711 ( .A(pi021), .B(n5022), .Z(n5021)); + AN2 U4712 ( .A(pi032), .B(n5023), .Z(n5020)); + IV2 U4713 ( .A(pi021), .Z(n5023)); + OR2 U4714 ( .A(n5024), .B(n5025), .Z(n5014)); + AN2 U4715 ( .A(n5026), .B(n5027), .Z(n5025)); + AN2 U4716 ( .A(n5028), .B(pi086), .Z(n5024)); + IV2 U4717 ( .A(n5026), .Z(n5028)); + OR2 U4718 ( .A(n5029), .B(n5030), .Z(n5026)); + AN2 U4719 ( .A(pi115), .B(n5031), .Z(n5030)); + AN2 U4720 ( .A(pi165), .B(n5032), .Z(n5029)); + IV2 U4721 ( .A(pi115), .Z(n5032)); + AN2 U4722 ( .A(n5033), .B(n5034), .Z(n4981)); + OR2 U4723 ( .A(n5035), .B(po035), .Z(n5034)); + IV2 U4724 ( .A(n5036), .Z(n5035)); + OR2 U4725 ( .A(n5036), .B(n5037), .Z(n5033)); + OR2 U4726 ( .A(n5038), .B(n5039), .Z(n5036)); + AN2 U4727 ( .A(po070), .B(n3286), .Z(n5039)); + AN2 U4728 ( .A(po099), .B(n5040), .Z(n5038)); + AN2 U4729 ( .A(n5041), .B(n5042), .Z(n4976)); + OR2 U4730 ( .A(n5043), .B(n5044), .Z(n5042)); + IV2 U4731 ( .A(n5045), .Z(n5041)); + AN2 U4732 ( .A(n5044), .B(n5043), .Z(n5045)); + OR2 U4733 ( .A(n5046), .B(n5047), .Z(n5043)); + IV2 U4734 ( .A(n5048), .Z(n5047)); + OR2 U4735 ( .A(n5049), .B(n5050), .Z(n5048)); + AN2 U4736 ( .A(n5050), .B(n5049), .Z(n5046)); + AN2 U4737 ( .A(n5051), .B(n5052), .Z(n5049)); + OR2 U4738 ( .A(n4319), .B(po013), .Z(n5052)); + OR2 U4739 ( .A(n5053), .B(po004), .Z(n5051)); + IV2 U4740 ( .A(po013), .Z(n5053)); + OR2 U4741 ( .A(n5054), .B(n5055), .Z(n5050)); + AN2 U4742 ( .A(po028), .B(n4013), .Z(n5055)); + AN2 U4743 ( .A(po040), .B(n5056), .Z(n5054)); + AN2 U4744 ( .A(n5057), .B(n5058), .Z(n5044)); + OR2 U4745 ( .A(n5059), .B(n5060), .Z(n5058)); + IV2 U4746 ( .A(n5061), .Z(n5059)); + OR2 U4747 ( .A(n5062), .B(n5061), .Z(n5057)); + OR2 U4748 ( .A(n5063), .B(n5064), .Z(n5061)); + AN2 U4749 ( .A(po064), .B(n4128), .Z(n5064)); + AN2 U4750 ( .A(po085), .B(n4133), .Z(n5063)); + IV2 U4751 ( .A(n5060), .Z(n5062)); + OR2 U4752 ( .A(n5065), .B(n5066), .Z(n5060)); + AN2 U4753 ( .A(po091), .B(n3265), .Z(n5066)); + AN2 U4754 ( .A(po103), .B(n4201), .Z(n5065)); + IV2 U4755 ( .A(n5067), .Z(po041)); + AN2 U4756 ( .A(n5068), .B(pi193), .Z(n5067)); + AN2 U4757 ( .A(pi057), .B(n5069), .Z(n5068)); + IV2 U4758 ( .A(pi037), .Z(n5069)); + OR2 U4759 ( .A(n5070), .B(n5071), .Z(po037)); + AN2 U4760 ( .A(n3021), .B(n5072), .Z(n5071)); + OR2 U4761 ( .A(n5073), .B(n5074), .Z(n5072)); + AN2 U4762 ( .A(n3018), .B(n5075), .Z(n5073)); + OR2 U4763 ( .A(n5076), .B(n5077), .Z(n5075)); + AN2 U4764 ( .A(n4663), .B(n3284), .Z(n5076)); + OR2 U4765 ( .A(n5078), .B(n5079), .Z(n4663)); + AN2 U4766 ( .A(n3064), .B(n3108), .Z(n5079)); + AN2 U4767 ( .A(n3173), .B(n3115), .Z(n5078)); + AN2 U4768 ( .A(n3083), .B(n5080), .Z(n5070)); + OR2 U4769 ( .A(n5081), .B(n5082), .Z(n5080)); + OR2 U4770 ( .A(n5083), .B(n5084), .Z(n5082)); + AN2 U4771 ( .A(po070), .B(n4327), .Z(n5084)); + OR2 U4772 ( .A(n5085), .B(n5086), .Z(n4327)); + OR2 U4773 ( .A(n5087), .B(n5088), .Z(n5086)); + AN2 U4774 ( .A(n3273), .B(n5089), .Z(n5088)); + IV2 U4775 ( .A(n3284), .Z(n3273)); + AN2 U4776 ( .A(n5090), .B(n3274), .Z(n5087)); + OR2 U4777 ( .A(n5091), .B(n3282), .Z(n5085)); + IV2 U4778 ( .A(n4666), .Z(n3282)); + AN2 U4779 ( .A(n5092), .B(n3199), .Z(n5083)); + OR2 U4780 ( .A(n5093), .B(n5094), .Z(n5092)); + OR2 U4781 ( .A(n5095), .B(n5096), .Z(n5094)); + AN2 U4782 ( .A(n5090), .B(po010), .Z(n5096)); + AN2 U4783 ( .A(n3037), .B(n3061), .Z(n5090)); + AN2 U4784 ( .A(n5097), .B(n5098), .Z(n5095)); + AN2 U4785 ( .A(n3037), .B(n5099), .Z(n5098)); + AN2 U4786 ( .A(n5100), .B(n3120), .Z(n5097)); + OR2 U4787 ( .A(n5101), .B(n3061), .Z(n3120)); + AN2 U4788 ( .A(n3106), .B(pi192), .Z(n3061)); + AN2 U4789 ( .A(po010), .B(pi192), .Z(n5101)); + AN2 U4790 ( .A(n3082), .B(pi192), .Z(n5093)); + IV2 U4791 ( .A(n3108), .Z(n3082)); + OR2 U4792 ( .A(pi033), .B(n3286), .Z(n3108)); + OR2 U4793 ( .A(n5102), .B(n5103), .Z(n5081)); + AN2 U4794 ( .A(n3015), .B(n5104), .Z(n5103)); + IV2 U4795 ( .A(n3018), .Z(n3015)); + AN2 U4796 ( .A(n5105), .B(n3205), .Z(n5102)); + OR2 U4797 ( .A(n5106), .B(n5107), .Z(n5105)); + OR2 U4798 ( .A(n5091), .B(n5108), .Z(n5107)); + AN2 U4799 ( .A(n5100), .B(n5109), .Z(n5108)); + OR2 U4800 ( .A(n5110), .B(n5111), .Z(n5109)); + AN2 U4801 ( .A(n5112), .B(n2925), .Z(n5111)); + AN2 U4802 ( .A(po010), .B(n5089), .Z(n5112)); + IV2 U4803 ( .A(n3100), .Z(n5089)); + AN2 U4804 ( .A(n5113), .B(n3080), .Z(n5110)); + AN2 U4805 ( .A(n2837), .B(po010), .Z(n3080)); + AN2 U4806 ( .A(n3112), .B(n5099), .Z(n5113)); + AN2 U4807 ( .A(n3065), .B(n5114), .Z(n5091)); + AN2 U4808 ( .A(n3112), .B(n3274), .Z(n5114)); + IV2 U4809 ( .A(n3280), .Z(n3274)); + AN2 U4810 ( .A(n2837), .B(n5115), .Z(n3065)); + AN2 U4811 ( .A(n3073), .B(n2837), .Z(n5106)); + IV2 U4812 ( .A(n3115), .Z(n3073)); + OR2 U4813 ( .A(pi141), .B(n3286), .Z(n3115)); + OR2 U4814 ( .A(n5116), .B(n5117), .Z(po034)); + OR2 U4815 ( .A(n5118), .B(n5119), .Z(n5117)); + AN2 U4816 ( .A(pi054), .B(n5120), .Z(n5119)); + AN2 U4817 ( .A(n5121), .B(n5122), .Z(n5118)); + AN2 U4818 ( .A(n5123), .B(n5124), .Z(n5122)); + OR2 U4819 ( .A(po085), .B(po064), .Z(n5124)); + OR2 U4820 ( .A(n4125), .B(n4133), .Z(n5123)); + AN2 U4821 ( .A(n4129), .B(n4128), .Z(n4125)); + AN2 U4822 ( .A(pi052), .B(n5125), .Z(n5121)); + AN2 U4823 ( .A(n5126), .B(n5127), .Z(n5116)); + OR2 U4824 ( .A(n4167), .B(n5128), .Z(n5127)); + OR2 U4825 ( .A(n5129), .B(n5130), .Z(n5128)); + AN2 U4826 ( .A(n5131), .B(po064), .Z(n5130)); + AN2 U4827 ( .A(pi054), .B(po085), .Z(n5131)); + AN2 U4828 ( .A(n4129), .B(n4133), .Z(n5129)); + OR2 U4829 ( .A(n5132), .B(n5133), .Z(po033)); + AN2 U4830 ( .A(n3371), .B(n5134), .Z(n5133)); + OR2 U4831 ( .A(n5135), .B(n5136), .Z(n5134)); + AN2 U4832 ( .A(n5137), .B(n3412), .Z(n5132)); + OR2 U4833 ( .A(n5138), .B(n5139), .Z(n5137)); + OR2 U4834 ( .A(n5140), .B(n5141), .Z(po030)); + AN2 U4835 ( .A(n5142), .B(pi192), .Z(n5141)); + OR2 U4836 ( .A(n5143), .B(n5144), .Z(n5142)); + AN2 U4837 ( .A(n2834), .B(n5145), .Z(n5144)); + OR2 U4838 ( .A(n5146), .B(n5147), .Z(n5145)); + AN2 U4839 ( .A(n2998), .B(n3847), .Z(n5147)); + AN2 U4840 ( .A(n5148), .B(n5149), .Z(n5146)); + OR2 U4841 ( .A(n2862), .B(n5150), .Z(n5149)); + OR2 U4842 ( .A(n2880), .B(n5151), .Z(n5150)); + AN2 U4843 ( .A(n2887), .B(n2901), .Z(n5151)); + AN2 U4844 ( .A(n2891), .B(n5152), .Z(n5148)); + IV2 U4845 ( .A(n5153), .Z(n5152)); + AN2 U4846 ( .A(n5154), .B(n2833), .Z(n5143)); + OR2 U4847 ( .A(n5155), .B(n5156), .Z(n5154)); + AN2 U4848 ( .A(n5157), .B(n5158), .Z(n5155)); + AN2 U4849 ( .A(n2930), .B(n2878), .Z(n5158)); + AN2 U4850 ( .A(n5159), .B(n2837), .Z(n5140)); + OR2 U4851 ( .A(n5160), .B(n5161), .Z(n5159)); + AN2 U4852 ( .A(n2846), .B(n5162), .Z(n5161)); + OR2 U4853 ( .A(n5163), .B(n5164), .Z(n5162)); + AN2 U4854 ( .A(n2998), .B(n5165), .Z(n5164)); + AN2 U4855 ( .A(n5166), .B(n5167), .Z(n5163)); + OR2 U4856 ( .A(n5168), .B(n5169), .Z(n5167)); + AN2 U4857 ( .A(n3222), .B(n2946), .Z(n5168)); + OR2 U4858 ( .A(n5170), .B(n2959), .Z(n3222)); + AN2 U4859 ( .A(n2982), .B(n2901), .Z(n2959)); + AN2 U4860 ( .A(po107), .B(n5171), .Z(n5170)); + IV2 U4861 ( .A(n2981), .Z(n5171)); + AN2 U4862 ( .A(pi081), .B(pi200), .Z(n2981)); + AN2 U4863 ( .A(n2947), .B(n5172), .Z(n5166)); + AN2 U4864 ( .A(n5173), .B(n2845), .Z(n5160)); + OR2 U4865 ( .A(n5174), .B(n5175), .Z(n5173)); + AN2 U4866 ( .A(n5157), .B(n5176), .Z(n5174)); + AN2 U4867 ( .A(n2908), .B(n2938), .Z(n5176)); + OR2 U4868 ( .A(pi081), .B(n2931), .Z(n2938)); + IV2 U4869 ( .A(n5169), .Z(n2908)); + AN2 U4870 ( .A(n2861), .B(pi200), .Z(n5157)); + OR2 U4871 ( .A(n5177), .B(n5178), .Z(po029)); + OR2 U4872 ( .A(n5179), .B(n5180), .Z(n5178)); + AN2 U4873 ( .A(n5181), .B(n4313), .Z(n5180)); + AN2 U4874 ( .A(n3945), .B(n5182), .Z(n5179)); + OR2 U4875 ( .A(n5183), .B(n5184), .Z(n5182)); + OR2 U4876 ( .A(n5185), .B(n5186), .Z(n5184)); + AN2 U4877 ( .A(n5187), .B(pi186), .Z(n5186)); + OR2 U4878 ( .A(n5188), .B(n5189), .Z(n5187)); + AN2 U4879 ( .A(n5190), .B(n5191), .Z(n5189)); + AN2 U4880 ( .A(n5192), .B(pi124), .Z(n5188)); + IV2 U4881 ( .A(n5190), .Z(n5192)); + AN2 U4882 ( .A(n5193), .B(n5194), .Z(n5185)); + OR2 U4883 ( .A(n5195), .B(n5196), .Z(n5193)); + AN2 U4884 ( .A(n5190), .B(pi124), .Z(n5196)); + OR2 U4885 ( .A(n5197), .B(n5198), .Z(n5190)); + AN2 U4886 ( .A(n5199), .B(n5200), .Z(n5198)); + AN2 U4887 ( .A(n5201), .B(pi109), .Z(n5197)); + IV2 U4888 ( .A(n5199), .Z(n5201)); + AN2 U4889 ( .A(n5202), .B(n5191), .Z(n5195)); + OR2 U4890 ( .A(n5203), .B(n5204), .Z(n5202)); + AN2 U4891 ( .A(n5199), .B(pi109), .Z(n5204)); + OR2 U4892 ( .A(n5205), .B(n5206), .Z(n5199)); + AN2 U4893 ( .A(n5207), .B(n5208), .Z(n5206)); + AN2 U4894 ( .A(n5181), .B(pi055), .Z(n5205)); + AN2 U4895 ( .A(n5209), .B(n5200), .Z(n5203)); + AN2 U4896 ( .A(pi055), .B(n5207), .Z(n5209)); + AN2 U4897 ( .A(n5210), .B(n5211), .Z(n5183)); + OR2 U4898 ( .A(n5212), .B(n5213), .Z(n5211)); + IV2 U4899 ( .A(n5214), .Z(n5210)); + AN2 U4900 ( .A(n5213), .B(n5212), .Z(n5214)); + OR2 U4901 ( .A(n5215), .B(n5216), .Z(n5212)); + IV2 U4902 ( .A(n5217), .Z(n5216)); + OR2 U4903 ( .A(n5218), .B(pi006), .Z(n5217)); + AN2 U4904 ( .A(n5218), .B(pi006), .Z(n5215)); + AN2 U4905 ( .A(n5219), .B(n5220), .Z(n5218)); + OR2 U4906 ( .A(n5221), .B(pi061), .Z(n5220)); + IV2 U4907 ( .A(pi051), .Z(n5221)); + OR2 U4908 ( .A(n5222), .B(pi051), .Z(n5219)); + IV2 U4909 ( .A(pi061), .Z(n5222)); + AN2 U4910 ( .A(n5223), .B(n5224), .Z(n5213)); + IV2 U4911 ( .A(n5225), .Z(n5224)); + AN2 U4912 ( .A(n5226), .B(n5227), .Z(n5225)); + OR2 U4913 ( .A(n5227), .B(n5226), .Z(n5223)); + OR2 U4914 ( .A(n5228), .B(n5229), .Z(n5226)); + AN2 U4915 ( .A(pi093), .B(n5230), .Z(n5229)); + IV2 U4916 ( .A(n5231), .Z(n5228)); + OR2 U4917 ( .A(n5230), .B(pi093), .Z(n5231)); + IV2 U4918 ( .A(pi122), .Z(n5230)); + AN2 U4919 ( .A(n5232), .B(n5233), .Z(n5227)); + IV2 U4920 ( .A(n5234), .Z(n5233)); + AN2 U4921 ( .A(pi134), .B(n5235), .Z(n5234)); + OR2 U4922 ( .A(n5235), .B(pi134), .Z(n5232)); + IV2 U4923 ( .A(pi198), .Z(n5235)); + OR2 U4924 ( .A(n5236), .B(n5237), .Z(n5177)); + AN2 U4925 ( .A(n5238), .B(n2837), .Z(n5237)); + OR2 U4926 ( .A(n5239), .B(n5240), .Z(n5238)); + AN2 U4927 ( .A(n5241), .B(n5242), .Z(n5240)); + OR2 U4928 ( .A(n3809), .B(n5243), .Z(n5242)); + IV2 U4929 ( .A(n3812), .Z(n3809)); + OR2 U4930 ( .A(n5244), .B(n3812), .Z(n5241)); + AN2 U4931 ( .A(n5245), .B(n5246), .Z(n3812)); + IV2 U4932 ( .A(n5247), .Z(n5246)); + AN2 U4933 ( .A(n5248), .B(n5249), .Z(n5247)); + OR2 U4934 ( .A(n5249), .B(n5248), .Z(n5245)); + OR2 U4935 ( .A(n5250), .B(n5251), .Z(n5248)); + AN2 U4936 ( .A(pi040), .B(n5252), .Z(n5251)); + IV2 U4937 ( .A(pi095), .Z(n5252)); + AN2 U4938 ( .A(pi095), .B(n4735), .Z(n5250)); + AN2 U4939 ( .A(n5253), .B(n5254), .Z(n5249)); + OR2 U4940 ( .A(n4747), .B(pi156), .Z(n5254)); + IV2 U4941 ( .A(pi151), .Z(n4747)); + OR2 U4942 ( .A(n4648), .B(pi151), .Z(n5253)); + AN2 U4943 ( .A(n5255), .B(n5256), .Z(n5239)); + OR2 U4944 ( .A(n3815), .B(n5257), .Z(n5256)); + OR2 U4945 ( .A(n5258), .B(n3818), .Z(n5255)); + IV2 U4946 ( .A(n3815), .Z(n3818)); + OR2 U4947 ( .A(n5259), .B(n5260), .Z(n3815)); + AN2 U4948 ( .A(n5261), .B(n5262), .Z(n5260)); + IV2 U4949 ( .A(n5263), .Z(n5259)); + OR2 U4950 ( .A(n5262), .B(n5261), .Z(n5263)); + OR2 U4951 ( .A(n5264), .B(n5265), .Z(n5261)); + AN2 U4952 ( .A(pi128), .B(n3177), .Z(n5265)); + AN2 U4953 ( .A(pi141), .B(n3205), .Z(n5264)); + AN2 U4954 ( .A(n5266), .B(n5267), .Z(n5262)); + OR2 U4955 ( .A(n5115), .B(pi185), .Z(n5267)); + OR2 U4956 ( .A(n5268), .B(pi174), .Z(n5266)); + IV2 U4957 ( .A(pi185), .Z(n5268)); + AN2 U4958 ( .A(pi192), .B(n5269), .Z(n5236)); + OR2 U4959 ( .A(n5270), .B(n5271), .Z(n5269)); + OR2 U4960 ( .A(n5272), .B(n5273), .Z(n5271)); + AN2 U4961 ( .A(n5274), .B(n5275), .Z(n5273)); + IV2 U4962 ( .A(n5276), .Z(n5275)); + AN2 U4963 ( .A(n5277), .B(n5278), .Z(n5276)); + OR2 U4964 ( .A(n5278), .B(n5277), .Z(n5274)); + AN2 U4965 ( .A(n5279), .B(n5280), .Z(n5277)); + OR2 U4966 ( .A(n5243), .B(pi036), .Z(n5280)); + IV2 U4967 ( .A(n5244), .Z(n5243)); + OR2 U4968 ( .A(n5244), .B(n5281), .Z(n5279)); + IV2 U4969 ( .A(pi036), .Z(n5281)); + OR2 U4970 ( .A(n3871), .B(n5282), .Z(n5244)); + AN2 U4971 ( .A(n5283), .B(pi192), .Z(n5282)); + OR2 U4972 ( .A(n5284), .B(n5285), .Z(n5283)); + AN2 U4973 ( .A(n5286), .B(n5287), .Z(n5285)); + IV2 U4974 ( .A(n5288), .Z(n5284)); + OR2 U4975 ( .A(n5287), .B(n5286), .Z(n5288)); + OR2 U4976 ( .A(n5289), .B(n5290), .Z(n5286)); + IV2 U4977 ( .A(n5291), .Z(n5290)); + OR2 U4978 ( .A(n5292), .B(pi017), .Z(n5291)); + AN2 U4979 ( .A(pi017), .B(n5292), .Z(n5289)); + AN2 U4980 ( .A(n5293), .B(n5294), .Z(n5292)); + OR2 U4981 ( .A(n5295), .B(pi083), .Z(n5294)); + IV2 U4982 ( .A(pi027), .Z(n5295)); + OR2 U4983 ( .A(n5296), .B(pi027), .Z(n5293)); + IV2 U4984 ( .A(pi083), .Z(n5296)); + AN2 U4985 ( .A(n5297), .B(n5298), .Z(n5287)); + OR2 U4986 ( .A(n5299), .B(pi089), .Z(n5298)); + IV2 U4987 ( .A(n5300), .Z(n5297)); + AN2 U4988 ( .A(n5299), .B(pi089), .Z(n5300)); + AN2 U4989 ( .A(n5301), .B(n5302), .Z(n5299)); + OR2 U4990 ( .A(n5303), .B(pi162), .Z(n5302)); + OR2 U4991 ( .A(n5304), .B(pi140), .Z(n5301)); + IV2 U4992 ( .A(pi162), .Z(n5304)); + AN2 U4993 ( .A(n5305), .B(n2837), .Z(n3871)); + OR2 U4994 ( .A(n5306), .B(n5307), .Z(n5305)); + AN2 U4995 ( .A(n5308), .B(n5309), .Z(n5307)); + IV2 U4996 ( .A(n5310), .Z(n5306)); + OR2 U4997 ( .A(n5309), .B(n5308), .Z(n5310)); + OR2 U4998 ( .A(n5311), .B(n5312), .Z(n5308)); + IV2 U4999 ( .A(n5313), .Z(n5312)); + OR2 U5000 ( .A(n5314), .B(pi064), .Z(n5313)); + AN2 U5001 ( .A(pi064), .B(n5314), .Z(n5311)); + AN2 U5002 ( .A(n5315), .B(n5316), .Z(n5314)); + OR2 U5003 ( .A(n4077), .B(pi108), .Z(n5316)); + OR2 U5004 ( .A(n5317), .B(pi076), .Z(n5315)); + IV2 U5005 ( .A(pi108), .Z(n5317)); + AN2 U5006 ( .A(n5318), .B(n5319), .Z(n5309)); + OR2 U5007 ( .A(n5320), .B(pi114), .Z(n5319)); + IV2 U5008 ( .A(n5321), .Z(n5320)); + OR2 U5009 ( .A(n5321), .B(n5322), .Z(n5318)); + OR2 U5010 ( .A(n5323), .B(n5324), .Z(n5321)); + AN2 U5011 ( .A(pi160), .B(n4074), .Z(n5324)); + AN2 U5012 ( .A(pi170), .B(n4358), .Z(n5323)); + OR2 U5013 ( .A(n5325), .B(n5326), .Z(n5278)); + IV2 U5014 ( .A(n5327), .Z(n5326)); + OR2 U5015 ( .A(n5328), .B(pi101), .Z(n5327)); + AN2 U5016 ( .A(n5328), .B(pi101), .Z(n5325)); + AN2 U5017 ( .A(n5329), .B(n5330), .Z(n5328)); + OR2 U5018 ( .A(n5331), .B(pi205), .Z(n5330)); + OR2 U5019 ( .A(n5332), .B(pi168), .Z(n5329)); + IV2 U5020 ( .A(pi205), .Z(n5332)); + AN2 U5021 ( .A(n5333), .B(n5334), .Z(n5272)); + AN2 U5022 ( .A(n5335), .B(n5200), .Z(n5334)); + IV2 U5023 ( .A(pi109), .Z(n5200)); + AN2 U5024 ( .A(n5191), .B(n5194), .Z(n5335)); + IV2 U5025 ( .A(pi186), .Z(n5194)); + IV2 U5026 ( .A(pi124), .Z(n5191)); + AN2 U5027 ( .A(n5181), .B(n5208), .Z(n5333)); + IV2 U5028 ( .A(pi055), .Z(n5208)); + IV2 U5029 ( .A(n5207), .Z(n5181)); + OR2 U5030 ( .A(n3977), .B(n5336), .Z(n5207)); + AN2 U5031 ( .A(n5337), .B(pi192), .Z(n5336)); + OR2 U5032 ( .A(n5338), .B(n5339), .Z(n5337)); + AN2 U5033 ( .A(n5340), .B(n5341), .Z(n5339)); + IV2 U5034 ( .A(n5342), .Z(n5338)); + OR2 U5035 ( .A(n5341), .B(n5340), .Z(n5342)); + OR2 U5036 ( .A(n5343), .B(n5344), .Z(n5340)); + IV2 U5037 ( .A(n5345), .Z(n5344)); + OR2 U5038 ( .A(n5346), .B(n5347), .Z(n5345)); + AN2 U5039 ( .A(n5346), .B(n5347), .Z(n5343)); + AN2 U5040 ( .A(n5348), .B(n5349), .Z(n5346)); + OR2 U5041 ( .A(n5350), .B(pi099), .Z(n5349)); + OR2 U5042 ( .A(n5351), .B(pi018), .Z(n5348)); + IV2 U5043 ( .A(pi099), .Z(n5351)); + AN2 U5044 ( .A(n5352), .B(n5353), .Z(n5341)); + OR2 U5045 ( .A(n5354), .B(pi150), .Z(n5353)); + IV2 U5046 ( .A(n5355), .Z(n5352)); + AN2 U5047 ( .A(pi150), .B(n5354), .Z(n5355)); + AN2 U5048 ( .A(n5356), .B(n5357), .Z(n5354)); + OR2 U5049 ( .A(n5358), .B(pi180), .Z(n5357)); + OR2 U5050 ( .A(n5359), .B(pi172), .Z(n5356)); + IV2 U5051 ( .A(pi180), .Z(n5359)); + AN2 U5052 ( .A(n5360), .B(n2837), .Z(n3977)); + AN2 U5053 ( .A(n5361), .B(n5362), .Z(n5360)); + IV2 U5054 ( .A(n5363), .Z(n5362)); + AN2 U5055 ( .A(n5364), .B(n5365), .Z(n5363)); + OR2 U5056 ( .A(n5365), .B(n5364), .Z(n5361)); + OR2 U5057 ( .A(n5366), .B(n5367), .Z(n5364)); + AN2 U5058 ( .A(n5368), .B(n3261), .Z(n5367)); + AN2 U5059 ( .A(n5369), .B(n3321), .Z(n5366)); + IV2 U5060 ( .A(n5368), .Z(n5369)); + OR2 U5061 ( .A(n5370), .B(n5371), .Z(n5368)); + AN2 U5062 ( .A(pi003), .B(n5372), .Z(n5371)); + AN2 U5063 ( .A(pi130), .B(n3597), .Z(n5370)); + AN2 U5064 ( .A(n5373), .B(n5374), .Z(n5365)); + OR2 U5065 ( .A(n5375), .B(pi142), .Z(n5374)); + IV2 U5066 ( .A(n5376), .Z(n5375)); + OR2 U5067 ( .A(n5376), .B(n4440), .Z(n5373)); + OR2 U5068 ( .A(n5377), .B(n5378), .Z(n5376)); + AN2 U5069 ( .A(pi177), .B(n5379), .Z(n5378)); + AN2 U5070 ( .A(pi195), .B(n5380), .Z(n5377)); + IV2 U5071 ( .A(pi177), .Z(n5380)); + AN2 U5072 ( .A(n5381), .B(n5382), .Z(n5270)); + IV2 U5073 ( .A(n5383), .Z(n5382)); + AN2 U5074 ( .A(n5384), .B(n5385), .Z(n5383)); + OR2 U5075 ( .A(n5385), .B(n5384), .Z(n5381)); + AN2 U5076 ( .A(n5386), .B(n5387), .Z(n5384)); + OR2 U5077 ( .A(n5257), .B(pi001), .Z(n5387)); + IV2 U5078 ( .A(n5258), .Z(n5257)); + OR2 U5079 ( .A(n5258), .B(n5388), .Z(n5386)); + IV2 U5080 ( .A(pi001), .Z(n5388)); + OR2 U5081 ( .A(n3831), .B(n5389), .Z(n5258)); + AN2 U5082 ( .A(n5390), .B(pi192), .Z(n5389)); + OR2 U5083 ( .A(n5391), .B(n5392), .Z(n5390)); + AN2 U5084 ( .A(n5393), .B(n5394), .Z(n5392)); + IV2 U5085 ( .A(n5395), .Z(n5391)); + OR2 U5086 ( .A(n5394), .B(n5393), .Z(n5395)); + OR2 U5087 ( .A(n5396), .B(n5397), .Z(n5393)); + IV2 U5088 ( .A(n5398), .Z(n5397)); + OR2 U5089 ( .A(n5399), .B(pi038), .Z(n5398)); + AN2 U5090 ( .A(pi038), .B(n5399), .Z(n5396)); + AN2 U5091 ( .A(n5400), .B(n5401), .Z(n5399)); + OR2 U5092 ( .A(n5402), .B(pi103), .Z(n5401)); + IV2 U5093 ( .A(pi053), .Z(n5402)); + OR2 U5094 ( .A(n5403), .B(pi053), .Z(n5400)); + IV2 U5095 ( .A(pi103), .Z(n5403)); + AN2 U5096 ( .A(n5404), .B(n5405), .Z(n5394)); + OR2 U5097 ( .A(n5406), .B(pi121), .Z(n5405)); + IV2 U5098 ( .A(n5407), .Z(n5404)); + AN2 U5099 ( .A(n5406), .B(pi121), .Z(n5407)); + AN2 U5100 ( .A(n5408), .B(n5409), .Z(n5406)); + OR2 U5101 ( .A(n5410), .B(pi184), .Z(n5409)); + IV2 U5102 ( .A(pi149), .Z(n5410)); + OR2 U5103 ( .A(n5411), .B(pi149), .Z(n5408)); + IV2 U5104 ( .A(pi184), .Z(n5411)); + AN2 U5105 ( .A(n5412), .B(n2837), .Z(n3831)); + OR2 U5106 ( .A(n5413), .B(n5414), .Z(n5412)); + IV2 U5107 ( .A(n5415), .Z(n5414)); + OR2 U5108 ( .A(n5416), .B(n5417), .Z(n5415)); + AN2 U5109 ( .A(n5417), .B(n5416), .Z(n5413)); + AN2 U5110 ( .A(n5418), .B(n5419), .Z(n5416)); + OR2 U5111 ( .A(n5420), .B(pi081), .Z(n5419)); + IV2 U5112 ( .A(n5421), .Z(n5420)); + OR2 U5113 ( .A(n5421), .B(n2982), .Z(n5418)); + OR2 U5114 ( .A(n5422), .B(n5423), .Z(n5421)); + AN2 U5115 ( .A(pi082), .B(n5424), .Z(n5423)); + IV2 U5116 ( .A(pi092), .Z(n5424)); + AN2 U5117 ( .A(pi092), .B(n2957), .Z(n5422)); + OR2 U5118 ( .A(n5425), .B(n5426), .Z(n5417)); + AN2 U5119 ( .A(n5427), .B(n5165), .Z(n5426)); + AN2 U5120 ( .A(n5428), .B(pi107), .Z(n5425)); + IV2 U5121 ( .A(n5427), .Z(n5428)); + OR2 U5122 ( .A(n5429), .B(n5430), .Z(n5427)); + AN2 U5123 ( .A(pi201), .B(n5431), .Z(n5430)); + AN2 U5124 ( .A(pi206), .B(n3141), .Z(n5429)); + OR2 U5125 ( .A(n5432), .B(n5433), .Z(n5385)); + IV2 U5126 ( .A(n5434), .Z(n5433)); + OR2 U5127 ( .A(n5435), .B(pi059), .Z(n5434)); + AN2 U5128 ( .A(n5435), .B(pi059), .Z(n5432)); + AN2 U5129 ( .A(n5436), .B(n5437), .Z(n5435)); + OR2 U5130 ( .A(n5438), .B(pi197), .Z(n5437)); + IV2 U5131 ( .A(pi131), .Z(n5438)); + OR2 U5132 ( .A(n5439), .B(pi131), .Z(n5436)); + OR2 U5133 ( .A(n5440), .B(n5441), .Z(po026)); + AN2 U5134 ( .A(n3355), .B(n5442), .Z(n5441)); + OR2 U5135 ( .A(n5443), .B(n5444), .Z(n5442)); + OR2 U5136 ( .A(n5445), .B(n5446), .Z(n5444)); + AN2 U5137 ( .A(po036), .B(n5447), .Z(n5446)); + OR2 U5138 ( .A(n4418), .B(n5448), .Z(n5447)); + AN2 U5139 ( .A(n5449), .B(n3236), .Z(n5445)); + AN2 U5140 ( .A(n5450), .B(n5451), .Z(n5449)); + OR2 U5141 ( .A(n5452), .B(n2837), .Z(n5451)); + OR2 U5142 ( .A(pi192), .B(n5453), .Z(n5450)); + AN2 U5143 ( .A(n4418), .B(n5448), .Z(n5443)); + AN2 U5144 ( .A(n3352), .B(n5454), .Z(n5440)); + IV2 U5145 ( .A(n5455), .Z(po022)); + AN2 U5146 ( .A(n5456), .B(n5457), .Z(n5455)); + AN2 U5147 ( .A(pi074), .B(pi046), .Z(n5457)); + AN2 U5148 ( .A(pi178), .B(pi113), .Z(n5456)); + OR2 U5149 ( .A(n5458), .B(n5459), .Z(po019)); + AN2 U5150 ( .A(n4478), .B(n5460), .Z(n5459)); + OR2 U5151 ( .A(n5461), .B(n4511), .Z(n5460)); + OR2 U5152 ( .A(n5462), .B(n5463), .Z(n4511)); + OR2 U5153 ( .A(n5464), .B(n5465), .Z(n5463)); + AN2 U5154 ( .A(n5466), .B(pi192), .Z(n5465)); + AN2 U5155 ( .A(n5467), .B(n2837), .Z(n5464)); + AN2 U5156 ( .A(n4475), .B(n5468), .Z(n5458)); + OR2 U5157 ( .A(n5469), .B(n5470), .Z(n5468)); + OR2 U5158 ( .A(n5471), .B(n4509), .Z(n5470)); + OR2 U5159 ( .A(n5472), .B(n5473), .Z(n4509)); + OR2 U5160 ( .A(n5474), .B(n5475), .Z(n5473)); + AN2 U5161 ( .A(n5476), .B(n4078), .Z(n5475)); + AN2 U5162 ( .A(n5477), .B(n5322), .Z(n5476)); + AN2 U5163 ( .A(n5478), .B(n4551), .Z(n5472)); + IV2 U5164 ( .A(n4544), .Z(n4551)); + OR2 U5165 ( .A(n4561), .B(n4066), .Z(n4544)); + AN2 U5166 ( .A(pi192), .B(n3901), .Z(n5478)); + AN2 U5167 ( .A(po102), .B(n4347), .Z(n5471)); + OR2 U5168 ( .A(n5479), .B(n4524), .Z(n4347)); + AN2 U5169 ( .A(n5480), .B(n4078), .Z(n4524)); + IV2 U5170 ( .A(n4066), .Z(n4078)); + AN2 U5171 ( .A(n4521), .B(n4072), .Z(n5479)); + OR2 U5172 ( .A(n5481), .B(n5482), .Z(n4521)); + AN2 U5173 ( .A(po059), .B(n5480), .Z(n5482)); + OR2 U5174 ( .A(n5483), .B(po024), .Z(n5480)); + AN2 U5175 ( .A(n5477), .B(n4074), .Z(n5481)); + OR2 U5176 ( .A(n5484), .B(n5485), .Z(n5469)); + AN2 U5177 ( .A(n4517), .B(n3780), .Z(n5485)); + OR2 U5178 ( .A(n5486), .B(n5487), .Z(n4517)); + AN2 U5179 ( .A(n4356), .B(n5488), .Z(n5487)); + AN2 U5180 ( .A(n4076), .B(n5489), .Z(n4356)); + AN2 U5181 ( .A(n4077), .B(n4578), .Z(n5489)); + AN2 U5182 ( .A(n5490), .B(n4543), .Z(n5486)); + AN2 U5183 ( .A(n4348), .B(n4353), .Z(n4543)); + AN2 U5184 ( .A(n3890), .B(n5491), .Z(n5490)); + AN2 U5185 ( .A(n4512), .B(n4072), .Z(n5484)); + OR2 U5186 ( .A(n5492), .B(n3773), .Z(n4072)); + AN2 U5187 ( .A(po025), .B(n3780), .Z(n5492)); + IV2 U5188 ( .A(n4087), .Z(n3780)); + OR2 U5189 ( .A(n5493), .B(n5494), .Z(n4512)); + OR2 U5190 ( .A(n5495), .B(n5496), .Z(n5494)); + AN2 U5191 ( .A(n5497), .B(pi192), .Z(n5496)); + AN2 U5192 ( .A(n5498), .B(n4348), .Z(n5497)); + OR2 U5193 ( .A(n5499), .B(n5500), .Z(n5498)); + AN2 U5194 ( .A(po102), .B(n3880), .Z(n5500)); + AN2 U5195 ( .A(n4353), .B(n3901), .Z(n5499)); + AN2 U5196 ( .A(n5501), .B(n4076), .Z(n5495)); + AN2 U5197 ( .A(n5488), .B(n4358), .Z(n5501)); + AN2 U5198 ( .A(n5502), .B(n4076), .Z(n5493)); + AN2 U5199 ( .A(n2837), .B(n5503), .Z(n4076)); + AN2 U5200 ( .A(po024), .B(n5322), .Z(n5502)); + OR2 U5201 ( .A(n5504), .B(n5505), .Z(po074)); + AN2 U5202 ( .A(n5506), .B(n5507), .Z(n5505)); + OR2 U5203 ( .A(n4167), .B(n5508), .Z(n5507)); + OR2 U5204 ( .A(pi054), .B(n5509), .Z(n5508)); + AN2 U5205 ( .A(pi025), .B(pi146), .Z(n5509)); + OR2 U5206 ( .A(n5510), .B(n5511), .Z(n5506)); + OR2 U5207 ( .A(n5512), .B(n5513), .Z(n5511)); + AN2 U5208 ( .A(n3926), .B(n5514), .Z(n5513)); + OR2 U5209 ( .A(n5515), .B(n5516), .Z(n5514)); + OR2 U5210 ( .A(n5517), .B(n5518), .Z(n5516)); + OR2 U5211 ( .A(pi056), .B(pi035), .Z(n5518)); + OR2 U5212 ( .A(pi100), .B(n5519), .Z(n5515)); + OR2 U5213 ( .A(pi190), .B(pi126), .Z(n5519)); + AN2 U5214 ( .A(n5520), .B(n4319), .Z(n5512)); + OR2 U5215 ( .A(n5521), .B(n5522), .Z(n5520)); + AN2 U5216 ( .A(pi198), .B(n3945), .Z(n5522)); + AN2 U5217 ( .A(n5523), .B(n5524), .Z(n5521)); + AN2 U5218 ( .A(n5525), .B(n5517), .Z(n5524)); + AN2 U5219 ( .A(n5056), .B(n4201), .Z(n5525)); + AN2 U5220 ( .A(n4391), .B(pi192), .Z(n5523)); + OR2 U5221 ( .A(n5526), .B(n5527), .Z(n5510)); + AN2 U5222 ( .A(n5528), .B(n5529), .Z(n5527)); + OR2 U5223 ( .A(pi198), .B(n4319), .Z(n5529)); + OR2 U5224 ( .A(n5530), .B(n5531), .Z(n5528)); + AN2 U5225 ( .A(n3945), .B(n5532), .Z(n5531)); + OR2 U5226 ( .A(n5533), .B(n5534), .Z(n5532)); + AN2 U5227 ( .A(pi061), .B(n4013), .Z(n5534)); + AN2 U5228 ( .A(n5535), .B(pi134), .Z(n5533)); + AN2 U5229 ( .A(n5536), .B(n4201), .Z(n5535)); + AN2 U5230 ( .A(n5537), .B(n5538), .Z(n5530)); + AN2 U5231 ( .A(n5536), .B(n3261), .Z(n5538)); + OR2 U5232 ( .A(pi061), .B(n4013), .Z(n5536)); + AN2 U5233 ( .A(n5539), .B(n5540), .Z(n5537)); + OR2 U5234 ( .A(pi134), .B(n4201), .Z(n5540)); + OR2 U5235 ( .A(n5541), .B(n5542), .Z(n5539)); + AN2 U5236 ( .A(n5543), .B(n5517), .Z(n5542)); + AN2 U5237 ( .A(pi192), .B(n5544), .Z(n5541)); + OR2 U5238 ( .A(n5545), .B(n5546), .Z(n5544)); + AN2 U5239 ( .A(pi006), .B(n3265), .Z(n5546)); + AN2 U5240 ( .A(n5543), .B(n5056), .Z(n5545)); + OR2 U5241 ( .A(pi006), .B(n3265), .Z(n5543)); + AN2 U5242 ( .A(n5547), .B(n5548), .Z(n5526)); + AN2 U5243 ( .A(n5549), .B(n5550), .Z(n5548)); + AN2 U5244 ( .A(n5517), .B(n2837), .Z(n5550)); + OR2 U5245 ( .A(n5551), .B(n5552), .Z(n5517)); + OR2 U5246 ( .A(n5553), .B(n5554), .Z(n5552)); + AN2 U5247 ( .A(n3945), .B(n5555), .Z(n5554)); + OR2 U5248 ( .A(n5556), .B(n5557), .Z(n5555)); + OR2 U5249 ( .A(n5558), .B(n5559), .Z(n5557)); + AN2 U5250 ( .A(n5560), .B(n3380), .Z(n5559)); + AN2 U5251 ( .A(n5561), .B(n5562), .Z(n5558)); + OR2 U5252 ( .A(n5563), .B(n5564), .Z(n5561)); + AN2 U5253 ( .A(pi055), .B(n3512), .Z(n5564)); + AN2 U5254 ( .A(n5565), .B(pi124), .Z(n5563)); + AN2 U5255 ( .A(n5566), .B(n3363), .Z(n5565)); + AN2 U5256 ( .A(pi109), .B(n4975), .Z(n5556)); + AN2 U5257 ( .A(n5567), .B(n5568), .Z(n5553)); + OR2 U5258 ( .A(n5569), .B(n5570), .Z(n5568)); + OR2 U5259 ( .A(n5571), .B(n5572), .Z(n5570)); + AN2 U5260 ( .A(n5573), .B(n5566), .Z(n5572)); + OR2 U5261 ( .A(pi055), .B(n3512), .Z(n5566)); + AN2 U5262 ( .A(n5574), .B(n3261), .Z(n5573)); + OR2 U5263 ( .A(n5575), .B(n5576), .Z(n5574)); + AN2 U5264 ( .A(pi124), .B(n5562), .Z(n5576)); + OR2 U5265 ( .A(n5577), .B(n5560), .Z(n5562)); + AN2 U5266 ( .A(n5578), .B(n3380), .Z(n5577)); + AN2 U5267 ( .A(n5579), .B(n3363), .Z(n5575)); + OR2 U5268 ( .A(n5580), .B(n5560), .Z(n5579)); + AN2 U5269 ( .A(n5578), .B(pi186), .Z(n5560)); + OR2 U5270 ( .A(pi109), .B(n4975), .Z(n5578)); + AN2 U5271 ( .A(pi109), .B(n3380), .Z(n5580)); + AN2 U5272 ( .A(n5581), .B(n5582), .Z(n5571)); + AN2 U5273 ( .A(n4975), .B(n3380), .Z(n5582)); + AN2 U5274 ( .A(n5583), .B(n3363), .Z(n5581)); + OR2 U5275 ( .A(n5584), .B(n5585), .Z(n5583)); + AN2 U5276 ( .A(pi192), .B(n3512), .Z(n5585)); + AN2 U5277 ( .A(pi055), .B(n3261), .Z(n5584)); + OR2 U5278 ( .A(n3926), .B(n5586), .Z(n5569)); + AN2 U5279 ( .A(n5587), .B(n5588), .Z(n5586)); + AN2 U5280 ( .A(n5589), .B(pi110), .Z(n5588)); + AN2 U5281 ( .A(pi167), .B(n2837), .Z(n5589)); + AN2 U5282 ( .A(pi019), .B(pi085), .Z(n5587)); + AN2 U5283 ( .A(n5590), .B(n5591), .Z(n5567)); + OR2 U5284 ( .A(pi192), .B(n5592), .Z(n5591)); + AN2 U5285 ( .A(n5593), .B(n5594), .Z(n5592)); + OR2 U5286 ( .A(pi164), .B(n3261), .Z(n5594)); + OR2 U5287 ( .A(n5595), .B(n5596), .Z(n5593)); + OR2 U5288 ( .A(n5597), .B(n5598), .Z(n5596)); + AN2 U5289 ( .A(n5599), .B(pi024), .Z(n5598)); + AN2 U5290 ( .A(pi195), .B(n5600), .Z(n5597)); + OR2 U5291 ( .A(n5601), .B(n5599), .Z(n5600)); + AN2 U5292 ( .A(n5602), .B(n5603), .Z(n5599)); + IV2 U5293 ( .A(n5604), .Z(n5603)); + AN2 U5294 ( .A(n5605), .B(n5606), .Z(n5604)); + OR2 U5295 ( .A(n5607), .B(n5608), .Z(n5606)); + AN2 U5296 ( .A(n5609), .B(n5610), .Z(n5608)); + OR2 U5297 ( .A(n5611), .B(n4961), .Z(n5610)); + IV2 U5298 ( .A(pi030), .Z(n4961)); + AN2 U5299 ( .A(n5612), .B(n3597), .Z(n5611)); + OR2 U5300 ( .A(n5612), .B(n3597), .Z(n5609)); + AN2 U5301 ( .A(n4969), .B(n4440), .Z(n5607)); + OR2 U5302 ( .A(n4440), .B(n4969), .Z(n5605)); + IV2 U5303 ( .A(pi159), .Z(n4969)); + AN2 U5304 ( .A(pi024), .B(n5602), .Z(n5601)); + OR2 U5305 ( .A(pi087), .B(pi130), .Z(n5602)); + AN2 U5306 ( .A(pi087), .B(pi130), .Z(n5595)); + OR2 U5307 ( .A(n2837), .B(n5613), .Z(n5590)); + OR2 U5308 ( .A(n5614), .B(n5615), .Z(n5613)); + AN2 U5309 ( .A(n5347), .B(n5616), .Z(n5615)); + AN2 U5310 ( .A(n5617), .B(n4943), .Z(n5614)); + OR2 U5311 ( .A(n5347), .B(n5616), .Z(n5617)); + OR2 U5312 ( .A(n5618), .B(n5619), .Z(n5616)); + OR2 U5313 ( .A(n5620), .B(n5621), .Z(n5619)); + AN2 U5314 ( .A(n5622), .B(pi099), .Z(n5621)); + AN2 U5315 ( .A(n5623), .B(n4937), .Z(n5620)); + OR2 U5316 ( .A(n5624), .B(n5622), .Z(n5623)); + AN2 U5317 ( .A(n5625), .B(n5626), .Z(n5622)); + IV2 U5318 ( .A(n5627), .Z(n5626)); + AN2 U5319 ( .A(n5628), .B(n5629), .Z(n5627)); + OR2 U5320 ( .A(n5630), .B(n5631), .Z(n5629)); + AN2 U5321 ( .A(n5632), .B(n5633), .Z(n5631)); + OR2 U5322 ( .A(po011), .B(n5634), .Z(n5633)); + AN2 U5323 ( .A(n5612), .B(n5358), .Z(n5634)); + OR2 U5324 ( .A(n5612), .B(n5358), .Z(n5632)); + IV2 U5325 ( .A(pi172), .Z(n5358)); + IV2 U5326 ( .A(po062), .Z(n5612)); + OR2 U5327 ( .A(n5635), .B(n5636), .Z(po062)); + AN2 U5328 ( .A(n5637), .B(n2837), .Z(n5636)); + OR2 U5329 ( .A(n5638), .B(n5639), .Z(n5637)); + AN2 U5330 ( .A(pi020), .B(pi095), .Z(n5639)); + AN2 U5331 ( .A(n5640), .B(n5641), .Z(n5638)); + OR2 U5332 ( .A(pi020), .B(pi095), .Z(n5641)); + OR2 U5333 ( .A(n5642), .B(n5643), .Z(n5640)); + AN2 U5334 ( .A(pi151), .B(n5644), .Z(n5643)); + AN2 U5335 ( .A(pi153), .B(n5645), .Z(n5642)); + OR2 U5336 ( .A(pi151), .B(n5644), .Z(n5645)); + OR2 U5337 ( .A(n5646), .B(n5647), .Z(n5644)); + AN2 U5338 ( .A(pi075), .B(pi156), .Z(n5647)); + AN2 U5339 ( .A(n5648), .B(n5649), .Z(n5646)); + OR2 U5340 ( .A(pi075), .B(pi156), .Z(n5649)); + OR2 U5341 ( .A(n5650), .B(n5651), .Z(n5648)); + AN2 U5342 ( .A(pi040), .B(n5652), .Z(n5651)); + AN2 U5343 ( .A(pi047), .B(n5653), .Z(n5650)); + OR2 U5344 ( .A(pi040), .B(n5652), .Z(n5653)); + AN2 U5345 ( .A(pi192), .B(n5654), .Z(n5635)); + OR2 U5346 ( .A(n5655), .B(n5656), .Z(n5654)); + OR2 U5347 ( .A(n5657), .B(n5658), .Z(n5656)); + AN2 U5348 ( .A(pi101), .B(n5659), .Z(n5658)); + AN2 U5349 ( .A(n5660), .B(n4628), .Z(n5657)); + OR2 U5350 ( .A(n5661), .B(n5659), .Z(n5660)); + OR2 U5351 ( .A(n5662), .B(n5663), .Z(n5659)); + AN2 U5352 ( .A(n5664), .B(pi036), .Z(n5663)); + AN2 U5353 ( .A(n5665), .B(n4861), .Z(n5662)); + OR2 U5354 ( .A(n5666), .B(n5664), .Z(n5665)); + AN2 U5355 ( .A(n5667), .B(n5668), .Z(n5664)); + IV2 U5356 ( .A(n5669), .Z(n5668)); + AN2 U5357 ( .A(n5670), .B(n5671), .Z(n5669)); + OR2 U5358 ( .A(po039), .B(n5672), .Z(n5671)); + AN2 U5359 ( .A(n5673), .B(n5331), .Z(n5672)); + OR2 U5360 ( .A(n5673), .B(n5331), .Z(n5670)); + IV2 U5361 ( .A(pi168), .Z(n5331)); + IV2 U5362 ( .A(n5652), .Z(n5673)); + OR2 U5363 ( .A(n5674), .B(n5675), .Z(n5652)); + AN2 U5364 ( .A(n5676), .B(n2837), .Z(n5675)); + OR2 U5365 ( .A(n5677), .B(n5678), .Z(n5676)); + AN2 U5366 ( .A(pi143), .B(pi108), .Z(n5678)); + AN2 U5367 ( .A(n5679), .B(n5680), .Z(n5677)); + OR2 U5368 ( .A(pi108), .B(pi143), .Z(n5680)); + OR2 U5369 ( .A(n5681), .B(n5682), .Z(n5679)); + AN2 U5370 ( .A(pi014), .B(pi114), .Z(n5682)); + AN2 U5371 ( .A(n5683), .B(n5684), .Z(n5681)); + OR2 U5372 ( .A(pi014), .B(pi114), .Z(n5684)); + OR2 U5373 ( .A(n5685), .B(n5686), .Z(n5683)); + OR2 U5374 ( .A(n5687), .B(n5688), .Z(n5686)); + AN2 U5375 ( .A(n5689), .B(pi170), .Z(n5688)); + AN2 U5376 ( .A(pi176), .B(n5690), .Z(n5687)); + OR2 U5377 ( .A(n5691), .B(n5689), .Z(n5690)); + AN2 U5378 ( .A(n5692), .B(n5693), .Z(n5689)); + IV2 U5379 ( .A(n5694), .Z(n5693)); + AN2 U5380 ( .A(n5695), .B(n5696), .Z(n5694)); + OR2 U5381 ( .A(n5697), .B(n4899), .Z(n5696)); + IV2 U5382 ( .A(pi097), .Z(n4899)); + AN2 U5383 ( .A(n5698), .B(n4077), .Z(n5697)); + OR2 U5384 ( .A(n5698), .B(n4077), .Z(n5695)); + AN2 U5385 ( .A(pi170), .B(n5692), .Z(n5691)); + OR2 U5386 ( .A(pi160), .B(pi189), .Z(n5692)); + AN2 U5387 ( .A(pi189), .B(pi160), .Z(n5685)); + AN2 U5388 ( .A(pi192), .B(n5699), .Z(n5674)); + OR2 U5389 ( .A(n5700), .B(n5701), .Z(n5699)); + AN2 U5390 ( .A(pi089), .B(n4881), .Z(n5701)); + AN2 U5391 ( .A(n5702), .B(n5703), .Z(n5700)); + OR2 U5392 ( .A(pi089), .B(n4881), .Z(n5703)); + OR2 U5393 ( .A(n5704), .B(n5705), .Z(n5702)); + AN2 U5394 ( .A(pi027), .B(n4885), .Z(n5705)); + AN2 U5395 ( .A(n5706), .B(n5707), .Z(n5704)); + OR2 U5396 ( .A(pi027), .B(n4885), .Z(n5707)); + OR2 U5397 ( .A(n5708), .B(n5709), .Z(n5706)); + OR2 U5398 ( .A(n5710), .B(n5711), .Z(n5709)); + AN2 U5399 ( .A(n5712), .B(pi083), .Z(n5711)); + AN2 U5400 ( .A(n5713), .B(n4877), .Z(n5710)); + OR2 U5401 ( .A(n5714), .B(n5712), .Z(n5713)); + AN2 U5402 ( .A(n5715), .B(n5716), .Z(n5712)); + IV2 U5403 ( .A(n5717), .Z(n5716)); + AN2 U5404 ( .A(n5718), .B(n5719), .Z(n5717)); + OR2 U5405 ( .A(po025), .B(n5720), .Z(n5719)); + AN2 U5406 ( .A(n5698), .B(n5303), .Z(n5720)); + OR2 U5407 ( .A(n5698), .B(n5303), .Z(n5718)); + IV2 U5408 ( .A(pi140), .Z(n5303)); + IV2 U5409 ( .A(n5721), .Z(n5698)); + OR2 U5410 ( .A(n5722), .B(n5723), .Z(n5721)); + AN2 U5411 ( .A(n5724), .B(n2837), .Z(n5723)); + OR2 U5412 ( .A(n5725), .B(n5726), .Z(n5724)); + OR2 U5413 ( .A(n5727), .B(n5728), .Z(n5726)); + AN2 U5414 ( .A(n5729), .B(pi094), .Z(n5728)); + AN2 U5415 ( .A(pi128), .B(n5730), .Z(n5727)); + OR2 U5416 ( .A(n5731), .B(n5729), .Z(n5730)); + AN2 U5417 ( .A(n5732), .B(n5733), .Z(n5729)); + IV2 U5418 ( .A(n5734), .Z(n5733)); + AN2 U5419 ( .A(n5735), .B(n5736), .Z(n5734)); + OR2 U5420 ( .A(n5737), .B(n5738), .Z(n5736)); + AN2 U5421 ( .A(n5739), .B(n5740), .Z(n5738)); + OR2 U5422 ( .A(n5741), .B(n5115), .Z(n5740)); + AN2 U5423 ( .A(n5742), .B(n4778), .Z(n5741)); + OR2 U5424 ( .A(n5742), .B(n4778), .Z(n5739)); + IV2 U5425 ( .A(pi163), .Z(n4778)); + AN2 U5426 ( .A(n3177), .B(n4770), .Z(n5737)); + OR2 U5427 ( .A(n3177), .B(n4770), .Z(n5735)); + IV2 U5428 ( .A(pi028), .Z(n4770)); + AN2 U5429 ( .A(pi094), .B(n5732), .Z(n5731)); + OR2 U5430 ( .A(pi173), .B(pi185), .Z(n5732)); + AN2 U5431 ( .A(pi173), .B(pi185), .Z(n5725)); + AN2 U5432 ( .A(pi192), .B(n5743), .Z(n5722)); + OR2 U5433 ( .A(n5744), .B(n5745), .Z(n5743)); + OR2 U5434 ( .A(n5746), .B(n5747), .Z(n5745)); + AN2 U5435 ( .A(pi131), .B(n5748), .Z(n5747)); + AN2 U5436 ( .A(n5749), .B(n5040), .Z(n5746)); + OR2 U5437 ( .A(n5750), .B(n5748), .Z(n5749)); + OR2 U5438 ( .A(n5751), .B(n5752), .Z(n5748)); + AN2 U5439 ( .A(n5753), .B(pi059), .Z(n5752)); + AN2 U5440 ( .A(n5754), .B(n3286), .Z(n5751)); + OR2 U5441 ( .A(n5755), .B(n5753), .Z(n5754)); + AN2 U5442 ( .A(n5756), .B(n5757), .Z(n5753)); + IV2 U5443 ( .A(n5758), .Z(n5757)); + AN2 U5444 ( .A(n5759), .B(n5760), .Z(n5758)); + OR2 U5445 ( .A(po010), .B(n5761), .Z(n5760)); + AN2 U5446 ( .A(n5742), .B(n5439), .Z(n5761)); + OR2 U5447 ( .A(n5742), .B(n5439), .Z(n5759)); + IV2 U5448 ( .A(pi197), .Z(n5439)); + IV2 U5449 ( .A(n5762), .Z(n5742)); + OR2 U5450 ( .A(n5763), .B(n5764), .Z(n5762)); + AN2 U5451 ( .A(n5765), .B(n2837), .Z(n5764)); + OR2 U5452 ( .A(n5766), .B(n5767), .Z(n5765)); + AN2 U5453 ( .A(pi021), .B(pi201), .Z(n5767)); + AN2 U5454 ( .A(n5768), .B(n5769), .Z(n5766)); + OR2 U5455 ( .A(pi021), .B(pi201), .Z(n5769)); + OR2 U5456 ( .A(n5770), .B(n5771), .Z(n5768)); + IV2 U5457 ( .A(n5772), .Z(n5771)); + AN2 U5458 ( .A(n5773), .B(n5774), .Z(n5772)); + OR2 U5459 ( .A(n5775), .B(n5022), .Z(n5774)); + OR2 U5460 ( .A(n5431), .B(n5776), .Z(n5773)); + AN2 U5461 ( .A(n5777), .B(n5775), .Z(n5776)); + OR2 U5462 ( .A(n5778), .B(n5779), .Z(n5775)); + AN2 U5463 ( .A(n5780), .B(n5781), .Z(n5779)); + OR2 U5464 ( .A(n5782), .B(n5783), .Z(n5781)); + AN2 U5465 ( .A(n5784), .B(n5785), .Z(n5783)); + OR2 U5466 ( .A(n5786), .B(n5787), .Z(n5785)); + IV2 U5467 ( .A(pi181), .Z(n5787)); + AN2 U5468 ( .A(n2982), .B(n5019), .Z(n5786)); + OR2 U5469 ( .A(n2982), .B(n5019), .Z(n5784)); + IV2 U5470 ( .A(pi011), .Z(n5019)); + AN2 U5471 ( .A(n5027), .B(n2957), .Z(n5782)); + OR2 U5472 ( .A(n2957), .B(n5027), .Z(n5780)); + IV2 U5473 ( .A(pi086), .Z(n5027)); + OR2 U5474 ( .A(n5022), .B(n5778), .Z(n5777)); + AN2 U5475 ( .A(n5165), .B(n5031), .Z(n5778)); + IV2 U5476 ( .A(pi165), .Z(n5031)); + IV2 U5477 ( .A(pi032), .Z(n5022)); + AN2 U5478 ( .A(pi165), .B(pi107), .Z(n5770)); + AN2 U5479 ( .A(pi192), .B(n5788), .Z(n5763)); + OR2 U5480 ( .A(n5789), .B(n5790), .Z(n5788)); + AN2 U5481 ( .A(pi121), .B(n5000), .Z(n5790)); + AN2 U5482 ( .A(n5791), .B(n5792), .Z(n5789)); + OR2 U5483 ( .A(pi121), .B(n5000), .Z(n5792)); + OR2 U5484 ( .A(n5793), .B(n5794), .Z(n5791)); + AN2 U5485 ( .A(pi053), .B(n5795), .Z(n5794)); + AN2 U5486 ( .A(n5796), .B(n5004), .Z(n5793)); + OR2 U5487 ( .A(pi053), .B(n5795), .Z(n5796)); + OR2 U5488 ( .A(n5797), .B(n5798), .Z(n5795)); + AN2 U5489 ( .A(pi184), .B(n5008), .Z(n5798)); + AN2 U5490 ( .A(n5799), .B(n5800), .Z(n5797)); + OR2 U5491 ( .A(pi184), .B(n5008), .Z(n5800)); + OR2 U5492 ( .A(n5801), .B(n5802), .Z(n5799)); + AN2 U5493 ( .A(pi181), .B(pi103), .Z(n5802)); + AN2 U5494 ( .A(n5803), .B(n2962), .Z(n5801)); + OR2 U5495 ( .A(pi103), .B(pi181), .Z(n5803)); + AN2 U5496 ( .A(pi059), .B(n5756), .Z(n5755)); + AN2 U5497 ( .A(pi131), .B(n5756), .Z(n5750)); + OR2 U5498 ( .A(pi001), .B(n5037), .Z(n5756)); + AN2 U5499 ( .A(pi001), .B(n5037), .Z(n5744)); + AN2 U5500 ( .A(pi083), .B(n5715), .Z(n5714)); + OR2 U5501 ( .A(pi162), .B(n4874), .Z(n5715)); + AN2 U5502 ( .A(pi162), .B(n4874), .Z(n5708)); + AN2 U5503 ( .A(pi036), .B(n5667), .Z(n5666)); + AN2 U5504 ( .A(pi101), .B(n5667), .Z(n5661)); + OR2 U5505 ( .A(pi205), .B(n4915), .Z(n5667)); + AN2 U5506 ( .A(pi205), .B(n4915), .Z(n5655)); + AN2 U5507 ( .A(po036), .B(n5350), .Z(n5630)); + OR2 U5508 ( .A(po036), .B(n5350), .Z(n5628)); + IV2 U5509 ( .A(pi018), .Z(n5350)); + AN2 U5510 ( .A(pi099), .B(n5625), .Z(n5624)); + OR2 U5511 ( .A(pi180), .B(n4947), .Z(n5625)); + AN2 U5512 ( .A(pi180), .B(n4947), .Z(n5618)); + AN2 U5513 ( .A(n3261), .B(pi049), .Z(n5347)); + AN2 U5514 ( .A(n3926), .B(n5804), .Z(n5551)); + OR2 U5515 ( .A(n5805), .B(n5806), .Z(n5804)); + OR2 U5516 ( .A(pi085), .B(pi019), .Z(n5806)); + OR2 U5517 ( .A(pi110), .B(n5807), .Z(n5805)); + OR2 U5518 ( .A(pi167), .B(pi164), .Z(n5807)); + AN2 U5519 ( .A(pi126), .B(pi190), .Z(n5549)); + AN2 U5520 ( .A(n5808), .B(pi035), .Z(n5547)); + AN2 U5521 ( .A(pi056), .B(pi100), .Z(n5808)); + AN2 U5522 ( .A(pi054), .B(n5809), .Z(n5504)); + OR2 U5523 ( .A(n4167), .B(n5810), .Z(n5809)); + OR2 U5524 ( .A(pi146), .B(pi025), .Z(n5810)); + AN2 U5525 ( .A(n5811), .B(n2882), .Z(po017)); + OR2 U5526 ( .A(pi200), .B(n3003), .Z(n5811)); + OR2 U5527 ( .A(n5812), .B(n5813), .Z(po016)); + OR2 U5528 ( .A(n5814), .B(n5815), .Z(n5813)); + AN2 U5529 ( .A(n3280), .B(n3064), .Z(n5815)); + AN2 U5530 ( .A(n5100), .B(n5816), .Z(n5814)); + OR2 U5531 ( .A(n5817), .B(n5818), .Z(n5816)); + AN2 U5532 ( .A(n3055), .B(n5819), .Z(n5818)); + OR2 U5533 ( .A(n2845), .B(n3143), .Z(n5819)); + OR2 U5534 ( .A(n2978), .B(n3147), .Z(n3143)); + AN2 U5535 ( .A(n3127), .B(n5820), .Z(n5817)); + OR2 U5536 ( .A(n2833), .B(n3138), .Z(n5820)); + OR2 U5537 ( .A(n2880), .B(n3147), .Z(n3138)); + OR2 U5538 ( .A(n2998), .B(n5821), .Z(n3147)); + OR2 U5539 ( .A(n2882), .B(n2862), .Z(n5821)); + OR2 U5540 ( .A(n2925), .B(n2901), .Z(n2882)); + AN2 U5541 ( .A(pi192), .B(n3036), .Z(n3127)); + IV2 U5542 ( .A(n5822), .Z(n5100)); + OR2 U5543 ( .A(n5823), .B(n5824), .Z(n5812)); + AN2 U5544 ( .A(n5825), .B(pi192), .Z(n5824)); + AN2 U5545 ( .A(n5826), .B(po010), .Z(n5825)); + AN2 U5546 ( .A(n5827), .B(n2837), .Z(n5823)); + AN2 U5547 ( .A(n5828), .B(n5829), .Z(n5827)); + OR2 U5548 ( .A(n5830), .B(n5831), .Z(po008)); + AN2 U5549 ( .A(n3344), .B(n3251), .Z(n5831)); + OR2 U5550 ( .A(n5832), .B(n5833), .Z(n3251)); + AN2 U5551 ( .A(n3355), .B(n5454), .Z(n5832)); + OR2 U5552 ( .A(n5834), .B(n5835), .Z(n5454)); + AN2 U5553 ( .A(n5836), .B(n4426), .Z(n5834)); + IV2 U5554 ( .A(n3352), .Z(n3355)); + AN2 U5555 ( .A(n3250), .B(n5837), .Z(n5830)); + OR2 U5556 ( .A(n5838), .B(n5839), .Z(n5837)); + OR2 U5557 ( .A(n5840), .B(n3245), .Z(n5839)); + OR2 U5558 ( .A(n5841), .B(n5842), .Z(n3245)); + AN2 U5559 ( .A(n3244), .B(n3699), .Z(n5842)); + AN2 U5560 ( .A(n3242), .B(n3700), .Z(n5841)); + IV2 U5561 ( .A(n5843), .Z(n3242)); + AN2 U5562 ( .A(n3352), .B(n3701), .Z(n5840)); + OR2 U5563 ( .A(n5844), .B(n5845), .Z(n5838)); + AN2 U5564 ( .A(n4418), .B(n3762), .Z(n5845)); + AN2 U5565 ( .A(n5846), .B(n3236), .Z(n5844)); + OR2 U5566 ( .A(pi037), .B(n5847), .Z(po007)); + IV2 U5567 ( .A(pi116), .Z(n5847)); + OR2 U5568 ( .A(n5848), .B(n5849), .Z(po006)); + AN2 U5569 ( .A(n3370), .B(n5850), .Z(n5849)); + OR2 U5570 ( .A(n5851), .B(n5852), .Z(n5850)); + OR2 U5571 ( .A(n5853), .B(n5138), .Z(n5852)); + OR2 U5572 ( .A(n5854), .B(n3566), .Z(n5138)); + AN2 U5573 ( .A(n3512), .B(n3926), .Z(n3566)); + AN2 U5574 ( .A(n3926), .B(n4368), .Z(n5854)); + OR2 U5575 ( .A(n5855), .B(n5856), .Z(n5851)); + AN2 U5576 ( .A(n5139), .B(n3380), .Z(n5856)); + OR2 U5577 ( .A(n5857), .B(n5858), .Z(n5139)); + AN2 U5578 ( .A(n5859), .B(n3261), .Z(n5857)); + AN2 U5579 ( .A(n5860), .B(pi118), .Z(n5855)); + AN2 U5580 ( .A(n5861), .B(n3261), .Z(n5860)); + OR2 U5581 ( .A(n5858), .B(n5859), .Z(n5861)); + OR2 U5582 ( .A(n5862), .B(n5863), .Z(n5859)); + OR2 U5583 ( .A(n3404), .B(n5864), .Z(n5863)); + AN2 U5584 ( .A(n5865), .B(pi060), .Z(n5864)); + AN2 U5585 ( .A(n4368), .B(n5866), .Z(n5865)); + IV2 U5586 ( .A(n3446), .Z(n3404)); + AN2 U5587 ( .A(n4367), .B(pi196), .Z(n5862)); + IV2 U5588 ( .A(n4364), .Z(n4367)); + IV2 U5589 ( .A(n5867), .Z(n5858)); + IV2 U5590 ( .A(n3393), .Z(n3370)); + AN2 U5591 ( .A(n3393), .B(n5868), .Z(n5848)); + OR2 U5592 ( .A(n5869), .B(n5870), .Z(n5868)); + OR2 U5593 ( .A(n5135), .B(n5871), .Z(n5870)); + AN2 U5594 ( .A(n3480), .B(n5872), .Z(n5871)); + AN2 U5595 ( .A(n5867), .B(n3321), .Z(n5135)); + OR2 U5596 ( .A(po104), .B(n4364), .Z(n5867)); + OR2 U5597 ( .A(n5873), .B(n5874), .Z(n5869)); + OR2 U5598 ( .A(n5875), .B(n5876), .Z(n5874)); + AN2 U5599 ( .A(n5877), .B(po071), .Z(n5876)); + OR2 U5600 ( .A(n5136), .B(n5878), .Z(n5877)); + OR2 U5601 ( .A(n5879), .B(n5880), .Z(n5136)); + OR2 U5602 ( .A(n5881), .B(n5882), .Z(n5880)); + AN2 U5603 ( .A(n3398), .B(n4364), .Z(n5882)); + AN2 U5604 ( .A(n4363), .B(n3419), .Z(n5879)); + AN2 U5605 ( .A(n5883), .B(n3398), .Z(n5875)); + AN2 U5606 ( .A(n3446), .B(n3533), .Z(n3398)); + AN2 U5607 ( .A(n4364), .B(n3913), .Z(n5883)); + OR2 U5608 ( .A(n4062), .B(po027), .Z(n4364)); + IV2 U5609 ( .A(n4061), .Z(n4062)); + AN2 U5610 ( .A(n3416), .B(n4363), .Z(n5873)); + IV2 U5611 ( .A(n4368), .Z(n4363)); + OR2 U5612 ( .A(n3363), .B(n4061), .Z(n4368)); + OR2 U5613 ( .A(n5884), .B(n5885), .Z(n4061)); + OR2 U5614 ( .A(n5886), .B(n5887), .Z(n5885)); + AN2 U5615 ( .A(n5888), .B(n4943), .Z(n5887)); + AN2 U5616 ( .A(n5889), .B(n3989), .Z(n5886)); + OR2 U5617 ( .A(n5890), .B(n5891), .Z(n5884)); + OR2 U5618 ( .A(n5892), .B(n3490), .Z(n5891)); + AN2 U5619 ( .A(n5893), .B(n5894), .Z(n5890)); + AN2 U5620 ( .A(n3495), .B(n5895), .Z(n5893)); + AN2 U5621 ( .A(n3446), .B(n3480), .Z(n3416)); + OR2 U5622 ( .A(po104), .B(n3942), .Z(n3446)); + OR2 U5623 ( .A(n5896), .B(n3253), .Z(po012)); + AN2 U5624 ( .A(n5897), .B(pi054), .Z(n3253)); + OR2 U5625 ( .A(n4133), .B(n5898), .Z(n5897)); + AN2 U5626 ( .A(n4127), .B(n3255), .Z(n5896)); + OR2 U5627 ( .A(pi054), .B(n5120), .Z(n3255)); + OR2 U5628 ( .A(n5899), .B(n4167), .Z(n5120)); + AN2 U5629 ( .A(n4133), .B(n4128), .Z(n5899)); + IV2 U5630 ( .A(po064), .Z(n4133)); + OR2 U5631 ( .A(n5900), .B(n4372), .Z(n4127)); + OR2 U5632 ( .A(n5901), .B(n5902), .Z(n4372)); + AN2 U5633 ( .A(n4380), .B(n4319), .Z(n5901)); + AN2 U5634 ( .A(n5903), .B(n4374), .Z(n5900)); + OR2 U5635 ( .A(n5904), .B(n5905), .Z(n4374)); + AN2 U5636 ( .A(n5906), .B(n3261), .Z(n5905)); + OR2 U5637 ( .A(n5907), .B(n5908), .Z(n5906)); + OR2 U5638 ( .A(n5909), .B(n5910), .Z(n5908)); + AN2 U5639 ( .A(n5911), .B(po103), .Z(n5910)); + AN2 U5640 ( .A(n5912), .B(pi058), .Z(n5911)); + AN2 U5641 ( .A(n5913), .B(n5914), .Z(n5912)); + AN2 U5642 ( .A(n5915), .B(n5916), .Z(n5913)); + OR2 U5643 ( .A(pi204), .B(n5917), .Z(n5916)); + AN2 U5644 ( .A(n4057), .B(n4013), .Z(n5917)); + OR2 U5645 ( .A(n5918), .B(n5919), .Z(n5915)); + AN2 U5646 ( .A(po040), .B(n3966), .Z(n5918)); + AN2 U5647 ( .A(n5920), .B(n3265), .Z(n5909)); + AN2 U5648 ( .A(n5921), .B(n5922), .Z(n5920)); + AN2 U5649 ( .A(n4057), .B(n4316), .Z(n5922)); + AN2 U5650 ( .A(n4157), .B(n5914), .Z(n5921)); + OR2 U5651 ( .A(n5923), .B(n4319), .Z(n5914)); + AN2 U5652 ( .A(pi065), .B(pi192), .Z(n5923)); + OR2 U5653 ( .A(pi204), .B(n4013), .Z(n4157)); + AN2 U5654 ( .A(n5924), .B(n4046), .Z(n5907)); + AN2 U5655 ( .A(po040), .B(n3263), .Z(n5924)); + OR2 U5656 ( .A(n5925), .B(n2837), .Z(n3263)); + AN2 U5657 ( .A(n3264), .B(pi058), .Z(n5925)); + AN2 U5658 ( .A(n4391), .B(n4319), .Z(n5904)); + AN2 U5659 ( .A(n3265), .B(n4013), .Z(n4391)); + IV2 U5660 ( .A(n4158), .Z(n5903)); + OR2 U5661 ( .A(n4312), .B(n5926), .Z(n4158)); + OR2 U5662 ( .A(n4040), .B(n4229), .Z(n5926)); + IV2 U5663 ( .A(n4184), .Z(n4229)); + OR2 U5664 ( .A(n5927), .B(n5928), .Z(n4184)); + OR2 U5665 ( .A(n5929), .B(n5930), .Z(n5928)); + AN2 U5666 ( .A(n5931), .B(n5932), .Z(n5929)); + OR2 U5667 ( .A(n5933), .B(n5934), .Z(n5932)); + AN2 U5668 ( .A(n3457), .B(n3493), .Z(n5934)); + IV2 U5669 ( .A(n3661), .Z(n3493)); + OR2 U5670 ( .A(n5935), .B(n5936), .Z(n3661)); + OR2 U5671 ( .A(n3229), .B(n3235), .Z(n5936)); + OR2 U5672 ( .A(n5937), .B(n5938), .Z(n3235)); + OR2 U5673 ( .A(n5939), .B(n5940), .Z(n5938)); + AN2 U5674 ( .A(n5452), .B(n3241), .Z(n5940)); + AN2 U5675 ( .A(n5453), .B(n3243), .Z(n5939)); + AN2 U5676 ( .A(po082), .B(n5846), .Z(n5937)); + OR2 U5677 ( .A(n5941), .B(n5942), .Z(n5846)); + AN2 U5678 ( .A(n5452), .B(n3700), .Z(n5942)); + AN2 U5679 ( .A(n3638), .B(n3635), .Z(n5452)); + IV2 U5680 ( .A(pi098), .Z(n3638)); + AN2 U5681 ( .A(n5453), .B(n3699), .Z(n5941)); + AN2 U5682 ( .A(n3597), .B(n3593), .Z(n5453)); + OR2 U5683 ( .A(n5943), .B(n5944), .Z(n3229)); + AN2 U5684 ( .A(po082), .B(n3344), .Z(n5944)); + AN2 U5685 ( .A(n3352), .B(n5945), .Z(n5943)); + OR2 U5686 ( .A(n5946), .B(n5947), .Z(n5945)); + OR2 U5687 ( .A(n3241), .B(n3243), .Z(n5947)); + AN2 U5688 ( .A(po082), .B(n3701), .Z(n5946)); + IV2 U5689 ( .A(n5833), .Z(n3701)); + OR2 U5690 ( .A(n3233), .B(n5948), .Z(n5935)); + AN2 U5691 ( .A(n3339), .B(n5949), .Z(n5948)); + AN2 U5692 ( .A(n5949), .B(po011), .Z(n3233)); + OR2 U5693 ( .A(n5950), .B(n5951), .Z(n5949)); + OR2 U5694 ( .A(n5952), .B(n5953), .Z(n5951)); + AN2 U5695 ( .A(n3241), .B(n3635), .Z(n5953)); + AN2 U5696 ( .A(n3992), .B(n3700), .Z(n3241)); + AN2 U5697 ( .A(n3632), .B(pi192), .Z(n3700)); + IV2 U5698 ( .A(pi004), .Z(n3992)); + AN2 U5699 ( .A(n3243), .B(n3593), .Z(n5952)); + OR2 U5700 ( .A(po036), .B(n4440), .Z(n3593)); + AN2 U5701 ( .A(n5372), .B(n3699), .Z(n3243)); + AN2 U5702 ( .A(po082), .B(n3762), .Z(n5950)); + OR2 U5703 ( .A(n5954), .B(n5955), .Z(n3762)); + OR2 U5704 ( .A(n5956), .B(n5957), .Z(n5955)); + AN2 U5705 ( .A(po036), .B(n5958), .Z(n5957)); + OR2 U5706 ( .A(n5959), .B(po001), .Z(n5958)); + AN2 U5707 ( .A(pi192), .B(n5960), .Z(n5956)); + OR2 U5708 ( .A(n5961), .B(n5962), .Z(n5960)); + AN2 U5709 ( .A(po001), .B(n4001), .Z(n5962)); + AN2 U5710 ( .A(n3635), .B(n3998), .Z(n5961)); + OR2 U5711 ( .A(po036), .B(n4001), .Z(n3635)); + IV2 U5712 ( .A(pi171), .Z(n4001)); + AN2 U5713 ( .A(n3699), .B(n4440), .Z(n5954)); + AN2 U5714 ( .A(n2837), .B(n3590), .Z(n3699)); + AN2 U5715 ( .A(n5963), .B(n3667), .Z(n5933)); + AN2 U5716 ( .A(n3291), .B(n3341), .Z(n3667)); + IV2 U5717 ( .A(n3339), .Z(n3341)); + OR2 U5718 ( .A(n5964), .B(n5965), .Z(n3339)); + AN2 U5719 ( .A(n5966), .B(n4441), .Z(n5965)); + AN2 U5720 ( .A(n5448), .B(po036), .Z(n5964)); + IV2 U5721 ( .A(n5966), .Z(n5448)); + OR2 U5722 ( .A(n5967), .B(n5968), .Z(n3291)); + AN2 U5723 ( .A(n5969), .B(n3688), .Z(n5968)); + IV2 U5724 ( .A(n3746), .Z(n5969)); + AN2 U5725 ( .A(po011), .B(n3746), .Z(n5967)); + OR2 U5726 ( .A(n3717), .B(n3705), .Z(n3746)); + AN2 U5727 ( .A(n3495), .B(n5970), .Z(n5963)); + OR2 U5728 ( .A(n5971), .B(n5972), .Z(n5970)); + OR2 U5729 ( .A(n5973), .B(n5974), .Z(n5972)); + AN2 U5730 ( .A(n5975), .B(pi192), .Z(n5974)); + AN2 U5731 ( .A(n3567), .B(n5976), .Z(n5975)); + OR2 U5732 ( .A(n5977), .B(n5978), .Z(n5976)); + OR2 U5733 ( .A(n5979), .B(n5980), .Z(n5978)); + AN2 U5734 ( .A(n4635), .B(n5981), .Z(n5979)); + IV2 U5735 ( .A(n4464), .Z(n4635)); + OR2 U5736 ( .A(po039), .B(n3870), .Z(n4464)); + IV2 U5737 ( .A(pi016), .Z(n3870)); + OR2 U5738 ( .A(n5982), .B(n5983), .Z(n5977)); + AN2 U5739 ( .A(n5984), .B(n3033), .Z(n5983)); + IV2 U5740 ( .A(n3038), .Z(n3033)); + OR2 U5741 ( .A(po070), .B(n3199), .Z(n3038)); + IV2 U5742 ( .A(pi096), .Z(n3199)); + AN2 U5743 ( .A(n5985), .B(n5986), .Z(n5982)); + OR2 U5744 ( .A(n5987), .B(n3042), .Z(n5986)); + IV2 U5745 ( .A(n3037), .Z(n3042)); + OR2 U5746 ( .A(po099), .B(n3171), .Z(n3037)); + AN2 U5747 ( .A(n3063), .B(n5988), .Z(n5987)); + OR2 U5748 ( .A(n5989), .B(n5990), .Z(n5988)); + AN2 U5749 ( .A(n3036), .B(n5991), .Z(n5989)); + OR2 U5750 ( .A(n5992), .B(n3010), .Z(n5991)); + OR2 U5751 ( .A(n5993), .B(n5994), .Z(n3010)); + AN2 U5752 ( .A(pi088), .B(n3012), .Z(n5992)); + IV2 U5753 ( .A(n5995), .Z(n3036)); + OR2 U5754 ( .A(n5996), .B(n5990), .Z(n5995)); + AN2 U5755 ( .A(pi166), .B(n3049), .Z(n5990)); + AN2 U5756 ( .A(po010), .B(n3106), .Z(n5996)); + OR2 U5757 ( .A(n3534), .B(n3363), .Z(n3567)); + AN2 U5758 ( .A(n5997), .B(n3457), .Z(n5973)); + IV2 U5759 ( .A(n4060), .Z(n3457)); + OR2 U5760 ( .A(n5998), .B(n5999), .Z(n4060)); + AN2 U5761 ( .A(po027), .B(n3451), .Z(n5998)); + AN2 U5762 ( .A(n3760), .B(n4652), .Z(n5997)); + AN2 U5763 ( .A(n6000), .B(n6001), .Z(n5971)); + OR2 U5764 ( .A(n3261), .B(n3525), .Z(n6001)); + AN2 U5765 ( .A(n3363), .B(n3321), .Z(n3525)); + OR2 U5766 ( .A(n6002), .B(n6003), .Z(n6000)); + AN2 U5767 ( .A(n6004), .B(n2837), .Z(n6003)); + OR2 U5768 ( .A(n6005), .B(n6006), .Z(n6004)); + OR2 U5769 ( .A(n6007), .B(n6008), .Z(n6006)); + AN2 U5770 ( .A(n4641), .B(n5981), .Z(n6007)); + IV2 U5771 ( .A(n4468), .Z(n4641)); + OR2 U5772 ( .A(po039), .B(n4735), .Z(n4468)); + IV2 U5773 ( .A(pi040), .Z(n4735)); + OR2 U5774 ( .A(n6009), .B(n6010), .Z(n6005)); + AN2 U5775 ( .A(n5985), .B(n6011), .Z(n6010)); + OR2 U5776 ( .A(n6012), .B(n6013), .Z(n6011)); + OR2 U5777 ( .A(n3066), .B(n6014), .Z(n6013)); + AN2 U5778 ( .A(n6015), .B(n6016), .Z(n6014)); + IV2 U5779 ( .A(n3112), .Z(n3066)); + OR2 U5780 ( .A(po099), .B(n3177), .Z(n3112)); + AN2 U5781 ( .A(n6017), .B(n6018), .Z(n6012)); + OR2 U5782 ( .A(n6019), .B(n6020), .Z(n6018)); + AN2 U5783 ( .A(n6021), .B(n3119), .Z(n6019)); + OR2 U5784 ( .A(n6022), .B(n5993), .Z(n6021)); + AN2 U5785 ( .A(n2890), .B(n5000), .Z(n5993)); + AN2 U5786 ( .A(pi201), .B(n3012), .Z(n6022)); + OR2 U5787 ( .A(n2890), .B(n5000), .Z(n3012)); + IV2 U5788 ( .A(n2886), .Z(n2890)); + OR2 U5789 ( .A(n6023), .B(n6024), .Z(n2886)); + OR2 U5790 ( .A(n6025), .B(n6026), .Z(n6024)); + AN2 U5791 ( .A(n6027), .B(n2998), .Z(n6026)); + AN2 U5792 ( .A(po079), .B(n6028), .Z(n6025)); + OR2 U5793 ( .A(n6029), .B(n4095), .Z(n6028)); + OR2 U5794 ( .A(n6030), .B(n6031), .Z(n4095)); + AN2 U5795 ( .A(n4098), .B(n2887), .Z(n6031)); + AN2 U5796 ( .A(n6032), .B(po031), .Z(n6030)); + AN2 U5797 ( .A(n2990), .B(n2974), .Z(n6032)); + AN2 U5798 ( .A(n2990), .B(n5169), .Z(n6029)); + OR2 U5799 ( .A(n6033), .B(po106), .Z(n2990)); + AN2 U5800 ( .A(n2837), .B(n5431), .Z(n6033)); + OR2 U5801 ( .A(n6034), .B(n6035), .Z(n6023)); + AN2 U5802 ( .A(n4099), .B(n6036), .Z(n6035)); + OR2 U5803 ( .A(n6037), .B(n6038), .Z(n6036)); + AN2 U5804 ( .A(n6039), .B(n5165), .Z(n6038)); + OR2 U5805 ( .A(n6040), .B(n5169), .Z(n6039)); + OR2 U5806 ( .A(n2978), .B(n2862), .Z(n5169)); + AN2 U5807 ( .A(po031), .B(n2974), .Z(n6040)); + AN2 U5808 ( .A(n6041), .B(n2974), .Z(n6037)); + AN2 U5809 ( .A(n5172), .B(n2957), .Z(n6041)); + AN2 U5810 ( .A(n2947), .B(n2837), .Z(n4099)); + AN2 U5811 ( .A(n6042), .B(n4098), .Z(n6034)); + AN2 U5812 ( .A(n2891), .B(pi192), .Z(n4098)); + IV2 U5813 ( .A(n2892), .Z(n2891)); + AN2 U5814 ( .A(n6043), .B(n3847), .Z(n6042)); + IV2 U5815 ( .A(n2885), .Z(n6043)); + AN2 U5816 ( .A(n5984), .B(n3076), .Z(n6009)); + IV2 U5817 ( .A(n3109), .Z(n3076)); + OR2 U5818 ( .A(po070), .B(n3205), .Z(n3109)); + IV2 U5819 ( .A(pi128), .Z(n3205)); + AN2 U5820 ( .A(n5985), .B(n6044), .Z(n6002)); + OR2 U5821 ( .A(n6045), .B(n6046), .Z(n5927)); + AN2 U5822 ( .A(n6047), .B(n3945), .Z(n6046)); + IV2 U5823 ( .A(n4313), .Z(n3945)); + OR2 U5824 ( .A(n3321), .B(n2837), .Z(n4313)); + AN2 U5825 ( .A(pi050), .B(n4975), .Z(n6047)); + AN2 U5826 ( .A(n6048), .B(n6049), .Z(n6045)); + AN2 U5827 ( .A(n6050), .B(n6051), .Z(n6049)); + OR2 U5828 ( .A(n3363), .B(n6052), .Z(n6051)); + OR2 U5829 ( .A(po027), .B(n3989), .Z(n6050)); + AN2 U5830 ( .A(n6053), .B(n4943), .Z(n6048)); + OR2 U5831 ( .A(n4239), .B(n4192), .Z(n4312)); + OR2 U5832 ( .A(n6054), .B(n6055), .Z(po003)); + OR2 U5833 ( .A(n6056), .B(n6057), .Z(n6055)); + AN2 U5834 ( .A(n6058), .B(pi054), .Z(n6057)); + OR2 U5835 ( .A(n6059), .B(n6060), .Z(n6058)); + AN2 U5836 ( .A(n4177), .B(n5126), .Z(n6060)); + AN2 U5837 ( .A(n5125), .B(n5898), .Z(n6059)); + AN2 U5838 ( .A(n6061), .B(n4129), .Z(n6056)); + AN2 U5839 ( .A(n4177), .B(n5125), .Z(n6061)); + OR2 U5840 ( .A(n6062), .B(n3257), .Z(n5125)); + OR2 U5841 ( .A(n5902), .B(n6063), .Z(n3257)); + OR2 U5842 ( .A(n6064), .B(n6065), .Z(n6063)); + AN2 U5843 ( .A(n4403), .B(n4319), .Z(n6065)); + IV2 U5844 ( .A(po004), .Z(n4319)); + OR2 U5845 ( .A(n6066), .B(n4380), .Z(n4403)); + AN2 U5846 ( .A(n6067), .B(n3259), .Z(n6066)); + AN2 U5847 ( .A(n4053), .B(n4013), .Z(n6067)); + OR2 U5848 ( .A(n6068), .B(n3265), .Z(n4053)); + AN2 U5849 ( .A(pi058), .B(n3261), .Z(n6068)); + AN2 U5850 ( .A(n6069), .B(n6070), .Z(n6064)); + AN2 U5851 ( .A(n4387), .B(n4013), .Z(n6070)); + IV2 U5852 ( .A(po040), .Z(n4013)); + AN2 U5853 ( .A(pi065), .B(n3259), .Z(n6069)); + OR2 U5854 ( .A(n6071), .B(n4379), .Z(n5902)); + IV2 U5855 ( .A(n4159), .Z(n4379)); + AN2 U5856 ( .A(n4380), .B(n4404), .Z(n6071)); + IV2 U5857 ( .A(n4161), .Z(n4404)); + IV2 U5858 ( .A(n4141), .Z(n4380)); + OR2 U5859 ( .A(n4016), .B(n6072), .Z(n4141)); + OR2 U5860 ( .A(n6073), .B(n6074), .Z(n6072)); + AN2 U5861 ( .A(n6075), .B(n4242), .Z(n6074)); + OR2 U5862 ( .A(n6076), .B(n6077), .Z(n4016)); + AN2 U5863 ( .A(n4040), .B(n3951), .Z(n6076)); + AN2 U5864 ( .A(n3259), .B(n6078), .Z(n6062)); + OR2 U5865 ( .A(n6079), .B(n3926), .Z(n6078)); + AN2 U5866 ( .A(n3264), .B(n4387), .Z(n6079)); + AN2 U5867 ( .A(n3261), .B(n4026), .Z(n4387)); + IV2 U5868 ( .A(n6080), .Z(n3264)); + OR2 U5869 ( .A(n6081), .B(n5919), .Z(n6080)); + AN2 U5870 ( .A(n4330), .B(n6082), .Z(n3259)); + AN2 U5871 ( .A(n4205), .B(n3314), .Z(n6082)); + IV2 U5872 ( .A(n5898), .Z(n4177)); + AN2 U5873 ( .A(n4172), .B(n5126), .Z(n6054)); + OR2 U5874 ( .A(n6083), .B(n6084), .Z(n5126)); + OR2 U5875 ( .A(n6085), .B(n6086), .Z(n6084)); + AN2 U5876 ( .A(n4227), .B(n4159), .Z(n6086)); + OR2 U5877 ( .A(po004), .B(n4161), .Z(n4159)); + OR2 U5878 ( .A(n4310), .B(n3321), .Z(n4161)); + OR2 U5879 ( .A(n6087), .B(n6088), .Z(n4227)); + OR2 U5880 ( .A(n6089), .B(n6077), .Z(n6088)); + OR2 U5881 ( .A(n6090), .B(n6091), .Z(n6077)); + OR2 U5882 ( .A(n3317), .B(n6092), .Z(n6091)); + AN2 U5883 ( .A(n4291), .B(n4056), .Z(n6092)); + AN2 U5884 ( .A(n3321), .B(po103), .Z(n3317)); + AN2 U5885 ( .A(n4040), .B(n3321), .Z(n6090)); + AN2 U5886 ( .A(n4192), .B(n6075), .Z(n6089)); + OR2 U5887 ( .A(n3321), .B(n6093), .Z(n6075)); + OR2 U5888 ( .A(n6073), .B(n6094), .Z(n6087)); + AN2 U5889 ( .A(n4040), .B(n4291), .Z(n6094)); + AN2 U5890 ( .A(po040), .B(n6095), .Z(n6073)); + OR2 U5891 ( .A(n4040), .B(n6096), .Z(n6095)); + OR2 U5892 ( .A(n3318), .B(n4293), .Z(n6096)); + OR2 U5893 ( .A(n3951), .B(n3321), .Z(n4293)); + AN2 U5894 ( .A(n4056), .B(n6097), .Z(n3318)); + AN2 U5895 ( .A(n4057), .B(pi192), .Z(n6097)); + IV2 U5896 ( .A(n4026), .Z(n4056)); + OR2 U5897 ( .A(pi058), .B(n3265), .Z(n4026)); + IV2 U5898 ( .A(n3314), .Z(n4040)); + OR2 U5899 ( .A(n6098), .B(n4201), .Z(n3314)); + IV2 U5900 ( .A(po091), .Z(n4201)); + AN2 U5901 ( .A(n3261), .B(n4200), .Z(n6098)); + AN2 U5902 ( .A(n6081), .B(pi192), .Z(n6085)); + AN2 U5903 ( .A(n4150), .B(po004), .Z(n6081)); + IV2 U5904 ( .A(pi065), .Z(n4150)); + OR2 U5905 ( .A(n6099), .B(n4396), .Z(n6083)); + AN2 U5906 ( .A(n4406), .B(n6100), .Z(n4396)); + OR2 U5907 ( .A(n6101), .B(n3321), .Z(n6100)); + AN2 U5908 ( .A(n6102), .B(n6103), .Z(n6101)); + AN2 U5909 ( .A(n4223), .B(n4057), .Z(n6103)); + AN2 U5910 ( .A(n4310), .B(n6104), .Z(n6102)); + OR2 U5911 ( .A(po040), .B(n5919), .Z(n6104)); + IV2 U5912 ( .A(pi204), .Z(n5919)); + IV2 U5913 ( .A(n4156), .Z(n4310)); + OR2 U5914 ( .A(pi065), .B(n2837), .Z(n4156)); + AN2 U5915 ( .A(po004), .B(n6105), .Z(n6099)); + OR2 U5916 ( .A(n6106), .B(n3321), .Z(n6105)); + AN2 U5917 ( .A(n4406), .B(n6093), .Z(n6106)); + OR2 U5918 ( .A(n6107), .B(n4028), .Z(n6093)); + AN2 U5919 ( .A(n4223), .B(n4291), .Z(n4028)); + AN2 U5920 ( .A(n4057), .B(n3951), .Z(n4291)); + IV2 U5921 ( .A(n4041), .Z(n3951)); + OR2 U5922 ( .A(pi204), .B(n2837), .Z(n4041)); + OR2 U5923 ( .A(po103), .B(n4316), .Z(n4223)); + IV2 U5924 ( .A(pi058), .Z(n4316)); + AN2 U5925 ( .A(po040), .B(n3322), .Z(n6107)); + OR2 U5926 ( .A(n4046), .B(n4045), .Z(n3322)); + OR2 U5927 ( .A(n6108), .B(n6109), .Z(n4045)); + AN2 U5928 ( .A(n4148), .B(n4057), .Z(n6109)); + OR2 U5929 ( .A(po091), .B(n3966), .Z(n4057)); + IV2 U5930 ( .A(pi129), .Z(n3966)); + AN2 U5931 ( .A(n4203), .B(po103), .Z(n6108)); + IV2 U5932 ( .A(n4200), .Z(n4203)); + OR2 U5933 ( .A(pi129), .B(n2837), .Z(n4200)); + AN2 U5934 ( .A(po103), .B(po091), .Z(n4046)); + AN2 U5935 ( .A(n5898), .B(n4129), .Z(n4172)); + IV2 U5936 ( .A(pi054), .Z(n4129)); + OR2 U5937 ( .A(n4167), .B(n4128), .Z(n5898)); + IV2 U5938 ( .A(po085), .Z(n4128)); + IV2 U5939 ( .A(pi052), .Z(n4167)); + AN2 U5940 ( .A(n6110), .B(n6111), .Z(po002)); + OR2 U5941 ( .A(n3306), .B(n4450), .Z(n6111)); + OR2 U5942 ( .A(n4458), .B(n4606), .Z(n6110)); + IV2 U5943 ( .A(n3306), .Z(n4458)); + OR2 U5944 ( .A(n6112), .B(n4652), .Z(n3306)); + OR2 U5945 ( .A(n6113), .B(n6114), .Z(n4652)); + AN2 U5946 ( .A(n6115), .B(n2837), .Z(n6114)); + OR2 U5947 ( .A(n6116), .B(n6117), .Z(n6115)); + AN2 U5948 ( .A(pi108), .B(n4881), .Z(n6117)); + AN2 U5949 ( .A(n4475), .B(n6118), .Z(n6116)); + OR2 U5950 ( .A(n5467), .B(n6119), .Z(n6118)); + IV2 U5951 ( .A(n5488), .Z(n6119)); + OR2 U5952 ( .A(po102), .B(n5322), .Z(n5488)); + IV2 U5953 ( .A(pi114), .Z(n5322)); + AN2 U5954 ( .A(n6120), .B(n6121), .Z(n5467)); + OR2 U5955 ( .A(pi114), .B(n4885), .Z(n6120)); + AN2 U5956 ( .A(pi192), .B(n6122), .Z(n6113)); + OR2 U5957 ( .A(n6123), .B(n6124), .Z(n6122)); + AN2 U5958 ( .A(pi148), .B(n4881), .Z(n6124)); + AN2 U5959 ( .A(n4475), .B(n6125), .Z(n6123)); + OR2 U5960 ( .A(n5466), .B(n6126), .Z(n6125)); + IV2 U5961 ( .A(n5491), .Z(n6126)); + OR2 U5962 ( .A(po102), .B(n3901), .Z(n5491)); + IV2 U5963 ( .A(pi069), .Z(n3901)); + AN2 U5964 ( .A(n6127), .B(n6128), .Z(n5466)); + OR2 U5965 ( .A(pi069), .B(n4885), .Z(n6127)); + AN2 U5966 ( .A(n5461), .B(n4475), .Z(n6112)); + AN2 U5967 ( .A(n4087), .B(n6129), .Z(n5461)); + AN2 U5968 ( .A(n6130), .B(n4341), .Z(n6129)); + IV2 U5969 ( .A(n5474), .Z(n6130)); + AN2 U5970 ( .A(n6131), .B(po102), .Z(n5474)); + AN2 U5971 ( .A(n4334), .B(n4333), .Z(n4087)); + OR2 U5972 ( .A(n6132), .B(n4656), .Z(n4334)); + OR2 U5973 ( .A(n6133), .B(n6134), .Z(n4656)); + AN2 U5974 ( .A(n5074), .B(n3083), .Z(n6133)); + AN2 U5975 ( .A(n6135), .B(n3083), .Z(n6132)); + AN2 U5976 ( .A(n3018), .B(n4326), .Z(n6135)); + OR2 U5977 ( .A(n6136), .B(n5077), .Z(n4326)); + OR2 U5978 ( .A(n6137), .B(n3100), .Z(n5077)); + AN2 U5979 ( .A(n3280), .B(n4666), .Z(n6137)); + OR2 U5980 ( .A(n3286), .B(n6138), .Z(n4666)); + AN2 U5981 ( .A(n5829), .B(n3049), .Z(n3280)); + AN2 U5982 ( .A(n6139), .B(n3284), .Z(n6136)); + OR2 U5983 ( .A(n3049), .B(n5829), .Z(n3284)); + OR2 U5984 ( .A(n6140), .B(n3287), .Z(n6139)); + OR2 U5985 ( .A(n6141), .B(n6142), .Z(n3287)); + AN2 U5986 ( .A(pi141), .B(n3173), .Z(n6141)); + AN2 U5987 ( .A(n6143), .B(n3286), .Z(n6140)); + OR2 U5988 ( .A(n3173), .B(n3064), .Z(n6143)); + OR2 U5989 ( .A(n6144), .B(n6145), .Z(po000)); + AN2 U5990 ( .A(n6146), .B(po103), .Z(n6145)); + OR2 U5991 ( .A(n6147), .B(n6148), .Z(n6146)); + AN2 U5992 ( .A(n6149), .B(n3326), .Z(n6148)); + AN2 U5993 ( .A(n4217), .B(n3320), .Z(n6147)); + AN2 U5994 ( .A(n6150), .B(n3265), .Z(n6144)); + IV2 U5995 ( .A(po103), .Z(n3265)); + OR2 U5996 ( .A(n6151), .B(n6152), .Z(n6150)); + AN2 U5997 ( .A(n6149), .B(n3320), .Z(n6152)); + OR2 U5998 ( .A(n4406), .B(n4192), .Z(n3320)); + IV2 U5999 ( .A(n4205), .Z(n4192)); + AN2 U6000 ( .A(n4242), .B(n4331), .Z(n4406)); + IV2 U6001 ( .A(n4330), .Z(n4331)); + AN2 U6002 ( .A(n4217), .B(n3326), .Z(n6151)); + OR2 U6003 ( .A(n6153), .B(n4239), .Z(n3326)); + IV2 U6004 ( .A(n4242), .Z(n4239)); + OR2 U6005 ( .A(po028), .B(n6154), .Z(n4242)); + AN2 U6006 ( .A(n6155), .B(n6156), .Z(n6154)); + OR2 U6007 ( .A(n3321), .B(n3969), .Z(n6156)); + IV2 U6008 ( .A(pi169), .Z(n3969)); + AN2 U6009 ( .A(n4330), .B(n4205), .Z(n6153)); + OR2 U6010 ( .A(n6157), .B(n5056), .Z(n4205)); + IV2 U6011 ( .A(po028), .Z(n5056)); + AN2 U6012 ( .A(n3261), .B(n6158), .Z(n6157)); + OR2 U6013 ( .A(pi169), .B(n2837), .Z(n6158)); + OR2 U6014 ( .A(n6159), .B(n6160), .Z(n4330)); + OR2 U6015 ( .A(n6161), .B(n5930), .Z(n6160)); + OR2 U6016 ( .A(n6162), .B(n6163), .Z(n5930)); + OR2 U6017 ( .A(n6164), .B(n6165), .Z(n6163)); + AN2 U6018 ( .A(n3393), .B(n6166), .Z(n6165)); + OR2 U6019 ( .A(n6167), .B(n5853), .Z(n6166)); + AN2 U6020 ( .A(n6168), .B(n3371), .Z(n6167)); + IV2 U6021 ( .A(n3412), .Z(n3371)); + AN2 U6022 ( .A(n5999), .B(n6053), .Z(n6164)); + AN2 U6023 ( .A(n3453), .B(n3363), .Z(n5999)); + AN2 U6024 ( .A(n3926), .B(n4975), .Z(n6162)); + AN2 U6025 ( .A(n3940), .B(n4975), .Z(n6161)); + OR2 U6026 ( .A(n6169), .B(n6170), .Z(n6159)); + AN2 U6027 ( .A(n5931), .B(n6171), .Z(n6170)); + OR2 U6028 ( .A(n6172), .B(n6173), .Z(n6171)); + OR2 U6029 ( .A(n6174), .B(n6175), .Z(n6173)); + AN2 U6030 ( .A(n5888), .B(n3363), .Z(n6175)); + OR2 U6031 ( .A(n6176), .B(n6177), .Z(n5888)); + OR2 U6032 ( .A(n3248), .B(n6178), .Z(n6177)); + AN2 U6033 ( .A(n5833), .B(n3250), .Z(n6178)); + AN2 U6034 ( .A(n4937), .B(n6179), .Z(n5833)); + OR2 U6035 ( .A(n6180), .B(n6181), .Z(n6176)); + AN2 U6036 ( .A(n3495), .B(n5835), .Z(n6181)); + OR2 U6037 ( .A(n6182), .B(n5894), .Z(n5835)); + AN2 U6038 ( .A(n5966), .B(n6183), .Z(n6182)); + OR2 U6039 ( .A(n6184), .B(n6185), .Z(n5966)); + AN2 U6040 ( .A(pi171), .B(pi192), .Z(n6185)); + AN2 U6041 ( .A(pi142), .B(n2837), .Z(n6184)); + AN2 U6042 ( .A(n6186), .B(n5836), .Z(n6180)); + OR2 U6043 ( .A(n6187), .B(n6188), .Z(n5836)); + AN2 U6044 ( .A(n3705), .B(n5843), .Z(n6188)); + AN2 U6045 ( .A(pi192), .B(pi098), .Z(n3705)); + AN2 U6046 ( .A(n3717), .B(n6189), .Z(n6187)); + AN2 U6047 ( .A(n2837), .B(pi003), .Z(n3717)); + AN2 U6048 ( .A(n5889), .B(n3534), .Z(n6174)); + AN2 U6049 ( .A(n3261), .B(pi060), .Z(n3534)); + AN2 U6050 ( .A(pi192), .B(n6190), .Z(n5889)); + OR2 U6051 ( .A(n6191), .B(n6192), .Z(n6190)); + OR2 U6052 ( .A(n6193), .B(n6194), .Z(n6192)); + AN2 U6053 ( .A(pi004), .B(n4947), .Z(n6194)); + AN2 U6054 ( .A(n3640), .B(n3250), .Z(n6193)); + IV2 U6055 ( .A(n3344), .Z(n3250)); + IV2 U6056 ( .A(n3632), .Z(n3640)); + OR2 U6057 ( .A(po001), .B(n3998), .Z(n3632)); + OR2 U6058 ( .A(n6195), .B(n6196), .Z(n6191)); + AN2 U6059 ( .A(n6197), .B(n3495), .Z(n6196)); + AN2 U6060 ( .A(pi171), .B(n6183), .Z(n6197)); + AN2 U6061 ( .A(n6198), .B(n6186), .Z(n6195)); + IV2 U6062 ( .A(n6199), .Z(n6186)); + AN2 U6063 ( .A(pi098), .B(n5843), .Z(n6198)); + OR2 U6064 ( .A(pi171), .B(n4441), .Z(n5843)); + OR2 U6065 ( .A(n5892), .B(n6200), .Z(n6172)); + AN2 U6066 ( .A(n6201), .B(n5894), .Z(n6200)); + AN2 U6067 ( .A(n4441), .B(n4417), .Z(n5894)); + AN2 U6068 ( .A(n3495), .B(n3453), .Z(n6201)); + IV2 U6069 ( .A(n3451), .Z(n3453)); + OR2 U6070 ( .A(n3533), .B(n3321), .Z(n3451)); + IV2 U6071 ( .A(n3477), .Z(n3533)); + OR2 U6072 ( .A(pi060), .B(n2837), .Z(n3477)); + IV2 U6073 ( .A(n6202), .Z(n3495)); + IV2 U6074 ( .A(n6203), .Z(n5892)); + OR2 U6075 ( .A(n6204), .B(n6155), .Z(n6203)); + AN2 U6076 ( .A(n6205), .B(n6206), .Z(n6204)); + AN2 U6077 ( .A(n6207), .B(n6208), .Z(n6206)); + OR2 U6078 ( .A(n6199), .B(n6209), .Z(n6208)); + OR2 U6079 ( .A(n3244), .B(n3597), .Z(n6209)); + IV2 U6080 ( .A(pi003), .Z(n3597)); + IV2 U6081 ( .A(n6189), .Z(n3244)); + OR2 U6082 ( .A(pi142), .B(n4441), .Z(n6189)); + OR2 U6083 ( .A(n4418), .B(n6202), .Z(n6199)); + IV2 U6084 ( .A(n4426), .Z(n4418)); + OR2 U6085 ( .A(n3688), .B(n3290), .Z(n4426)); + IV2 U6086 ( .A(po011), .Z(n3688)); + OR2 U6087 ( .A(n6202), .B(n6210), .Z(n6207)); + OR2 U6088 ( .A(n4430), .B(n4440), .Z(n6210)); + IV2 U6089 ( .A(pi142), .Z(n4440)); + IV2 U6090 ( .A(n6183), .Z(n4430)); + OR2 U6091 ( .A(n4417), .B(n4441), .Z(n6183)); + IV2 U6092 ( .A(po036), .Z(n4441)); + IV2 U6093 ( .A(n3236), .Z(n4417)); + OR2 U6094 ( .A(n3234), .B(po011), .Z(n3236)); + IV2 U6095 ( .A(n3290), .Z(n3234)); + OR2 U6096 ( .A(n6211), .B(n6212), .Z(n3290)); + OR2 U6097 ( .A(n6213), .B(n6214), .Z(n6212)); + OR2 U6098 ( .A(n6215), .B(n6216), .Z(n6214)); + AN2 U6099 ( .A(pi192), .B(n5980), .Z(n6216)); + OR2 U6100 ( .A(n6217), .B(n6218), .Z(n5980)); + OR2 U6101 ( .A(n6219), .B(n6220), .Z(n6218)); + AN2 U6102 ( .A(pi045), .B(n4915), .Z(n6220)); + AN2 U6103 ( .A(n4621), .B(n4751), .Z(n6219)); + IV2 U6104 ( .A(n4465), .Z(n4621)); + OR2 U6105 ( .A(po014), .B(n3908), .Z(n4465)); + IV2 U6106 ( .A(pi079), .Z(n3908)); + OR2 U6107 ( .A(n6221), .B(n6222), .Z(n6217)); + AN2 U6108 ( .A(n6223), .B(n3757), .Z(n6222)); + AN2 U6109 ( .A(pi158), .B(n4628), .Z(n6223)); + AN2 U6110 ( .A(n6224), .B(n6225), .Z(n6221)); + AN2 U6111 ( .A(pi175), .B(n5037), .Z(n6224)); + AN2 U6112 ( .A(n6008), .B(n2837), .Z(n6215)); + OR2 U6113 ( .A(n6226), .B(n6227), .Z(n6008)); + OR2 U6114 ( .A(n6228), .B(n6229), .Z(n6227)); + AN2 U6115 ( .A(pi095), .B(n4915), .Z(n6229)); + AN2 U6116 ( .A(n4623), .B(n4751), .Z(n6228)); + IV2 U6117 ( .A(n4469), .Z(n4623)); + OR2 U6118 ( .A(po014), .B(n4648), .Z(n4469)); + IV2 U6119 ( .A(pi156), .Z(n4648)); + OR2 U6120 ( .A(n6230), .B(n6231), .Z(n6226)); + AN2 U6121 ( .A(n6232), .B(n3757), .Z(n6231)); + AN2 U6122 ( .A(pi151), .B(n4628), .Z(n6232)); + AN2 U6123 ( .A(n6233), .B(n6225), .Z(n6230)); + AN2 U6124 ( .A(pi185), .B(n5037), .Z(n6233)); + AN2 U6125 ( .A(n5985), .B(n6234), .Z(n6213)); + OR2 U6126 ( .A(n6235), .B(n6236), .Z(n6234)); + OR2 U6127 ( .A(n6237), .B(n6238), .Z(n6236)); + OR2 U6128 ( .A(n6239), .B(n6240), .Z(n6238)); + AN2 U6129 ( .A(n6241), .B(n3055), .Z(n6240)); + AN2 U6130 ( .A(n5822), .B(n3119), .Z(n6241)); + OR2 U6131 ( .A(n6242), .B(n6016), .Z(n3119)); + AN2 U6132 ( .A(pi141), .B(po099), .Z(n6242)); + AN2 U6133 ( .A(n5994), .B(n6243), .Z(n6239)); + AN2 U6134 ( .A(n6244), .B(n3049), .Z(n6237)); + OR2 U6135 ( .A(n6243), .B(n6245), .Z(n6244)); + OR2 U6136 ( .A(n6020), .B(n6246), .Z(n6245)); + AN2 U6137 ( .A(n6247), .B(n5826), .Z(n6246)); + AN2 U6138 ( .A(n3106), .B(n5829), .Z(n5826)); + OR2 U6139 ( .A(n5994), .B(n5822), .Z(n5829)); + IV2 U6140 ( .A(pi166), .Z(n3106)); + AN2 U6141 ( .A(n3063), .B(pi192), .Z(n6247)); + AN2 U6142 ( .A(n6016), .B(n5994), .Z(n6020)); + AN2 U6143 ( .A(n3286), .B(n3177), .Z(n6016)); + OR2 U6144 ( .A(n6142), .B(n6248), .Z(n6243)); + AN2 U6145 ( .A(n3207), .B(n3286), .Z(n6248)); + OR2 U6146 ( .A(n6249), .B(n6250), .Z(n3207)); + AN2 U6147 ( .A(n3064), .B(n3171), .Z(n6250)); + AN2 U6148 ( .A(n3173), .B(n3177), .Z(n6249)); + IV2 U6149 ( .A(pi141), .Z(n3177)); + AN2 U6150 ( .A(pi033), .B(n3064), .Z(n6142)); + OR2 U6151 ( .A(n6251), .B(n6252), .Z(n6235)); + OR2 U6152 ( .A(n6044), .B(n3100), .Z(n6252)); + AN2 U6153 ( .A(n3286), .B(n6138), .Z(n3100)); + OR2 U6154 ( .A(n6253), .B(n6254), .Z(n6138)); + AN2 U6155 ( .A(pi033), .B(pi192), .Z(n6254)); + AN2 U6156 ( .A(pi141), .B(n2837), .Z(n6253)); + AN2 U6157 ( .A(n6255), .B(pi141), .Z(n6044)); + OR2 U6158 ( .A(n3071), .B(n6256), .Z(n6255)); + AN2 U6159 ( .A(n3055), .B(n5994), .Z(n6256)); + IV2 U6160 ( .A(n6257), .Z(n5994)); + OR2 U6161 ( .A(n2925), .B(n5099), .Z(n6257)); + OR2 U6162 ( .A(n6258), .B(n6259), .Z(n5099)); + OR2 U6163 ( .A(n3146), .B(n6260), .Z(n6259)); + OR2 U6164 ( .A(n6261), .B(n6262), .Z(n6260)); + AN2 U6165 ( .A(n2845), .B(n2837), .Z(n6262)); + IV2 U6166 ( .A(n2846), .Z(n2845)); + AN2 U6167 ( .A(n6263), .B(n6264), .Z(n2846)); + OR2 U6168 ( .A(n3141), .B(po044), .Z(n6263)); + IV2 U6169 ( .A(pi201), .Z(n3141)); + AN2 U6170 ( .A(pi192), .B(n2833), .Z(n6261)); + IV2 U6171 ( .A(n2834), .Z(n2833)); + AN2 U6172 ( .A(n6265), .B(n6266), .Z(n2834)); + OR2 U6173 ( .A(n3136), .B(po044), .Z(n6265)); + IV2 U6174 ( .A(pi088), .Z(n3136)); + OR2 U6175 ( .A(n6267), .B(n6268), .Z(n3146)); + AN2 U6176 ( .A(n2880), .B(pi192), .Z(n6268)); + IV2 U6177 ( .A(n2878), .Z(n2880)); + OR2 U6178 ( .A(pi077), .B(n2962), .Z(n2878)); + AN2 U6179 ( .A(n2978), .B(n2837), .Z(n6267)); + IV2 U6180 ( .A(n2939), .Z(n2978)); + OR2 U6181 ( .A(n2998), .B(n6269), .Z(n6258)); + OR2 U6182 ( .A(n2901), .B(n2862), .Z(n6269)); + IV2 U6183 ( .A(pi200), .Z(n2901)); + IV2 U6184 ( .A(n3003), .Z(n2925)); + OR2 U6185 ( .A(pi192), .B(n2960), .Z(n3003)); + IV2 U6186 ( .A(n6270), .Z(n2960)); + OR2 U6187 ( .A(n6271), .B(n6272), .Z(n6270)); + AN2 U6188 ( .A(pi081), .B(n2931), .Z(n6272)); + IV2 U6189 ( .A(po107), .Z(n2931)); + AN2 U6190 ( .A(po107), .B(n2982), .Z(n6271)); + AN2 U6191 ( .A(n2837), .B(n6017), .Z(n3055)); + IV2 U6192 ( .A(n5828), .Z(n6017)); + OR2 U6193 ( .A(n6273), .B(n6015), .Z(n5828)); + AN2 U6194 ( .A(pi174), .B(n3049), .Z(n6015)); + AN2 U6195 ( .A(po010), .B(n5115), .Z(n6273)); + IV2 U6196 ( .A(pi174), .Z(n5115)); + AN2 U6197 ( .A(n3049), .B(n3173), .Z(n3071)); + AN2 U6198 ( .A(n2837), .B(pi174), .Z(n3173)); + IV2 U6199 ( .A(po010), .Z(n3049)); + AN2 U6200 ( .A(n6274), .B(n3063), .Z(n6251)); + IV2 U6201 ( .A(n6275), .Z(n3063)); + OR2 U6202 ( .A(n6276), .B(n6277), .Z(n6275)); + AN2 U6203 ( .A(pi033), .B(n3286), .Z(n6277)); + IV2 U6204 ( .A(po099), .Z(n3286)); + AN2 U6205 ( .A(po099), .B(n3171), .Z(n6276)); + IV2 U6206 ( .A(pi033), .Z(n3171)); + AN2 U6207 ( .A(n3064), .B(n5822), .Z(n6274)); + OR2 U6208 ( .A(n6278), .B(n6279), .Z(n5822)); + OR2 U6209 ( .A(n6280), .B(n6281), .Z(n6279)); + AN2 U6210 ( .A(n6282), .B(pi192), .Z(n6281)); + AN2 U6211 ( .A(n5156), .B(n6266), .Z(n6282)); + OR2 U6212 ( .A(pi088), .B(n5000), .Z(n6266)); + OR2 U6213 ( .A(n6283), .B(n5153), .Z(n5156)); + AN2 U6214 ( .A(n2861), .B(n6284), .Z(n6283)); + OR2 U6215 ( .A(n2885), .B(n2892), .Z(n6284)); + AN2 U6216 ( .A(n5008), .B(pi157), .Z(n2892)); + AN2 U6217 ( .A(n2930), .B(n2876), .Z(n2885)); + IV2 U6218 ( .A(n2887), .Z(n2876)); + OR2 U6219 ( .A(po031), .B(n3846), .Z(n2887)); + IV2 U6220 ( .A(pi077), .Z(n3846)); + AN2 U6221 ( .A(n6285), .B(n2837), .Z(n6280)); + AN2 U6222 ( .A(n5175), .B(n6264), .Z(n6285)); + OR2 U6223 ( .A(pi201), .B(n5000), .Z(n6264)); + OR2 U6224 ( .A(n6286), .B(n6287), .Z(n5175)); + AN2 U6225 ( .A(n2861), .B(n6288), .Z(n6286)); + OR2 U6226 ( .A(n6289), .B(n2929), .Z(n6288)); + IV2 U6227 ( .A(n2947), .Z(n2929)); + OR2 U6228 ( .A(po106), .B(n5431), .Z(n2947)); + IV2 U6229 ( .A(pi206), .Z(n5431)); + AN2 U6230 ( .A(n2930), .B(n4113), .Z(n6289)); + OR2 U6231 ( .A(n2919), .B(n2936), .Z(n4113)); + IV2 U6232 ( .A(n2946), .Z(n2936)); + OR2 U6233 ( .A(po031), .B(n2957), .Z(n2946)); + IV2 U6234 ( .A(pi082), .Z(n2957)); + AN2 U6235 ( .A(n2902), .B(n2939), .Z(n2919)); + OR2 U6236 ( .A(pi082), .B(n2962), .Z(n2939)); + IV2 U6237 ( .A(po031), .Z(n2962)); + IV2 U6238 ( .A(n2974), .Z(n2902)); + OR2 U6239 ( .A(po107), .B(n2982), .Z(n2974)); + IV2 U6240 ( .A(pi081), .Z(n2982)); + IV2 U6241 ( .A(n2862), .Z(n2930)); + OR2 U6242 ( .A(n6290), .B(n6291), .Z(n2862)); + AN2 U6243 ( .A(n6292), .B(n5008), .Z(n6291)); + IV2 U6244 ( .A(po106), .Z(n5008)); + AN2 U6245 ( .A(n6293), .B(po106), .Z(n6290)); + IV2 U6246 ( .A(n6292), .Z(n6293)); + OR2 U6247 ( .A(n6294), .B(n6295), .Z(n6292)); + AN2 U6248 ( .A(pi192), .B(pi157), .Z(n6295)); + AN2 U6249 ( .A(pi206), .B(n2837), .Z(n6294)); + IV2 U6250 ( .A(n2998), .Z(n2861)); + OR2 U6251 ( .A(n6296), .B(n6297), .Z(n2998)); + OR2 U6252 ( .A(n6298), .B(n6299), .Z(n6297)); + AN2 U6253 ( .A(n5153), .B(pi192), .Z(n6299)); + AN2 U6254 ( .A(n5004), .B(pi026), .Z(n5153)); + IV2 U6255 ( .A(po079), .Z(n5004)); + AN2 U6256 ( .A(n6287), .B(n2837), .Z(n6298)); + IV2 U6257 ( .A(n5172), .Z(n6287)); + OR2 U6258 ( .A(po079), .B(n5165), .Z(n5172)); + AN2 U6259 ( .A(po079), .B(n6027), .Z(n6296)); + OR2 U6260 ( .A(n6300), .B(n6301), .Z(n6027)); + AN2 U6261 ( .A(pi192), .B(n3847), .Z(n6301)); + IV2 U6262 ( .A(pi026), .Z(n3847)); + AN2 U6263 ( .A(n5165), .B(n2837), .Z(n6300)); + IV2 U6264 ( .A(pi107), .Z(n5165)); + AN2 U6265 ( .A(n3011), .B(n5000), .Z(n6278)); + IV2 U6266 ( .A(po044), .Z(n5000)); + OR2 U6267 ( .A(n6302), .B(n6303), .Z(n3011)); + AN2 U6268 ( .A(pi088), .B(pi192), .Z(n6303)); + AN2 U6269 ( .A(pi201), .B(n2837), .Z(n6302)); + AN2 U6270 ( .A(pi192), .B(pi166), .Z(n3064)); + AN2 U6271 ( .A(n3018), .B(n5984), .Z(n5985)); + AN2 U6272 ( .A(n6304), .B(n5104), .Z(n3018)); + IV2 U6273 ( .A(n5074), .Z(n5104)); + OR2 U6274 ( .A(n6305), .B(n5040), .Z(n6304)); + OR2 U6275 ( .A(n6306), .B(n6307), .Z(n6211)); + OR2 U6276 ( .A(n6308), .B(n6309), .Z(n6307)); + AN2 U6277 ( .A(n4624), .B(n5981), .Z(n6309)); + AN2 U6278 ( .A(n3300), .B(n3305), .Z(n4624)); + AN2 U6279 ( .A(n5984), .B(n5074), .Z(n6308)); + AN2 U6280 ( .A(n5040), .B(n6305), .Z(n5074)); + OR2 U6281 ( .A(n6310), .B(n6311), .Z(n6305)); + AN2 U6282 ( .A(pi096), .B(pi192), .Z(n6311)); + AN2 U6283 ( .A(pi128), .B(n2837), .Z(n6310)); + IV2 U6284 ( .A(po070), .Z(n5040)); + AN2 U6285 ( .A(n3083), .B(n6225), .Z(n5984)); + AN2 U6286 ( .A(n6312), .B(n6313), .Z(n6225)); + AN2 U6287 ( .A(n3760), .B(n4341), .Z(n6313)); + AN2 U6288 ( .A(n4333), .B(n4482), .Z(n6312)); + OR2 U6289 ( .A(n6314), .B(n6315), .Z(n4333)); + AN2 U6290 ( .A(po025), .B(n6316), .Z(n6315)); + OR2 U6291 ( .A(n6317), .B(n3888), .Z(n6316)); + AN2 U6292 ( .A(pi192), .B(pi191), .Z(n3888)); + AN2 U6293 ( .A(pi076), .B(n2837), .Z(n6317)); + AN2 U6294 ( .A(n3781), .B(n4557), .Z(n6314)); + OR2 U6295 ( .A(n4538), .B(n3890), .Z(n3781)); + IV2 U6296 ( .A(n6318), .Z(n3890)); + OR2 U6297 ( .A(pi191), .B(n2837), .Z(n6318)); + AN2 U6298 ( .A(n4077), .B(n2837), .Z(n4538)); + IV2 U6299 ( .A(n3021), .Z(n3083)); + OR2 U6300 ( .A(n6319), .B(n6134), .Z(n3021)); + AN2 U6301 ( .A(n6320), .B(n5037), .Z(n6134)); + IV2 U6302 ( .A(po035), .Z(n5037)); + AN2 U6303 ( .A(n6321), .B(po035), .Z(n6319)); + IV2 U6304 ( .A(n6320), .Z(n6321)); + OR2 U6305 ( .A(n6322), .B(n6323), .Z(n6320)); + AN2 U6306 ( .A(pi175), .B(pi192), .Z(n6323)); + AN2 U6307 ( .A(pi185), .B(n2837), .Z(n6322)); + AN2 U6308 ( .A(n3760), .B(n6324), .Z(n6306)); + OR2 U6309 ( .A(n6325), .B(n6326), .Z(n6324)); + OR2 U6310 ( .A(n6327), .B(n6328), .Z(n6326)); + AN2 U6311 ( .A(n4482), .B(n4340), .Z(n6328)); + OR2 U6312 ( .A(n6329), .B(n6330), .Z(n4340)); + AN2 U6313 ( .A(n6121), .B(n2837), .Z(n6330)); + OR2 U6314 ( .A(n6331), .B(n4567), .Z(n6121)); + IV2 U6315 ( .A(n4578), .Z(n4567)); + OR2 U6316 ( .A(po024), .B(n4358), .Z(n4578)); + AN2 U6317 ( .A(n4084), .B(n4066), .Z(n6331)); + OR2 U6318 ( .A(n6332), .B(n4539), .Z(n4084)); + IV2 U6319 ( .A(n5503), .Z(n4539)); + OR2 U6320 ( .A(po059), .B(n4074), .Z(n5503)); + IV2 U6321 ( .A(pi170), .Z(n4074)); + AN2 U6322 ( .A(n4576), .B(n3778), .Z(n6332)); + IV2 U6323 ( .A(n4580), .Z(n4576)); + OR2 U6324 ( .A(po025), .B(n4077), .Z(n4580)); + IV2 U6325 ( .A(pi076), .Z(n4077)); + AN2 U6326 ( .A(pi192), .B(n6128), .Z(n6329)); + OR2 U6327 ( .A(n6333), .B(n6334), .Z(n6128)); + OR2 U6328 ( .A(n4561), .B(n6335), .Z(n6334)); + AN2 U6329 ( .A(n6336), .B(n4341), .Z(n6335)); + AN2 U6330 ( .A(n4066), .B(n3778), .Z(n4341)); + IV2 U6331 ( .A(n3773), .Z(n3778)); + OR2 U6332 ( .A(n6337), .B(n6338), .Z(n3773)); + AN2 U6333 ( .A(n6339), .B(n4877), .Z(n6338)); + IV2 U6334 ( .A(po059), .Z(n4877)); + AN2 U6335 ( .A(n6340), .B(po059), .Z(n6337)); + IV2 U6336 ( .A(n6339), .Z(n6340)); + OR2 U6337 ( .A(n6341), .B(n6342), .Z(n6339)); + AN2 U6338 ( .A(pi135), .B(pi192), .Z(n6342)); + AN2 U6339 ( .A(pi170), .B(n2837), .Z(n6341)); + AN2 U6340 ( .A(pi191), .B(n4557), .Z(n6336)); + IV2 U6341 ( .A(po025), .Z(n4557)); + IV2 U6342 ( .A(n4348), .Z(n4561)); + OR2 U6343 ( .A(po024), .B(n3896), .Z(n4348)); + AN2 U6344 ( .A(n4085), .B(n4066), .Z(n6333)); + OR2 U6345 ( .A(n6343), .B(n6344), .Z(n4066)); + OR2 U6346 ( .A(n6345), .B(n6346), .Z(n6344)); + AN2 U6347 ( .A(n6347), .B(po024), .Z(n6346)); + AN2 U6348 ( .A(pi005), .B(pi192), .Z(n6347)); + AN2 U6349 ( .A(n6348), .B(n4874), .Z(n6345)); + IV2 U6350 ( .A(po024), .Z(n4874)); + OR2 U6351 ( .A(n6349), .B(n5483), .Z(n6348)); + AN2 U6352 ( .A(pi192), .B(n3896), .Z(n5483)); + IV2 U6353 ( .A(pi005), .Z(n3896)); + AN2 U6354 ( .A(n4358), .B(n2837), .Z(n6349)); + IV2 U6355 ( .A(pi160), .Z(n4358)); + AN2 U6356 ( .A(pi160), .B(n5477), .Z(n6343)); + AN2 U6357 ( .A(n2837), .B(po024), .Z(n5477)); + IV2 U6358 ( .A(n4353), .Z(n4085)); + OR2 U6359 ( .A(po059), .B(n3880), .Z(n4353)); + IV2 U6360 ( .A(pi135), .Z(n3880)); + AN2 U6361 ( .A(n4342), .B(n4475), .Z(n4482)); + AN2 U6362 ( .A(n6350), .B(n6351), .Z(n4342)); + OR2 U6363 ( .A(n6131), .B(po102), .Z(n6351)); + IV2 U6364 ( .A(n6352), .Z(n6131)); + OR2 U6365 ( .A(n6352), .B(n4885), .Z(n6350)); + AN2 U6366 ( .A(n5462), .B(n4475), .Z(n6327)); + IV2 U6367 ( .A(n4478), .Z(n4475)); + OR2 U6368 ( .A(n6353), .B(n6325), .Z(n4478)); + AN2 U6369 ( .A(n6354), .B(po072), .Z(n6353)); + IV2 U6370 ( .A(n6355), .Z(n6354)); + AN2 U6371 ( .A(n6352), .B(n4885), .Z(n5462)); + IV2 U6372 ( .A(po102), .Z(n4885)); + OR2 U6373 ( .A(n6356), .B(n6357), .Z(n6352)); + AN2 U6374 ( .A(pi069), .B(pi192), .Z(n6357)); + AN2 U6375 ( .A(pi114), .B(n2837), .Z(n6356)); + AN2 U6376 ( .A(n6355), .B(n4881), .Z(n6325)); + IV2 U6377 ( .A(po072), .Z(n4881)); + OR2 U6378 ( .A(n6358), .B(n6359), .Z(n6355)); + AN2 U6379 ( .A(pi148), .B(pi192), .Z(n6359)); + AN2 U6380 ( .A(pi108), .B(n2837), .Z(n6358)); + AN2 U6381 ( .A(n4450), .B(n5981), .Z(n3760)); + AN2 U6382 ( .A(n3301), .B(n4751), .Z(n5981)); + AN2 U6383 ( .A(n4006), .B(n3757), .Z(n4751)); + IV2 U6384 ( .A(n4444), .Z(n3757)); + OR2 U6385 ( .A(n6360), .B(n3754), .Z(n4444)); + AN2 U6386 ( .A(n6361), .B(n4915), .Z(n3754)); + IV2 U6387 ( .A(po063), .Z(n4915)); + AN2 U6388 ( .A(n6362), .B(po063), .Z(n6360)); + IV2 U6389 ( .A(n6361), .Z(n6362)); + OR2 U6390 ( .A(n6363), .B(n6364), .Z(n6361)); + AN2 U6391 ( .A(pi045), .B(pi192), .Z(n6364)); + AN2 U6392 ( .A(pi095), .B(n2837), .Z(n6363)); + AN2 U6393 ( .A(n6365), .B(n6366), .Z(n4006)); + OR2 U6394 ( .A(n6367), .B(po092), .Z(n6366)); + IV2 U6395 ( .A(n4752), .Z(n6367)); + OR2 U6396 ( .A(n4752), .B(n4628), .Z(n6365)); + IV2 U6397 ( .A(po092), .Z(n4628)); + OR2 U6398 ( .A(n6368), .B(n6369), .Z(n4752)); + AN2 U6399 ( .A(pi158), .B(pi192), .Z(n6369)); + AN2 U6400 ( .A(pi151), .B(n2837), .Z(n6368)); + IV2 U6401 ( .A(n3295), .Z(n3301)); + OR2 U6402 ( .A(n6370), .B(n6371), .Z(n3295)); + AN2 U6403 ( .A(n4703), .B(n4861), .Z(n6371)); + IV2 U6404 ( .A(po014), .Z(n4861)); + AN2 U6405 ( .A(n4736), .B(po014), .Z(n6370)); + IV2 U6406 ( .A(n4703), .Z(n4736)); + OR2 U6407 ( .A(n6372), .B(n6373), .Z(n4703)); + AN2 U6408 ( .A(pi079), .B(pi192), .Z(n6373)); + AN2 U6409 ( .A(pi156), .B(n2837), .Z(n6372)); + IV2 U6410 ( .A(n4606), .Z(n4450)); + AN2 U6411 ( .A(n6374), .B(n6375), .Z(n4606)); + OR2 U6412 ( .A(n3305), .B(po039), .Z(n6375)); + OR2 U6413 ( .A(n3300), .B(n6376), .Z(n6374)); + IV2 U6414 ( .A(n3305), .Z(n6376)); + OR2 U6415 ( .A(n4685), .B(n4692), .Z(n3305)); + AN2 U6416 ( .A(pi192), .B(pi016), .Z(n4692)); + AN2 U6417 ( .A(n2837), .B(pi040), .Z(n4685)); + IV2 U6418 ( .A(po039), .Z(n3300)); + OR2 U6419 ( .A(n3352), .B(n3344), .Z(n6202)); + AN2 U6420 ( .A(n6377), .B(n6378), .Z(n3352)); + OR2 U6421 ( .A(n6179), .B(po001), .Z(n6378)); + IV2 U6422 ( .A(n6379), .Z(n6179)); + OR2 U6423 ( .A(n6379), .B(n4937), .Z(n6377)); + IV2 U6424 ( .A(po001), .Z(n4937)); + OR2 U6425 ( .A(n5959), .B(n6380), .Z(n6379)); + AN2 U6426 ( .A(pi192), .B(n3998), .Z(n6380)); + IV2 U6427 ( .A(pi068), .Z(n3998)); + AN2 U6428 ( .A(n2837), .B(n5379), .Z(n5959)); + AN2 U6429 ( .A(n6381), .B(n6382), .Z(n6205)); + OR2 U6430 ( .A(n3344), .B(n3590), .Z(n6382)); + OR2 U6431 ( .A(po001), .B(n5379), .Z(n3590)); + IV2 U6432 ( .A(pi195), .Z(n5379)); + OR2 U6433 ( .A(n6383), .B(n3248), .Z(n3344)); + AN2 U6434 ( .A(n6384), .B(n4947), .Z(n3248)); + IV2 U6435 ( .A(po082), .Z(n4947)); + AN2 U6436 ( .A(n6385), .B(po082), .Z(n6383)); + IV2 U6437 ( .A(n6384), .Z(n6385)); + OR2 U6438 ( .A(n6386), .B(n6387), .Z(n6384)); + AN2 U6439 ( .A(pi004), .B(pi192), .Z(n6387)); + AN2 U6440 ( .A(pi130), .B(n2837), .Z(n6386)); + OR2 U6441 ( .A(po082), .B(n5372), .Z(n6381)); + IV2 U6442 ( .A(pi130), .Z(n5372)); + AN2 U6443 ( .A(n3225), .B(n6053), .Z(n5931)); + IV2 U6444 ( .A(n3247), .Z(n3225)); + OR2 U6445 ( .A(n6388), .B(n3490), .Z(n3247)); + AN2 U6446 ( .A(n4943), .B(n5895), .Z(n3490)); + OR2 U6447 ( .A(n3926), .B(n3989), .Z(n5895)); + IV2 U6448 ( .A(n6389), .Z(n6388)); + OR2 U6449 ( .A(n4943), .B(n6390), .Z(n6389)); + AN2 U6450 ( .A(n6391), .B(n3261), .Z(n6390)); + OR2 U6451 ( .A(n2837), .B(pi133), .Z(n6391)); + AN2 U6452 ( .A(n6392), .B(n6053), .Z(n6169)); + AN2 U6453 ( .A(n3393), .B(n6393), .Z(n6053)); + IV2 U6454 ( .A(n3461), .Z(n6393)); + OR2 U6455 ( .A(n3401), .B(n3412), .Z(n3461)); + OR2 U6456 ( .A(n6394), .B(n5853), .Z(n3412)); + OR2 U6457 ( .A(n3466), .B(n3392), .Z(n5853)); + AN2 U6458 ( .A(n3380), .B(n3926), .Z(n3392)); + IV2 U6459 ( .A(po071), .Z(n3380)); + AN2 U6460 ( .A(n3261), .B(n3381), .Z(n3466)); + IV2 U6461 ( .A(n3399), .Z(n3381)); + OR2 U6462 ( .A(po071), .B(n3913), .Z(n3399)); + AN2 U6463 ( .A(po071), .B(n5878), .Z(n6394)); + OR2 U6464 ( .A(n3480), .B(n3321), .Z(n5878)); + AN2 U6465 ( .A(n3913), .B(pi192), .Z(n3480)); + IV2 U6466 ( .A(pi118), .Z(n3913)); + OR2 U6467 ( .A(n5881), .B(n6395), .Z(n3401)); + OR2 U6468 ( .A(n6168), .B(n6396), .Z(n6395)); + AN2 U6469 ( .A(po104), .B(n3321), .Z(n6396)); + AN2 U6470 ( .A(n3485), .B(n3261), .Z(n6168)); + IV2 U6471 ( .A(n3419), .Z(n3485)); + OR2 U6472 ( .A(n6397), .B(po104), .Z(n3419)); + AN2 U6473 ( .A(pi192), .B(n3942), .Z(n6397)); + IV2 U6474 ( .A(pi196), .Z(n3942)); + AN2 U6475 ( .A(pi192), .B(n5872), .Z(n5881)); + IV2 U6476 ( .A(n5866), .Z(n5872)); + OR2 U6477 ( .A(pi196), .B(n3512), .Z(n5866)); + IV2 U6478 ( .A(po104), .Z(n3512)); + OR2 U6479 ( .A(n6398), .B(n6399), .Z(n3393)); + AN2 U6480 ( .A(n6400), .B(n4975), .Z(n6399)); + IV2 U6481 ( .A(po038), .Z(n4975)); + OR2 U6482 ( .A(n6401), .B(n3321), .Z(n6400)); + AN2 U6483 ( .A(pi192), .B(n3943), .Z(n6401)); + IV2 U6484 ( .A(pi050), .Z(n3943)); + AN2 U6485 ( .A(po038), .B(n6402), .Z(n6398)); + OR2 U6486 ( .A(n3940), .B(n3926), .Z(n6402)); + AN2 U6487 ( .A(n3261), .B(pi050), .Z(n3940)); + AN2 U6488 ( .A(n6403), .B(n4943), .Z(n6392)); + IV2 U6489 ( .A(po057), .Z(n4943)); + OR2 U6490 ( .A(n6404), .B(n6052), .Z(n6403)); + OR2 U6491 ( .A(n6405), .B(n3926), .Z(n6052)); + IV2 U6492 ( .A(n6155), .Z(n3926)); + OR2 U6493 ( .A(pi192), .B(n3321), .Z(n6155)); + AN2 U6494 ( .A(pi060), .B(n3989), .Z(n6405)); + AN2 U6495 ( .A(n3989), .B(n3363), .Z(n6404)); + IV2 U6496 ( .A(po027), .Z(n3363)); + AN2 U6497 ( .A(n3261), .B(pi133), .Z(n3989)); + IV2 U6498 ( .A(n3321), .Z(n3261)); + IV2 U6499 ( .A(n6149), .Z(n4217)); + OR2 U6500 ( .A(n4148), .B(n3321), .Z(n6149)); + AN2 U6501 ( .A(pi161), .B(pi012), .Z(n3321)); + IV2 U6502 ( .A(n4247), .Z(n4148)); + OR2 U6503 ( .A(pi058), .B(n2837), .Z(n4247)); + IV2 U6504 ( .A(pi192), .Z(n2837)); + +endmodule + +module IV2(A, Z); + input A; + output Z; + + assign Z = ~A; +endmodule + +module AN2(A, B, Z); + input A, B; + output Z; + + assign Z = A & B; +endmodule + +module OR2(A, B, Z); + input A, B; + output Z; + + assign Z = A | B; +endmodule diff --git a/chips/yosys/examples/smtbmc/glift/C7552.ys b/chips/yosys/examples/smtbmc/glift/C7552.ys new file mode 100644 index 0000000000000000000000000000000000000000..dcae30e85fe6419dfc7f00415ba376d14576f148 --- /dev/null +++ b/chips/yosys/examples/smtbmc/glift/C7552.ys @@ -0,0 +1,41 @@ +read_verilog C7552.v +techmap +flatten +select C7552_lev2 +glift -create-instrumented-model +techmap +opt +rename C7552_lev2 uut +cd .. +delete [AIONX][NVXR]2 +read_verilog C7552.v +techmap +flatten +select C7552_lev2 +glift -create-precise-model +techmap +opt +rename C7552_lev2 spec +cd .. +delete [AIONX][NVXR]2 + +design -push-copy +miter -equiv spec uut miter +flatten +delete uut spec +techmap +opt +stat miter +qbfsat -O2 -write-solution C7552.soln -solver yices -timeout 3600 -nocleanup -assume-outputs -assume-negative-polarity miter +design -pop +stat + +copy uut solved +qbfsat -specialize-from-file C7552.soln solved +opt solved +miter -equiv spec solved satmiter +flatten +sat -prove trigger 0 satmiter +delete satmiter +stat +shell diff --git a/chips/yosys/examples/smtbmc/glift/C880.v b/chips/yosys/examples/smtbmc/glift/C880.v new file mode 100644 index 0000000000000000000000000000000000000000..799c02ddf21e4199fce6669d4f5a195bed99122b --- /dev/null +++ b/chips/yosys/examples/smtbmc/glift/C880.v @@ -0,0 +1,451 @@ +module C880_lev2(pi00, pi01, pi02, pi03, pi04, pi05, pi06, pi07, pi08, pi09, + pi10, pi11, pi12, pi13, pi14, pi15, pi16, pi17, pi18, pi19, + pi20, pi21, pi22, pi23, pi24, pi25, pi26, pi27, pi28, pi29, + pi30, pi31, pi32, pi33, pi34, pi35, pi36, pi37, pi38, pi39, + pi40, pi41, pi42, pi43, pi44, pi45, pi46, pi47, pi48, pi49, + pi50, pi51, pi52, pi53, pi54, pi55, pi56, pi57, pi58, pi59, + po00, po01, po02, po03, po04, po05, po06, po07, po08, po09, + po10, po11, po12, po13, po14, po15, po16, po17, po18, po19, + po20, po21, po22, po23, po24, po25); + +input pi00, pi01, pi02, pi03, pi04, pi05, pi06, pi07, pi08, pi09, + pi10, pi11, pi12, pi13, pi14, pi15, pi16, pi17, pi18, pi19, + pi20, pi21, pi22, pi23, pi24, pi25, pi26, pi27, pi28, pi29, + pi30, pi31, pi32, pi33, pi34, pi35, pi36, pi37, pi38, pi39, + pi40, pi41, pi42, pi43, pi44, pi45, pi46, pi47, pi48, pi49, + pi50, pi51, pi52, pi53, pi54, pi55, pi56, pi57, pi58, pi59; + +output po00, po01, po02, po03, po04, po05, po06, po07, po08, po09, + po10, po11, po12, po13, po14, po15, po16, po17, po18, po19, + po20, po21, po22, po23, po24, po25; + +wire n137, n346, n364, n415, n295, n427, n351, n377, n454, n357, + n358, n359, n360, n361, n362, n363, n365, n366, n367, n368, + n369, n370, n371, n372, n373, n374, n375, n376, n378, n379, + n380, n381, n382, n383, n384, n385, n386, n387, n388, n389, + n390, n391, n392, n393, n394, n395, n396, n397, n398, n399, + n400, n401, n402, n403, n404, n405, n406, n407, n408, n409, + n410, n411, n412, n413, n414, n416, n417, n418, n419, n420, + n421, n422, n423, n424, n425, n426, n428, n429, n430, n431, + n432, n433, n434, n435, n436, n437, n438, n439, n440, n441, + n442, n443, n444, n445, n446, n447, n448, n449, n450, n451, + n452, n453, n455, n456, n457, n458, n459, n460, n461, n462, + n463, n464, n465, n466, n467, n468, n469, n470, n471, n472, + n473, n474, n475, n476, n477, n478, n479, n480, n481, n482, + n483, n484, n485, n486, n487, n488, n489, n490, n491, n492, + n493, n494, n495, n496, n497, n498, n499, n500, n501, n502, + n503, n504, n505, n506, n507, n508, n509, n510, n511, n512, + n513, n514, n515, n516, n517, n518, n519, n520, n521, n522, + n523, n524, n525, n526, n527, n528, n529, n530, n531, n532, + n533, n534, n535, n536, n537, n538, n539, n540, n541, n542, + n543, n544, n545, n546, n547, n548, n549, n550, n551, n552, + n553, n554, n555, n556, n557, n558, n559, n560, n561, n562, + n563, n564, n565, n566, n567, n568, n569, n570, n571, n572, + n573, n574, n575, n576, n577, n578, n579, n580, n581, n582, + n583, n584, n585, n586, n587, n588, n589, n590, n591, n592, + n593, n594, n595, n596, n597, n598, n599, n600, n601, n602, + n603, n604, n605, n606, n607, n608, n609, n610, n611, n612, + n613, n614, n615, n616, n617, n618, n619, n620, n621, n622, + n623, n624, n625, n626, n627, n628, n629, n630, n631, n632, + n633, n634, n635, n636, n637, n638, n639, n640, n641, n642, + n643, n644, n645, n646, n647, n648, n649, n650, n651, n652, + n653, n654, n655, n656, n657, n658, n659, n660, n661, n662, + n663, n664, n665, n666, n667, n668, n669, n670, n671, n672, + n673, n674, n675, n676, n677, n678, n679, n680, n681, n682, + n683, n684, n685, n686, n687, n688, n689, n690, n691, n692, + n693, n694, n695, n696; + + +assign po22 = n137; +assign po19 = n346; +assign po16 = n364; +assign po17 = n415; +assign po18 = n295; +assign po00 = n427; +assign po09 = n351; +assign po04 = n377; +assign po06 = n454; + AN2 U371 ( .A(pi11), .B(pi08), .Z(n357)); + AN2 U372 ( .A(pi28), .B(n357), .Z(n346)); + AN2 U373 ( .A(pi41), .B(pi25), .Z(n369)); + AN2 U374 ( .A(pi52), .B(n369), .Z(n361)); + AN2 U375 ( .A(pi51), .B(pi54), .Z(n359)); + AN2 U376 ( .A(pi28), .B(pi31), .Z(n604)); + AN2 U377 ( .A(n604), .B(pi55), .Z(n358)); + AN2 U378 ( .A(n359), .B(n358), .Z(n602)); + AN2 U379 ( .A(pi53), .B(n602), .Z(n360)); + AN2 U380 ( .A(n361), .B(n360), .Z(n577)); + IV2 U381 ( .A(pi20), .Z(n607)); + OR2 U382 ( .A(n607), .B(pi25), .Z(n362)); + IV2 U383 ( .A(n362), .Z(n365)); + AN2 U384 ( .A(pi25), .B(n607), .Z(n363)); + OR2 U385 ( .A(n365), .B(n363), .Z(n367)); + AN2 U386 ( .A(pi41), .B(pi24), .Z(n378)); + AN2 U387 ( .A(n346), .B(n378), .Z(n366)); + AN2 U388 ( .A(n367), .B(n366), .Z(n373)); + AN2 U389 ( .A(pi28), .B(pi54), .Z(n368)); + AN2 U390 ( .A(pi20), .B(n368), .Z(n603)); + AN2 U391 ( .A(pi08), .B(n603), .Z(n371)); + IV2 U392 ( .A(pi56), .Z(n694)); + IV2 U393 ( .A(n369), .Z(n692)); + OR2 U394 ( .A(n694), .B(n692), .Z(n370)); + AN2 U395 ( .A(n371), .B(n370), .Z(n372)); + OR2 U396 ( .A(n373), .B(n372), .Z(n424)); + AN2 U397 ( .A(pi14), .B(n424), .Z(n384)); + AN2 U398 ( .A(pi56), .B(pi48), .Z(n608)); + AN2 U399 ( .A(n608), .B(n346), .Z(n374)); + AN2 U400 ( .A(pi07), .B(n374), .Z(n376)); + IV2 U401 ( .A(pi43), .Z(n375)); + AN2 U402 ( .A(n376), .B(n375), .Z(n406)); + AN2 U403 ( .A(pi20), .B(n406), .Z(n403)); + IV2 U404 ( .A(n378), .Z(n379)); + AN2 U405 ( .A(n346), .B(n379), .Z(n407)); + AN2 U406 ( .A(pi55), .B(n407), .Z(n399)); + AN2 U407 ( .A(pi44), .B(n399), .Z(n381)); + AN2 U408 ( .A(pi37), .B(pi54), .Z(n380)); + OR2 U409 ( .A(n381), .B(n380), .Z(n382)); + OR2 U410 ( .A(n403), .B(n382), .Z(n383)); + OR2 U411 ( .A(n384), .B(n383), .Z(n436)); + AN2 U412 ( .A(pi26), .B(n436), .Z(n385)); + OR2 U413 ( .A(n577), .B(n385), .Z(n386)); + AN2 U414 ( .A(pi34), .B(n386), .Z(n448)); + AN2 U415 ( .A(pi43), .B(pi05), .Z(n388)); + AN2 U416 ( .A(pi32), .B(n436), .Z(n387)); + OR2 U417 ( .A(n388), .B(n387), .Z(n446)); + AN2 U418 ( .A(pi08), .B(pi37), .Z(n393)); + AN2 U419 ( .A(pi50), .B(n399), .Z(n390)); + AN2 U420 ( .A(pi18), .B(n424), .Z(n389)); + OR2 U421 ( .A(n390), .B(n389), .Z(n391)); + OR2 U422 ( .A(n403), .B(n391), .Z(n392)); + OR2 U423 ( .A(n393), .B(n392), .Z(n494)); + AN2 U424 ( .A(pi27), .B(n494), .Z(n497)); + OR2 U425 ( .A(pi27), .B(n494), .Z(n499)); + AN2 U426 ( .A(pi20), .B(pi37), .Z(n398)); + AN2 U427 ( .A(pi45), .B(n399), .Z(n395)); + AN2 U428 ( .A(pi22), .B(n424), .Z(n394)); + OR2 U429 ( .A(n395), .B(n394), .Z(n396)); + OR2 U430 ( .A(n403), .B(n396), .Z(n397)); + OR2 U431 ( .A(n398), .B(n397), .Z(n536)); + AN2 U432 ( .A(pi17), .B(n536), .Z(n539)); + OR2 U433 ( .A(pi17), .B(n536), .Z(n541)); + AN2 U434 ( .A(pi23), .B(n424), .Z(n405)); + AN2 U435 ( .A(pi30), .B(pi37), .Z(n401)); + AN2 U436 ( .A(pi29), .B(n399), .Z(n400)); + OR2 U437 ( .A(n401), .B(n400), .Z(n402)); + OR2 U438 ( .A(n403), .B(n402), .Z(n404)); + OR2 U439 ( .A(n405), .B(n404), .Z(n579)); + AN2 U440 ( .A(pi21), .B(n579), .Z(n582)); + OR2 U441 ( .A(pi21), .B(n579), .Z(n584)); + AN2 U442 ( .A(n406), .B(pi55), .Z(n429)); + IV2 U443 ( .A(pi28), .Z(n409)); + AN2 U444 ( .A(n407), .B(pi20), .Z(n408)); + OR2 U445 ( .A(n409), .B(n408), .Z(n423)); + AN2 U446 ( .A(pi50), .B(n423), .Z(n411)); + AN2 U447 ( .A(pi42), .B(n424), .Z(n410)); + OR2 U448 ( .A(n411), .B(n410), .Z(n412)); + OR2 U449 ( .A(n429), .B(n412), .Z(n514)); + AN2 U450 ( .A(pi15), .B(n514), .Z(n517)); + OR2 U451 ( .A(pi15), .B(n514), .Z(n519)); + AN2 U452 ( .A(pi45), .B(n423), .Z(n414)); + AN2 U453 ( .A(pi40), .B(n424), .Z(n413)); + OR2 U454 ( .A(n414), .B(n413), .Z(n416)); + OR2 U455 ( .A(n429), .B(n416), .Z(n556)); + AN2 U456 ( .A(pi03), .B(n556), .Z(n559)); + OR2 U457 ( .A(pi03), .B(n556), .Z(n561)); + AN2 U458 ( .A(pi29), .B(n423), .Z(n418)); + AN2 U459 ( .A(pi04), .B(n424), .Z(n417)); + OR2 U460 ( .A(n418), .B(n417), .Z(n419)); + OR2 U461 ( .A(n429), .B(n419), .Z(n471)); + AN2 U462 ( .A(pi10), .B(n471), .Z(n480)); + OR2 U463 ( .A(pi10), .B(n471), .Z(n482)); + AN2 U464 ( .A(pi46), .B(n482), .Z(n420)); + OR2 U465 ( .A(n480), .B(n420), .Z(n562)); + AN2 U466 ( .A(n561), .B(n562), .Z(n421)); + OR2 U467 ( .A(n559), .B(n421), .Z(n520)); + AN2 U468 ( .A(n519), .B(n520), .Z(n422)); + OR2 U469 ( .A(n517), .B(n422), .Z(n449)); + AN2 U470 ( .A(pi44), .B(n423), .Z(n426)); + AN2 U471 ( .A(pi49), .B(n424), .Z(n425)); + OR2 U472 ( .A(n426), .B(n425), .Z(n428)); + OR2 U473 ( .A(n429), .B(n428), .Z(n464)); + AN2 U474 ( .A(n449), .B(n464), .Z(n432)); + OR2 U475 ( .A(n449), .B(n464), .Z(n430)); + AN2 U476 ( .A(pi09), .B(n430), .Z(n431)); + OR2 U477 ( .A(n432), .B(n431), .Z(n585)); + AN2 U478 ( .A(n584), .B(n585), .Z(n433)); + OR2 U479 ( .A(n582), .B(n433), .Z(n542)); + AN2 U480 ( .A(n541), .B(n542), .Z(n434)); + OR2 U481 ( .A(n539), .B(n434), .Z(n500)); + AN2 U482 ( .A(n499), .B(n500), .Z(n435)); + OR2 U483 ( .A(n497), .B(n435), .Z(n597)); + OR2 U484 ( .A(pi34), .B(n436), .Z(n598)); + AN2 U485 ( .A(n436), .B(pi34), .Z(n600)); + IV2 U486 ( .A(n600), .Z(n437)); + AN2 U487 ( .A(n598), .B(n437), .Z(n442)); + OR2 U488 ( .A(n597), .B(n442), .Z(n440)); + AN2 U489 ( .A(n597), .B(n442), .Z(n438)); + IV2 U490 ( .A(n438), .Z(n439)); + AN2 U491 ( .A(n440), .B(n439), .Z(n441)); + AN2 U492 ( .A(pi12), .B(n441), .Z(n444)); + AN2 U493 ( .A(n442), .B(pi19), .Z(n443)); + OR2 U494 ( .A(n444), .B(n443), .Z(n445)); + OR2 U495 ( .A(n446), .B(n445), .Z(n447)); + OR2 U496 ( .A(n448), .B(n447), .Z(n137)); + IV2 U497 ( .A(n464), .Z(n459)); + AN2 U498 ( .A(pi12), .B(n449), .Z(n456)); + AN2 U499 ( .A(n459), .B(n456), .Z(n453)); + IV2 U500 ( .A(n449), .Z(n450)); + AN2 U501 ( .A(n450), .B(pi12), .Z(n451)); + OR2 U502 ( .A(pi19), .B(n451), .Z(n458)); + AN2 U503 ( .A(n464), .B(n458), .Z(n452)); + OR2 U504 ( .A(n453), .B(n452), .Z(n455)); + IV2 U505 ( .A(pi09), .Z(n612)); + AN2 U506 ( .A(n455), .B(n612), .Z(n470)); + OR2 U507 ( .A(pi26), .B(n456), .Z(n457)); + AN2 U508 ( .A(n464), .B(n457), .Z(n462)); + AN2 U509 ( .A(n459), .B(n458), .Z(n460)); + OR2 U510 ( .A(n577), .B(n460), .Z(n461)); + OR2 U511 ( .A(n462), .B(n461), .Z(n463)); + AN2 U512 ( .A(pi09), .B(n463), .Z(n468)); + AN2 U513 ( .A(pi23), .B(pi05), .Z(n466)); + AN2 U514 ( .A(pi32), .B(n464), .Z(n465)); + OR2 U515 ( .A(n466), .B(n465), .Z(n467)); + OR2 U516 ( .A(n468), .B(n467), .Z(n469)); + OR2 U517 ( .A(n470), .B(n469), .Z(n295)); + AN2 U518 ( .A(pi26), .B(n480), .Z(n479)); + AN2 U519 ( .A(pi40), .B(pi05), .Z(n473)); + AN2 U520 ( .A(pi32), .B(n471), .Z(n472)); + OR2 U521 ( .A(n473), .B(n472), .Z(n477)); + AN2 U522 ( .A(pi38), .B(pi36), .Z(n475)); + AN2 U523 ( .A(pi10), .B(n577), .Z(n474)); + OR2 U524 ( .A(n475), .B(n474), .Z(n476)); + OR2 U525 ( .A(n477), .B(n476), .Z(n478)); + OR2 U526 ( .A(n479), .B(n478), .Z(n491)); + IV2 U527 ( .A(n480), .Z(n481)); + AN2 U528 ( .A(n482), .B(n481), .Z(n487)); + OR2 U529 ( .A(pi46), .B(n487), .Z(n485)); + AN2 U530 ( .A(pi46), .B(n487), .Z(n483)); + IV2 U531 ( .A(n483), .Z(n484)); + AN2 U532 ( .A(n485), .B(n484), .Z(n486)); + AN2 U533 ( .A(pi12), .B(n486), .Z(n489)); + AN2 U534 ( .A(n487), .B(pi19), .Z(n488)); + OR2 U535 ( .A(n489), .B(n488), .Z(n490)); + OR2 U536 ( .A(n491), .B(n490), .Z(n351)); + AN2 U537 ( .A(pi26), .B(n494), .Z(n492)); + OR2 U538 ( .A(n577), .B(n492), .Z(n493)); + AN2 U539 ( .A(pi27), .B(n493), .Z(n511)); + AN2 U540 ( .A(pi14), .B(pi05), .Z(n496)); + AN2 U541 ( .A(pi32), .B(n494), .Z(n495)); + OR2 U542 ( .A(n496), .B(n495), .Z(n509)); + IV2 U543 ( .A(n497), .Z(n498)); + AN2 U544 ( .A(n499), .B(n498), .Z(n505)); + OR2 U545 ( .A(n500), .B(n505), .Z(n503)); + AN2 U546 ( .A(n500), .B(n505), .Z(n501)); + IV2 U547 ( .A(n501), .Z(n502)); + AN2 U548 ( .A(n503), .B(n502), .Z(n504)); + AN2 U549 ( .A(pi12), .B(n504), .Z(n507)); + AN2 U550 ( .A(n505), .B(pi19), .Z(n506)); + OR2 U551 ( .A(n507), .B(n506), .Z(n508)); + OR2 U552 ( .A(n509), .B(n508), .Z(n510)); + OR2 U553 ( .A(n511), .B(n510), .Z(n364)); + AN2 U554 ( .A(pi26), .B(n514), .Z(n512)); + OR2 U555 ( .A(n577), .B(n512), .Z(n513)); + AN2 U556 ( .A(pi15), .B(n513), .Z(n533)); + AN2 U557 ( .A(pi49), .B(pi05), .Z(n531)); + AN2 U558 ( .A(pi33), .B(pi36), .Z(n516)); + AN2 U559 ( .A(pi32), .B(n514), .Z(n515)); + OR2 U560 ( .A(n516), .B(n515), .Z(n529)); + IV2 U561 ( .A(n517), .Z(n518)); + AN2 U562 ( .A(n519), .B(n518), .Z(n525)); + OR2 U563 ( .A(n520), .B(n525), .Z(n523)); + AN2 U564 ( .A(n520), .B(n525), .Z(n521)); + IV2 U565 ( .A(n521), .Z(n522)); + AN2 U566 ( .A(n523), .B(n522), .Z(n524)); + AN2 U567 ( .A(pi12), .B(n524), .Z(n527)); + AN2 U568 ( .A(n525), .B(pi19), .Z(n526)); + OR2 U569 ( .A(n527), .B(n526), .Z(n528)); + OR2 U570 ( .A(n529), .B(n528), .Z(n530)); + OR2 U571 ( .A(n531), .B(n530), .Z(n532)); + OR2 U572 ( .A(n533), .B(n532), .Z(n377)); + AN2 U573 ( .A(pi26), .B(n536), .Z(n534)); + OR2 U574 ( .A(n577), .B(n534), .Z(n535)); + AN2 U575 ( .A(pi17), .B(n535), .Z(n553)); + AN2 U576 ( .A(pi18), .B(pi05), .Z(n538)); + AN2 U577 ( .A(pi32), .B(n536), .Z(n537)); + OR2 U578 ( .A(n538), .B(n537), .Z(n551)); + IV2 U579 ( .A(n539), .Z(n540)); + AN2 U580 ( .A(n541), .B(n540), .Z(n547)); + OR2 U581 ( .A(n542), .B(n547), .Z(n545)); + AN2 U582 ( .A(n542), .B(n547), .Z(n543)); + IV2 U583 ( .A(n543), .Z(n544)); + AN2 U584 ( .A(n545), .B(n544), .Z(n546)); + AN2 U585 ( .A(pi12), .B(n546), .Z(n549)); + AN2 U586 ( .A(n547), .B(pi19), .Z(n548)); + OR2 U587 ( .A(n549), .B(n548), .Z(n550)); + OR2 U588 ( .A(n551), .B(n550), .Z(n552)); + OR2 U589 ( .A(n553), .B(n552), .Z(n415)); + AN2 U590 ( .A(pi26), .B(n556), .Z(n554)); + OR2 U591 ( .A(n577), .B(n554), .Z(n555)); + AN2 U592 ( .A(pi03), .B(n555), .Z(n575)); + AN2 U593 ( .A(pi42), .B(pi05), .Z(n573)); + AN2 U594 ( .A(pi47), .B(pi36), .Z(n558)); + AN2 U595 ( .A(pi32), .B(n556), .Z(n557)); + OR2 U596 ( .A(n558), .B(n557), .Z(n571)); + IV2 U597 ( .A(n559), .Z(n560)); + AN2 U598 ( .A(n561), .B(n560), .Z(n567)); + OR2 U599 ( .A(n562), .B(n567), .Z(n565)); + AN2 U600 ( .A(n562), .B(n567), .Z(n563)); + IV2 U601 ( .A(n563), .Z(n564)); + AN2 U602 ( .A(n565), .B(n564), .Z(n566)); + AN2 U603 ( .A(pi12), .B(n566), .Z(n569)); + AN2 U604 ( .A(n567), .B(pi19), .Z(n568)); + OR2 U605 ( .A(n569), .B(n568), .Z(n570)); + OR2 U606 ( .A(n571), .B(n570), .Z(n572)); + OR2 U607 ( .A(n573), .B(n572), .Z(n574)); + OR2 U608 ( .A(n575), .B(n574), .Z(n427)); + AN2 U609 ( .A(pi26), .B(n579), .Z(n576)); + OR2 U610 ( .A(n577), .B(n576), .Z(n578)); + AN2 U611 ( .A(pi21), .B(n578), .Z(n596)); + AN2 U612 ( .A(pi22), .B(pi05), .Z(n581)); + AN2 U613 ( .A(pi32), .B(n579), .Z(n580)); + OR2 U614 ( .A(n581), .B(n580), .Z(n594)); + IV2 U615 ( .A(n582), .Z(n583)); + AN2 U616 ( .A(n584), .B(n583), .Z(n590)); + OR2 U617 ( .A(n585), .B(n590), .Z(n588)); + AN2 U618 ( .A(n585), .B(n590), .Z(n586)); + IV2 U619 ( .A(n586), .Z(n587)); + AN2 U620 ( .A(n588), .B(n587), .Z(n589)); + AN2 U621 ( .A(pi12), .B(n589), .Z(n592)); + AN2 U622 ( .A(n590), .B(pi19), .Z(n591)); + OR2 U623 ( .A(n592), .B(n591), .Z(n593)); + OR2 U624 ( .A(n594), .B(n593), .Z(n595)); + OR2 U625 ( .A(n596), .B(n595), .Z(n454)); + AN2 U626 ( .A(n598), .B(n597), .Z(n599)); + OR2 U627 ( .A(n600), .B(n599), .Z(po07)); + OR2 U628 ( .A(pi58), .B(pi00), .Z(n609)); + AN2 U629 ( .A(pi59), .B(n609), .Z(po24)); + AN2 U630 ( .A(n602), .B(pi57), .Z(n601)); + AN2 U631 ( .A(pi41), .B(n601), .Z(po13)); + AN2 U632 ( .A(pi48), .B(n602), .Z(po08)); + AN2 U633 ( .A(n603), .B(pi31), .Z(po03)); + AN2 U634 ( .A(pi48), .B(pi16), .Z(n610)); + AN2 U635 ( .A(pi25), .B(n610), .Z(po25)); + AN2 U636 ( .A(pi11), .B(n604), .Z(n605)); + IV2 U637 ( .A(n605), .Z(n606)); + OR2 U638 ( .A(n607), .B(n606), .Z(n691)); + OR2 U639 ( .A(po25), .B(n691), .Z(po02)); + AN2 U640 ( .A(n608), .B(pi25), .Z(po10)); + AN2 U641 ( .A(pi13), .B(n609), .Z(po12)); + AN2 U642 ( .A(pi07), .B(n610), .Z(po14)); + IV2 U643 ( .A(pi15), .Z(n611)); + AN2 U644 ( .A(pi09), .B(n611), .Z(n614)); + AN2 U645 ( .A(pi15), .B(n612), .Z(n613)); + OR2 U646 ( .A(n614), .B(n613), .Z(n618)); + IV2 U647 ( .A(pi35), .Z(n654)); + OR2 U648 ( .A(n654), .B(pi06), .Z(n617)); + IV2 U649 ( .A(pi06), .Z(n615)); + OR2 U650 ( .A(n615), .B(pi35), .Z(n616)); + AN2 U651 ( .A(n617), .B(n616), .Z(n619)); + OR2 U652 ( .A(n618), .B(n619), .Z(n622)); + AN2 U653 ( .A(n619), .B(n618), .Z(n620)); + IV2 U654 ( .A(n620), .Z(n621)); + AN2 U655 ( .A(n622), .B(n621), .Z(n628)); + IV2 U656 ( .A(pi10), .Z(n624)); + OR2 U657 ( .A(n624), .B(pi03), .Z(n623)); + IV2 U658 ( .A(n623), .Z(n626)); + AN2 U659 ( .A(pi03), .B(n624), .Z(n625)); + OR2 U660 ( .A(n626), .B(n625), .Z(n627)); + OR2 U661 ( .A(n628), .B(n627), .Z(n631)); + AN2 U662 ( .A(n628), .B(n627), .Z(n629)); + IV2 U663 ( .A(n629), .Z(n630)); + AN2 U664 ( .A(n631), .B(n630), .Z(n637)); + IV2 U665 ( .A(pi34), .Z(n632)); + AN2 U666 ( .A(pi27), .B(n632), .Z(n635)); + OR2 U667 ( .A(n632), .B(pi27), .Z(n633)); + IV2 U668 ( .A(n633), .Z(n634)); + OR2 U669 ( .A(n635), .B(n634), .Z(n636)); + OR2 U670 ( .A(n637), .B(n636), .Z(n640)); + AN2 U671 ( .A(n637), .B(n636), .Z(n638)); + IV2 U672 ( .A(n638), .Z(n639)); + AN2 U673 ( .A(n640), .B(n639), .Z(n647)); + IV2 U674 ( .A(pi21), .Z(n642)); + OR2 U675 ( .A(n642), .B(pi17), .Z(n641)); + IV2 U676 ( .A(n641), .Z(n644)); + AN2 U677 ( .A(pi17), .B(n642), .Z(n643)); + OR2 U678 ( .A(n644), .B(n643), .Z(n646)); + OR2 U679 ( .A(n647), .B(n646), .Z(n645)); + IV2 U680 ( .A(n645), .Z(n649)); + AN2 U681 ( .A(n647), .B(n646), .Z(n648)); + OR2 U682 ( .A(n649), .B(n648), .Z(po15)); + IV2 U683 ( .A(pi42), .Z(n650)); + AN2 U684 ( .A(pi49), .B(n650), .Z(n653)); + IV2 U685 ( .A(pi49), .Z(n651)); + AN2 U686 ( .A(pi42), .B(n651), .Z(n652)); + OR2 U687 ( .A(n653), .B(n652), .Z(n658)); + OR2 U688 ( .A(n654), .B(pi39), .Z(n657)); + IV2 U689 ( .A(pi39), .Z(n655)); + OR2 U690 ( .A(n655), .B(pi35), .Z(n656)); + AN2 U691 ( .A(n657), .B(n656), .Z(n659)); + OR2 U692 ( .A(n658), .B(n659), .Z(n662)); + AN2 U693 ( .A(n659), .B(n658), .Z(n660)); + IV2 U694 ( .A(n660), .Z(n661)); + AN2 U695 ( .A(n662), .B(n661), .Z(n668)); + IV2 U696 ( .A(pi04), .Z(n664)); + OR2 U697 ( .A(n664), .B(pi18), .Z(n663)); + IV2 U698 ( .A(n663), .Z(n666)); + AN2 U699 ( .A(pi18), .B(n664), .Z(n665)); + OR2 U700 ( .A(n666), .B(n665), .Z(n667)); + OR2 U701 ( .A(n668), .B(n667), .Z(n671)); + AN2 U702 ( .A(n668), .B(n667), .Z(n669)); + IV2 U703 ( .A(n669), .Z(n670)); + AN2 U704 ( .A(n671), .B(n670), .Z(n677)); + IV2 U705 ( .A(pi22), .Z(n673)); + OR2 U706 ( .A(n673), .B(pi14), .Z(n672)); + IV2 U707 ( .A(n672), .Z(n675)); + AN2 U708 ( .A(pi14), .B(n673), .Z(n674)); + OR2 U709 ( .A(n675), .B(n674), .Z(n676)); + OR2 U710 ( .A(n677), .B(n676), .Z(n680)); + AN2 U711 ( .A(n677), .B(n676), .Z(n678)); + IV2 U712 ( .A(n678), .Z(n679)); + AN2 U713 ( .A(n680), .B(n679), .Z(n687)); + IV2 U714 ( .A(pi40), .Z(n682)); + OR2 U715 ( .A(n682), .B(pi23), .Z(n681)); + IV2 U716 ( .A(n681), .Z(n684)); + AN2 U717 ( .A(pi23), .B(n682), .Z(n683)); + OR2 U718 ( .A(n684), .B(n683), .Z(n686)); + OR2 U719 ( .A(n687), .B(n686), .Z(n685)); + IV2 U720 ( .A(n685), .Z(n689)); + AN2 U721 ( .A(n687), .B(n686), .Z(n688)); + OR2 U722 ( .A(n689), .B(n688), .Z(po20)); + AN2 U723 ( .A(pi01), .B(pi02), .Z(po21)); + IV2 U724 ( .A(po25), .Z(n690)); + OR2 U725 ( .A(n691), .B(n690), .Z(po23)); + IV2 U726 ( .A(pi16), .Z(n696)); + OR2 U727 ( .A(n692), .B(n696), .Z(po11)); + AN2 U728 ( .A(pi07), .B(pi41), .Z(n693)); + IV2 U729 ( .A(n693), .Z(n695)); + OR2 U730 ( .A(n694), .B(n695), .Z(po01)); + OR2 U731 ( .A(n696), .B(n695), .Z(po05)); + +endmodule + +module IV2(A, Z); + input A; + output Z; + + assign Z = ~A; +endmodule + +module AN2(A, B, Z); + input A, B; + output Z; + + assign Z = A & B; +endmodule + +module OR2(A, B, Z); + input A, B; + output Z; + + assign Z = A | B; +endmodule diff --git a/chips/yosys/examples/smtbmc/glift/C880.ys b/chips/yosys/examples/smtbmc/glift/C880.ys new file mode 100644 index 0000000000000000000000000000000000000000..37b568da1d5b0e79c4233e72b5843242654bfc8b --- /dev/null +++ b/chips/yosys/examples/smtbmc/glift/C880.ys @@ -0,0 +1,41 @@ +read_verilog C880.v +techmap +flatten +select C880_lev2 +glift -create-instrumented-model +techmap +opt +rename C880_lev2 uut +cd .. +delete [AIONX][NVXR]2 +read_verilog C880.v +techmap +flatten +select C880_lev2 +glift -create-precise-model +techmap +opt +rename C880_lev2 spec +cd .. +delete [AIONX][NVXR]2 + +design -push-copy +miter -equiv spec uut miter +flatten +delete uut spec +techmap +opt +stat miter +qbfsat -O2 -write-solution C880.soln -solver yices -timeout 3600 -nocleanup -assume-outputs -assume-negative-polarity miter +design -pop +stat + +copy uut solved +qbfsat -specialize-from-file C880.soln solved +opt solved +miter -equiv spec solved satmiter +flatten +sat -prove trigger 0 satmiter +delete satmiter +stat +shell diff --git a/chips/yosys/examples/smtbmc/glift/alu2.v b/chips/yosys/examples/smtbmc/glift/alu2.v new file mode 100644 index 0000000000000000000000000000000000000000..ac2b2b10c18810335722179cc37122488136b82f --- /dev/null +++ b/chips/yosys/examples/smtbmc/glift/alu2.v @@ -0,0 +1,400 @@ +module alu2_lev2(pi0, pi1, pi2, pi3, pi4, pi5, pi6, pi7, pi8, pi9, + po0, po1, po2, po3, po4, po5); + +input pi0, pi1, pi2, pi3, pi4, pi5, pi6, pi7, pi8, pi9; + +output po0, po1, po2, po3, po4, po5; + +wire n358, n359, n360, n361, n362, n363, n364, n365, n366, n367, + n368, n369, n370, n371, n372, n373, n374, n375, n376, n377, + n378, n379, n380, n381, n382, n383, n384, n385, n386, n387, + n388, n389, n390, n391, n392, n393, n394, n395, n396, n397, + n398, n399, n400, n401, n402, n403, n404, n405, n406, n407, + n408, n409, n410, n411, n412, n413, n414, n415, n416, n417, + n418, n419, n420, n421, n422, n423, n424, n425, n426, n427, + n428, n429, n430, n431, n432, n433, n434, n435, n436, n437, + n438, n439, n440, n441, n442, n443, n444, n445, n446, n447, + n448, n449, n450, n451, n452, n453, n454, n455, n456, n457, + n458, n459, n460, n461, n462, n463, n464, n465, n466, n467, + n468, n469, n470, n471, n472, n473, n474, n475, n476, n477, + n478, n479, n480, n481, n482, n483, n484, n485, n486, n487, + n488, n489, n490, n491, n492, n493, n494, n495, n496, n497, + n498, n499, n500, n501, n502, n503, n504, n505, n506, n507, + n508, n509, n510, n511, n512, n513, n514, n515, n516, n517, + n518, n519, n520, n521, n522, n523, n524, n525, n526, n527, + n528, n529, n530, n531, n532, n533, n534, n535, n536, n537, + n538, n539, n540, n541, n542, n543, n544, n545, n546, n547, + n548, n549, n550, n551, n552, n553, n554, n555, n556, n557, + n558, n559, n560, n561, n562, n563, n564, n565, n566, n567, + n568, n569, n570, n571, n572, n573, n574, n575, n576, n577, + n578, n579, n580, n581, n582, n583, n584, n585, n586, n587, + n588, n589, n590, n591, n592, n593, n594, n595, n596, n597, + n598, n599, n600, n601, n602, n603, n604, n605, n606, n607, + n608, n609, n610, n611, n612, n613, n614, n615, n616, n617, + n618, n619, n620, n621, n622, n623, n624, n625, n626, n627, + n628, n629, n630, n631, n632, n633, n634, n635, n636, n637, + n638, n639, n640, n641, n642, n643, n644, n645, n646, n647, + n648, n649, n650, n651, n652, n653, n654, n655, n656, n657, + n658, n659, n660, n661, n662, n663, n664, n665, n666, n667, + n668, n669, n670, n671, n672, n673, n674, n675, n676, n677, + n678, n679, n680, n681, n682, n683, n684, n685, n686, n687; + + AN2 U363 ( .A(n358), .B(po2), .Z(po5)); + OR2 U364 ( .A(n359), .B(n360), .Z(n358)); + AN2 U365 ( .A(n361), .B(n362), .Z(n359)); + AN2 U366 ( .A(pi9), .B(n363), .Z(po4)); + OR2 U367 ( .A(n364), .B(n365), .Z(n363)); + OR2 U368 ( .A(n366), .B(n367), .Z(n365)); + AN2 U369 ( .A(pi6), .B(n368), .Z(n367)); + OR2 U370 ( .A(n369), .B(n370), .Z(n368)); + OR2 U371 ( .A(n371), .B(n372), .Z(n370)); + OR2 U372 ( .A(n373), .B(n374), .Z(n372)); + AN2 U373 ( .A(n375), .B(n376), .Z(n374)); + AN2 U374 ( .A(n377), .B(n378), .Z(n375)); + OR2 U375 ( .A(n379), .B(n380), .Z(n377)); + OR2 U376 ( .A(n381), .B(n382), .Z(n380)); + OR2 U377 ( .A(n383), .B(n384), .Z(n379)); + AN2 U378 ( .A(n385), .B(pi5), .Z(n384)); + AN2 U379 ( .A(n386), .B(n387), .Z(n383)); + AN2 U380 ( .A(pi4), .B(n361), .Z(n386)); + AN2 U381 ( .A(n388), .B(n389), .Z(n373)); + OR2 U382 ( .A(n390), .B(n391), .Z(n388)); + AN2 U383 ( .A(pi1), .B(n392), .Z(n390)); + OR2 U384 ( .A(n393), .B(n394), .Z(n392)); + OR2 U385 ( .A(pi7), .B(n395), .Z(n394)); + AN2 U386 ( .A(n381), .B(n396), .Z(n395)); + OR2 U387 ( .A(n397), .B(n398), .Z(n369)); + AN2 U388 ( .A(n399), .B(n400), .Z(n398)); + AN2 U389 ( .A(n387), .B(n401), .Z(n399)); + AN2 U390 ( .A(n402), .B(n403), .Z(n397)); + AN2 U391 ( .A(pi0), .B(n404), .Z(n402)); + OR2 U392 ( .A(pi1), .B(n389), .Z(n404)); + AN2 U393 ( .A(n405), .B(n406), .Z(n366)); + OR2 U394 ( .A(n407), .B(n408), .Z(n406)); + AN2 U395 ( .A(n360), .B(n409), .Z(n408)); + OR2 U396 ( .A(n410), .B(n411), .Z(n409)); + OR2 U397 ( .A(n412), .B(n413), .Z(n411)); + AN2 U398 ( .A(n414), .B(pi3), .Z(n413)); + AN2 U399 ( .A(n389), .B(n415), .Z(n410)); + AN2 U400 ( .A(po3), .B(n416), .Z(n407)); + OR2 U401 ( .A(n417), .B(n414), .Z(n416)); + OR2 U402 ( .A(n418), .B(n419), .Z(n364)); + OR2 U403 ( .A(n420), .B(n421), .Z(n419)); + AN2 U404 ( .A(n422), .B(n382), .Z(n421)); + AN2 U405 ( .A(pi7), .B(n389), .Z(n422)); + AN2 U406 ( .A(n423), .B(n424), .Z(n418)); + AN2 U407 ( .A(n425), .B(n426), .Z(n423)); + OR2 U408 ( .A(n427), .B(po3), .Z(po2)); + AN2 U409 ( .A(n428), .B(n429), .Z(n427)); + OR2 U410 ( .A(n430), .B(n431), .Z(po1)); + AN2 U411 ( .A(pi9), .B(n432), .Z(n431)); + OR2 U412 ( .A(n433), .B(n434), .Z(n432)); + OR2 U413 ( .A(n435), .B(n436), .Z(n434)); + AN2 U414 ( .A(n437), .B(n438), .Z(n436)); + IV2 U415 ( .A(n425), .Z(n438)); + AN2 U416 ( .A(n424), .B(n426), .Z(n437)); + OR2 U417 ( .A(n439), .B(n440), .Z(n424)); + OR2 U418 ( .A(n441), .B(n442), .Z(n440)); + AN2 U419 ( .A(n381), .B(n443), .Z(n442)); + OR2 U420 ( .A(n444), .B(n445), .Z(n443)); + AN2 U421 ( .A(n446), .B(n447), .Z(n441)); + AN2 U422 ( .A(n387), .B(n361), .Z(n446)); + AN2 U423 ( .A(n448), .B(n425), .Z(n435)); + OR2 U424 ( .A(n449), .B(n450), .Z(n425)); + OR2 U425 ( .A(n420), .B(n451), .Z(n450)); + OR2 U426 ( .A(n452), .B(n453), .Z(n451)); + AN2 U427 ( .A(pi6), .B(n454), .Z(n453)); + OR2 U428 ( .A(n371), .B(n455), .Z(n454)); + AN2 U429 ( .A(n376), .B(n456), .Z(n455)); + OR2 U430 ( .A(n457), .B(n458), .Z(n456)); + OR2 U431 ( .A(n459), .B(n460), .Z(n458)); + AN2 U432 ( .A(n461), .B(n378), .Z(n460)); + OR2 U433 ( .A(n462), .B(n463), .Z(n461)); + AN2 U434 ( .A(n385), .B(n464), .Z(n462)); + OR2 U435 ( .A(n465), .B(pi5), .Z(n464)); + AN2 U436 ( .A(pi7), .B(n466), .Z(n459)); + OR2 U437 ( .A(n467), .B(n468), .Z(n466)); + OR2 U438 ( .A(n469), .B(n470), .Z(n468)); + AN2 U439 ( .A(n381), .B(pi1), .Z(n470)); + AN2 U440 ( .A(n471), .B(n428), .Z(n469)); + AN2 U441 ( .A(pi0), .B(n387), .Z(n471)); + AN2 U442 ( .A(n412), .B(n361), .Z(n467)); + AN2 U443 ( .A(n472), .B(n473), .Z(n457)); + AN2 U444 ( .A(n360), .B(n428), .Z(n472)); + AN2 U445 ( .A(n463), .B(n428), .Z(n371)); + AN2 U446 ( .A(n474), .B(n475), .Z(n452)); + OR2 U447 ( .A(n476), .B(n477), .Z(n474)); + OR2 U448 ( .A(n478), .B(n479), .Z(n477)); + AN2 U449 ( .A(n480), .B(n428), .Z(n479)); + AN2 U450 ( .A(n481), .B(n482), .Z(n480)); + OR2 U451 ( .A(n360), .B(n389), .Z(n482)); + OR2 U452 ( .A(n401), .B(n483), .Z(n481)); + AN2 U453 ( .A(pi7), .B(n484), .Z(n483)); + OR2 U454 ( .A(n393), .B(n485), .Z(n484)); + AN2 U455 ( .A(n376), .B(n415), .Z(n485)); + AN2 U456 ( .A(n414), .B(n429), .Z(n393)); + AN2 U457 ( .A(n486), .B(n378), .Z(n478)); + OR2 U458 ( .A(n412), .B(n389), .Z(n486)); + AN2 U459 ( .A(n487), .B(pi1), .Z(n412)); + OR2 U460 ( .A(n488), .B(n489), .Z(n476)); + AN2 U461 ( .A(n490), .B(n401), .Z(n488)); + AN2 U462 ( .A(pi1), .B(n429), .Z(n490)); + AN2 U463 ( .A(n385), .B(n491), .Z(n420)); + IV2 U464 ( .A(n492), .Z(n491)); + OR2 U465 ( .A(n493), .B(n487), .Z(n492)); + AN2 U466 ( .A(n494), .B(n495), .Z(n493)); + OR2 U467 ( .A(pi6), .B(n389), .Z(n495)); + OR2 U468 ( .A(pi7), .B(pi1), .Z(n494)); + OR2 U469 ( .A(n496), .B(n497), .Z(n449)); + AN2 U470 ( .A(n498), .B(n376), .Z(n497)); + AN2 U471 ( .A(n381), .B(n382), .Z(n498)); + AN2 U472 ( .A(n499), .B(n389), .Z(n496)); + OR2 U473 ( .A(n500), .B(n501), .Z(n499)); + OR2 U474 ( .A(n502), .B(n503), .Z(n501)); + AN2 U475 ( .A(n385), .B(n504), .Z(n503)); + OR2 U476 ( .A(n505), .B(n506), .Z(n504)); + AN2 U477 ( .A(po3), .B(n400), .Z(n506)); + AN2 U478 ( .A(n507), .B(n428), .Z(n505)); + AN2 U479 ( .A(n508), .B(n387), .Z(n502)); + OR2 U480 ( .A(n509), .B(n510), .Z(n508)); + OR2 U481 ( .A(n489), .B(n511), .Z(n510)); + OR2 U482 ( .A(n465), .B(n512), .Z(n511)); + AN2 U483 ( .A(n513), .B(pi1), .Z(n512)); + AN2 U484 ( .A(pi0), .B(n514), .Z(n513)); + OR2 U485 ( .A(n507), .B(n515), .Z(n514)); + AN2 U486 ( .A(n361), .B(n428), .Z(n465)); + AN2 U487 ( .A(po3), .B(n360), .Z(n489)); + OR2 U488 ( .A(n516), .B(n517), .Z(n509)); + OR2 U489 ( .A(n518), .B(n519), .Z(n517)); + AN2 U490 ( .A(n391), .B(n362), .Z(n519)); + AN2 U491 ( .A(n428), .B(n400), .Z(n391)); + AN2 U492 ( .A(n520), .B(n521), .Z(n518)); + OR2 U493 ( .A(n522), .B(n362), .Z(n521)); + AN2 U494 ( .A(n429), .B(n523), .Z(n520)); + AN2 U495 ( .A(n417), .B(n378), .Z(n516)); + AN2 U496 ( .A(n522), .B(n382), .Z(n500)); + AN2 U497 ( .A(pi1), .B(n396), .Z(n382)); + AN2 U498 ( .A(n361), .B(n378), .Z(n522)); + OR2 U499 ( .A(n524), .B(n525), .Z(n448)); + OR2 U500 ( .A(n526), .B(n527), .Z(n525)); + OR2 U501 ( .A(pi8), .B(n528), .Z(n524)); + AN2 U502 ( .A(n529), .B(n530), .Z(n430)); + OR2 U503 ( .A(n531), .B(n532), .Z(n529)); + OR2 U504 ( .A(n533), .B(n534), .Z(n532)); + OR2 U505 ( .A(n535), .B(n536), .Z(n534)); + AN2 U506 ( .A(n537), .B(n376), .Z(n536)); + IV2 U507 ( .A(n389), .Z(n376)); + AN2 U508 ( .A(n538), .B(n389), .Z(n535)); + OR2 U509 ( .A(n539), .B(n540), .Z(n389)); + OR2 U510 ( .A(n541), .B(n542), .Z(n540)); + OR2 U511 ( .A(n543), .B(n544), .Z(n542)); + AN2 U512 ( .A(pi1), .B(n545), .Z(n544)); + AN2 U513 ( .A(n546), .B(n428), .Z(n543)); + AN2 U514 ( .A(n547), .B(n548), .Z(n546)); + OR2 U515 ( .A(pi3), .B(n396), .Z(n548)); + AN2 U516 ( .A(pi9), .B(n549), .Z(n541)); + OR2 U517 ( .A(n550), .B(n551), .Z(n549)); + OR2 U518 ( .A(n552), .B(n553), .Z(n551)); + AN2 U519 ( .A(n554), .B(n507), .Z(n553)); + AN2 U520 ( .A(n396), .B(pi0), .Z(n554)); + AN2 U521 ( .A(n555), .B(n556), .Z(n552)); + AN2 U522 ( .A(n557), .B(n415), .Z(n556)); + AN2 U523 ( .A(po3), .B(n558), .Z(n555)); + OR2 U524 ( .A(n559), .B(n560), .Z(n550)); + AN2 U525 ( .A(n561), .B(n429), .Z(n560)); + AN2 U526 ( .A(n417), .B(n562), .Z(n561)); + OR2 U527 ( .A(n563), .B(n564), .Z(n562)); + AN2 U528 ( .A(n558), .B(n428), .Z(n564)); + AN2 U529 ( .A(pi1), .B(n565), .Z(n563)); + AN2 U530 ( .A(pi3), .B(n566), .Z(n559)); + OR2 U531 ( .A(n567), .B(n414), .Z(n566)); + AN2 U532 ( .A(n568), .B(n569), .Z(n567)); + AN2 U533 ( .A(n565), .B(n428), .Z(n568)); + OR2 U534 ( .A(n570), .B(n571), .Z(n539)); + AN2 U535 ( .A(n572), .B(n429), .Z(n571)); + AN2 U536 ( .A(po3), .B(n573), .Z(n570)); + OR2 U537 ( .A(n574), .B(n575), .Z(n538)); + OR2 U538 ( .A(n445), .B(n576), .Z(n575)); + AN2 U539 ( .A(n577), .B(pi3), .Z(n576)); + AN2 U540 ( .A(n578), .B(pi1), .Z(n574)); + AN2 U541 ( .A(n507), .B(pi1), .Z(n533)); + OR2 U542 ( .A(n579), .B(n580), .Z(n531)); + OR2 U543 ( .A(n581), .B(n582), .Z(n580)); + AN2 U544 ( .A(n444), .B(po3), .Z(n582)); + AN2 U545 ( .A(pi1), .B(pi3), .Z(po3)); + AN2 U546 ( .A(n583), .B(n557), .Z(n581)); + AN2 U547 ( .A(n584), .B(n429), .Z(n583)); + OR2 U548 ( .A(n585), .B(n414), .Z(n584)); + AN2 U549 ( .A(n417), .B(n428), .Z(n585)); + AN2 U550 ( .A(n586), .B(pi7), .Z(n579)); + AN2 U551 ( .A(n587), .B(n588), .Z(n586)); + OR2 U552 ( .A(pi3), .B(n589), .Z(n588)); + AN2 U553 ( .A(pi1), .B(n523), .Z(n589)); + OR2 U554 ( .A(n429), .B(n590), .Z(n587)); + OR2 U555 ( .A(n417), .B(n591), .Z(n590)); + AN2 U556 ( .A(n592), .B(n428), .Z(n591)); + IV2 U557 ( .A(pi1), .Z(n428)); + IV2 U558 ( .A(pi3), .Z(n429)); + OR2 U559 ( .A(n593), .B(n594), .Z(po0)); + OR2 U560 ( .A(n595), .B(n596), .Z(n594)); + AN2 U561 ( .A(n597), .B(pi8), .Z(n596)); + AN2 U562 ( .A(n598), .B(n381), .Z(n597)); + AN2 U563 ( .A(pi0), .B(n385), .Z(n381)); + AN2 U564 ( .A(n507), .B(n487), .Z(n598)); + AN2 U565 ( .A(n528), .B(n426), .Z(n595)); + AN2 U566 ( .A(pi6), .B(n599), .Z(n528)); + IV2 U567 ( .A(n600), .Z(n599)); + OR2 U568 ( .A(n601), .B(n361), .Z(n600)); + AN2 U569 ( .A(n602), .B(n603), .Z(n601)); + AN2 U570 ( .A(n604), .B(n605), .Z(n603)); + OR2 U571 ( .A(pi7), .B(n606), .Z(n605)); + OR2 U572 ( .A(n607), .B(n387), .Z(n606)); + OR2 U573 ( .A(n378), .B(n487), .Z(n604)); + AN2 U574 ( .A(n608), .B(n609), .Z(n602)); + OR2 U575 ( .A(pi2), .B(n415), .Z(n608)); + OR2 U576 ( .A(n610), .B(n611), .Z(n593)); + AN2 U577 ( .A(pi9), .B(n612), .Z(n611)); + OR2 U578 ( .A(n613), .B(n614), .Z(n612)); + OR2 U579 ( .A(n433), .B(n615), .Z(n614)); + AN2 U580 ( .A(n527), .B(n426), .Z(n615)); + OR2 U581 ( .A(n616), .B(n617), .Z(n527)); + AN2 U582 ( .A(n618), .B(n361), .Z(n617)); + OR2 U583 ( .A(n619), .B(n620), .Z(n618)); + OR2 U584 ( .A(n621), .B(n622), .Z(n620)); + AN2 U585 ( .A(n592), .B(n362), .Z(n622)); + AN2 U586 ( .A(n385), .B(n623), .Z(n621)); + OR2 U587 ( .A(n624), .B(n625), .Z(n623)); + AN2 U588 ( .A(n626), .B(n415), .Z(n625)); + AN2 U589 ( .A(n507), .B(n523), .Z(n624)); + AN2 U590 ( .A(n473), .B(n557), .Z(n619)); + AN2 U591 ( .A(n523), .B(n387), .Z(n473)); + AN2 U592 ( .A(n569), .B(n387), .Z(n616)); + AN2 U593 ( .A(n578), .B(n627), .Z(n433)); + AN2 U594 ( .A(n378), .B(n475), .Z(n627)); + OR2 U595 ( .A(n628), .B(n629), .Z(n613)); + AN2 U596 ( .A(n526), .B(n426), .Z(n629)); + IV2 U597 ( .A(pi8), .Z(n426)); + AN2 U598 ( .A(n360), .B(n405), .Z(n526)); + AN2 U599 ( .A(pi8), .B(n630), .Z(n628)); + OR2 U600 ( .A(n631), .B(n439), .Z(n630)); + OR2 U601 ( .A(n632), .B(n633), .Z(n439)); + OR2 U602 ( .A(n634), .B(n635), .Z(n633)); + AN2 U603 ( .A(n636), .B(n378), .Z(n635)); + OR2 U604 ( .A(n637), .B(n360), .Z(n636)); + AN2 U605 ( .A(n387), .B(n475), .Z(n637)); + AN2 U606 ( .A(n638), .B(n475), .Z(n634)); + OR2 U607 ( .A(n639), .B(n640), .Z(n638)); + AN2 U608 ( .A(n558), .B(pi4), .Z(n639)); + OR2 U609 ( .A(n463), .B(n641), .Z(n632)); + AN2 U610 ( .A(n642), .B(n385), .Z(n641)); + AN2 U611 ( .A(n557), .B(n361), .Z(n642)); + AN2 U612 ( .A(n361), .B(n578), .Z(n463)); + AN2 U613 ( .A(n403), .B(n361), .Z(n631)); + IV2 U614 ( .A(n609), .Z(n403)); + OR2 U615 ( .A(n385), .B(n378), .Z(n609)); + AN2 U616 ( .A(n643), .B(n530), .Z(n610)); + OR2 U617 ( .A(n644), .B(n645), .Z(n643)); + OR2 U618 ( .A(n646), .B(n647), .Z(n645)); + OR2 U619 ( .A(n648), .B(n649), .Z(n647)); + AN2 U620 ( .A(n537), .B(n385), .Z(n649)); + IV2 U621 ( .A(n387), .Z(n385)); + OR2 U622 ( .A(n650), .B(n651), .Z(n537)); + AN2 U623 ( .A(n396), .B(pi6), .Z(n651)); + AN2 U624 ( .A(n400), .B(n475), .Z(n650)); + AN2 U625 ( .A(n652), .B(n387), .Z(n648)); + OR2 U626 ( .A(n653), .B(n654), .Z(n387)); + OR2 U627 ( .A(n655), .B(n656), .Z(n654)); + OR2 U628 ( .A(n657), .B(n658), .Z(n656)); + AN2 U629 ( .A(n360), .B(n573), .Z(n658)); + OR2 U630 ( .A(n659), .B(n660), .Z(n573)); + AN2 U631 ( .A(n405), .B(n578), .Z(n660)); + AN2 U632 ( .A(n396), .B(n661), .Z(n659)); + OR2 U633 ( .A(n405), .B(n557), .Z(n661)); + AN2 U634 ( .A(n475), .B(pi7), .Z(n405)); + IV2 U635 ( .A(n607), .Z(n396)); + OR2 U636 ( .A(pi5), .B(pi4), .Z(n607)); + AN2 U637 ( .A(n640), .B(n417), .Z(n657)); + AN2 U638 ( .A(n572), .B(n362), .Z(n655)); + OR2 U639 ( .A(n662), .B(n663), .Z(n572)); + OR2 U640 ( .A(n664), .B(n665), .Z(n663)); + AN2 U641 ( .A(n578), .B(n557), .Z(n665)); + AN2 U642 ( .A(n417), .B(n626), .Z(n664)); + AN2 U643 ( .A(n507), .B(n530), .Z(n662)); + OR2 U644 ( .A(n666), .B(n667), .Z(n653)); + OR2 U645 ( .A(n668), .B(n669), .Z(n667)); + AN2 U646 ( .A(n670), .B(n545), .Z(n669)); + OR2 U647 ( .A(n400), .B(n671), .Z(n545)); + AN2 U648 ( .A(pi9), .B(n414), .Z(n671)); + AN2 U649 ( .A(n378), .B(n414), .Z(n400)); + IV2 U650 ( .A(pi7), .Z(n378)); + OR2 U651 ( .A(pi0), .B(pi2), .Z(n670)); + AN2 U652 ( .A(n672), .B(n547), .Z(n668)); + AN2 U653 ( .A(n475), .B(n530), .Z(n547)); + IV2 U654 ( .A(pi9), .Z(n530)); + AN2 U655 ( .A(n361), .B(n415), .Z(n672)); + AN2 U656 ( .A(n558), .B(n569), .Z(n666)); + AN2 U657 ( .A(n557), .B(n417), .Z(n569)); + OR2 U658 ( .A(n673), .B(n674), .Z(n652)); + OR2 U659 ( .A(n445), .B(n675), .Z(n674)); + AN2 U660 ( .A(n577), .B(pi2), .Z(n675)); + AN2 U661 ( .A(n523), .B(n447), .Z(n445)); + OR2 U662 ( .A(n577), .B(n507), .Z(n447)); + AN2 U663 ( .A(n475), .B(n415), .Z(n577)); + AN2 U664 ( .A(n578), .B(pi0), .Z(n673)); + IV2 U665 ( .A(n487), .Z(n578)); + OR2 U666 ( .A(n415), .B(n523), .Z(n487)); + AN2 U667 ( .A(n507), .B(pi0), .Z(n646)); + AN2 U668 ( .A(pi6), .B(pi7), .Z(n507)); + OR2 U669 ( .A(n676), .B(n677), .Z(n644)); + OR2 U670 ( .A(n678), .B(n679), .Z(n677)); + AN2 U671 ( .A(n444), .B(n360), .Z(n679)); + IV2 U672 ( .A(n401), .Z(n360)); + OR2 U673 ( .A(n362), .B(n361), .Z(n401)); + AN2 U674 ( .A(pi6), .B(n417), .Z(n444)); + AN2 U675 ( .A(n680), .B(n557), .Z(n678)); + IV2 U676 ( .A(n626), .Z(n557)); + OR2 U677 ( .A(pi7), .B(n475), .Z(n626)); + AN2 U678 ( .A(n681), .B(n362), .Z(n680)); + OR2 U679 ( .A(n682), .B(n414), .Z(n681)); + AN2 U680 ( .A(n417), .B(n361), .Z(n682)); + IV2 U681 ( .A(pi0), .Z(n361)); + AN2 U682 ( .A(pi7), .B(n683), .Z(n676)); + OR2 U683 ( .A(n684), .B(n685), .Z(n683)); + OR2 U684 ( .A(n686), .B(n687), .Z(n685)); + AN2 U685 ( .A(n592), .B(n558), .Z(n687)); + IV2 U686 ( .A(n565), .Z(n558)); + OR2 U687 ( .A(pi0), .B(n362), .Z(n565)); + AN2 U688 ( .A(n475), .B(n414), .Z(n592)); + IV2 U689 ( .A(n515), .Z(n414)); + OR2 U690 ( .A(pi5), .B(n415), .Z(n515)); + IV2 U691 ( .A(pi6), .Z(n475)); + AN2 U692 ( .A(n640), .B(n523), .Z(n686)); + IV2 U693 ( .A(pi5), .Z(n523)); + AN2 U694 ( .A(n362), .B(pi0), .Z(n640)); + IV2 U695 ( .A(pi2), .Z(n362)); + AN2 U696 ( .A(n417), .B(pi2), .Z(n684)); + AN2 U697 ( .A(n415), .B(pi5), .Z(n417)); + IV2 U698 ( .A(pi4), .Z(n415)); + +endmodule + +module IV2(A, Z); + input A; + output Z; + + assign Z = ~A; +endmodule + +module AN2(A, B, Z); + input A, B; + output Z; + + assign Z = A & B; +endmodule + +module OR2(A, B, Z); + input A, B; + output Z; + + assign Z = A | B; +endmodule diff --git a/chips/yosys/examples/smtbmc/glift/alu2.ys b/chips/yosys/examples/smtbmc/glift/alu2.ys new file mode 100644 index 0000000000000000000000000000000000000000..f43dad07565025c6edead50fbf3c3cf6de4a9419 --- /dev/null +++ b/chips/yosys/examples/smtbmc/glift/alu2.ys @@ -0,0 +1,41 @@ +read_verilog alu2.v +techmap +flatten +select alu2_lev2 +glift -create-instrumented-model +techmap +opt +rename alu2_lev2 uut +cd .. +delete [AIONX][NVXR]2 +read_verilog alu2.v +techmap +flatten +select alu2_lev2 +glift -create-precise-model +techmap +opt +rename alu2_lev2 spec +cd .. +delete [AIONX][NVXR]2 + +design -push-copy +miter -equiv spec uut miter +flatten +delete uut spec +techmap +opt +stat miter +qbfsat -O2 -write-solution alu2.soln -solver yices -timeout 3600 -nocleanup -assume-outputs -assume-negative-polarity miter +design -pop +stat + +copy uut solved +qbfsat -specialize-from-file alu2.soln solved +opt solved +miter -equiv spec solved satmiter +flatten +sat -prove trigger 0 satmiter +delete satmiter +stat +shell diff --git a/chips/yosys/examples/smtbmc/glift/alu4.v b/chips/yosys/examples/smtbmc/glift/alu4.v new file mode 100644 index 0000000000000000000000000000000000000000..bc221eb04c7275587418ef26e575b62137ad0b6a --- /dev/null +++ b/chips/yosys/examples/smtbmc/glift/alu4.v @@ -0,0 +1,802 @@ +module alu4_lev2(pi00, pi01, pi02, pi03, pi04, pi05, pi06, pi07, pi08, pi09, + pi10, pi11, pi12, pi13, po0, po1, po2, po3, po4, po5, po6, po7); + +input pi00, pi01, pi02, pi03, pi04, pi05, pi06, pi07, pi08, pi09, + pi10, pi11, pi12, pi13; + +output po0, po1, po2, po3, po4, po5, po6, po7; + +wire n705, n706, n707, n708, n709, n710, n711, n712, n713, n714, + n715, n716, n717, n718, n719, n720, n721, n722, n723, n724, + n725, n726, n727, n728, n729, n730, n731, n732, n733, n734, + n735, n736, n737, n738, n739, n740, n741, n742, n743, n744, + n745, n746, n747, n748, n749, n750, n751, n752, n753, n754, + n755, n756, n757, n758, n759, n760, n761, n762, n763, n764, + n765, n766, n767, n768, n769, n770, n771, n772, n773, n774, + n775, n776, n777, n778, n779, n780, n781, n782, n783, n784, + n785, n786, n787, n788, n789, n790, n791, n792, n793, n794, + n795, n796, n797, n798, n799, n800, n801, n802, n803, n804, + n805, n806, n807, n808, n809, n810, n811, n812, n813, n814, + n815, n816, n817, n818, n819, n820, n821, n822, n823, n824, + n825, n826, n827, n828, n829, n830, n831, n832, n833, n834, + n835, n836, n837, n838, n839, n840, n841, n842, n843, n844, + n845, n846, n847, n848, n849, n850, n851, n852, n853, n854, + n855, n856, n857, n858, n859, n860, n861, n862, n863, n864, + n865, n866, n867, n868, n869, n870, n871, n872, n873, n874, + n875, n876, n877, n878, n879, n880, n881, n882, n883, n884, + n885, n886, n887, n888, n889, n890, n891, n892, n893, n894, + n895, n896, n897, n898, n899, n900, n901, n902, n903, n904, + n905, n906, n907, n908, n909, n910, n911, n912, n913, n914, + n915, n916, n917, n918, n919, n920, n921, n922, n923, n924, + n925, n926, n927, n928, n929, n930, n931, n932, n933, n934, + n935, n936, n937, n938, n939, n940, n941, n942, n943, n944, + n945, n946, n947, n948, n949, n950, n951, n952, n953, n954, + n955, n956, n957, n958, n959, n960, n961, n962, n963, n964, + n965, n966, n967, n968, n969, n970, n971, n972, n973, n974, + n975, n976, n977, n978, n979, n980, n981, n982, n983, n984, + n985, n986, n987, n988, n989, n990, n991, n992, n993, n994, + n995, n996, n997, n998, n999, n1000, n1001, n1002, n1003, n1004, + n1005, n1006, n1007, n1008, n1009, n1010, n1011, n1012, n1013, n1014, + n1015, n1016, n1017, n1018, n1019, n1020, n1021, n1022, n1023, n1024, + n1025, n1026, n1027, n1028, n1029, n1030, n1031, n1032, n1033, n1034, + n1035, n1036, n1037, n1038, n1039, n1040, n1041, n1042, n1043, n1044, + n1045, n1046, n1047, n1048, n1049, n1050, n1051, n1052, n1053, n1054, + n1055, n1056, n1057, n1058, n1059, n1060, n1061, n1062, n1063, n1064, + n1065, n1066, n1067, n1068, n1069, n1070, n1071, n1072, n1073, n1074, + n1075, n1076, n1077, n1078, n1079, n1080, n1081, n1082, n1083, n1084, + n1085, n1086, n1087, n1088, n1089, n1090, n1091, n1092, n1093, n1094, + n1095, n1096, n1097, n1098, n1099, n1100, n1101, n1102, n1103, n1104, + n1105, n1106, n1107, n1108, n1109, n1110, n1111, n1112, n1113, n1114, + n1115, n1116, n1117, n1118, n1119, n1120, n1121, n1122, n1123, n1124, + n1125, n1126, n1127, n1128, n1129, n1130, n1131, n1132, n1133, n1134, + n1135, n1136, n1137, n1138, n1139, n1140, n1141, n1142, n1143, n1144, + n1145, n1146, n1147, n1148, n1149, n1150, n1151, n1152, n1153, n1154, + n1155, n1156, n1157, n1158, n1159, n1160, n1161, n1162, n1163, n1164, + n1165, n1166, n1167, n1168, n1169, n1170, n1171, n1172, n1173, n1174, + n1175, n1176, n1177, n1178, n1179, n1180, n1181, n1182, n1183, n1184, + n1185, n1186, n1187, n1188, n1189, n1190, n1191, n1192, n1193, n1194, + n1195, n1196, n1197, n1198, n1199, n1200, n1201, n1202, n1203, n1204, + n1205, n1206, n1207, n1208, n1209, n1210, n1211, n1212, n1213, n1214, + n1215, n1216, n1217, n1218, n1219, n1220, n1221, n1222, n1223, n1224, + n1225, n1226, n1227, n1228, n1229, n1230, n1231, n1232, n1233, n1234, + n1235, n1236, n1237, n1238, n1239, n1240, n1241, n1242, n1243, n1244, + n1245, n1246, n1247, n1248, n1249, n1250, n1251, n1252, n1253, n1254, + n1255, n1256, n1257, n1258, n1259, n1260, n1261, n1262, n1263, n1264, + n1265, n1266, n1267, n1268, n1269, n1270, n1271, n1272, n1273, n1274, + n1275, n1276, n1277, n1278, n1279, n1280, n1281, n1282, n1283, n1284, + n1285, n1286, n1287, n1288, n1289, n1290, n1291, n1292, n1293, n1294, + n1295, n1296, n1297, n1298, n1299, n1300, n1301, n1302, n1303, n1304, + n1305, n1306, n1307, n1308, n1309, n1310, n1311, n1312, n1313, n1314, + n1315, n1316, n1317, n1318, n1319, n1320, n1321, n1322, n1323, n1324, + n1325, n1326, n1327, n1328, n1329, n1330, n1331, n1332, n1333, n1334, + n1335, n1336, n1337, n1338, n1339, n1340, n1341, n1342, n1343, n1344, + n1345, n1346, n1347, n1348, n1349, n1350, n1351, n1352, n1353, n1354, + n1355, n1356, n1357, n1358, n1359, n1360, n1361, n1362, n1363, n1364, + n1365, n1366, n1367, n1368, n1369, n1370, n1371, n1372, n1373, n1374, + n1375, n1376, n1377, n1378, n1379, n1380, n1381, n1382, n1383, n1384, + n1385, n1386, n1387, n1388, n1389, n1390, n1391, n1392, n1393, n1394, + n1395, n1396; + + AN2 U712 ( .A(n705), .B(po4), .Z(po7)); + OR2 U713 ( .A(n706), .B(n707), .Z(n705)); + AN2 U714 ( .A(n708), .B(n709), .Z(n707)); + OR2 U715 ( .A(n710), .B(n711), .Z(n708)); + AN2 U716 ( .A(n712), .B(n713), .Z(n711)); + AN2 U717 ( .A(n714), .B(n715), .Z(n710)); + AN2 U718 ( .A(n716), .B(n717), .Z(n714)); + AN2 U719 ( .A(n718), .B(n719), .Z(n706)); + OR2 U720 ( .A(n720), .B(n712), .Z(n719)); + OR2 U721 ( .A(n721), .B(n722), .Z(n712)); + AN2 U722 ( .A(n723), .B(n724), .Z(n722)); + AN2 U723 ( .A(n725), .B(n726), .Z(n721)); + OR2 U724 ( .A(n724), .B(n727), .Z(n726)); + AN2 U725 ( .A(n727), .B(n723), .Z(n720)); + OR2 U726 ( .A(n728), .B(n729), .Z(po6)); + AN2 U727 ( .A(pi13), .B(n730), .Z(n729)); + OR2 U728 ( .A(n731), .B(n732), .Z(n730)); + OR2 U729 ( .A(n733), .B(n734), .Z(n732)); + OR2 U730 ( .A(n735), .B(n736), .Z(n734)); + AN2 U731 ( .A(n737), .B(n738), .Z(n736)); + OR2 U732 ( .A(n739), .B(n740), .Z(n737)); + OR2 U733 ( .A(n741), .B(n742), .Z(n740)); + AN2 U734 ( .A(n743), .B(n744), .Z(n742)); + OR2 U735 ( .A(n745), .B(n746), .Z(n743)); + AN2 U736 ( .A(pi03), .B(n747), .Z(n745)); + AN2 U737 ( .A(n748), .B(n749), .Z(n741)); + AN2 U738 ( .A(n750), .B(n751), .Z(n748)); + AN2 U739 ( .A(pi11), .B(n752), .Z(n735)); + OR2 U740 ( .A(n753), .B(n754), .Z(n752)); + OR2 U741 ( .A(n755), .B(n756), .Z(n754)); + AN2 U742 ( .A(n757), .B(n747), .Z(n756)); + OR2 U743 ( .A(n758), .B(n759), .Z(n757)); + IV2 U744 ( .A(n760), .Z(n755)); + AN2 U745 ( .A(n761), .B(n762), .Z(n753)); + OR2 U746 ( .A(n763), .B(po5), .Z(n762)); + AN2 U747 ( .A(n764), .B(n765), .Z(n763)); + AN2 U748 ( .A(n766), .B(n767), .Z(n733)); + OR2 U749 ( .A(n768), .B(n769), .Z(n767)); + AN2 U750 ( .A(n770), .B(n771), .Z(n768)); + IV2 U751 ( .A(n772), .Z(n766)); + OR2 U752 ( .A(n773), .B(n774), .Z(n731)); + AN2 U753 ( .A(n775), .B(n776), .Z(n774)); + AN2 U754 ( .A(n777), .B(n778), .Z(n775)); + AN2 U755 ( .A(n779), .B(n780), .Z(n773)); + AN2 U756 ( .A(n781), .B(n782), .Z(n779)); + AN2 U757 ( .A(n783), .B(n781), .Z(n728)); + AN2 U758 ( .A(n782), .B(n784), .Z(n783)); + OR2 U759 ( .A(n785), .B(n786), .Z(po3)); + OR2 U760 ( .A(n787), .B(n788), .Z(n786)); + OR2 U761 ( .A(n789), .B(n790), .Z(n788)); + OR2 U762 ( .A(n791), .B(n792), .Z(n790)); + AN2 U763 ( .A(n793), .B(n782), .Z(n792)); + AN2 U764 ( .A(n794), .B(n795), .Z(n791)); + OR2 U765 ( .A(n796), .B(n797), .Z(n789)); + IV2 U766 ( .A(n798), .Z(n797)); + OR2 U767 ( .A(n799), .B(n778), .Z(n798)); + AN2 U768 ( .A(n778), .B(n799), .Z(n796)); + OR2 U769 ( .A(n800), .B(n801), .Z(n799)); + IV2 U770 ( .A(n802), .Z(n778)); + OR2 U771 ( .A(n803), .B(n804), .Z(n802)); + AN2 U772 ( .A(n805), .B(n806), .Z(n803)); + AN2 U773 ( .A(n807), .B(n808), .Z(n806)); + AN2 U774 ( .A(n809), .B(n810), .Z(n808)); + OR2 U775 ( .A(pi11), .B(n811), .Z(n810)); + AN2 U776 ( .A(n812), .B(n813), .Z(n811)); + AN2 U777 ( .A(n814), .B(n815), .Z(n813)); + OR2 U778 ( .A(n782), .B(n816), .Z(n815)); + OR2 U779 ( .A(n817), .B(n818), .Z(n814)); + OR2 U780 ( .A(n819), .B(n820), .Z(n818)); + AN2 U781 ( .A(n750), .B(n821), .Z(n820)); + AN2 U782 ( .A(n749), .B(n747), .Z(n819)); + IV2 U783 ( .A(n821), .Z(n749)); + AN2 U784 ( .A(n822), .B(n823), .Z(n812)); + OR2 U785 ( .A(n824), .B(n825), .Z(n823)); + OR2 U786 ( .A(n826), .B(n827), .Z(n822)); + AN2 U787 ( .A(pi10), .B(n828), .Z(n826)); + OR2 U788 ( .A(n829), .B(n830), .Z(n828)); + OR2 U789 ( .A(n831), .B(n738), .Z(n809)); + AN2 U790 ( .A(n832), .B(n833), .Z(n831)); + AN2 U791 ( .A(n834), .B(n760), .Z(n833)); + OR2 U792 ( .A(n817), .B(n835), .Z(n760)); + OR2 U793 ( .A(pi03), .B(n836), .Z(n835)); + OR2 U794 ( .A(n817), .B(n837), .Z(n834)); + OR2 U795 ( .A(n715), .B(n827), .Z(n837)); + IV2 U796 ( .A(n836), .Z(n715)); + AN2 U797 ( .A(n838), .B(n839), .Z(n832)); + OR2 U798 ( .A(n765), .B(n840), .Z(n839)); + OR2 U799 ( .A(n841), .B(n825), .Z(n840)); + OR2 U800 ( .A(n816), .B(n842), .Z(n838)); + OR2 U801 ( .A(n843), .B(n844), .Z(n842)); + AN2 U802 ( .A(n845), .B(n846), .Z(n844)); + OR2 U803 ( .A(n847), .B(n848), .Z(n845)); + AN2 U804 ( .A(n758), .B(n747), .Z(n848)); + IV2 U805 ( .A(n849), .Z(n758)); + AN2 U806 ( .A(n750), .B(n849), .Z(n847)); + AN2 U807 ( .A(n849), .B(n759), .Z(n843)); + OR2 U808 ( .A(n850), .B(n851), .Z(n849)); + AN2 U809 ( .A(n852), .B(n853), .Z(n850)); + IV2 U810 ( .A(n854), .Z(n816)); + AN2 U811 ( .A(n855), .B(n856), .Z(n807)); + OR2 U812 ( .A(n857), .B(n858), .Z(n856)); + OR2 U813 ( .A(n859), .B(n860), .Z(n858)); + AN2 U814 ( .A(n861), .B(n739), .Z(n859)); + OR2 U815 ( .A(n862), .B(n863), .Z(n739)); + AN2 U816 ( .A(n759), .B(n795), .Z(n862)); + OR2 U817 ( .A(n846), .B(n864), .Z(n861)); + IV2 U818 ( .A(n865), .Z(n864)); + AN2 U819 ( .A(n795), .B(n863), .Z(n865)); + IV2 U820 ( .A(n759), .Z(n846)); + OR2 U821 ( .A(n866), .B(n867), .Z(n759)); + AN2 U822 ( .A(n868), .B(po5), .Z(n867)); + AN2 U823 ( .A(n750), .B(n869), .Z(n866)); + OR2 U824 ( .A(n825), .B(n870), .Z(n855)); + OR2 U825 ( .A(n871), .B(n872), .Z(n870)); + AN2 U826 ( .A(n764), .B(n873), .Z(n872)); + IV2 U827 ( .A(po5), .Z(n873)); + AN2 U828 ( .A(n841), .B(po4), .Z(n871)); + OR2 U829 ( .A(n874), .B(po5), .Z(po4)); + IV2 U830 ( .A(n764), .Z(n841)); + OR2 U831 ( .A(n875), .B(n724), .Z(n764)); + AN2 U832 ( .A(n876), .B(n877), .Z(n875)); + AN2 U833 ( .A(n878), .B(n879), .Z(n805)); + AN2 U834 ( .A(n880), .B(n881), .Z(n879)); + OR2 U835 ( .A(n782), .B(n882), .Z(n881)); + OR2 U836 ( .A(n781), .B(n883), .Z(n882)); + IV2 U837 ( .A(n884), .Z(n781)); + OR2 U838 ( .A(n795), .B(n885), .Z(n880)); + AN2 U839 ( .A(n886), .B(n887), .Z(n878)); + OR2 U840 ( .A(pi03), .B(n888), .Z(n887)); + AN2 U841 ( .A(n889), .B(n890), .Z(n888)); + IV2 U842 ( .A(n891), .Z(n890)); + AN2 U843 ( .A(n830), .B(n892), .Z(n891)); + OR2 U844 ( .A(n893), .B(n894), .Z(n830)); + IV2 U845 ( .A(n895), .Z(n894)); + OR2 U846 ( .A(n746), .B(n750), .Z(n895)); + AN2 U847 ( .A(n750), .B(n746), .Z(n893)); + OR2 U848 ( .A(n896), .B(n897), .Z(n746)); + AN2 U849 ( .A(pi02), .B(n898), .Z(n896)); + IV2 U850 ( .A(n747), .Z(n750)); + OR2 U851 ( .A(n899), .B(n900), .Z(n747)); + AN2 U852 ( .A(n901), .B(n771), .Z(n900)); + OR2 U853 ( .A(pi03), .B(n795), .Z(n771)); + AN2 U854 ( .A(n902), .B(n903), .Z(n899)); + OR2 U855 ( .A(n904), .B(n905), .Z(n903)); + OR2 U856 ( .A(n906), .B(n907), .Z(n905)); + AN2 U857 ( .A(n782), .B(n892), .Z(n907)); + AN2 U858 ( .A(n769), .B(n751), .Z(n906)); + AN2 U859 ( .A(po5), .B(n908), .Z(n904)); + OR2 U860 ( .A(n909), .B(n772), .Z(n889)); + AN2 U861 ( .A(n910), .B(n911), .Z(n909)); + OR2 U862 ( .A(n912), .B(n795), .Z(n911)); + OR2 U863 ( .A(n782), .B(n770), .Z(n910)); + OR2 U864 ( .A(n827), .B(n913), .Z(n886)); + OR2 U865 ( .A(n914), .B(n772), .Z(n913)); + OR2 U866 ( .A(n915), .B(n916), .Z(n914)); + AN2 U867 ( .A(n912), .B(n795), .Z(n916)); + IV2 U868 ( .A(n770), .Z(n912)); + AN2 U869 ( .A(n782), .B(n770), .Z(n915)); + OR2 U870 ( .A(n917), .B(n918), .Z(n770)); + AN2 U871 ( .A(n919), .B(n920), .Z(n917)); + IV2 U872 ( .A(n795), .Z(n782)); + OR2 U873 ( .A(n921), .B(n922), .Z(n787)); + AN2 U874 ( .A(n923), .B(n824), .Z(n922)); + AN2 U875 ( .A(n924), .B(n925), .Z(n923)); + OR2 U876 ( .A(n926), .B(n927), .Z(n925)); + AN2 U877 ( .A(pi11), .B(pi03), .Z(n926)); + AN2 U878 ( .A(pi07), .B(n928), .Z(n921)); + OR2 U879 ( .A(n929), .B(n930), .Z(n928)); + AN2 U880 ( .A(n931), .B(n804), .Z(n929)); + OR2 U881 ( .A(n932), .B(n933), .Z(n931)); + AN2 U882 ( .A(n854), .B(n795), .Z(n933)); + AN2 U883 ( .A(n934), .B(n827), .Z(n932)); + OR2 U884 ( .A(n935), .B(n936), .Z(n785)); + OR2 U885 ( .A(n937), .B(n938), .Z(n936)); + AN2 U886 ( .A(n939), .B(n940), .Z(n938)); + OR2 U887 ( .A(n941), .B(n942), .Z(n940)); + OR2 U888 ( .A(n769), .B(n943), .Z(n942)); + AN2 U889 ( .A(n874), .B(n944), .Z(n943)); + AN2 U890 ( .A(n795), .B(pi03), .Z(n769)); + OR2 U891 ( .A(n945), .B(n946), .Z(n795)); + OR2 U892 ( .A(n947), .B(n948), .Z(n946)); + AN2 U893 ( .A(n949), .B(n824), .Z(n948)); + AN2 U894 ( .A(n950), .B(n765), .Z(n947)); + IV2 U895 ( .A(n874), .Z(n765)); + OR2 U896 ( .A(n951), .B(n952), .Z(n945)); + OR2 U897 ( .A(n953), .B(n954), .Z(n952)); + AN2 U898 ( .A(n955), .B(n827), .Z(n954)); + OR2 U899 ( .A(n956), .B(n957), .Z(n955)); + AN2 U900 ( .A(n958), .B(n784), .Z(n956)); + AN2 U901 ( .A(pi07), .B(n959), .Z(n958)); + AN2 U902 ( .A(po5), .B(n960), .Z(n953)); + OR2 U903 ( .A(n961), .B(n962), .Z(n960)); + AN2 U904 ( .A(n892), .B(n963), .Z(n962)); + AN2 U905 ( .A(n964), .B(n965), .Z(n961)); + AN2 U906 ( .A(pi13), .B(n966), .Z(n951)); + OR2 U907 ( .A(n967), .B(n968), .Z(n966)); + OR2 U908 ( .A(n969), .B(n970), .Z(n968)); + AN2 U909 ( .A(n971), .B(pi02), .Z(n970)); + AN2 U910 ( .A(n972), .B(n973), .Z(n969)); + AN2 U911 ( .A(n974), .B(n975), .Z(n972)); + OR2 U912 ( .A(n874), .B(n959), .Z(n975)); + AN2 U913 ( .A(n827), .B(n824), .Z(n874)); + IV2 U914 ( .A(pi03), .Z(n827)); + OR2 U915 ( .A(n964), .B(n976), .Z(n974)); + AN2 U916 ( .A(pi03), .B(n824), .Z(n976)); + IV2 U917 ( .A(pi07), .Z(n824)); + IV2 U918 ( .A(n959), .Z(n964)); + OR2 U919 ( .A(n977), .B(n978), .Z(n959)); + AN2 U920 ( .A(n979), .B(pi02), .Z(n978)); + AN2 U921 ( .A(n980), .B(n717), .Z(n977)); + OR2 U922 ( .A(n979), .B(pi02), .Z(n980)); + AN2 U923 ( .A(n981), .B(po5), .Z(n967)); + AN2 U924 ( .A(po5), .B(n982), .Z(n941)); + AN2 U925 ( .A(pi03), .B(pi07), .Z(po5)); + AN2 U926 ( .A(n983), .B(pi03), .Z(n935)); + OR2 U927 ( .A(n984), .B(n985), .Z(po2)); + OR2 U928 ( .A(n986), .B(n987), .Z(n985)); + OR2 U929 ( .A(n988), .B(n989), .Z(n987)); + OR2 U930 ( .A(n990), .B(n991), .Z(n989)); + AN2 U931 ( .A(n793), .B(n992), .Z(n991)); + AN2 U932 ( .A(n794), .B(n993), .Z(n990)); + OR2 U933 ( .A(n994), .B(n995), .Z(n988)); + AN2 U934 ( .A(n777), .B(n801), .Z(n995)); + IV2 U935 ( .A(n800), .Z(n777)); + AN2 U936 ( .A(n776), .B(n800), .Z(n994)); + OR2 U937 ( .A(n996), .B(n804), .Z(n800)); + AN2 U938 ( .A(n997), .B(n998), .Z(n996)); + AN2 U939 ( .A(n999), .B(n1000), .Z(n998)); + AN2 U940 ( .A(n1001), .B(n1002), .Z(n1000)); + OR2 U941 ( .A(n1003), .B(n817), .Z(n1002)); + AN2 U942 ( .A(n1004), .B(n836), .Z(n1003)); + OR2 U943 ( .A(pi00), .B(n1005), .Z(n836)); + OR2 U944 ( .A(pi02), .B(pi01), .Z(n1005)); + AN2 U945 ( .A(n1006), .B(n1007), .Z(n1004)); + OR2 U946 ( .A(pi11), .B(n1008), .Z(n1007)); + AN2 U947 ( .A(n1009), .B(n821), .Z(n1008)); + OR2 U948 ( .A(n898), .B(n1010), .Z(n821)); + OR2 U949 ( .A(n1011), .B(n851), .Z(n1009)); + AN2 U950 ( .A(n1012), .B(n1013), .Z(n1011)); + OR2 U951 ( .A(n738), .B(n1014), .Z(n1006)); + OR2 U952 ( .A(n1015), .B(n1016), .Z(n1014)); + AN2 U953 ( .A(n713), .B(n1017), .Z(n1015)); + OR2 U954 ( .A(n1018), .B(n1019), .Z(n1001)); + OR2 U955 ( .A(n744), .B(n1020), .Z(n1019)); + OR2 U956 ( .A(n1021), .B(n1022), .Z(n1018)); + AN2 U957 ( .A(n717), .B(n1023), .Z(n1022)); + AN2 U958 ( .A(n863), .B(n1024), .Z(n1021)); + OR2 U959 ( .A(n1025), .B(n1026), .Z(n1024)); + OR2 U960 ( .A(n992), .B(n852), .Z(n1026)); + IV2 U961 ( .A(n1027), .Z(n1025)); + OR2 U962 ( .A(n1028), .B(n1027), .Z(n863)); + OR2 U963 ( .A(n1029), .B(n1030), .Z(n1027)); + AN2 U964 ( .A(n1031), .B(n1032), .Z(n1029)); + AN2 U965 ( .A(n1033), .B(n993), .Z(n1028)); + AN2 U966 ( .A(n885), .B(n1034), .Z(n999)); + OR2 U967 ( .A(n825), .B(n1035), .Z(n1034)); + OR2 U968 ( .A(n1036), .B(n1037), .Z(n1035)); + AN2 U969 ( .A(n1038), .B(n1039), .Z(n1037)); + IV2 U970 ( .A(n724), .Z(n1039)); + OR2 U971 ( .A(n877), .B(n738), .Z(n1038)); + IV2 U972 ( .A(n876), .Z(n1036)); + OR2 U973 ( .A(n1040), .B(n884), .Z(n885)); + OR2 U974 ( .A(n1041), .B(n1042), .Z(n884)); + OR2 U975 ( .A(n993), .B(n1032), .Z(n1042)); + AN2 U976 ( .A(n1043), .B(n1044), .Z(n997)); + AN2 U977 ( .A(n1045), .B(n1046), .Z(n1044)); + OR2 U978 ( .A(pi02), .B(n1047), .Z(n1046)); + AN2 U979 ( .A(n1048), .B(n1049), .Z(n1047)); + OR2 U980 ( .A(n876), .B(n1050), .Z(n1049)); + OR2 U981 ( .A(n717), .B(n825), .Z(n1050)); + AN2 U982 ( .A(n1051), .B(n1052), .Z(n1048)); + OR2 U983 ( .A(n1053), .B(n1054), .Z(n1052)); + OR2 U984 ( .A(n1055), .B(n772), .Z(n1051)); + AN2 U985 ( .A(n1056), .B(n1057), .Z(n1055)); + OR2 U986 ( .A(n1058), .B(n993), .Z(n1057)); + OR2 U987 ( .A(n992), .B(n919), .Z(n1056)); + OR2 U988 ( .A(n1059), .B(n1016), .Z(n1045)); + AN2 U989 ( .A(n1060), .B(n1061), .Z(n1059)); + AN2 U990 ( .A(n1062), .B(n1063), .Z(n1061)); + OR2 U991 ( .A(n876), .B(n1064), .Z(n1062)); + OR2 U992 ( .A(pi06), .B(n825), .Z(n1064)); + OR2 U993 ( .A(n1065), .B(n725), .Z(n876)); + AN2 U994 ( .A(n718), .B(n1066), .Z(n1065)); + AN2 U995 ( .A(n1067), .B(n1068), .Z(n1060)); + OR2 U996 ( .A(n772), .B(n1069), .Z(n1068)); + OR2 U997 ( .A(n1070), .B(n1071), .Z(n1069)); + AN2 U998 ( .A(n1058), .B(n993), .Z(n1071)); + IV2 U999 ( .A(n919), .Z(n1058)); + AN2 U1000 ( .A(n992), .B(n919), .Z(n1070)); + OR2 U1001 ( .A(n1072), .B(n1073), .Z(n919)); + AN2 U1002 ( .A(n1074), .B(n1075), .Z(n1072)); + OR2 U1003 ( .A(n1054), .B(n1076), .Z(n1067)); + IV2 U1004 ( .A(n1053), .Z(n1076)); + AN2 U1005 ( .A(n1077), .B(n1078), .Z(n1053)); + OR2 U1006 ( .A(n897), .B(n851), .Z(n1078)); + IV2 U1007 ( .A(n1079), .Z(n1077)); + AN2 U1008 ( .A(n851), .B(n897), .Z(n1079)); + OR2 U1009 ( .A(n1080), .B(n1081), .Z(n897)); + AN2 U1010 ( .A(pi01), .B(n1082), .Z(n1080)); + AN2 U1011 ( .A(n1083), .B(n1084), .Z(n1043)); + OR2 U1012 ( .A(pi10), .B(n1085), .Z(n1084)); + OR2 U1013 ( .A(n1086), .B(n1087), .Z(n1085)); + AN2 U1014 ( .A(n1088), .B(n1089), .Z(n1087)); + AN2 U1015 ( .A(n852), .B(n898), .Z(n1088)); + IV2 U1016 ( .A(n1033), .Z(n852)); + AN2 U1017 ( .A(n1090), .B(n853), .Z(n1086)); + IV2 U1018 ( .A(n1089), .Z(n853)); + AN2 U1019 ( .A(n1091), .B(n1082), .Z(n1089)); + OR2 U1020 ( .A(n1031), .B(n1092), .Z(n1091)); + OR2 U1021 ( .A(n851), .B(n1033), .Z(n1090)); + OR2 U1022 ( .A(n1093), .B(n1094), .Z(n1033)); + AN2 U1023 ( .A(n868), .B(n724), .Z(n1094)); + AN2 U1024 ( .A(n851), .B(n869), .Z(n1093)); + IV2 U1025 ( .A(n898), .Z(n851)); + OR2 U1026 ( .A(n1095), .B(n1096), .Z(n898)); + AN2 U1027 ( .A(n901), .B(n920), .Z(n1096)); + OR2 U1028 ( .A(pi02), .B(n993), .Z(n920)); + AN2 U1029 ( .A(n902), .B(n1097), .Z(n1095)); + OR2 U1030 ( .A(n1098), .B(n1099), .Z(n1097)); + OR2 U1031 ( .A(n1100), .B(n1101), .Z(n1099)); + AN2 U1032 ( .A(n992), .B(n892), .Z(n1101)); + AN2 U1033 ( .A(n918), .B(n751), .Z(n1100)); + AN2 U1034 ( .A(n908), .B(n724), .Z(n1098)); + OR2 U1035 ( .A(n1102), .B(n992), .Z(n1083)); + IV2 U1036 ( .A(n993), .Z(n992)); + AN2 U1037 ( .A(n1103), .B(n1104), .Z(n1102)); + OR2 U1038 ( .A(n883), .B(n1105), .Z(n1104)); + IV2 U1039 ( .A(n1106), .Z(n883)); + IV2 U1040 ( .A(n801), .Z(n776)); + OR2 U1041 ( .A(n1107), .B(n1108), .Z(n801)); + OR2 U1042 ( .A(pi12), .B(n1109), .Z(n1108)); + OR2 U1043 ( .A(n1110), .B(n1111), .Z(n986)); + AN2 U1044 ( .A(n1112), .B(n717), .Z(n1111)); + AN2 U1045 ( .A(n924), .B(n1113), .Z(n1112)); + OR2 U1046 ( .A(n1114), .B(n927), .Z(n1113)); + AN2 U1047 ( .A(pi11), .B(pi02), .Z(n1114)); + AN2 U1048 ( .A(pi06), .B(n1115), .Z(n1110)); + OR2 U1049 ( .A(n1116), .B(n930), .Z(n1115)); + AN2 U1050 ( .A(n1117), .B(n804), .Z(n1116)); + OR2 U1051 ( .A(n1118), .B(n1119), .Z(n1117)); + AN2 U1052 ( .A(n854), .B(n993), .Z(n1119)); + AN2 U1053 ( .A(n934), .B(n1016), .Z(n1118)); + OR2 U1054 ( .A(n1120), .B(n1121), .Z(n984)); + OR2 U1055 ( .A(n937), .B(n1122), .Z(n1121)); + AN2 U1056 ( .A(n939), .B(n1123), .Z(n1122)); + OR2 U1057 ( .A(n1124), .B(n1125), .Z(n1123)); + OR2 U1058 ( .A(n918), .B(n1126), .Z(n1125)); + AN2 U1059 ( .A(n724), .B(n982), .Z(n1126)); + AN2 U1060 ( .A(n993), .B(pi02), .Z(n918)); + OR2 U1061 ( .A(n1127), .B(n1128), .Z(n993)); + OR2 U1062 ( .A(n1129), .B(n1130), .Z(n1128)); + AN2 U1063 ( .A(n949), .B(n717), .Z(n1130)); + AN2 U1064 ( .A(n950), .B(n877), .Z(n1129)); + IV2 U1065 ( .A(n727), .Z(n877)); + OR2 U1066 ( .A(n1131), .B(n1132), .Z(n1127)); + OR2 U1067 ( .A(n1133), .B(n1134), .Z(n1132)); + AN2 U1068 ( .A(n1135), .B(n1016), .Z(n1134)); + OR2 U1069 ( .A(n1136), .B(n957), .Z(n1135)); + AN2 U1070 ( .A(n1137), .B(n979), .Z(n1136)); + AN2 U1071 ( .A(n784), .B(pi06), .Z(n1137)); + AN2 U1072 ( .A(n724), .B(n1138), .Z(n1133)); + OR2 U1073 ( .A(n1139), .B(n1140), .Z(n1138)); + AN2 U1074 ( .A(n965), .B(n1141), .Z(n1139)); + AN2 U1075 ( .A(pi02), .B(pi06), .Z(n724)); + AN2 U1076 ( .A(pi13), .B(n1142), .Z(n1131)); + OR2 U1077 ( .A(n1143), .B(n1144), .Z(n1142)); + AN2 U1078 ( .A(n971), .B(pi01), .Z(n1144)); + AN2 U1079 ( .A(n1145), .B(n973), .Z(n1143)); + AN2 U1080 ( .A(n1146), .B(n1147), .Z(n1145)); + OR2 U1081 ( .A(n727), .B(n979), .Z(n1147)); + IV2 U1082 ( .A(n1141), .Z(n979)); + OR2 U1083 ( .A(n1148), .B(n1141), .Z(n1146)); + OR2 U1084 ( .A(n1149), .B(n1150), .Z(n1141)); + AN2 U1085 ( .A(n1151), .B(n1017), .Z(n1150)); + AN2 U1086 ( .A(pi05), .B(n1152), .Z(n1149)); + OR2 U1087 ( .A(n1151), .B(n1017), .Z(n1152)); + AN2 U1088 ( .A(pi02), .B(n717), .Z(n1148)); + AN2 U1089 ( .A(n944), .B(n727), .Z(n1124)); + AN2 U1090 ( .A(n1016), .B(n717), .Z(n727)); + IV2 U1091 ( .A(pi06), .Z(n717)); + IV2 U1092 ( .A(pi02), .Z(n1016)); + AN2 U1093 ( .A(n983), .B(pi02), .Z(n1120)); + OR2 U1094 ( .A(n1153), .B(n1154), .Z(po1)); + OR2 U1095 ( .A(n1155), .B(n1156), .Z(n1154)); + OR2 U1096 ( .A(n1157), .B(n1158), .Z(n1156)); + OR2 U1097 ( .A(n1159), .B(n1160), .Z(n1158)); + AN2 U1098 ( .A(n793), .B(n1105), .Z(n1160)); + AN2 U1099 ( .A(n794), .B(n1032), .Z(n1159)); + OR2 U1100 ( .A(n1161), .B(n1162), .Z(n1157)); + AN2 U1101 ( .A(n1163), .B(n1107), .Z(n1162)); + IV2 U1102 ( .A(n1164), .Z(n1161)); + OR2 U1103 ( .A(n1107), .B(n1163), .Z(n1164)); + AN2 U1104 ( .A(n1165), .B(n1166), .Z(n1163)); + OR2 U1105 ( .A(n1167), .B(n804), .Z(n1107)); + AN2 U1106 ( .A(n1168), .B(n1169), .Z(n1167)); + AN2 U1107 ( .A(n1170), .B(n1171), .Z(n1169)); + OR2 U1108 ( .A(n817), .B(n1172), .Z(n1171)); + OR2 U1109 ( .A(pi11), .B(n1173), .Z(n1172)); + AN2 U1110 ( .A(n1010), .B(n1174), .Z(n1173)); + OR2 U1111 ( .A(n1012), .B(n1013), .Z(n1174)); + OR2 U1112 ( .A(n1175), .B(n1082), .Z(n1010)); + AN2 U1113 ( .A(n1176), .B(n1177), .Z(n1170)); + OR2 U1114 ( .A(pi10), .B(n1178), .Z(n1177)); + OR2 U1115 ( .A(n1179), .B(n1180), .Z(n1178)); + AN2 U1116 ( .A(n1181), .B(n1031), .Z(n1180)); + IV2 U1117 ( .A(n1182), .Z(n1179)); + OR2 U1118 ( .A(n1181), .B(n1031), .Z(n1182)); + OR2 U1119 ( .A(n1183), .B(n1184), .Z(n1181)); + AN2 U1120 ( .A(n1185), .B(n1082), .Z(n1184)); + AN2 U1121 ( .A(n1012), .B(n1092), .Z(n1183)); + OR2 U1122 ( .A(n825), .B(n1186), .Z(n1176)); + OR2 U1123 ( .A(n1187), .B(n1188), .Z(n1186)); + AN2 U1124 ( .A(n1189), .B(n1190), .Z(n1187)); + IV2 U1125 ( .A(n725), .Z(n1190)); + OR2 U1126 ( .A(n1066), .B(n738), .Z(n1189)); + AN2 U1127 ( .A(n1191), .B(n1192), .Z(n1168)); + AN2 U1128 ( .A(n1193), .B(n1194), .Z(n1192)); + OR2 U1129 ( .A(n1195), .B(n1017), .Z(n1194)); + AN2 U1130 ( .A(n1196), .B(n1197), .Z(n1195)); + AN2 U1131 ( .A(n1198), .B(n1199), .Z(n1197)); + OR2 U1132 ( .A(pi05), .B(n1200), .Z(n1199)); + AN2 U1133 ( .A(n1201), .B(n1063), .Z(n1198)); + OR2 U1134 ( .A(n1202), .B(n772), .Z(n1201)); + AN2 U1135 ( .A(n1203), .B(n1204), .Z(n1202)); + OR2 U1136 ( .A(n1074), .B(n1032), .Z(n1204)); + OR2 U1137 ( .A(n1105), .B(n1205), .Z(n1203)); + AN2 U1138 ( .A(n1206), .B(n1207), .Z(n1196)); + OR2 U1139 ( .A(n1208), .B(n1054), .Z(n1207)); + AN2 U1140 ( .A(n1209), .B(n1210), .Z(n1208)); + OR2 U1141 ( .A(n1081), .B(n1082), .Z(n1210)); + OR2 U1142 ( .A(n1012), .B(n1211), .Z(n1209)); + IV2 U1143 ( .A(n1081), .Z(n1211)); + OR2 U1144 ( .A(n817), .B(n1212), .Z(n1206)); + OR2 U1145 ( .A(n713), .B(n738), .Z(n1212)); + OR2 U1146 ( .A(pi01), .B(n1213), .Z(n1193)); + AN2 U1147 ( .A(n1214), .B(n1215), .Z(n1213)); + AN2 U1148 ( .A(n1216), .B(n1217), .Z(n1215)); + OR2 U1149 ( .A(n1054), .B(n1218), .Z(n1216)); + OR2 U1150 ( .A(n1012), .B(n1081), .Z(n1218)); + AN2 U1151 ( .A(pi00), .B(n1175), .Z(n1081)); + OR2 U1152 ( .A(pi08), .B(n1020), .Z(n1054)); + AN2 U1153 ( .A(n1219), .B(n1220), .Z(n1214)); + OR2 U1154 ( .A(n772), .B(n1221), .Z(n1220)); + OR2 U1155 ( .A(n1222), .B(n1223), .Z(n1221)); + AN2 U1156 ( .A(n1074), .B(n1032), .Z(n1223)); + AN2 U1157 ( .A(n1105), .B(n1205), .Z(n1222)); + OR2 U1158 ( .A(n1224), .B(n738), .Z(n772)); + AN2 U1159 ( .A(n1225), .B(n829), .Z(n1224)); + OR2 U1160 ( .A(n751), .B(n1023), .Z(n1225)); + OR2 U1161 ( .A(n716), .B(n1200), .Z(n1219)); + OR2 U1162 ( .A(n718), .B(n825), .Z(n1200)); + IV2 U1163 ( .A(n761), .Z(n825)); + AN2 U1164 ( .A(n1226), .B(n1227), .Z(n1191)); + OR2 U1165 ( .A(n1228), .B(n1229), .Z(n1227)); + OR2 U1166 ( .A(n1020), .B(n1230), .Z(n1229)); + OR2 U1167 ( .A(n1231), .B(n1232), .Z(n1230)); + AN2 U1168 ( .A(n1233), .B(n1234), .Z(n1232)); + AN2 U1169 ( .A(n1235), .B(n1031), .Z(n1233)); + OR2 U1170 ( .A(n1030), .B(n1032), .Z(n1235)); + AN2 U1171 ( .A(n1092), .B(n1041), .Z(n1030)); + IV2 U1172 ( .A(n1236), .Z(n1231)); + OR2 U1173 ( .A(n1234), .B(n1031), .Z(n1236)); + OR2 U1174 ( .A(n1237), .B(n1238), .Z(n1031)); + AN2 U1175 ( .A(n868), .B(n725), .Z(n1238)); + AN2 U1176 ( .A(n1012), .B(n869), .Z(n1237)); + IV2 U1177 ( .A(n1082), .Z(n1012)); + OR2 U1178 ( .A(n1239), .B(n1240), .Z(n1082)); + AN2 U1179 ( .A(n901), .B(n1075), .Z(n1240)); + OR2 U1180 ( .A(pi01), .B(n1032), .Z(n1075)); + AN2 U1181 ( .A(n902), .B(n1241), .Z(n1239)); + OR2 U1182 ( .A(n1242), .B(n1243), .Z(n1241)); + OR2 U1183 ( .A(n1244), .B(n1245), .Z(n1243)); + AN2 U1184 ( .A(n1105), .B(n892), .Z(n1245)); + AN2 U1185 ( .A(n1073), .B(n751), .Z(n1244)); + AN2 U1186 ( .A(n908), .B(n725), .Z(n1242)); + OR2 U1187 ( .A(n1185), .B(n1246), .Z(n1234)); + OR2 U1188 ( .A(n1247), .B(n1105), .Z(n1246)); + IV2 U1189 ( .A(n1248), .Z(n1020)); + OR2 U1190 ( .A(n1249), .B(n744), .Z(n1228)); + AN2 U1191 ( .A(n716), .B(n1023), .Z(n1249)); + AN2 U1192 ( .A(n1250), .B(n1251), .Z(n1226)); + OR2 U1193 ( .A(n1105), .B(n1103), .Z(n1251)); + IV2 U1194 ( .A(n1252), .Z(n1103)); + OR2 U1195 ( .A(n1253), .B(n1254), .Z(n1252)); + AN2 U1196 ( .A(n1106), .B(n1041), .Z(n1254)); + OR2 U1197 ( .A(n1255), .B(n780), .Z(n1106)); + AN2 U1198 ( .A(n973), .B(n738), .Z(n1255)); + AN2 U1199 ( .A(n854), .B(n738), .Z(n1253)); + IV2 U1200 ( .A(n1032), .Z(n1105)); + OR2 U1201 ( .A(n1032), .B(n1256), .Z(n1250)); + OR2 U1202 ( .A(n1040), .B(n1041), .Z(n1256)); + IV2 U1203 ( .A(n1257), .Z(n1040)); + OR2 U1204 ( .A(n1258), .B(n1259), .Z(n1155)); + AN2 U1205 ( .A(n1260), .B(n716), .Z(n1259)); + AN2 U1206 ( .A(n924), .B(n1261), .Z(n1260)); + OR2 U1207 ( .A(n1262), .B(n927), .Z(n1261)); + AN2 U1208 ( .A(pi11), .B(pi01), .Z(n1262)); + AN2 U1209 ( .A(pi05), .B(n1263), .Z(n1258)); + OR2 U1210 ( .A(n1264), .B(n930), .Z(n1263)); + AN2 U1211 ( .A(n1265), .B(n804), .Z(n1264)); + OR2 U1212 ( .A(n1266), .B(n1267), .Z(n1265)); + AN2 U1213 ( .A(n854), .B(n1032), .Z(n1267)); + AN2 U1214 ( .A(n934), .B(n1017), .Z(n1266)); + AN2 U1215 ( .A(pi11), .B(n761), .Z(n934)); + OR2 U1216 ( .A(n1268), .B(n1269), .Z(n1153)); + OR2 U1217 ( .A(n937), .B(n1270), .Z(n1269)); + AN2 U1218 ( .A(n939), .B(n1271), .Z(n1270)); + OR2 U1219 ( .A(n1272), .B(n1273), .Z(n1271)); + OR2 U1220 ( .A(n1073), .B(n1274), .Z(n1273)); + AN2 U1221 ( .A(n725), .B(n982), .Z(n1274)); + AN2 U1222 ( .A(n1032), .B(pi01), .Z(n1073)); + OR2 U1223 ( .A(n1275), .B(n1276), .Z(n1032)); + OR2 U1224 ( .A(n1277), .B(n1278), .Z(n1276)); + AN2 U1225 ( .A(n949), .B(n716), .Z(n1278)); + AN2 U1226 ( .A(n950), .B(n1066), .Z(n1277)); + IV2 U1227 ( .A(n723), .Z(n1066)); + OR2 U1228 ( .A(n1279), .B(n1280), .Z(n1275)); + OR2 U1229 ( .A(n1281), .B(n1282), .Z(n1280)); + AN2 U1230 ( .A(n1283), .B(n1017), .Z(n1282)); + OR2 U1231 ( .A(n1284), .B(n957), .Z(n1283)); + AN2 U1232 ( .A(n1285), .B(n784), .Z(n1284)); + AN2 U1233 ( .A(pi05), .B(n1286), .Z(n1285)); + AN2 U1234 ( .A(n725), .B(n1287), .Z(n1281)); + OR2 U1235 ( .A(n1288), .B(n1140), .Z(n1287)); + AN2 U1236 ( .A(n965), .B(n1151), .Z(n1288)); + AN2 U1237 ( .A(n744), .B(n902), .Z(n965)); + AN2 U1238 ( .A(pi01), .B(pi05), .Z(n725)); + AN2 U1239 ( .A(pi13), .B(n1289), .Z(n1279)); + OR2 U1240 ( .A(n1290), .B(n1291), .Z(n1289)); + AN2 U1241 ( .A(n971), .B(pi00), .Z(n1291)); + AN2 U1242 ( .A(n892), .B(n1292), .Z(n971)); + AN2 U1243 ( .A(pi10), .B(pi11), .Z(n1292)); + AN2 U1244 ( .A(n1293), .B(n973), .Z(n1290)); + AN2 U1245 ( .A(n1294), .B(n1295), .Z(n1293)); + OR2 U1246 ( .A(n723), .B(n1286), .Z(n1295)); + IV2 U1247 ( .A(n1151), .Z(n1286)); + OR2 U1248 ( .A(n1151), .B(n1296), .Z(n1294)); + AN2 U1249 ( .A(pi01), .B(n716), .Z(n1296)); + AN2 U1250 ( .A(n944), .B(n723), .Z(n1272)); + AN2 U1251 ( .A(n1017), .B(n716), .Z(n723)); + IV2 U1252 ( .A(pi05), .Z(n716)); + IV2 U1253 ( .A(pi01), .Z(n1017)); + AN2 U1254 ( .A(n983), .B(pi01), .Z(n1268)); + AN2 U1255 ( .A(pi11), .B(n1297), .Z(n983)); + OR2 U1256 ( .A(n1298), .B(n1299), .Z(po0)); + OR2 U1257 ( .A(n1300), .B(n1301), .Z(n1299)); + OR2 U1258 ( .A(n1302), .B(n1303), .Z(n1301)); + OR2 U1259 ( .A(n1304), .B(n1305), .Z(n1303)); + AN2 U1260 ( .A(n793), .B(n1247), .Z(n1305)); + AN2 U1261 ( .A(n924), .B(n1306), .Z(n793)); + IV2 U1262 ( .A(n1307), .Z(n1306)); + OR2 U1263 ( .A(n854), .B(n1308), .Z(n1307)); + AN2 U1264 ( .A(pi08), .B(n1063), .Z(n1308)); + IV2 U1265 ( .A(n1309), .Z(n1063)); + AN2 U1266 ( .A(n794), .B(n1041), .Z(n1304)); + AN2 U1267 ( .A(n1310), .B(n924), .Z(n794)); + OR2 U1268 ( .A(pi11), .B(n854), .Z(n1310)); + AN2 U1269 ( .A(pi11), .B(n1311), .Z(n1302)); + OR2 U1270 ( .A(n1312), .B(n1313), .Z(n1311)); + OR2 U1271 ( .A(n1314), .B(n1315), .Z(n1313)); + AN2 U1272 ( .A(n924), .B(n1316), .Z(n1315)); + AN2 U1273 ( .A(n1317), .B(n761), .Z(n1314)); + AN2 U1274 ( .A(n1023), .B(n908), .Z(n761)); + AN2 U1275 ( .A(n1151), .B(n804), .Z(n1317)); + AN2 U1276 ( .A(n1297), .B(pi00), .Z(n1312)); + AN2 U1277 ( .A(n804), .B(n1318), .Z(n1297)); + OR2 U1278 ( .A(pi10), .B(n892), .Z(n1318)); + OR2 U1279 ( .A(n1319), .B(n1320), .Z(n1300)); + AN2 U1280 ( .A(n1321), .B(n709), .Z(n1320)); + AN2 U1281 ( .A(n927), .B(n924), .Z(n1321)); + AN2 U1282 ( .A(pi04), .B(n1322), .Z(n1319)); + OR2 U1283 ( .A(n1323), .B(n930), .Z(n1322)); + AN2 U1284 ( .A(n939), .B(n1324), .Z(n930)); + AN2 U1285 ( .A(n744), .B(pi11), .Z(n1324)); + AN2 U1286 ( .A(n957), .B(n1041), .Z(n1323)); + OR2 U1287 ( .A(n1325), .B(n1326), .Z(n1298)); + OR2 U1288 ( .A(n937), .B(n1327), .Z(n1326)); + AN2 U1289 ( .A(pi13), .B(n1328), .Z(n1327)); + OR2 U1290 ( .A(n1329), .B(n1330), .Z(n1328)); + AN2 U1291 ( .A(n1109), .B(n1166), .Z(n1330)); + IV2 U1292 ( .A(pi12), .Z(n1166)); + IV2 U1293 ( .A(n1165), .Z(n1109)); + AN2 U1294 ( .A(pi12), .B(n1165), .Z(n1329)); + OR2 U1295 ( .A(n1331), .B(n1332), .Z(n1165)); + AN2 U1296 ( .A(pi13), .B(n1333), .Z(n1332)); + OR2 U1297 ( .A(n1334), .B(n1335), .Z(n1333)); + OR2 U1298 ( .A(n1336), .B(n1337), .Z(n1335)); + AN2 U1299 ( .A(n1247), .B(n1257), .Z(n1337)); + OR2 U1300 ( .A(n1338), .B(n780), .Z(n1257)); + AN2 U1301 ( .A(n1023), .B(n751), .Z(n780)); + AN2 U1302 ( .A(n944), .B(pi09), .Z(n1338)); + AN2 U1303 ( .A(pi11), .B(n1339), .Z(n1336)); + OR2 U1304 ( .A(n1340), .B(n1341), .Z(n1339)); + OR2 U1305 ( .A(n1342), .B(n1343), .Z(n1341)); + AN2 U1306 ( .A(n1344), .B(pi00), .Z(n1343)); + AN2 U1307 ( .A(n1345), .B(n1247), .Z(n1344)); + AN2 U1308 ( .A(pi10), .B(n1346), .Z(n1345)); + AN2 U1309 ( .A(n1041), .B(n713), .Z(n1342)); + IV2 U1310 ( .A(n1217), .Z(n1340)); + OR2 U1311 ( .A(pi00), .B(n817), .Z(n1217)); + OR2 U1312 ( .A(n1023), .B(n1346), .Z(n817)); + OR2 U1313 ( .A(n1347), .B(n1348), .Z(n1334)); + OR2 U1314 ( .A(n1349), .B(n1350), .Z(n1348)); + AN2 U1315 ( .A(n1316), .B(n1023), .Z(n1350)); + AN2 U1316 ( .A(n854), .B(n1351), .Z(n1349)); + OR2 U1317 ( .A(n1352), .B(n1353), .Z(n1351)); + AN2 U1318 ( .A(pi00), .B(n738), .Z(n1353)); + AN2 U1319 ( .A(pi09), .B(n1041), .Z(n1352)); + AN2 U1320 ( .A(n1248), .B(n1354), .Z(n1347)); + OR2 U1321 ( .A(n1355), .B(n1356), .Z(n1354)); + OR2 U1322 ( .A(n1357), .B(n1358), .Z(n1356)); + AN2 U1323 ( .A(n1185), .B(n1041), .Z(n1358)); + IV2 U1324 ( .A(n1092), .Z(n1185)); + AN2 U1325 ( .A(n1247), .B(n1092), .Z(n1357)); + OR2 U1326 ( .A(n1359), .B(n1360), .Z(n1092)); + AN2 U1327 ( .A(n868), .B(n718), .Z(n1360)); + AN2 U1328 ( .A(n1023), .B(n901), .Z(n868)); + AN2 U1329 ( .A(n973), .B(pi11), .Z(n901)); + AN2 U1330 ( .A(n869), .B(n1013), .Z(n1359)); + AN2 U1331 ( .A(n1361), .B(n927), .Z(n869)); + AN2 U1332 ( .A(n963), .B(pi08), .Z(n927)); + IV2 U1333 ( .A(n1041), .Z(n1247)); + AN2 U1334 ( .A(n1175), .B(n713), .Z(n1355)); + IV2 U1335 ( .A(n1013), .Z(n1175)); + AN2 U1336 ( .A(n1361), .B(n738), .Z(n1248)); + AN2 U1337 ( .A(n1362), .B(n751), .Z(n1331)); + AN2 U1338 ( .A(n902), .B(n1013), .Z(n1362)); + OR2 U1339 ( .A(n1363), .B(n1364), .Z(n1013)); + IV2 U1340 ( .A(n902), .Z(n1364)); + AN2 U1341 ( .A(n1365), .B(n1366), .Z(n1363)); + OR2 U1342 ( .A(n1188), .B(n857), .Z(n1366)); + IV2 U1343 ( .A(n908), .Z(n857)); + IV2 U1344 ( .A(n718), .Z(n1188)); + AN2 U1345 ( .A(n1367), .B(n1368), .Z(n1365)); + OR2 U1346 ( .A(n1346), .B(n1205), .Z(n1368)); + IV2 U1347 ( .A(n1074), .Z(n1205)); + IV2 U1348 ( .A(n751), .Z(n1346)); + OR2 U1349 ( .A(n829), .B(n1041), .Z(n1367)); + IV2 U1350 ( .A(n892), .Z(n829)); + AN2 U1351 ( .A(n1309), .B(n1369), .Z(n937)); + AN2 U1352 ( .A(pi13), .B(n751), .Z(n1369)); + AN2 U1353 ( .A(n939), .B(n1370), .Z(n1325)); + OR2 U1354 ( .A(n1371), .B(n1372), .Z(n1370)); + OR2 U1355 ( .A(n1074), .B(n1373), .Z(n1372)); + AN2 U1356 ( .A(n1374), .B(n944), .Z(n1373)); + AN2 U1357 ( .A(n713), .B(n709), .Z(n1374)); + AN2 U1358 ( .A(n1041), .B(pi00), .Z(n1074)); + OR2 U1359 ( .A(n1375), .B(n1376), .Z(n1041)); + OR2 U1360 ( .A(n1377), .B(n1378), .Z(n1376)); + OR2 U1361 ( .A(n1379), .B(n1380), .Z(n1378)); + AN2 U1362 ( .A(n949), .B(n709), .Z(n1380)); + OR2 U1363 ( .A(n1381), .B(n1382), .Z(n949)); + OR2 U1364 ( .A(n1383), .B(n1384), .Z(n1382)); + AN2 U1365 ( .A(n751), .B(n963), .Z(n1384)); + AN2 U1366 ( .A(n1385), .B(n860), .Z(n1383)); + IV2 U1367 ( .A(n963), .Z(n860)); + AN2 U1368 ( .A(n1386), .B(n924), .Z(n1381)); + AN2 U1369 ( .A(n804), .B(n1361), .Z(n924)); + AN2 U1370 ( .A(pi08), .B(pi10), .Z(n1386)); + AN2 U1371 ( .A(n718), .B(n1140), .Z(n1379)); + OR2 U1372 ( .A(n1387), .B(n981), .Z(n1140)); + AN2 U1373 ( .A(pi11), .B(n1388), .Z(n981)); + AN2 U1374 ( .A(n1023), .B(n1389), .Z(n1388)); + OR2 U1375 ( .A(n751), .B(n892), .Z(n1389)); + AN2 U1376 ( .A(n744), .B(n1361), .Z(n892)); + AN2 U1377 ( .A(pi09), .B(pi08), .Z(n751)); + AN2 U1378 ( .A(n944), .B(n1361), .Z(n1387)); + AN2 U1379 ( .A(n744), .B(n963), .Z(n944)); + AN2 U1380 ( .A(n784), .B(n1151), .Z(n1377)); + AN2 U1381 ( .A(n713), .B(pi04), .Z(n1151)); + AN2 U1382 ( .A(n973), .B(n902), .Z(n784)); + AN2 U1383 ( .A(n963), .B(pi13), .Z(n902)); + AN2 U1384 ( .A(n738), .B(pi10), .Z(n963)); + OR2 U1385 ( .A(n1390), .B(n1391), .Z(n1375)); + OR2 U1386 ( .A(n1392), .B(n1393), .Z(n1391)); + AN2 U1387 ( .A(n950), .B(n1394), .Z(n1393)); + OR2 U1388 ( .A(pi00), .B(pi04), .Z(n1394)); + AN2 U1389 ( .A(n1395), .B(n908), .Z(n950)); + AN2 U1390 ( .A(n1361), .B(pi08), .Z(n908)); + IV2 U1391 ( .A(pi09), .Z(n1361)); + OR2 U1392 ( .A(pi13), .B(n1309), .Z(n1395)); + AN2 U1393 ( .A(n1023), .B(n738), .Z(n1309)); + IV2 U1394 ( .A(pi11), .Z(n738)); + AN2 U1395 ( .A(n1385), .B(n1316), .Z(n1392)); + AN2 U1396 ( .A(n709), .B(pi00), .Z(n1316)); + IV2 U1397 ( .A(pi04), .Z(n709)); + AN2 U1398 ( .A(n973), .B(pi13), .Z(n1385)); + AN2 U1399 ( .A(n744), .B(pi09), .Z(n973)); + AN2 U1400 ( .A(n957), .B(n713), .Z(n1390)); + IV2 U1401 ( .A(pi00), .Z(n713)); + AN2 U1402 ( .A(n804), .B(n854), .Z(n957)); + AN2 U1403 ( .A(n744), .B(n1023), .Z(n854)); + IV2 U1404 ( .A(pi10), .Z(n1023)); + AN2 U1405 ( .A(n718), .B(n982), .Z(n1371)); + OR2 U1406 ( .A(n1396), .B(pi11), .Z(n982)); + AN2 U1407 ( .A(pi10), .B(n744), .Z(n1396)); + IV2 U1408 ( .A(pi08), .Z(n744)); + AN2 U1409 ( .A(pi00), .B(pi04), .Z(n718)); + AN2 U1410 ( .A(n804), .B(pi09), .Z(n939)); + IV2 U1411 ( .A(pi13), .Z(n804)); + +endmodule + +module IV2(A, Z); + input A; + output Z; + + assign Z = ~A; +endmodule + +module AN2(A, B, Z); + input A, B; + output Z; + + assign Z = A & B; +endmodule + +module OR2(A, B, Z); + input A, B; + output Z; + + assign Z = A | B; +endmodule diff --git a/chips/yosys/examples/smtbmc/glift/alu4.ys b/chips/yosys/examples/smtbmc/glift/alu4.ys new file mode 100644 index 0000000000000000000000000000000000000000..593ba45a7d20026bb35368a9c5b624156b89871a --- /dev/null +++ b/chips/yosys/examples/smtbmc/glift/alu4.ys @@ -0,0 +1,41 @@ +read_verilog alu4.v +techmap +flatten +select alu4_lev2 +glift -create-instrumented-model +techmap +opt +rename alu4_lev2 uut +cd .. +delete [AIONX][NVXR]2 +read_verilog alu4.v +techmap +flatten +select alu4_lev2 +glift -create-precise-model +techmap +opt +rename alu4_lev2 spec +cd .. +delete [AIONX][NVXR]2 + +design -push-copy +miter -equiv spec uut miter +flatten +delete uut spec +techmap +opt +stat miter +qbfsat -O2 -write-solution alu4.soln -solver yices -timeout 3600 -nocleanup -assume-outputs -assume-negative-polarity miter +design -pop +stat + +copy uut solved +qbfsat -specialize-from-file alu4.soln solved +opt solved +miter -equiv spec solved satmiter +flatten +sat -prove trigger 0 satmiter +delete satmiter +stat +shell diff --git a/chips/yosys/examples/smtbmc/glift/mux2.ys b/chips/yosys/examples/smtbmc/glift/mux2.ys new file mode 100644 index 0000000000000000000000000000000000000000..a8e99912b26e20c15d4fbdcaf9dedf3ab1607f7f --- /dev/null +++ b/chips/yosys/examples/smtbmc/glift/mux2.ys @@ -0,0 +1,40 @@ +logger -expect log "SAT proof finished - no model found: SUCCESS!" 1 +logger -expect log "Number of cells:.*[\t ]12" 1 +logger -expect log "Number of cells:.*[\t ]20" 1 +logger -expect log "Problem is satisfiable with \\gate.__glift_weight = 11." 1 +logger -expect log "Problem is NOT satisfiable with \\gate.__glift_weight <= 10." 1 +logger -expect log "Wire \\gate.__glift_weight is minimized at 11." 1 +logger -expect log "Specializing .* from file with .* = 1." 2 +logger -expect log "Specializing .* from file with .* = 0." 4 +read_verilog <= 2.27.0. + self.submodules = true; + + nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable"; + flake-utils.url = "github:numtide/flake-utils"; + }; + + outputs = + { + self, + nixpkgs, + flake-utils, + }: + flake-utils.lib.eachDefaultSystem ( + system: + let + pkgs = import nixpkgs { + inherit system; + + overlays = [ + (final: prev: { + yosys = final.callPackage ./nix/pkgs/yosys.nix { + src = self; + rev = (self.shortRev or self.dirtyShortRev or "unknown"); + }; + }) + ]; + }; + + yosys-clang = pkgs.yosys.override { stdenv = pkgs.clangStdenv; }; + + win32Pkgs = pkgs.callPackage ./nix/cross/win32.nix { }; + win64Pkgs = pkgs.callPackage ./nix/cross/win64.nix { }; + + mkShell = t: import ./nix/shell.nix { inherit pkgs; yosys = t; }; + in + { + formatter = pkgs.nixfmt-tree; + + devShells = rec { + shell = mkShell yosys-clang; + shell-gcc = mkShell pkgs.yosys; + shell-win32 = mkShell win32Pkgs.yosys; + shell-win64 = mkShell win64Pkgs.yosys; + + default = shell; + }; + + packages = rec { + yosys = yosys-clang; + yosys-gcc = pkgs.yosys; + yosys-win32 = win32Pkgs.yosys; + yosys-win64 = win64Pkgs.yosys; + + default = yosys; + }; + } + ); +} diff --git a/chips/yosys/frontends/CMakeLists.txt b/chips/yosys/frontends/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..8abe1a11293ad825f4eec85a968333ec44076a24 --- /dev/null +++ b/chips/yosys/frontends/CMakeLists.txt @@ -0,0 +1,12 @@ +add_subdirectory(aiger) +add_subdirectory(ast) +add_subdirectory(blif) +add_subdirectory(json) +add_subdirectory(liberty) +add_subdirectory(rpc) +add_subdirectory(rtlil) +if (NOT YOSYS_WITHOUT_SLANG) + add_subdirectory(slang) +endif() +add_subdirectory(verific) +add_subdirectory(verilog) diff --git a/chips/yosys/frontends/aiger/CMakeLists.txt b/chips/yosys/frontends/aiger/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..b08a87592a14060e68b9118d62c1a4f409d88c02 --- /dev/null +++ b/chips/yosys/frontends/aiger/CMakeLists.txt @@ -0,0 +1,6 @@ +yosys_frontend(aiger + aigerparse.cc + aigerparse.h + REQUIRES + opt_clean +) diff --git a/chips/yosys/frontends/aiger/aigerparse.cc b/chips/yosys/frontends/aiger/aigerparse.cc new file mode 100644 index 0000000000000000000000000000000000000000..ef5c370828838b9db2a94359125328137f428681 --- /dev/null +++ b/chips/yosys/frontends/aiger/aigerparse.cc @@ -0,0 +1,1000 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * 2019 Eddie Hung + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +// [[CITE]] The AIGER And-Inverter Graph (AIG) Format Version 20071012 +// Armin Biere. The AIGER And-Inverter Graph (AIG) Format Version 20071012. Technical Report 07/1, October 2011, FMV Reports Series, Institute for Formal Models and Verification, Johannes Kepler University, Altenbergerstr. 69, 4040 Linz, Austria. +// http://fmv.jku.at/papers/Biere-FMV-TR-07-1.pdf + +// https://stackoverflow.com/a/46137633 +#ifdef _MSC_VER +#include +#define __builtin_bswap32 _byteswap_ulong +#elif defined(__APPLE__) +#include +#define __builtin_bswap32 OSSwapInt32 +#endif +#ifndef __STDC_FORMAT_MACROS +#define __STDC_FORMAT_MACROS +#endif +#include + +#include "kernel/yosys.h" +#include "kernel/sigtools.h" +#include "kernel/newcelltypes.h" +#include "aigerparse.h" + +YOSYS_NAMESPACE_BEGIN + +inline int32_t from_big_endian(int32_t i32) { +#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ + return __builtin_bswap32(i32); +#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ + return i32; +#else +#error "Unknown endianness" +#endif +} + +#define log_debug2(...) ; +//#define log_debug2(...) log_debug(__VA_ARGS__) + +struct ConstEvalAig +{ + RTLIL::Module *module; + dict values_map; + dict sig2driver; + dict> sig2deps; + + ConstEvalAig(RTLIL::Module *module) : module(module) + { + for (auto &it : module->cells_) { + if (!yosys_celltypes.cell_known(it.second->type)) + continue; + for (auto &it2 : it.second->connections()) + if (yosys_celltypes.cell_output(it.second->type, it2.first)) { + auto r = sig2driver.insert(std::make_pair(it2.second, it.second)); + log_assert(r.second); + } + } + } + + void clear() + { + values_map.clear(); + sig2deps.clear(); + } + + void set(RTLIL::SigBit sig, RTLIL::State value) + { + auto it = values_map.find(sig); +#ifndef NDEBUG + if (it != values_map.end()) { + RTLIL::State current_val = it->second; + log_assert(current_val == value); + } +#endif + if (it != values_map.end()) + it->second = value; + else + values_map[sig] = value; + } + + void set_incremental(RTLIL::SigSpec sig, RTLIL::Const value) + { + log_assert(GetSize(sig) == GetSize(value)); + + for (int i = 0; i < GetSize(sig); i++) { + auto it = values_map.find(sig[i]); + if (it != values_map.end()) { + RTLIL::State current_val = it->second; + if (current_val != value[i]) + for (auto dep : sig2deps[sig[i]]) + values_map.erase(dep); + it->second = value[i]; + } + else + values_map[sig[i]] = value[i]; + } + } + + void compute_deps(RTLIL::SigBit output, const pool &inputs) + { + sig2deps[output].insert(output); + + RTLIL::Cell *cell = sig2driver.at(output); + RTLIL::SigBit sig_a = cell->getPort(ID::A); + + bool contains_a = std::all_of(sig2deps[output].begin(), sig2deps[output].end(), [&](SigBit bit) { + return sig2deps[sig_a].count(bit) > 0; + }); + + if (!contains_a) { + // Reserve so that any invalidation that may occur does so here, and not mid insertion (below) + sig2deps[sig_a].reserve(sig2deps[sig_a].size() + sig2deps[output].size()); + + sig2deps[sig_a].insert(sig2deps[output].begin(), sig2deps[output].end()); + if (!inputs.count(sig_a)) + compute_deps(sig_a, inputs); + } + + if (cell->type == ID($_AND_)) { + RTLIL::SigSpec sig_b = cell->getPort(ID::B); + + bool contains_b = std::all_of(sig2deps[output].begin(), sig2deps[output].end(), [&](SigBit bit) { + return sig2deps[sig_b].count(bit) > 0; + }); + + if (!contains_b) { + // Reserve so that any invalidation that may occur does so here, and not mid insertion (below) + sig2deps[sig_b].reserve(sig2deps[sig_b].size() + sig2deps[output].size()); + + sig2deps[sig_b].insert(sig2deps[output].begin(), sig2deps[output].end()); + if (!inputs.count(sig_b)) + compute_deps(sig_b, inputs); + } + } + else if (cell->type != ID($_NOT_)) { + log_abort(); + } + } + + bool eval(RTLIL::Cell *cell) + { + RTLIL::SigBit sig_y = cell->getPort(ID::Y); + if (values_map.count(sig_y)) + return true; + + RTLIL::SigBit sig_a = cell->getPort(ID::A); + if (!eval(sig_a)) + return false; + + RTLIL::State eval_ret = RTLIL::Sx; + if (cell->type == ID($_NOT_)) { + if (sig_a == State::S0) eval_ret = State::S1; + else if (sig_a == State::S1) eval_ret = State::S0; + } + else if (cell->type == ID($_AND_)) { + if (sig_a == State::S0) { + eval_ret = State::S0; + goto eval_end; + } + + { + RTLIL::SigBit sig_b = cell->getPort(ID::B); + if (!eval(sig_b)) + return false; + if (sig_b == State::S0) { + eval_ret = State::S0; + goto eval_end; + } + + if (sig_a != State::S1 || sig_b != State::S1) + goto eval_end; + + eval_ret = State::S1; + } + } + else log_abort(); + +eval_end: + set(sig_y, eval_ret); + return true; + } + + bool eval(RTLIL::SigBit &sig) + { + auto it = values_map.find(sig); + if (it != values_map.end()) { + sig = it->second; + return true; + } + + RTLIL::Cell *cell = sig2driver.at(sig); + if (!eval(cell)) + return false; + + it = values_map.find(sig); + if (it != values_map.end()) { + sig = it->second; + return true; + } + + return false; + } +}; + +AigerReader::AigerReader(RTLIL::Design *design, std::istream &f, RTLIL::IdString module_name, RTLIL::IdString clk_name, std::string map_filename) + : design(design), f(f), clk_name(clk_name), map_filename(map_filename), aiger_autoidx(design->twines().next_autoidx()) +{ + module = new RTLIL::Module(design); + module->name = module_name; + if (design->module(module->name)) + log_error("Duplicate definition of module %s!\n", module); +} + +void AigerReader::parse_aiger() +{ + std::string header; + f >> header; + if (header != "aag" && header != "aig") + log_error("Unsupported AIGER file!\n"); + + // Parse rest of header + if (!(f >> M >> I >> L >> O >> A)) + log_error("Invalid AIGER header\n"); + + // Optional values + B = C = J = F = 0; + if (f.peek() != ' ') goto end_of_header; + if (!(f >> B)) log_error("Invalid AIGER header\n"); + if (f.peek() != ' ') goto end_of_header; + if (!(f >> C)) log_error("Invalid AIGER header\n"); + if (f.peek() != ' ') goto end_of_header; + if (!(f >> J)) log_error("Invalid AIGER header\n"); + if (f.peek() != ' ') goto end_of_header; + if (!(f >> F)) log_error("Invalid AIGER header\n"); +end_of_header: + + std::string line; + std::getline(f, line); // Ignore up to start of next line, as standard + // says anything that follows could be used for + // optional sections + + log_debug("M=%u I=%u L=%u O=%u A=%u B=%u C=%u J=%u F=%u\n", M, I, L, O, A, B, C, J, F); + + design->scratchpad_set_int("read_aiger.inputs", I); + design->scratchpad_set_int("read_aiger.outputs", O); + + line_count = 1; + piNum = 0; + flopNum = 0; + + if (header == "aag") + parse_aiger_ascii(); + else if (header == "aig") + parse_aiger_binary(); + else + log_abort(); + + RTLIL::Wire* n0 = aiger_wires.count(0) ? aiger_wires.at(0) : nullptr; + if (n0) + module->connect(n0, State::S0); + + // Parse footer (symbol table, comments, etc.) + unsigned l1; + std::string s; + for (int c = f.peek(); c != EOF; c = f.peek(), ++line_count) { + if (c == 'i' || c == 'l' || c == 'o' || c == 'b') { + f.ignore(1); + if (!(f >> l1 >> s)) + log_error("Line %u cannot be interpreted as a symbol entry!\n", line_count); + + if ((c == 'i' && l1 > inputs.size()) || (c == 'l' && l1 > latches.size()) || (c == 'o' && l1 > outputs.size())) + log_error("Line %u has invalid symbol position!\n", line_count); + + std::string escaped_s = stringf("\\%s", s); + RTLIL::Wire* wire; + if (c == 'i') { + log_assert(l1 < inputs.size()); + wire = inputs[l1]; + } else if (c == 'l') { + log_assert(l1 < latches.size()); + wire = latches[l1]; + } else if (c == 'o') { + wire = module->wire(escaped_s); + log_assert(l1 < outputs.size()); + if (wire) { + // Could have been renamed by a latch + module->swap_names(wire, outputs[l1]); + module->connect(outputs[l1], wire); + goto next; + } + wire = outputs[l1]; + } else if (c == 'b') { + wire = bad_properties[l1]; + } else log_abort(); + + module->rename(wire, design->twines().add(escaped_s)); + } + else if (c == 'j' || c == 'f') { + // TODO + } + else if (c == 'c') { + f.ignore(1); + if (f.peek() == '\r') + f.ignore(1); + if (f.peek() == '\n') + break; + // Else constraint (TODO) + } + else + log_error("Line %u: cannot interpret first character '%c'!\n", line_count, c); +next: + std::getline(f, line); // Ignore up to start of next line + } + + post_process(); +} + +static uint32_t parse_xaiger_literal(std::istream &f) +{ + uint32_t l; + f.read(reinterpret_cast(&l), sizeof(l)); + if (f.gcount() != sizeof(l)) +#if defined(_WIN32) && defined(__MINGW32__) + log_error("Offset %I64d: unable to read literal!\n", static_cast(f.tellg())); +#else + log_error("Offset %" PRId64 ": unable to read literal!\n", static_cast(f.tellg())); +#endif + return from_big_endian(l); +} + +RTLIL::Wire* AigerReader::createWireIfNotExists(RTLIL::Module *module, unsigned literal) +{ + if (auto it = aiger_wires.find(literal); it != aiger_wires.end()) + return it->second; + const unsigned variable = literal >> 1; + RTLIL::Wire *wire = literal & 1 ? getOrCreateInvertedWire(module, variable) : getOrCreateNormalWire(module, variable); + aiger_wires[literal] = wire; + return wire; +} + +RTLIL::Wire* AigerReader::getOrCreateNormalWire(RTLIL::Module *module, unsigned variable) +{ + std::string name = stringf("$aiger%d$%d", aiger_autoidx, variable); + if (RTLIL::Wire *wire = module->wire(name)) + return wire; + log_debug2("Creating %s\n", name); + return module->addWire(std::move(name)); +} + +RTLIL::Wire* AigerReader::getOrCreateInvertedWire(RTLIL::Module *module, unsigned variable) +{ + std::string name = stringf("$aiger%d$%db", aiger_autoidx, variable); + if (RTLIL::Wire *wire = module->wire(name)) + return wire; + log_debug2("Creating %s\n", name); + RTLIL::Wire *inverted = module->addWire(std::move(name)); + RTLIL::Wire *normal = createWireIfNotExists(module, variable << 1); + log_debug2("Creating %s = ~%s\n", inverted->name, normal->name); + module->addNotGate(stringf("$not$aiger%d$%d", aiger_autoidx, variable), normal, inverted); + return inverted; +} + +void AigerReader::parse_xaiger() +{ + std::string header; + f >> header; + if (header != "aag" && header != "aig") + log_error("Unsupported AIGER file!\n"); + + // Parse rest of header + if (!(f >> M >> I >> L >> O >> A)) + log_error("Invalid AIGER header\n"); + + // Optional values + B = C = J = F = 0; + + std::string line; + std::getline(f, line); // Ignore up to start of next line, as standard + // says anything that follows could be used for + // optional sections + + log_debug("M=%u I=%u L=%u O=%u A=%u\n", M, I, L, O, A); + + design->scratchpad_set_int("read_aiger.inputs", I); + design->scratchpad_set_int("read_aiger.outputs", O); + + line_count = 1; + piNum = 0; + flopNum = 0; + + if (header == "aag") + parse_aiger_ascii(); + else if (header == "aig") + parse_aiger_binary(); + else + log_abort(); + + RTLIL::Wire* n0 = aiger_wires.count(0) ? aiger_wires.at(0) : nullptr; + if (n0) + module->connect(n0, State::S0); + + // Skip the symbol table (present after e.g. '&get -n'); XAIGER wires are positional + std::string s; + int c = f.get(); + while (c == 'i' || c == 'l' || c == 'o' || c == 'b') { + std::getline(f, s); + c = f.get(); + } + if (c != 'c') // 'c'omment section (used for extensions) + log_error("Line %u: cannot interpret first character '%c'!\n", line_count, c); + if (f.peek() == '\n') + f.get(); + + // Parse footer (comments, extensions) + for (int c = f.get(); c != EOF; c = f.get()) { + // XAIGER extensions + if (c == 'm') { // LUT 'm'apping + uint32_t dataSize = parse_xaiger_literal(f); + uint32_t lutNum = parse_xaiger_literal(f); + uint32_t lutSize = parse_xaiger_literal(f); + log_debug("m: dataSize=%u lutNum=%u lutSize=%u\n", dataSize, lutNum, lutSize); + ConstEvalAig ce(module); + for (unsigned i = 0; i < lutNum; ++i) { + uint32_t rootNodeID = parse_xaiger_literal(f); + uint32_t cutLeavesM = parse_xaiger_literal(f); + log_debug2("rootNodeID=%d cutLeavesM=%d\n", rootNodeID, cutLeavesM); + RTLIL::Wire *output_sig = aiger_wires.at(rootNodeID << 1); + log_assert(output_sig); + uint32_t nodeID; + RTLIL::SigSpec input_sig; + for (unsigned j = 0; j < cutLeavesM; ++j) { + nodeID = parse_xaiger_literal(f); + log_debug2("\t%u\n", nodeID); + if (nodeID == 0) { + log_debug("\tLUT '$lut$aiger%d$%d' input %d is constant!\n", aiger_autoidx, rootNodeID, cutLeavesM); + continue; + } + RTLIL::Wire *wire = aiger_wires.at(nodeID << 1); + log_assert(wire); + input_sig.append(wire); + } + // Reverse input order as fastest input is returned first + input_sig.reverse(); + // TODO: Compute LUT mask from AIG in less than O(2 ** input_sig.size()) + ce.clear(); + ce.compute_deps(output_sig, input_sig.to_sigbit_pool()); + RTLIL::Const lut_mask(RTLIL::State::Sx, 1 << GetSize(input_sig)); + for (int j = 0; j < GetSize(lut_mask); ++j) { + int gray = j ^ (j >> 1); + ce.set_incremental(input_sig, RTLIL::Const{gray, GetSize(input_sig)}); + RTLIL::SigBit o(output_sig); + bool success = ce.eval(o); + log_assert(success); + log_assert(o.wire == nullptr); + lut_mask.set(gray, o.data); + } + RTLIL::Cell *output_cell = module->cell(stringf("$and$aiger%d$%d", aiger_autoidx, rootNodeID)); + log_assert(output_cell); + module->remove(output_cell); + module->addLut(stringf("$lut$aiger%d$%d", aiger_autoidx, rootNodeID), input_sig, output_sig, std::move(lut_mask)); + } + } + else if (c == 'M') { // cell 'M'apping + struct MappingCell { + RTLIL::IdString type; + RTLIL::IdString out; + std::vector ins; + }; + std::vector mapping_cells; + + /* uint32_t dataSize = */ (void)parse_xaiger_literal(f); + uint32_t cellNum = parse_xaiger_literal(f); + uint32_t instanceNum = parse_xaiger_literal(f); + log_debug2("M: dataSize=%u cellNum=%u instanceNum=%u\n", dataSize, cellNum, instanceNum); + + for (unsigned i = 0; i < cellNum; ++i) { + MappingCell mapping_cell{}; + auto cellName = std::string{}; // name of cell + auto outPinName = std::string{}; // name of cell output pin + std::getline(f, cellName, '\0'); + std::getline(f, outPinName, '\0'); + uint32_t inPinNum = parse_xaiger_literal(f); + log_debug2("M: cellID=%u cellName=%s outPinName=%s inPinNum=%u\n", i, cellName, outPinName, inPinNum); + mapping_cell.type = design->twines().add(RTLIL::escape_id(cellName)); + mapping_cell.out = design->twines().add(RTLIL::escape_id(outPinName)); + + for (unsigned j = 0; j < inPinNum; ++j) { + auto inPinName = std::string{}; + std::getline(f, inPinName, '\0'); + log_debug2("M: inPinName=%s\n", inPinName); + mapping_cell.ins.push_back(design->twines().add(RTLIL::escape_id(inPinName))); + } + + if (!design->module(mapping_cell.type)) { + auto module = design->addModule(mapping_cell.type); + module->set_bool_attribute(ID::blackbox); + module->addWire(mapping_cell.out)->port_output = true; + for (unsigned j = 0; j < inPinNum; ++j) { + module->addWire(mapping_cell.ins.at(j))->port_input = true; + } + module->fixup_ports(); + } + + mapping_cells.push_back(std::move(mapping_cell)); + } + + for (unsigned i = 0; i < instanceNum; ++i) { + uint32_t cellID = parse_xaiger_literal(f); + uint32_t rootNodeID = parse_xaiger_literal(f); + + log_assert(cellID < cellNum); + MappingCell &mapping_cell = mapping_cells.at(cellID); + + log_debug2("M: instanceID=%u cellID=%u outPort=%s rootNodeID=%u\n", i, cellID, design->twines().unescaped_str(mapping_cell.out), rootNodeID); + + RTLIL::Wire *output_sig = createWireIfNotExists(module, rootNodeID); + log_assert(output_sig); + + { + std::string output_cell_name; + if ((rootNodeID & 1) == 0) { // uninverted + output_cell_name = stringf("$and$aiger%d$%d", aiger_autoidx, rootNodeID >> 1); + } else { // inverted + output_cell_name = stringf("$not$aiger%d$%d", aiger_autoidx, rootNodeID >> 1); + } + RTLIL::Cell *output_cell = module->cell(output_cell_name); + log_assert(output_cell); + module->remove(output_cell); + } + + RTLIL::Cell *cell = module->addCell(stringf("$sc$aiger%d$%d", aiger_autoidx, rootNodeID), mapping_cell.type); + cell->set_bool_attribute(ID::abc9_cell); + cell->setPort(mapping_cell.out, output_sig); + + for (unsigned j = 0; j < mapping_cell.ins.size(); ++j) { + auto nodeID = parse_xaiger_literal(f); + log_debug("M: inPort=%s nodeID=%u\n", design->twines().unescaped_str(mapping_cell.ins.at(j)), nodeID); + RTLIL::Wire *input_sig = createWireIfNotExists(module, nodeID); + cell->setPort(mapping_cell.ins.at(j), input_sig); + } + } + } + else if (c == 'r') { // 'r'egister classes + uint32_t dataSize = parse_xaiger_literal(f); + flopNum = parse_xaiger_literal(f); + log_debug("flopNum = %u\n", flopNum); + log_assert(dataSize == (flopNum+1) * sizeof(uint32_t)); + mergeability.reserve(flopNum); + for (unsigned i = 0; i < flopNum; i++) + mergeability.emplace_back(parse_xaiger_literal(f)); + } + else if (c == 's') { // register initial 's'tates + uint32_t dataSize = parse_xaiger_literal(f); + flopNum = parse_xaiger_literal(f); + log_assert(dataSize == (flopNum+1) * sizeof(uint32_t)); + initial_state.reserve(flopNum); + for (unsigned i = 0; i < flopNum; i++) + initial_state.emplace_back(parse_xaiger_literal(f)); + } + else if (c == 'n') { // 'n'ame + parse_xaiger_literal(f); + f >> s; + log_debug("n: '%s'\n", s); + } + else if (c == 'h') { // 'h'ierarchy information + f.ignore(sizeof(uint32_t)); // length + uint32_t version = parse_xaiger_literal(f); + log_assert(version == 1); + uint32_t ciNum = parse_xaiger_literal(f); + log_debug("ciNum = %u\n", ciNum); + uint32_t coNum = parse_xaiger_literal(f); + log_debug("coNum = %u\n", coNum); + piNum = parse_xaiger_literal(f); + log_debug("piNum = %u\n", piNum); + uint32_t poNum = parse_xaiger_literal(f); + log_debug("poNum = %u\n", poNum); + uint32_t boxNum = parse_xaiger_literal(f); + log_debug("boxNum = %u\n", boxNum); + for (unsigned i = 0; i < boxNum; i++) { + uint32_t boxInputs = parse_xaiger_literal(f); + uint32_t boxOutputs = parse_xaiger_literal(f); + uint32_t boxUniqueId = parse_xaiger_literal(f); + log_assert(boxUniqueId > 0); + uint32_t oldBoxNum = parse_xaiger_literal(f); + IdString _type = module->twines().add(stringf("$__boxid%u", boxUniqueId)); + RTLIL::Cell* cell = module->addCell(stringf("$box%u", oldBoxNum), _type); + cell->setPort(ID::i, SigSpec(State::S0, boxInputs)); + cell->setPort(ID::o, SigSpec(State::S0, boxOutputs)); + cell->attributes[ID::abc9_box_seq] = oldBoxNum; + boxes.emplace_back(cell); + } + } + else if (c == 'a' /* 'a'dditional AIG */ || c == 'i' /* 'i'nput arrival times */ || c == 'o' /* 'o'utput required times */) { + uint32_t dataSize = parse_xaiger_literal(f); + f.ignore(dataSize); + log_debug("ignoring '%c'\n", c); + } + else { + break; + } + } + + post_process(); +} + +void AigerReader::parse_aiger_ascii() +{ + std::string line; + std::stringstream ss; + + unsigned l1, l2, l3; + + // Parse inputs + for (unsigned i = 1; i <= I; ++i, ++line_count) { + if (!(f >> l1)) + log_error("Line %u cannot be interpreted as an input!\n", line_count); + log_debug2("%d is an input\n", l1); + log_assert(!(l1 & 1)); // Inputs can't be inverted + RTLIL::Wire *wire = module->addWire(stringf("$aiger$i%d", l1 >> 1)); + wire->port_input = true; + module->connect(createWireIfNotExists(module, l1), wire); + inputs.push_back(wire); + } + + // Parse latches + RTLIL::Wire *clk_wire = nullptr; + if (L > 0 && !clk_name.empty()) { + clk_wire = module->wire(clk_name); + log_assert(!clk_wire); + log_debug2("Creating %s\n", clk_name); + clk_wire = module->addWire(clk_name); + clk_wire->port_input = true; + clk_wire->port_output = false; + } + + for (unsigned i = 0; i < L; ++i, ++line_count) { + if (!(f >> l1 >> l2)) + log_error("Line %u cannot be interpreted as a latch!\n", line_count); + log_debug2("%d %d is a latch\n", l1, l2); + log_assert(!(l1 & 1)); + RTLIL::Wire *q_wire = module->addWire(stringf("$aiger$l%d", l1 >> 1)); + module->connect(createWireIfNotExists(module, l1), q_wire); + RTLIL::Wire *d_wire = createWireIfNotExists(module, l2); + + if (clk_wire) + module->addDffGate(NEW_ID, clk_wire, d_wire, q_wire); + else + module->addFfGate(NEW_ID, d_wire, q_wire); + + // Reset logic is optional in AIGER 1.9 + if (f.peek() == ' ') { + if (!(f >> l3)) + log_error("Line %u cannot be interpreted as a latch!\n", line_count); + + if (l3 == 0) + q_wire->attributes[ID::init] = State::S0; + else if (l3 == 1) + q_wire->attributes[ID::init] = State::S1; + else if (l3 == l1) { + //q_wire->attributes[ID::init] = RTLIL::Sx; + } + else + log_error("Line %u has invalid reset literal for latch!\n", line_count); + } + else { + // AIGER latches are assumed to be initialized to zero + q_wire->attributes[ID::init] = State::S0; + } + latches.push_back(q_wire); + } + + // Parse outputs + for (unsigned i = 0; i < O; ++i, ++line_count) { + if (!(f >> l1)) + log_error("Line %u cannot be interpreted as an output!\n", line_count); + std::getline(f, line); // Ignore up to start of next line + + log_debug2("%d is an output\n", l1); + RTLIL::Wire *wire = module->addWire(stringf("$aiger$o%d", i)); + wire->port_output = true; + module->connect(wire, createWireIfNotExists(module, l1)); + outputs.push_back(wire); + } + + // Parse bad properties + for (unsigned i = 0; i < B; ++i, ++line_count) { + if (!(f >> l1)) + log_error("Line %u cannot be interpreted as a bad state property!\n", line_count); + std::getline(f, line); // Ignore up to start of next line + + log_debug2("%d is a bad state property\n", l1); + RTLIL::Wire *wire = createWireIfNotExists(module, l1); + wire->port_output = true; + bad_properties.push_back(wire); + } + + // TODO: Parse invariant constraints + for (unsigned i = 0; i < C; ++i, ++line_count) + std::getline(f, line); // Ignore up to start of next line + + // TODO: Parse justice properties + for (unsigned i = 0; i < J; ++i, ++line_count) + std::getline(f, line); // Ignore up to start of next line + + // TODO: Parse fairness constraints + for (unsigned i = 0; i < F; ++i, ++line_count) + std::getline(f, line); // Ignore up to start of next line + + // Parse AND + for (unsigned i = 0; i < A; ++i) { + if (!(f >> l1 >> l2 >> l3)) + log_error("Line %u cannot be interpreted as an AND!\n", line_count); + std::getline(f, line); // Ignore up to start of next line + + log_debug2("%d %d %d is an AND\n", l1, l2, l3); + log_assert(!(l1 & 1)); + RTLIL::Wire *o_wire = createWireIfNotExists(module, l1); + RTLIL::Wire *i1_wire = createWireIfNotExists(module, l2); + RTLIL::Wire *i2_wire = createWireIfNotExists(module, l3); + module->addAndGate("$and" + o_wire->name.str(), i1_wire, i2_wire, o_wire); + } +} + +static unsigned parse_next_delta_literal(std::istream &f, unsigned ref) +{ + unsigned x = 0, i = 0; + unsigned char ch; + while ((ch = f.get()) & 0x80) + x |= (ch & 0x7f) << (7 * i++); + return ref - (x | (ch << (7 * i))); +} + +void AigerReader::parse_aiger_binary() +{ + unsigned l1, l2, l3; + std::string line; + + if (M != I + L + A) + log_error("Binary AIGER input is malformed: maximum variable index M is %u, but number of inputs, latches and AND gates adds up to %u.\n", M, I + L + A); + + // Parse inputs + for (unsigned i = 1; i <= I; ++i) { + log_debug2("%d is an input\n", i); + RTLIL::Wire *wire = module->addWire(stringf("$aiger$i%d", i)); + wire->port_input = true; + module->connect(createWireIfNotExists(module, i << 1), wire); + inputs.push_back(wire); + } + + // Parse latches + RTLIL::Wire *clk_wire = nullptr; + if (L > 0 && !clk_name.empty()) { + clk_wire = module->wire(clk_name); + log_assert(!clk_wire); + log_debug2("Creating %s\n", clk_name); + clk_wire = module->addWire(clk_name); + clk_wire->port_input = true; + clk_wire->port_output = false; + } + + l1 = (I+1) * 2; + for (unsigned i = 0; i < L; ++i, ++line_count, l1 += 2) { + if (!(f >> l2)) + log_error("Line %u cannot be interpreted as a latch!\n", line_count); + log_debug("%d %d is a latch\n", l1, l2); + RTLIL::Wire *q_wire = module->addWire(stringf("$aiger$l%d", l1 >> 1)); + module->connect(createWireIfNotExists(module, l1), q_wire); + RTLIL::Wire *d_wire = createWireIfNotExists(module, l2); + + if (clk_wire) + module->addDff(NEW_ID, clk_wire, d_wire, q_wire); + else + module->addFf(NEW_ID, d_wire, q_wire); + + // Reset logic is optional in AIGER 1.9 + if (f.peek() == ' ') { + if (!(f >> l3)) + log_error("Line %u cannot be interpreted as a latch!\n", line_count); + + if (l3 == 0) + q_wire->attributes[ID::init] = State::S0; + else if (l3 == 1) + q_wire->attributes[ID::init] = State::S1; + else if (l3 == l1) { + //q_wire->attributes[ID::init] = RTLIL::Sx; + } + else + log_error("Line %u has invalid reset literal for latch!\n", line_count); + } + else { + // AIGER latches are assumed to be initialized to zero + q_wire->attributes[ID::init] = State::S0; + } + latches.push_back(q_wire); + } + + // Parse outputs + for (unsigned i = 0; i < O; ++i, ++line_count) { + if (!(f >> l1)) + log_error("Line %u cannot be interpreted as an output!\n", line_count); + std::getline(f, line); // Ignore up to start of next line + + log_debug2("%d is an output\n", l1); + RTLIL::Wire *wire = module->addWire(stringf("$aiger$o%d", i)); + wire->port_output = true; + module->connect(wire, createWireIfNotExists(module, l1)); + outputs.push_back(wire); + } + + // Parse bad properties + for (unsigned i = 0; i < B; ++i, ++line_count) { + if (!(f >> l1)) + log_error("Line %u cannot be interpreted as a bad state property!\n", line_count); + std::getline(f, line); // Ignore up to start of next line + + log_debug2("%d is a bad state property\n", l1); + RTLIL::Wire *wire = createWireIfNotExists(module, l1); + wire->port_output = true; + bad_properties.push_back(wire); + } + + // TODO: Parse invariant constraints + for (unsigned i = 0; i < C; ++i, ++line_count) + std::getline(f, line); // Ignore up to start of next line + + // TODO: Parse justice properties + for (unsigned i = 0; i < J; ++i, ++line_count) + std::getline(f, line); // Ignore up to start of next line + + // TODO: Parse fairness constraints + for (unsigned i = 0; i < F; ++i, ++line_count) + std::getline(f, line); // Ignore up to start of next line + + // Parse AND + l1 = (I+L+1) << 1; + for (unsigned i = 0; i < A; ++i, ++line_count, l1 += 2) { + l2 = parse_next_delta_literal(f, l1); + l3 = parse_next_delta_literal(f, l2); + + log_debug2("%d %d %d is an AND\n", l1, l2, l3); + log_assert(!(l1 & 1)); + RTLIL::Wire *o_wire = createWireIfNotExists(module, l1); + RTLIL::Wire *i1_wire = createWireIfNotExists(module, l2); + RTLIL::Wire *i2_wire = createWireIfNotExists(module, l3); + module->addAndGate("$and" + o_wire->name.str(), i1_wire, i2_wire, o_wire); + } +} + +void AigerReader::post_process() +{ + unsigned ci_count = 0, co_count = 0; + for (auto cell : boxes) { + for (auto &bit : cell->connections_.at(ID(i))) { + log_assert(bit == State::S0); + log_assert(co_count < outputs.size()); + bit = outputs[co_count++]; + log_assert(bit.wire && GetSize(bit.wire) == 1); + log_assert(bit.wire->port_output); + bit.wire->port_output = false; + } + for (auto &bit : cell->connections_.at(ID(o))) { + log_assert(bit == State::S0); + log_assert((piNum + ci_count) < inputs.size()); + bit = inputs[piNum + ci_count++]; + log_assert(bit.wire && GetSize(bit.wire) == 1); + log_assert(bit.wire->port_input); + bit.wire->port_input = false; + } + } + + for (uint32_t i = 0; i < flopNum; i++) { + RTLIL::Wire *d = outputs[outputs.size() - flopNum + i]; + log_assert(d); + log_assert(d->port_output); + d->port_output = false; + + RTLIL::Wire *q = inputs[piNum - flopNum + i]; + log_assert(q); + log_assert(q->port_input); + q->port_input = false; + + Cell* ff = module->addFfGate(NEW_ID, d, q); + ff->attributes[ID::abc9_mergeability] = mergeability[i]; + q->attributes[ID::init] = initial_state[i]; + } + + module->fixup_ports(); + + design->scratchpad_set_int("read_aiger.co_count", co_count); + + design->add(module); + Pass::call_on_module(design, module, "clean"); + + for (auto cell : module->cells().to_vector()) { + if (cell->type != ID($lut)) continue; + auto y_port = cell->getPort(ID::Y).as_bit(); + if (y_port.wire->width == 1) + module->rename(cell, stringf("$lut%s", y_port.wire->name)); + else + module->rename(cell, stringf("$lut%s[%d]", y_port.wire->name, y_port.offset)); + } +} + +struct AigerFrontend : public Frontend { + AigerFrontend() : Frontend("aiger", "read AIGER file") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" read_aiger [options] [filename]\n"); + log("\n"); + log("Load module from an AIGER file into the current design.\n"); + log("\n"); + log(" -module_name \n"); + log(" name of module to be created (default: )\n"); + log("\n"); + log(" -clk_name \n"); + log(" if specified, AIGER latches to be transformed into $_DFF_P_ cells\n"); + log(" clocked by wire of this name. otherwise, $_FF_ cells will be used\n"); + log("\n"); + log(" -map \n"); + log(" read file with port and latch symbols\n"); + log("\n"); + log(" -xaiger\n"); + log(" read XAIGER extensions\n"); + log("\n"); + } + void execute(std::istream *&f, std::string filename, std::vector args, RTLIL::Design *design) override + { + log_header(design, "Executing AIGER frontend.\n"); + + RTLIL::IdString clk_name; + RTLIL::IdString module_name; + std::string map_filename; + bool xaiger = false; + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) { + std::string arg = args[argidx]; + if (arg == "-module_name" && argidx+1 < args.size()) { + module_name = design->twines().add(RTLIL::escape_id(args[++argidx])); + continue; + } + if (arg == "-clk_name" && argidx+1 < args.size()) { + clk_name = design->twines().add(RTLIL::escape_id(args[++argidx])); + continue; + } + if (map_filename.empty() && arg == "-map" && argidx+1 < args.size()) { + map_filename = args[++argidx]; + continue; + } + if (arg == "-xaiger") { + xaiger = true; + continue; + } + break; + } + extra_args(f, filename, args, argidx, true); + + if (module_name.empty()) { +#ifdef _WIN32 + char fname[_MAX_FNAME]; + _splitpath(filename.c_str(), NULL /* drive */, NULL /* dir */, fname, NULL /* ext */); + char* bn = strdup(fname); + module_name = design->twines().add(RTLIL::escape_id(bn)); + free(bn); +#else + char* bn = strdup(filename.c_str()); + module_name = design->twines().add(RTLIL::escape_id(bn)); + free(bn); +#endif + } + + AigerReader reader(design, *f, module_name, clk_name, map_filename); + if (xaiger) + reader.parse_xaiger(); + else + reader.parse_aiger(); + } +} AigerFrontend; + +YOSYS_NAMESPACE_END diff --git a/chips/yosys/frontends/aiger/aigerparse.h b/chips/yosys/frontends/aiger/aigerparse.h new file mode 100644 index 0000000000000000000000000000000000000000..3c5e199ef95e55b2b5010d7f880724fa1ebffdf9 --- /dev/null +++ b/chips/yosys/frontends/aiger/aigerparse.h @@ -0,0 +1,64 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * 2019 Eddie Hung + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#ifndef ABC_AIGERPARSE +#define ABC_AIGERPARSE + +#include "kernel/yosys.h" + +YOSYS_NAMESPACE_BEGIN + +struct AigerReader +{ + RTLIL::Design *design; + std::istream &f; + RTLIL::IdString clk_name; + RTLIL::Module *module; + std::string map_filename; + const int aiger_autoidx; + + unsigned M, I, L, O, A; + unsigned B, C, J, F; // Optional in AIGER 1.9 + unsigned line_count; + uint32_t piNum, flopNum; + + std::vector inputs; + std::vector latches; + std::vector outputs; + std::vector bad_properties; + std::vector boxes; + std::vector mergeability, initial_state; + dict aiger_wires; + + AigerReader(RTLIL::Design *design, std::istream &f, RTLIL::IdString module_name, RTLIL::IdString clk_name, std::string map_filename); + void parse_aiger(); + void parse_xaiger(); + void parse_aiger_ascii(); + void parse_aiger_binary(); + void post_process(); + + RTLIL::Wire* createWireIfNotExists(RTLIL::Module *module, unsigned literal); + RTLIL::Wire* getOrCreateNormalWire(RTLIL::Module *module, unsigned variable); + RTLIL::Wire* getOrCreateInvertedWire(RTLIL::Module *module, unsigned variable); +}; + +YOSYS_NAMESPACE_END + +#endif diff --git a/chips/yosys/frontends/ast/CMakeLists.txt b/chips/yosys/frontends/ast/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..8c4388abcf0190240f5659bb844d54f4090f8860 --- /dev/null +++ b/chips/yosys/frontends/ast/CMakeLists.txt @@ -0,0 +1,11 @@ +yosys_core(ast + ast.cc + ast.h + dpicall.cc + genrtlil.cc + simplify.cc + LIBRARIES + $<${YOSYS_ENABLE_LIBFFI}:${Dlfcn_LIBRARIES};PkgConfig::libffi> + REQUIRES + sha1 +) diff --git a/chips/yosys/frontends/ast/ast.cc b/chips/yosys/frontends/ast/ast.cc new file mode 100644 index 0000000000000000000000000000000000000000..43d9c0ea2452bea4948d463fe923460423b2f37c --- /dev/null +++ b/chips/yosys/frontends/ast/ast.cc @@ -0,0 +1,2044 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * Copyright (C) 2018 Ruben Undheim + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * --- + * + * This is the AST frontend library. + * + * The AST frontend library is not a frontend on its own but provides an + * abstract syntax tree (AST) abstraction for the open source Verilog frontend + * at frontends/verilog. + * + * + */ + +#include "kernel/yosys.h" +#include "libs/sha1/sha1.h" +#include "ast.h" + +YOSYS_NAMESPACE_BEGIN + +using namespace AST; +using namespace AST_INTERNAL; + +// instantiate global variables (public API) +namespace AST { + bool sv_mode_but_global_and_used_for_literally_one_condition; + unsigned long long astnodes = 0; + unsigned long long astnode_count() { return astnodes; } +} + +TwinePool &AST::ast_name_pool() +{ + static TwinePool pool; + return pool; +} + +static RTLIL::Design *ast_scoped_design = nullptr; + +AST::DesignScope::DesignScope(RTLIL::Design *design) : prev(ast_scoped_design) +{ + ast_scoped_design = design; +} + +AST::DesignScope::~DesignScope() { ast_scoped_design = prev; } + +static RTLIL::Design *scoped_design() +{ + log_assert(ast_scoped_design != nullptr); + return ast_scoped_design; +} + +int AST::ast_autoidx() { return scoped_design()->twines().next_autoidx(); } + +// instantiate global variables (private API) +namespace AST_INTERNAL { + bool flag_nodisplay, flag_dump_ast1, flag_dump_ast2, flag_no_dump_ptr, flag_dump_vlog1, flag_dump_vlog2, flag_dump_rtlil, flag_nolatches, flag_nomeminit; + bool flag_nomem2reg, flag_mem2reg, flag_noblackbox, flag_lib, flag_nowb, flag_noopt, flag_icells, flag_pwires, flag_autowire; + int flag_unroll_limit; + AstNode *current_ast, *current_ast_mod; + std::map current_scope; + const dict *genRTLIL_subst_ptr = NULL; + RTLIL::SigSpec ignoreThisSignalsInInitial; + AstNode *current_always, *current_top_block, *current_block, *current_block_child; + Module *current_module; + bool current_always_clocked; + dict current_memwr_count; + dict> current_memwr_visible; +} + +// convert node types to string +std::string AST::type2str(AstNodeType type) +{ + switch (type) + { +#define X(_item) case _item: return #_item; + X(AST_NONE) + X(AST_DESIGN) + X(AST_MODULE) + X(AST_TASK) + X(AST_FUNCTION) + X(AST_DPI_FUNCTION) + X(AST_WIRE) + X(AST_MEMORY) + X(AST_AUTOWIRE) + X(AST_PARAMETER) + X(AST_LOCALPARAM) + X(AST_DEFPARAM) + X(AST_PARASET) + X(AST_ARGUMENT) + X(AST_RANGE) + X(AST_MULTIRANGE) + X(AST_CONSTANT) + X(AST_REALVALUE) + X(AST_CELLTYPE) + X(AST_IDENTIFIER) + X(AST_PREFIX) + X(AST_ASSERT) + X(AST_ASSUME) + X(AST_LIVE) + X(AST_FAIR) + X(AST_COVER) + X(AST_ENUM) + X(AST_ENUM_ITEM) + X(AST_FCALL) + X(AST_TO_BITS) + X(AST_TO_SIGNED) + X(AST_TO_UNSIGNED) + X(AST_SELFSZ) + X(AST_CAST_SIZE) + X(AST_CONCAT) + X(AST_REPLICATE) + X(AST_ASSIGN_PATTERN) + X(AST_BIT_NOT) + X(AST_BIT_AND) + X(AST_BIT_OR) + X(AST_BIT_XOR) + X(AST_BIT_XNOR) + X(AST_REDUCE_AND) + X(AST_REDUCE_OR) + X(AST_REDUCE_XOR) + X(AST_REDUCE_XNOR) + X(AST_REDUCE_BOOL) + X(AST_SHIFT_LEFT) + X(AST_SHIFT_RIGHT) + X(AST_SHIFT_SLEFT) + X(AST_SHIFT_SRIGHT) + X(AST_SHIFTX) + X(AST_SHIFT) + X(AST_LT) + X(AST_LE) + X(AST_EQ) + X(AST_NE) + X(AST_EQX) + X(AST_NEX) + X(AST_GE) + X(AST_GT) + X(AST_ADD) + X(AST_SUB) + X(AST_MUL) + X(AST_DIV) + X(AST_MOD) + X(AST_POW) + X(AST_POS) + X(AST_NEG) + X(AST_LOGIC_AND) + X(AST_LOGIC_OR) + X(AST_LOGIC_NOT) + X(AST_TERNARY) + X(AST_MEMRD) + X(AST_MEMWR) + X(AST_MEMINIT) + X(AST_TCALL) + X(AST_ASSIGN) + X(AST_CELL) + X(AST_PRIMITIVE) + X(AST_CELLARRAY) + X(AST_ALWAYS) + X(AST_INITIAL) + X(AST_BLOCK) + X(AST_ASSIGN_EQ) + X(AST_ASSIGN_LE) + X(AST_CASE) + X(AST_COND) + X(AST_CONDX) + X(AST_CONDZ) + X(AST_DEFAULT) + X(AST_FOR) + X(AST_WHILE) + X(AST_REPEAT) + X(AST_GENVAR) + X(AST_GENFOR) + X(AST_GENIF) + X(AST_GENCASE) + X(AST_GENBLOCK) + X(AST_TECALL) + X(AST_POSEDGE) + X(AST_NEGEDGE) + X(AST_EDGE) + X(AST_INTERFACE) + X(AST_INTERFACEPORT) + X(AST_INTERFACEPORTTYPE) + X(AST_MODPORT) + X(AST_MODPORTMEMBER) + X(AST_PACKAGE) + X(AST_IMPORT) + X(AST_WIRETYPE) + X(AST_TYPEDEF) + X(AST_STRUCT) + X(AST_UNION) + X(AST_STRUCT_ITEM) +#undef X + default: + log_abort(); + } +} + +// check if attribute exists and has non-zero value +bool AstNode::get_bool_attribute(RTLIL::IdString id) +{ + if (attributes.count(id) == 0) + return false; + + auto& attr = attributes.at(id); + if (attr->type != AST_CONSTANT) + attr->input_error("Attribute `%s' with non-constant value!\n", attr_name_str(id)); + + return attr->integer != 0; +} + +// create new node (AstNode constructor) +// (the optional child arguments make it easier to create AST trees) +AstNode::AstNode(AstSrcLocType loc, AstNodeType type, std::unique_ptr child1, std::unique_ptr child2, std::unique_ptr child3, std::unique_ptr child4) +{ + hashidx_ = ast_scoped_design ? ast_scoped_design->next_hashidx() : LARGE_HASHIDX_COLLIDER; + astnodes++; + + this->type = type; + location = loc; + is_input = false; + is_output = false; + is_reg = false; + is_logic = false; + is_signed = false; + is_string = false; + is_enum = false; + is_wand = false; + is_wor = false; + is_unsized = false; + was_checked = false; + range_valid = false; + range_swapped = false; + is_custom_type = false; + port_id = 0; + range_left = -1; + range_right = 0; + unpacked_dimensions = 0; + integer = 0; + realvalue = 0; + id2ast = NULL; + basic_prep = false; + lookahead = false; + in_lvalue_from_above = false; + in_param_from_above = false; + in_lvalue = false; + in_param = false; + + if (child1) + children.push_back(std::move(child1)); + if (child2) + children.push_back(std::move(child2)); + if (child3) + children.push_back(std::move(child3)); + if (child4) + children.push_back(std::move(child4)); + + fixup_hierarchy_flags(); +} + +// create a (deep recursive) copy of a node +std::unique_ptr AstNode::clone() const +{ + auto that = std::make_unique(this->location, this->type); + cloneInto(*that.get()); + return that; +} + +// create a (deep recursive) copy of a node use 'other' as target root node +void AstNode::cloneInto(AstNode &other) const +{ + other.type = type; + other.str = str; + other.bits = bits; + other.is_input = is_input; + other.is_output = is_output; + other.is_reg = is_reg; + other.is_logic = is_logic; + other.is_signed = is_signed; + other.is_string = is_string; + other.is_wand = is_wand; + other.is_wor = is_wor; + other.range_valid = range_valid; + other.range_swapped = range_swapped; + other.was_checked = was_checked; + other.is_unsized = is_unsized; + other.is_custom_type = is_custom_type; + other.port_id = port_id, + other.range_left = range_left, + other.range_right = range_right; + other.integer = integer; + other.realvalue = realvalue; + other.is_enum = is_enum; + other.dimensions = dimensions; + other.unpacked_dimensions = unpacked_dimensions; + other.id2ast = id2ast; + other.basic_prep = basic_prep; + other.lookahead = lookahead; + other.location = location; + other.in_lvalue = in_lvalue; + other.in_param = in_param; + // Keep in_lvalue_from_above and in_param_from_above untouched + + other.delete_children(); + for (auto& child : this->children) + other.children.push_back(child->clone()); + for (auto& [key, val] : this->attributes) + other.attributes[key] = (val->clone()); + // fixup to set flags on cloned children + other.fixup_hierarchy_flags(); +} + +// delete all children in this node +void AstNode::delete_children() +{ + children.clear(); + attributes.clear(); +} + +// AstNode destructor +AstNode::~AstNode() +{ + astnodes--; + delete_children(); +} + +// create a nice text representation of the node +// (traverse tree by recursion, use 'other' pointer for diffing two AST trees) +void AstNode::dumpAst(FILE *f, std::string indent) const +{ + if (f == NULL) { + logger().for_each_sink([&](LogSink &sink) { + FILE *f = sink.file_handle(); + if (f) + dumpAst(f, indent); + }); + return; + } + + std::string type_name = type2str(type); + fprintf(f, "%s%s <%s>", indent.c_str(), type_name.c_str(), loc_string().c_str()); + + if (!flag_no_dump_ptr) { + if (id2ast) + fprintf(f, " [%p -> %p]", this, id2ast); + else + fprintf(f, " [%p]", this); + } + + if (!str.empty()) + fprintf(f, " str='%s'", str.c_str()); + if (!bits.empty()) { + fprintf(f, " bits='"); + for (size_t i = bits.size(); i > 0; i--) + fprintf(f, "%c", bits[i-1] == State::S0 ? '0' : + bits[i-1] == State::S1 ? '1' : + bits[i-1] == RTLIL::Sx ? 'x' : + bits[i-1] == RTLIL::Sz ? 'z' : '?'); + fprintf(f, "'(%d)", GetSize(bits)); + } + if (is_input) + fprintf(f, " input"); + if (is_output) + fprintf(f, " output"); + if (is_logic) + fprintf(f, " logic"); + if (is_reg) // this is an AST dump, not Verilog - if we see "logic reg" that's fine. + fprintf(f, " reg"); + if (is_signed) + fprintf(f, " signed"); + if (is_unsized) + fprintf(f, " unsized"); + if (basic_prep) + fprintf(f, " basic_prep"); + if (lookahead) + fprintf(f, " lookahead"); + if (port_id > 0) + fprintf(f, " port=%d", port_id); + if (range_valid || range_left != -1 || range_right != 0) + fprintf(f, " %srange=[%d:%d]%s", range_swapped ? "swapped_" : "", range_left, range_right, range_valid ? "" : "!"); + if (integer != 0) + fprintf(f, " int=%u", (int)integer); + if (realvalue != 0) + fprintf(f, " real=%e", realvalue); + if (!dimensions.empty()) { + fprintf(f, " dimensions="); + for (auto &dim : dimensions) { + int left = dim.range_right + dim.range_width - 1; + int right = dim.range_right; + if (dim.range_swapped) + std::swap(left, right); + fprintf(f, "[%d:%d]", left, right); + } + } + if (is_enum) { + fprintf(f, " type=enum"); + } + if (in_lvalue) + fprintf(f, " in_lvalue"); + if (in_param) + fprintf(f, " in_param"); + fprintf(f, "\n"); + + for (auto &it : attributes) { + fprintf(f, "%s ATTR %s:\n", indent.c_str(), attr_name_str(it.first).c_str()); + it.second->dumpAst(f, indent + " "); + } + + for (size_t i = 0; i < children.size(); i++) + children[i]->dumpAst(f, indent + " "); + + fflush(f); +} + +// helper function for AstNode::dumpVlog() +static std::string id2vl(std::string txt) +{ + if (txt.size() > 1 && txt[0] == '\\') + txt = txt.substr(1); + for (size_t i = 0; i < txt.size(); i++) { + if ('A' <= txt[i] && txt[i] <= 'Z') continue; + if ('a' <= txt[i] && txt[i] <= 'z') continue; + if ('0' <= txt[i] && txt[i] <= '9') continue; + if (txt[i] == '_') continue; + txt = "\\" + txt + " "; + break; + } + return txt; +} + +// dump AST node as Verilog pseudo-code +void AstNode::dumpVlog(FILE *f, std::string indent) const +{ + bool first = true; + std::string txt; + std::vector rem_children1, rem_children2; + + if (f == NULL) { + logger().for_each_sink([&](LogSink &sink) { + FILE *f = sink.file_handle(); + if (f) + dumpVlog(f, indent); + }); + return; + } + + for (auto &it : attributes) { + fprintf(f, "%s" "(* %s = ", indent.c_str(), id2vl(attr_name_str(it.first)).c_str()); + it.second->dumpVlog(f, ""); + fprintf(f, " *)%s", indent.empty() ? "" : "\n"); + } + + switch (type) + { + case AST_MODULE: + fprintf(f, "%s" "module %s(", indent.c_str(), id2vl(str).c_str()); + for (const auto& child : children) + if (child->type == AST_WIRE && (child->is_input || child->is_output)) { + fprintf(f, "%s%s", first ? "" : ", ", id2vl(child->str).c_str()); + first = false; + } + fprintf(f, ");\n"); + + for (const auto& child : children) + if (child->type == AST_PARAMETER || child->type == AST_LOCALPARAM || child->type == AST_DEFPARAM) + child->dumpVlog(f, indent + " "); + else + rem_children1.push_back(child.get()); + + for (auto child : rem_children1) + if (child->type == AST_WIRE || child->type == AST_AUTOWIRE || child->type == AST_MEMORY) + child->dumpVlog(f, indent + " "); + else + rem_children2.push_back(child); + rem_children1.clear(); + + for (auto child : rem_children2) + if (child->type == AST_TASK || child->type == AST_FUNCTION) + child->dumpVlog(f, indent + " "); + else + rem_children1.push_back(child); + rem_children2.clear(); + + for (auto child : rem_children1) + child->dumpVlog(f, indent + " "); + rem_children1.clear(); + + fprintf(f, "%s" "endmodule\n", indent.c_str()); + break; + + case AST_WIRE: + if (is_input && is_output) + fprintf(f, "%s" "inout", indent.c_str()); + else if (is_input) + fprintf(f, "%s" "input", indent.c_str()); + else if (is_output) + fprintf(f, "%s" "output", indent.c_str()); + else if (!is_reg) + fprintf(f, "%s" "wire", indent.c_str()); + if (is_reg) + fprintf(f, "%s" "reg", (is_input || is_output) ? " " : indent.c_str()); + if (is_signed) + fprintf(f, " signed"); + for (const auto& child : children) { + fprintf(f, " "); + child->dumpVlog(f, ""); + } + fprintf(f, " %s", id2vl(str).c_str()); + fprintf(f, ";\n"); + break; + + case AST_WIRETYPE: + fprintf(f, "%s", id2vl(str).c_str()); + break; + + case AST_MEMORY: + fprintf(f, "%s" "memory", indent.c_str()); + if (is_signed) + fprintf(f, " signed"); + for (const auto& child : children) { + fprintf(f, " "); + child->dumpVlog(f, ""); + if (first) + fprintf(f, " %s", id2vl(str).c_str()); + first = false; + } + fprintf(f, ";\n"); + break; + + if (0) { case AST_MEMRD: txt = "@memrd@"; } + if (0) { case AST_MEMINIT: txt = "@meminit@"; } + if (0) { case AST_MEMWR: txt = "@memwr@"; } + fprintf(f, "%s%s", indent.c_str(), txt.c_str()); + for (const auto& child : children) { + fprintf(f, first ? "(" : ", "); + child->dumpVlog(f, ""); + first = false; + } + fprintf(f, ")"); + if (type != AST_MEMRD) + fprintf(f, ";\n"); + break; + + case AST_RANGE: + if (range_valid) { + if (range_swapped) + fprintf(f, "[%d:%d]", range_right, range_left); + else + fprintf(f, "[%d:%d]", range_left, range_right); + } else { + for (const auto& child : children) { + fprintf(f, "%c", first ? '[' : ':'); + child->dumpVlog(f, ""); + first = false; + } + fprintf(f, "]"); + } + break; + + case AST_MULTIRANGE: + for (const auto& child : children) + child->dumpVlog(f, ""); + break; + + case AST_ALWAYS: + fprintf(f, "%s" "always @", indent.c_str()); + for (const auto& child : children) { + if (child->type != AST_POSEDGE && child->type != AST_NEGEDGE && child->type != AST_EDGE) + continue; + fprintf(f, first ? "(" : ", "); + child->dumpVlog(f, ""); + first = false; + } + fprintf(f, first ? "*\n" : ")\n"); + for (const auto& child : children) { + if (child->type != AST_POSEDGE && child->type != AST_NEGEDGE && child->type != AST_EDGE) + child->dumpVlog(f, indent + " "); + } + break; + + case AST_INITIAL: + fprintf(f, "%s" "initial\n", indent.c_str()); + for (const auto& child : children) { + if (child->type != AST_POSEDGE && child->type != AST_NEGEDGE && child->type != AST_EDGE) + child->dumpVlog(f, indent + " "); + } + break; + + case AST_POSEDGE: + case AST_NEGEDGE: + case AST_EDGE: + if (type == AST_POSEDGE) + fprintf(f, "posedge "); + if (type == AST_NEGEDGE) + fprintf(f, "negedge "); + for (const auto& child : children) + child->dumpVlog(f, ""); + break; + + case AST_IDENTIFIER: + { + AstNode *member_node = get_struct_member(); + if (member_node) + fprintf(f, "%s[%d:%d]", id2vl(str).c_str(), member_node->range_left, member_node->range_right); + else + fprintf(f, "%s", id2vl(str).c_str()); + } + for (const auto& child : children) + child->dumpVlog(f, ""); + break; + + case AST_STRUCT: + case AST_UNION: + case AST_STRUCT_ITEM: + fprintf(f, "%s", id2vl(str).c_str()); + break; + + case AST_CONSTANT: + if (!str.empty()) + fprintf(f, "\"%s\"", str.c_str()); + else if (bits.size() == 32) + fprintf(f, "%d", RTLIL::Const(bits).as_int()); + else + fprintf(f, "%d'b %s", GetSize(bits), RTLIL::Const(bits).as_string().c_str()); + break; + + case AST_REALVALUE: + fprintf(f, "%e", realvalue); + break; + + case AST_BLOCK: + if (children.size() == 1) { + children[0]->dumpVlog(f, indent); + } else { + fprintf(f, "%s" "begin\n", indent.c_str()); + for (const auto& child : children) + child->dumpVlog(f, indent + " "); + fprintf(f, "%s" "end\n", indent.c_str()); + } + break; + + case AST_CASE: + if (children.size() > 1 && children[1]->type == AST_CONDX) + fprintf(f, "%s" "casex (", indent.c_str()); + else if (children.size() > 1 && children[1]->type == AST_CONDZ) + fprintf(f, "%s" "casez (", indent.c_str()); + else + fprintf(f, "%s" "case (", indent.c_str()); + children[0]->dumpVlog(f, ""); + fprintf(f, ")\n"); + for (size_t i = 1; i < children.size(); i++) { + const auto& child = children[i]; + child->dumpVlog(f, indent + " "); + } + fprintf(f, "%s" "endcase\n", indent.c_str()); + break; + + case AST_COND: + case AST_CONDX: + case AST_CONDZ: + for (const auto& child : children) { + if (child->type == AST_BLOCK) { + fprintf(f, ":\n"); + child->dumpVlog(f, indent + " "); + first = true; + } else { + fprintf(f, "%s", first ? indent.c_str() : ", "); + if (child->type == AST_DEFAULT) + fprintf(f, "default"); + else + child->dumpVlog(f, ""); + first = false; + } + } + break; + + case AST_ASSIGN: + fprintf(f, "%sassign ", indent.c_str()); + children[0]->dumpVlog(f, ""); + fprintf(f, " = "); + children[1]->dumpVlog(f, ""); + fprintf(f, ";\n"); + break; + + case AST_ASSIGN_EQ: + case AST_ASSIGN_LE: + fprintf(f, "%s", indent.c_str()); + children[0]->dumpVlog(f, ""); + fprintf(f, " %s ", type == AST_ASSIGN_EQ ? "=" : "<="); + children[1]->dumpVlog(f, ""); + fprintf(f, ";\n"); + break; + + case AST_CONCAT: + fprintf(f, "{"); + for (int i = GetSize(children)-1; i >= 0; i--) { + const auto& child = children[i]; + if (!first) + fprintf(f, ", "); + child->dumpVlog(f, ""); + first = false; + } + fprintf(f, "}"); + break; + + case AST_REPLICATE: + fprintf(f, "{"); + children[0]->dumpVlog(f, ""); + fprintf(f, "{"); + children[1]->dumpVlog(f, ""); + fprintf(f, "}}"); + break; + + case AST_ASSIGN_PATTERN: + fprintf(f, "'{"); + for (int i = 0; i < GetSize(children); i++) { + if (i != 0) + fprintf(f, ", "); + children[i]->dumpVlog(f, ""); + } + fprintf(f, "}"); + break; + + if (0) { case AST_BIT_NOT: txt = "~"; } + if (0) { case AST_REDUCE_AND: txt = "&"; } + if (0) { case AST_REDUCE_OR: txt = "|"; } + if (0) { case AST_REDUCE_XOR: txt = "^"; } + if (0) { case AST_REDUCE_XNOR: txt = "~^"; } + if (0) { case AST_REDUCE_BOOL: txt = "|"; } + if (0) { case AST_POS: txt = "+"; } + if (0) { case AST_NEG: txt = "-"; } + if (0) { case AST_LOGIC_NOT: txt = "!"; } + if (0) { case AST_SELFSZ: txt = "@selfsz@"; } + if (0) { case AST_TO_SIGNED: txt = "signed'"; } + if (0) { case AST_TO_UNSIGNED: txt = "unsigned'"; } + fprintf(f, "%s(", txt.c_str()); + children[0]->dumpVlog(f, ""); + fprintf(f, ")"); + break; + + case AST_CAST_SIZE: + switch (children[0]->type) + { + case AST_WIRE: + if (children[0]->children.size() > 0) + children[0]->children[0]->dumpVlog(f, ""); + else + fprintf(f, "%d'", children[0]->range_left - children[0]->range_right + 1); + break; + default: + children[0]->dumpVlog(f, ""); + } + fprintf(f, "'("); + children[1]->dumpVlog(f, ""); + fprintf(f, ")"); + break; + + if (0) { case AST_BIT_AND: txt = "&"; } + if (0) { case AST_BIT_OR: txt = "|"; } + if (0) { case AST_BIT_XOR: txt = "^"; } + if (0) { case AST_BIT_XNOR: txt = "~^"; } + if (0) { case AST_SHIFT_LEFT: txt = "<<"; } + if (0) { case AST_SHIFT_RIGHT: txt = ">>"; } + if (0) { case AST_SHIFT_SLEFT: txt = "<<<"; } + if (0) { case AST_SHIFT_SRIGHT: txt = ">>>"; } + if (0) { case AST_SHIFTX: txt = "@shiftx@"; } + if (0) { case AST_SHIFT: txt = "@shift@"; } + if (0) { case AST_LT: txt = "<"; } + if (0) { case AST_LE: txt = "<="; } + if (0) { case AST_EQ: txt = "=="; } + if (0) { case AST_NE: txt = "!="; } + if (0) { case AST_EQX: txt = "==="; } + if (0) { case AST_NEX: txt = "!=="; } + if (0) { case AST_GE: txt = ">="; } + if (0) { case AST_GT: txt = ">"; } + if (0) { case AST_ADD: txt = "+"; } + if (0) { case AST_SUB: txt = "-"; } + if (0) { case AST_MUL: txt = "*"; } + if (0) { case AST_DIV: txt = "/"; } + if (0) { case AST_MOD: txt = "%"; } + if (0) { case AST_POW: txt = "**"; } + if (0) { case AST_LOGIC_AND: txt = "&&"; } + if (0) { case AST_LOGIC_OR: txt = "||"; } + fprintf(f, "("); + children[0]->dumpVlog(f, ""); + fprintf(f, ")%s(", txt.c_str()); + children[1]->dumpVlog(f, ""); + fprintf(f, ")"); + break; + + case AST_TERNARY: + fprintf(f, "("); + children[0]->dumpVlog(f, ""); + fprintf(f, ") ? ("); + children[1]->dumpVlog(f, ""); + fprintf(f, ") : ("); + children[2]->dumpVlog(f, ""); + fprintf(f, ")"); + break; + + default: + std::string type_name = type2str(type); + fprintf(f, "%s" "/** %s **/%s", indent.c_str(), type_name.c_str(), indent.empty() ? "" : "\n"); + // dumpAst(f, indent, NULL); + } + + fflush(f); +} + +// check if two AST nodes are identical +bool AstNode::operator==(const AstNode &other) const +{ + if (type != other.type) + return false; + if (children.size() != other.children.size()) + return false; + if (str != other.str) + return false; + if (bits != other.bits) + return false; + if (is_input != other.is_input) + return false; + if (is_output != other.is_output) + return false; + if (is_logic != other.is_logic) + return false; + if (is_reg != other.is_reg) + return false; + if (is_signed != other.is_signed) + return false; + if (is_string != other.is_string) + return false; + if (range_valid != other.range_valid) + return false; + if (range_swapped != other.range_swapped) + return false; + if (port_id != other.port_id) + return false; + if (range_left != other.range_left) + return false; + if (range_right != other.range_right) + return false; + if (integer != other.integer) + return false; + for (size_t i = 0; i < children.size(); i++) + if (*children[i] != *other.children[i]) + return false; + return true; +} + +// check if two AST nodes are not identical +bool AstNode::operator!=(const AstNode &other) const +{ + return !(*this == other); +} + +// check if this AST contains the given node +bool AstNode::contains(const AstNode *other) const +{ + if (this == other) + return true; + for (const auto& child : children) + if (child->contains(other)) + return true; + return false; +} + +// create an AST node for a constant (using a 32 bit int as value) +std::unique_ptr AstNode::mkconst_int(AstSrcLocType loc, uint32_t v, bool is_signed, int width) +{ + auto node = std::make_unique(loc, AST_CONSTANT); + node->integer = v; + node->is_signed = is_signed; + for (int i = 0; i < width; i++) { + node->bits.push_back((v & 1) ? State::S1 : State::S0); + v = v >> 1; + } + node->range_valid = true; + node->range_left = width-1; + node->range_right = 0; + return node; +} + +// create an AST node for a constant (using a bit vector as value) +std::unique_ptr AstNode::mkconst_bits(AstSrcLocType loc, const std::vector &v, bool is_signed, bool is_unsized) +{ + auto node = std::make_unique(loc, AST_CONSTANT); + node->is_signed = is_signed; + node->bits = v; + for (size_t i = 0; i < 32; i++) { + if (i < node->bits.size()) + node->integer |= (node->bits[i] == State::S1) << i; + else if (is_signed && !node->bits.empty()) + node->integer |= (node->bits.back() == State::S1) << i; + } + node->range_valid = true; + node->range_left = node->bits.size()-1; + node->range_right = 0; + node->is_unsized = is_unsized; + return node; +} + +std::unique_ptr AstNode::mkconst_bits(AstSrcLocType loc, const std::vector &v, bool is_signed) +{ + return mkconst_bits(loc, v, is_signed, false); +} + +// create an AST node for a constant (using a string in bit vector form as value) +std::unique_ptr AstNode::mkconst_str(AstSrcLocType loc, const std::vector &v) +{ + auto node = mkconst_str(loc, RTLIL::Const(v).decode_string()); + while (GetSize(node->bits) < GetSize(v)) + node->bits.push_back(RTLIL::State::S0); + log_assert(node->bits == v); + return node; +} + +// create an AST node for a constant (using a string as value) +std::unique_ptr AstNode::mkconst_str(AstSrcLocType loc, const std::string &str) +{ + std::unique_ptr node; + + // LRM 1364-2005 5.2.3.3 The empty string literal ("") shall be considered + // equivalent to the ASCII NUL ("\0") + if (str.empty()) { + node = AstNode::mkconst_int(loc, 0, false, 8); + } else { + std::vector data; + data.reserve(str.size() * 8); + for (size_t i = 0; i < str.size(); i++) { + unsigned char ch = str[str.size() - i - 1]; + for (int j = 0; j < 8; j++) { + data.push_back((ch & 1) ? State::S1 : State::S0); + ch = ch >> 1; + } + } + node = AstNode::mkconst_bits(loc, data, false); + } + + node->is_string = true; + node->str = str; + return node; +} + +// create a temporary register +std::unique_ptr AstNode::mktemp_logic(AstSrcLocType loc, const std::string &name, AstNode *mod, bool nosync, int range_left, int range_right, bool is_signed) +{ + auto wire_owned = std::make_unique(loc, AST_WIRE, std::make_unique(loc, AST_RANGE, mkconst_int(loc, range_left, true), mkconst_int(loc, range_right, true))); + auto* wire = wire_owned.get(); + wire->str = stringf("%s%s:%d$%d", name, RTLIL::encode_filename(*location.begin.filename), location.begin.line, ast_autoidx()); + if (nosync) + wire->set_attribute(ID::nosync, AstNode::mkconst_int(loc, 1, false)); + wire->is_signed = is_signed; + wire->is_logic = true; + mod->children.push_back(std::move(wire_owned)); + while (wire->simplify(true, 1, -1, false)) { } + + auto ident = std::make_unique(loc, AST_IDENTIFIER); + ident->str = wire->str; + ident->id2ast = wire; + + return ident; +} + +bool AstNode::bits_only_01() const +{ + for (auto bit : bits) + if (bit != State::S0 && bit != State::S1) + return false; + return true; +} + +RTLIL::Const AstNode::bitsAsUnsizedConst(int width) +{ + RTLIL::State extbit = bits.back(); + while (width > GetSize(bits)) + bits.push_back(extbit); + return RTLIL::Const(bits); +} + +RTLIL::Const AstNode::bitsAsConst(int width, bool is_signed) +{ + std::vector bits = this->bits; + if (width >= 0 && width < GetSize(bits)) + bits.resize(width); + if (width >= 0 && width > GetSize(bits)) { + RTLIL::State extbit = RTLIL::State::S0; + if ((is_signed || is_unsized) && !bits.empty()) + extbit = bits.back(); + while (width > GetSize(bits)) + bits.push_back(extbit); + } + return RTLIL::Const(bits); +} + +RTLIL::Const AstNode::bitsAsConst(int width) +{ + return bitsAsConst(width, is_signed); +} + +RTLIL::Const AstNode::asAttrConst() const +{ + log_assert(type == AST_CONSTANT); + + if (is_string) + return RTLIL::Const(str); + RTLIL::Const val(bits); + if (is_signed) + val.flags |= RTLIL::CONST_FLAG_SIGNED; + return val; +} + +RTLIL::Const AstNode::asParaConst() const +{ + if (type == AST_REALVALUE) + { + auto strnode = AstNode::mkconst_str(location, stringf("%f", realvalue)); + RTLIL::Const val = strnode->asAttrConst(); + val.flags |= RTLIL::CONST_FLAG_REAL; + return val; + } + + RTLIL::Const val = asAttrConst(); + if (is_signed) + val.flags |= RTLIL::CONST_FLAG_SIGNED; + if (is_unsized) + val.flags |= RTLIL::CONST_FLAG_UNSIZED; + return val; +} + +bool AstNode::asBool() const +{ + if (type == AST_REALVALUE) + return realvalue != 0; + log_assert(type == AST_CONSTANT); + for (auto &bit : bits) + if (bit == RTLIL::State::S1) + return true; + return false; +} + +int AstNode::isConst() const +{ + if (type == AST_CONSTANT) + return 1; + if (type == AST_REALVALUE) + return 2; + return 0; +} + +uint64_t AstNode::asInt(bool is_signed) +{ + if (type == AST_CONSTANT) + { + RTLIL::Const v = bitsAsConst(64, is_signed); + uint64_t ret = 0; + + for (int i = 0; i < 64; i++) + if (v.at(i) == RTLIL::State::S1) + ret |= uint64_t(1) << i; + + return ret; + } + + if (type == AST_REALVALUE) + return uint64_t(realvalue); + + log_abort(); +} + +double AstNode::asReal(bool is_signed) +{ + if (type == AST_CONSTANT) + { + RTLIL::Const val(bits); + + bool is_negative = is_signed && !val.empty() && val.back() == RTLIL::State::S1; + if (is_negative) + val = const_neg(val, val, false, false, val.size()); + + double v = 0; + for (auto i = 0; i < val.size(); i++) + // IEEE Std 1800-2012 Par 6.12.2: Individual bits that are x or z in + // the net or the variable shall be treated as zero upon conversion. + if (val.at(i) == RTLIL::State::S1) + v += exp2(i); + if (is_negative) + v *= -1; + + return v; + } + + if (type == AST_REALVALUE) + return realvalue; + + log_abort(); +} + +RTLIL::Const AstNode::valueAsConst(int width) +{ + if (type == AST_REALVALUE) + return realAsConst(width); + log_assert(type == AST_CONSTANT); + return bitsAsConst(width); +} + +RTLIL::Const AstNode::realAsConst(int width) +{ + double v = round(realvalue); + RTLIL::Const result; + if (!std::isfinite(v)) { + result = std::vector(width, RTLIL::State::Sx); + } else { + bool is_negative = v < 0; + if (is_negative) + v *= -1; + RTLIL::Const::Builder b(width); + for (int i = 0; i < width; i++, v /= 2) + b.push_back((fmod(floor(v), 2) != 0) ? RTLIL::State::S1 : RTLIL::State::S0); + result = b.build(); + if (is_negative) + result = const_neg(result, result, false, false, result.size()); + } + return result; +} + +std::string AstNode::loc_string() const +{ + return stringf("%s:%d.%d-%d.%d", location.begin.filename->c_str(), location.begin.line, location.begin.column, location.end.line, location.end.column); +} + +static IdString build_hier_content(TwinePool &pool, std::string_view content) +{ + size_t dot = content.rfind('.'); + if (dot == std::string_view::npos) + return pool.add(TwineSpec::Root{std::string{content}}).tag(true); + IdString prefix = build_hier_content(pool, content.substr(0, dot)); + return pool.add(TwineSpec::Suffix{prefix, std::string{content.substr(dot)}}); +} + +IdString AST::intern_hier_name(RTLIL::Design *design, std::string_view escaped) +{ + if (escaped.size() > 1 && escaped[0] == '\\') + return build_hier_content(design->twines(), escaped.substr(1)); + return design->twines().add(escaped); +} + +IdString AST::intern_src_loc(RTLIL::Design *design, const AstSrcLocType &location) +{ + return design->twines().add(stringf("$%s:%d", + RTLIL::encode_filename(*location.begin.filename), location.begin.line)); +} + +IdString AST::intern_src_name(RTLIL::Design *design, const AstSrcLocType &location, + std::string_view kind, int idx) +{ + return design->twines().add(TwineSpec::Suffix{intern_src_loc(design, location), + stringf("%s$%d", kind, idx)}); +} + +void AST::set_src_attr(RTLIL::AttrObject *obj, const AstNode *ast) +{ + obj->attributes[ID::src] = ast->loc_string(); +} + +static bool param_has_no_default(const AstNode* param) { + const auto &children = param->children; + log_assert(param->type == AST_PARAMETER); + log_assert(children.size() <= 2); + return children.empty() || + (children.size() == 1 && children[0]->type == AST_RANGE); +} + +static RTLIL::Module *process_module(RTLIL::Design *design, AstNode *ast, bool defer, std::unique_ptr original_ast = NULL, bool quiet = false) +{ + log_assert(current_scope.empty()); + log_assert(ast->type == AST_MODULE || ast->type == AST_INTERFACE); + + if (defer) + log("Storing AST representation for module `%s'.\n", ast->str); + else if (!quiet) { + log("Generating RTLIL representation for module `%s'.\n", ast->str); + } + + AstModule *module = new AstModule(design); + current_module = module; + + module->ast = nullptr; + module->name = design->twines().add(ast->str); + set_src_attr(module, ast); + module->set_bool_attribute(ID::cells_not_processed); + + current_ast_mod = ast; + std::unique_ptr ast_before_simplify; + if (original_ast != NULL) + ast_before_simplify = std::move(original_ast); + else + ast_before_simplify = ast->clone(); + + if (flag_dump_ast1) { + log("Dumping AST before simplification:\n"); + ast->dumpAst(NULL, " "); + log("--- END OF AST DUMP ---\n"); + } + if (flag_dump_vlog1) { + log("Dumping Verilog AST before simplification:\n"); + ast->dumpVlog(NULL, " "); + log("--- END OF AST DUMP ---\n"); + } + + if (!defer) + { + for (auto& node : ast->children) + if (node->type == AST_PARAMETER && param_has_no_default(node.get())) + node->input_error("Parameter `%s' has no default value and has not been overridden!\n", node->str); + + bool blackbox_module = flag_lib; + + if (!blackbox_module && !flag_noblackbox) { + blackbox_module = true; + for (const auto& child : ast->children) { + if (child->type == AST_WIRE && (child->is_input || child->is_output)) + continue; + if (child->type == AST_PARAMETER || child->type == AST_LOCALPARAM) + continue; + if (child->type == AST_CELL && child->children.size() > 0 && child->children[0]->type == AST_CELLTYPE && + (child->children[0]->str == "$specify2" || child->children[0]->str == "$specify3" || child->children[0]->str == "$specrule")) + continue; + blackbox_module = false; + break; + } + } + + // simplify this module or interface using the current design as context + // for lookup up ports and wires within cells + set_simplify_design_context(design); + while (ast->simplify(!flag_noopt, 0, -1, false)) { } + set_simplify_design_context(nullptr); + + if (flag_dump_ast2) { + log("Dumping AST after simplification:\n"); + ast->dumpAst(NULL, " "); + log("--- END OF AST DUMP ---\n"); + } + + if (flag_dump_vlog2) { + log("Dumping Verilog AST after simplification:\n"); + ast->dumpVlog(NULL, " "); + log("--- END OF AST DUMP ---\n"); + } + for (auto &attr: ast->attributes) + log_assert((bool)attr.second.get()); + if (flag_nowb && ast->attributes.count(ID::whitebox)) { + ast->attributes.erase(ID::whitebox); + } + for (auto &attr: ast->attributes) + log_assert((bool)attr.second.get()); + if (ast->attributes.count(ID::lib_whitebox)) { + if (flag_lib && !flag_nowb) { + ast->attributes[ID::whitebox] = std::move( + ast->attributes[ID::lib_whitebox] + ); + } + ast->attributes.erase(ID::lib_whitebox); + } + for (auto &attr: ast->attributes) + log_assert((bool)attr.second.get()); + + if (!blackbox_module && ast->attributes.count(ID::blackbox)) { + auto& n = ast->attributes.at(ID::blackbox); + if (n->type != AST_CONSTANT) + ast->input_error("Got blackbox attribute with non-constant value!\n"); + blackbox_module = n->asBool(); + } + + if (blackbox_module && ast->attributes.count(ID::whitebox)) { + auto& n = ast->attributes.at(ID::whitebox); + if (n->type != AST_CONSTANT) + ast->input_error("Got whitebox attribute with non-constant value!\n"); + blackbox_module = !n->asBool(); + } + + if (ast->attributes.count(ID::noblackbox)) { + if (blackbox_module) { + auto& n = ast->attributes.at(ID::noblackbox); + if (n->type != AST_CONSTANT) + ast->input_error("Got noblackbox attribute with non-constant value!\n"); + blackbox_module = !n->asBool(); + } + ast->attributes.erase(ID::noblackbox); + } + for (auto &attr: ast->attributes) + log_assert((bool)attr.second.get()); + if (blackbox_module) + { + if (ast->attributes.count(ID::whitebox)) { + ast->attributes.erase(ID::whitebox); + } + + if (ast->attributes.count(ID::lib_whitebox)) { + ast->attributes.erase(ID::lib_whitebox); + } + + std::vector> new_children; + for (auto& child : ast->children) { + if (child->type == AST_WIRE && (child->is_input || child->is_output)) { + new_children.push_back(std::move(child)); + } else if (child->type == AST_PARAMETER) { + new_children.push_back(std::move(child)); + } else if (child->type == AST_CELL && child->children.size() > 0 && child->children[0]->type == AST_CELLTYPE && + (child->children[0]->str == "$specify2" || child->children[0]->str == "$specify3" || child->children[0]->str == "$specrule")) { + new_children.push_back(std::move(child)); + } + } + + ast->children.swap(new_children); + + if (ast->attributes.count(ID::blackbox) == 0) { + ast->set_attribute(ID::blackbox, AstNode::mkconst_int(ast->location, 1, false)); + } + } + + ignoreThisSignalsInInitial = RTLIL::SigSpec(); + + for (auto &attr : ast->attributes) { + log_assert((bool)attr.second.get()); + if (attr.second->type != AST_CONSTANT) + ast->input_error("Attribute `%s' with non-constant value!\n", attr_name_str(attr.first)); + module->attributes[design->twines().add(attr_name_str(attr.first))] = attr.second->asAttrConst(); + } + for (size_t i = 0; i < ast->children.size(); i++) { + const auto& node = ast->children[i]; + if (node->type == AST_WIRE || node->type == AST_MEMORY) + node->genRTLIL(); + } + for (size_t i = 0; i < ast->children.size(); i++) { + const auto& node = ast->children[i]; + if (node->type != AST_WIRE && node->type != AST_MEMORY && node->type != AST_INITIAL) + node->genRTLIL(); + } + + ignoreThisSignalsInInitial.sort_and_unify(); + + for (size_t i = 0; i < ast->children.size(); i++) { + const auto& node = ast->children[i]; + if (node->type == AST_INITIAL) + node->genRTLIL(); + } + + ignoreThisSignalsInInitial = RTLIL::SigSpec(); + current_scope.clear(); + } + else { + for (auto &attr : ast->attributes) { + if (attr.second->type != AST_CONSTANT) + continue; + module->attributes[design->twines().add(attr_name_str(attr.first))] = attr.second->asAttrConst(); + } + for (const auto& node : ast->children) + if (node->type == AST_PARAMETER) + current_module->avail_parameters(design->twines().add(node->str)); + } + + if (ast->type == AST_INTERFACE) + module->set_bool_attribute(ID::is_interface); + module->ast = std::move(ast_before_simplify); + module->nolatches = flag_nolatches; + module->nomeminit = flag_nomeminit; + module->nomem2reg = flag_nomem2reg; + module->mem2reg = flag_mem2reg; + module->noblackbox = flag_noblackbox; + module->lib = flag_lib; + module->nowb = flag_nowb; + module->noopt = flag_noopt; + module->icells = flag_icells; + module->pwires = flag_pwires; + module->autowire = flag_autowire; + module->fixup_ports(); + + if (flag_dump_rtlil) { + log("Dumping generated RTLIL:\n"); + log_module(module); + log("--- END OF RTLIL DUMP ---\n"); + } + + design->add(current_module); + return current_module; +} + +RTLIL::Module * +AST_INTERNAL::process_and_replace_module(RTLIL::Design *design, + RTLIL::Module *old_module, + AST::AstNode *new_ast, + std::unique_ptr original_ast) +{ + // The old module will be deleted. Rename and mark for deletion, using + // a static counter to make sure we get a unique name. + static unsigned counter; + std::ostringstream new_name; + new_name << old_module->name.str() + << "_before_process_and_replace_module_" + << counter; + ++counter; + + design->rename(old_module, new_name.str()); + old_module->set_bool_attribute(ID::to_delete); + + // Check if the module was the top module. If it was, we need to remove + // the top attribute and put it on the new module. + bool is_top = false; + if (old_module->get_bool_attribute(ID::initial_top)) { + old_module->attributes.erase(ID::initial_top); + is_top = true; + } + + // Generate RTLIL from AST for the new module and add to the design: + RTLIL::Module* new_module = process_module(design, new_ast, false, std::move(original_ast)); + + if (is_top) + new_module->set_bool_attribute(ID::top); + + return new_module; +} + +// renames identifiers in tasks and functions within a package +static void rename_in_package_stmts(AstNode *pkg) +{ + std::unordered_set idents; + for (auto& item : pkg->children) + idents.insert(item->str); + std::function&)> rename = + [&rename, &idents, pkg](std::unique_ptr& node) { + for (auto& child : node->children) { + if (idents.count(child->str)) + child->str = pkg->str + "::" + child->str.substr(1); + rename(child); + } + }; + for (auto& item : pkg->children) + if (item->type == AST_FUNCTION || item->type == AST_TASK) + rename(item); +} + +// create AstModule instances for all modules in the AST tree and add them to 'design' +void AST::process(RTLIL::Design *design, AstNode *ast, bool nodisplay, bool dump_ast1, bool dump_ast2, bool no_dump_ptr, bool dump_vlog1, bool dump_vlog2, bool dump_rtlil, + bool nolatches, bool nomeminit, bool nomem2reg, bool mem2reg, bool noblackbox, bool lib, bool nowb, bool noopt, bool icells, bool pwires, bool nooverwrite, bool overwrite, bool defer, bool autowire, int unroll_limit) +{ + current_ast = ast; + current_ast_mod = nullptr; + flag_nodisplay = nodisplay; + flag_dump_ast1 = dump_ast1; + flag_dump_ast2 = dump_ast2; + flag_no_dump_ptr = no_dump_ptr; + flag_dump_vlog1 = dump_vlog1; + flag_dump_vlog2 = dump_vlog2; + flag_dump_rtlil = dump_rtlil; + flag_nolatches = nolatches; + flag_nomeminit = nomeminit; + flag_nomem2reg = nomem2reg; + flag_mem2reg = mem2reg; + flag_noblackbox = noblackbox; + flag_lib = lib; + flag_nowb = nowb; + flag_noopt = noopt; + flag_icells = icells; + flag_pwires = pwires; + flag_autowire = autowire; + flag_unroll_limit = unroll_limit; + + ast->fixup_hierarchy_flags(true); + + log_assert(current_ast->type == AST_DESIGN); + for (const auto& child : current_ast->children) + { + if (child->type == AST_MODULE || child->type == AST_INTERFACE) + { + for (auto& n : design->verilog_globals) + child->children.push_back(n->clone()); + + // append nodes from previous packages using package-qualified names + for (auto& n : design->verilog_packages) { + for (auto &o : n->children) { + auto cloned_node = o->clone(); + // log("cloned node %s\n", type2str(cloned_node->type)); + if (cloned_node->type == AST_ENUM) { + for (auto &e : cloned_node->children) { + log_assert(e->type == AST_ENUM_ITEM); + e->str = n->str + std::string("::") + e->str.substr(1); + } + } else { + cloned_node->str = n->str + std::string("::") + cloned_node->str.substr(1); + } + child->children.push_back(std::move(cloned_node)); + } + } + + if (flag_icells && child->str.compare(0, 2, "\\$") == 0) + child->str = child->str.substr(1); + + bool defer_local = defer; + if (!defer_local) + for (const auto& node : child->children) + if (node->type == AST_PARAMETER && param_has_no_default(node.get())) + { + log("Deferring `%s' because it contains parameter(s) without defaults.\n", child->str); + defer_local = true; + break; + } + + + if (defer_local) + child->str = "$abstract" + child->str; + + IdString mod_name = design->twines().find(child->str); + if (design->has(mod_name)) { + RTLIL::Module *existing_mod = design->module(mod_name); + if (!nooverwrite && !overwrite && !existing_mod->get_blackbox_attribute()) { + log_file_error(child->location.to_loc(), "Re-definition of module `%s'!\n", child->str); + } else if (nooverwrite) { + log("Ignoring re-definition of module `%s' at %s.\n", + child->str, child->loc_string()); + continue; + } else { + log("Replacing existing%s module `%s' at %s.\n", + existing_mod->get_bool_attribute(ID::blackbox) ? " blackbox" : "", + child->str, child->loc_string()); + design->remove(existing_mod); + } + } + + process_module(design, child.get(), defer_local); + current_ast_mod = nullptr; + } + else if (child->type == AST_PACKAGE) { + // process enum/other declarations + child->simplify(true, 1, -1, false); + rename_in_package_stmts(child.get()); + design->verilog_packages.push_back(child->clone()); + current_scope.clear(); + } + else { + // must be global definition + if (child->type == AST_PARAMETER) + child->type = AST_LOCALPARAM; // cannot be overridden + design->verilog_globals.push_back(child->clone()); + current_scope.clear(); + } + } + +} + +// An interface port with modport is specified like this: +// . +// This function splits the interface_name from the modport_name, and fails if it is not a valid combination +std::pair AST::split_modport_from_type(std::string name_type) +{ + std::string interface_type = ""; + std::string interface_modport = ""; + size_t ndots = std::count(name_type.begin(), name_type.end(), '.'); + // Separate the interface instance name from any modports: + if (ndots == 0) { // Does not have modport + interface_type = name_type; + } + else { + std::stringstream name_type_stream(name_type); + std::string segment; + std::vector seglist; + while(std::getline(name_type_stream, segment, '.')) { + seglist.push_back(segment); + } + if (ndots == 1) { // Has modport + interface_type = seglist[0]; + interface_modport = seglist[1]; + } + else { // Erroneous port type + log_error("More than two '.' in signal port type (%s)\n", name_type); + } + } + return std::pair(interface_type, interface_modport); + +} + +AstNode * AST::find_modport(AstNode *intf, std::string name) +{ + for (auto &ch : intf->children) + if (ch->type == AST_MODPORT) + if (ch->str == name) // Modport found + return ch.get(); + return NULL; +} + +// Iterate over all wires in an interface and add them as wires in the AST module: +void AST::explode_interface_port(AstNode *module_ast, RTLIL::Module * intfmodule, std::string intfname, AstNode *modport) +{ + for (auto w : intfmodule->wires()){ + auto loc = module_ast->location; + auto wire = std::make_unique(loc, AST_WIRE, std::make_unique(loc, AST_RANGE, AstNode::mkconst_int(loc, w->width -1, true), AstNode::mkconst_int(loc, 0, true))); + std::string origname = w->name.unescape(); + std::string newname = intfname + "." + origname; + wire->str = newname; + if (modport != NULL) { + bool found_in_modport = false; + // Search for the current wire in the wire list for the current modport + for (auto &ch : modport->children) { + if (ch->type == AST_MODPORTMEMBER) { + std::string compare_name = "\\" + origname; + if (ch->str == compare_name) { // Found signal. The modport decides whether it is input or output + found_in_modport = true; + wire->is_input = ch->is_input; + wire->is_output = ch->is_output; + break; + } + } + } + if (found_in_modport) { + module_ast->children.push_back(std::move(wire)); + } + } + else { // If no modport, set inout + wire->is_input = true; + wire->is_output = true; + module_ast->children.push_back(std::move(wire)); + } + } +} + +// AstModules may contain cells marked with ID::reprocess_after, which indicates +// that it should be reprocessed once the specified module has been elaborated. +bool AstModule::reprocess_if_necessary(RTLIL::Design *design) +{ + DesignScope design_scope(design); + for (const RTLIL::Cell *cell : cells()) + { + std::string modname = cell->get_string_attribute(ID::reprocess_after); + if (modname.empty()) + continue; + IdString mod_ref = design->twines().find(modname); + IdString abstract_ref = design->twines().find("$abstract" + modname); + if (design->module(mod_ref) || design->module(abstract_ref)) { + log("Reprocessing module %s because instantiated module %s has become available.\n", + PooledName(design, name).unescape(), RTLIL::unescape_id(modname)); + loadconfig(); + process_and_replace_module(design, this, ast.get(), NULL); + return true; + } + } + return false; +} + +// When an interface instance is found in a module, the whole RTLIL for the module will be rederived again +// from AST. The interface members are copied into the AST module with the prefix of the interface. +void AstModule::expand_interfaces(RTLIL::Design *design, const dict &local_interfaces) +{ + DesignScope design_scope(design); + loadconfig(); + + auto new_ast = ast->clone(); + auto loc = ast->location; + for (auto &intf : local_interfaces) { + std::string intfname = design->twines().str(intf.first); + RTLIL::Module *intfmodule = intf.second; + for (auto w : intfmodule->wires()){ + auto wire = std::make_unique(loc, AST_WIRE, std::make_unique(loc, AST_RANGE, AstNode::mkconst_int(loc, w->width -1, true), AstNode::mkconst_int(loc, 0, true))); + std::string newname = w->name.unescape(); + newname = intfname + "." + newname; + wire->str = newname; + new_ast->children.push_back(std::move(wire)); + } + } + + auto ast_before_replacing_interface_ports = new_ast->clone(); + + // Explode all interface ports. Note this will only have an effect on 'top + // level' modules. Other sub-modules will have their interface ports + // exploded via the derive(..) function + for (size_t i =0; ichildren.size(); i++) + { + const auto& ch2 = new_ast->children[i]; + if (ch2->type == AST_INTERFACEPORT) { // Is an interface port + std::string name_port = ch2->str; // Name of the interface port + if (ch2->children.size() > 0) { + for(size_t j=0; jchildren.size();j++) { + const auto& ch = ch2->children[j]; + if(ch->type == AST_INTERFACEPORTTYPE) { // Found the AST node containing the type of the interface + std::pair res = split_modport_from_type(ch->str); + std::string interface_type = res.first; + std::string interface_modport = res.second; // Is "", if no modport + IdString interface_type_ref = design->twines().find(interface_type); + if (design->module(interface_type_ref) != nullptr) { + // Add a cell to the module corresponding to the interface port such that + // it can further propagated down if needed: + auto celltype_for_intf = std::make_unique(loc, AST_CELLTYPE); + celltype_for_intf->str = interface_type; + auto cell_for_intf = std::make_unique(loc, AST_CELL, std::move(celltype_for_intf)); + cell_for_intf->str = name_port + "_inst_from_top_dummy"; + new_ast->children.push_back(std::move(cell_for_intf)); + + // Get all members of this non-overridden dummy interface instance: + RTLIL::Module *intfmodule = design->module(interface_type_ref); // All interfaces should at this point in time (assuming + // reprocess_module is called from the hierarchy pass) be + // present in design->modules_ + AstModule *ast_module_of_interface = (AstModule*)intfmodule; + std::string interface_modport_compare_str = "\\" + interface_modport; + AstNode *modport = find_modport(ast_module_of_interface->ast.get(), interface_modport_compare_str); // modport == NULL if no modport + // Iterate over all wires in the interface and add them to the module: + explode_interface_port(new_ast.get(), intfmodule, name_port, modport); + } + break; + } + } + } + } + } + + // Generate RTLIL from AST for the new module and add to the design, + // renaming this module to move it out of the way. + RTLIL::Module* new_module = + process_and_replace_module(design, this, new_ast.get(), std::move(ast_before_replacing_interface_ports)); + + // Set the attribute "interfaces_replaced_in_module" so that it does not happen again. + new_module->set_bool_attribute(ID::interfaces_replaced_in_module); +} + +// create a new parametric module (when needed) and return the name of the generated module - WITH support for interfaces +// This method is used to explode the interface when the interface is a port of the module (not instantiated inside) +RTLIL::IdString AstModule::derive(RTLIL::Design *design, const dict ¶meters, const dict &interfaces, const dict &modports, bool /*mayfail*/) +{ + DesignScope design_scope(design); + std::unique_ptr new_ast = NULL; + std::string modname = derive_common(design, parameters, &new_ast); + + // Since interfaces themselves may be instantiated with different parameters, + // "modname" must also take those into account, so that unique modules + // are derived for any variant of interface connections: + std::string interf_info = ""; + + bool has_interfaces = false; + for(auto &intf : interfaces) { + interf_info += intf.second->name.unescape(); + has_interfaces = true; + } + + std::string new_modname = modname; + if (has_interfaces) + new_modname += "$interfaces$" + interf_info; + + IdString new_modname_ref = design->twines().find(new_modname); + if (!design->has(new_modname_ref)) { + if (!new_ast) { + IdString modname_ref = design->twines().find(modname); + auto mod = dynamic_cast(design->module(modname_ref)); + new_ast = mod->ast->clone(); + } + modname = new_modname; + new_ast->str = modname; + + // Iterate over all interfaces which are ports in this module: + for(auto &intf : interfaces) { + RTLIL::Module * intfmodule = intf.second; + std::string intfname = design->twines().str(intf.first); + // Check if a modport applies for the interface port: + AstNode *modport = NULL; + if (modports.count(intf.first) > 0) { + std::string interface_modport = design->twines().str(modports.at(intf.first)); + AstModule *ast_module_of_interface = (AstModule*)intfmodule; + AstNode *ast_node_of_interface = ast_module_of_interface->ast.get(); + modport = find_modport(ast_node_of_interface, interface_modport); + } + // Iterate over all wires in the interface and add them to the module: + explode_interface_port(new_ast.get(), intfmodule, intfname, modport); + } + + process_module(design, new_ast.get(), false); + IdString new_ref = design->twines().find(modname); + design->module(new_ref)->check(); + + RTLIL::Module* mod = design->module(new_ref); + + // Now that the interfaces have been exploded, we can delete the dummy port related to every interface. + for(auto &intf : interfaces) { + IdString intf_name = intf.first; + if(mod->wire(intf_name) != nullptr) { + // Normally, removing wires would be batched together as it's an + // expensive operation, however, in this case doing so would mean + // that a cell with the same name cannot be created (below)... + // Since we won't expect many interfaces to exist in a module, + // we can let this slide... + pool to_remove; + to_remove.insert(mod->wire(intf_name)); + mod->remove(to_remove); + mod->fixup_ports(); + // We copy the cell of the interface to the sub-module such that it + // can further be found if it is propagated down to sub-sub-modules etc. + RTLIL::Cell *new_subcell = mod->addCell(intf.first, intf.second->name); + new_subcell->set_bool_attribute(ID::is_interface); + } + else { + log_error("No port with matching name found (%s) in %s. Stopping\n", mod->twines().str(intf.first), modname); + } + } + + // If any interfaces were replaced, set the attribute 'interfaces_replaced_in_module': + if (interfaces.size() > 0) { + mod->set_bool_attribute(ID::interfaces_replaced_in_module); + } + + } else { + modname = new_modname; + log("Found cached RTLIL representation for module `%s'.\n", modname); + } + + return design->twines().add(modname); +} + +// create a new parametric module (when needed) and return the name of the generated module - without support for interfaces +RTLIL::IdString AstModule::derive(RTLIL::Design *design, const dict ¶meters, bool /*mayfail*/) +{ + DesignScope design_scope(design); + bool quiet = lib || attributes.count(ID::blackbox) || attributes.count(ID::whitebox); + + std::unique_ptr new_ast = NULL; + std::string modname = derive_common(design, parameters, &new_ast, quiet); + + IdString modname_ref = design->twines().add(modname); + if (!design->has(modname_ref) && new_ast) { + new_ast->str = modname; + process_module(design, new_ast.get(), false, NULL, quiet); + design->module(modname_ref)->check(); + } else if (!quiet) { + log("Found cached RTLIL representation for module `%s'.\n", modname); + } + + return modname_ref; +} + +static std::string serialize_param_value(const RTLIL::Const &val) { + std::string res; + if (val.flags & RTLIL::ConstFlags::CONST_FLAG_STRING) + res.push_back('t'); + if (val.flags & RTLIL::ConstFlags::CONST_FLAG_SIGNED) + res.push_back('s'); + if (val.flags & RTLIL::ConstFlags::CONST_FLAG_REAL) + res.push_back('r'); + if (val.flags & RTLIL::ConstFlags::CONST_FLAG_UNSIZED) + res.push_back('u'); + else + res += stringf("%d", GetSize(val)); + res.push_back('\''); + res.append(val.as_string("?")); + return res; +} + +std::string AST::derived_module_name(std::string stripped_name, const std::vector> ¶meters) { + std::string para_info; + for (const auto &elem : parameters) + para_info += stringf("%s=%s", elem.first, serialize_param_value(elem.second)); + + if (para_info.size() > 60) + return "$paramod$" + sha1(para_info) + stripped_name; + else + return "$paramod" + stripped_name + para_info; +} + +// create a new parametric module (when needed) and return the name of the generated module +std::string AstModule::derive_common(RTLIL::Design *design, const dict ¶meters, std::unique_ptr* new_ast_out, bool quiet) +{ + std::string stripped_name = name.str(); + (*new_ast_out) = nullptr; + + if (stripped_name.compare(0, 9, "$abstract") == 0) + stripped_name = stripped_name.substr(9); + + int para_counter = 0; + std::vector> named_parameters; + for (const auto& child : ast->children) { + if (child->type != AST_PARAMETER) + continue; + para_counter++; + auto it = parameters.find(design->twines().find(child->str)); + if (it != parameters.end()) { + if (!quiet) + log("Parameter %s = %s\n", child->str, log_signal(it->second)); + named_parameters.emplace_back(child->str, it->second); + continue; + } + it = parameters.find(design->twines().find(stringf("$%d", para_counter))); + if (it != parameters.end()) { + if (!quiet) + log("Parameter %d (%s) = %s\n", para_counter, child->str, log_signal(it->second)); + named_parameters.emplace_back(child->str, it->second); + continue; + } + } + + std::string modname = stripped_name; + if (parameters.size()) // not named_parameters to cover hierarchical defparams + modname = derived_module_name(stripped_name, named_parameters); + + if (design->has(modname)) + return modname; + + if (!quiet) + log_header(design, "Executing AST frontend in derive mode using pre-parsed AST for module `%s'.\n", stripped_name); + loadconfig(); + + pool rewritten; + rewritten.reserve(GetSize(parameters)); + + auto new_ast = ast->clone(); + auto loc = ast->location; + if (!new_ast->attributes.count(ID::hdlname)) + new_ast->set_attribute(ID::hdlname, AstNode::mkconst_str(loc, stripped_name.substr(1))); + + para_counter = 0; + for (auto& child : new_ast->children) { + if (child->type != AST_PARAMETER) + continue; + para_counter++; + auto it = parameters.find(design->twines().find(child->str)); + if (it != parameters.end()) { + if (!quiet) + log("Parameter %s = %s\n", child->str, log_signal(it->second)); + goto rewrite_parameter; + } + it = parameters.find(design->twines().find(stringf("$%d", para_counter))); + if (it != parameters.end()) { + if (!quiet) + log("Parameter %d (%s) = %s\n", para_counter, child->str, log_signal(it->second)); + goto rewrite_parameter; + } + continue; + rewrite_parameter: + if (param_has_no_default(child.get())) + child->children.insert(child->children.begin(), nullptr); + if ((it->second.flags & RTLIL::CONST_FLAG_REAL) != 0) { + child->children[0] = std::make_unique(loc, AST_REALVALUE); + child->children[0]->realvalue = std::stod(it->second.decode_string()); + } else if ((it->second.flags & RTLIL::CONST_FLAG_STRING) != 0) + child->children[0] = AstNode::mkconst_str(loc, it->second.decode_string()); + else + child->children[0] = AstNode::mkconst_bits(loc, it->second.to_bits(), (it->second.flags & RTLIL::CONST_FLAG_SIGNED) != 0, (it->second.flags & RTLIL::CONST_FLAG_UNSIZED) != 0); + rewritten.insert(it->first); + } + + if (GetSize(rewritten) < GetSize(parameters)) + for (const auto ¶m : parameters) { + if (rewritten.count(param.first)) + continue; + auto defparam = std::make_unique(loc, AST_DEFPARAM, std::make_unique(loc, AST_IDENTIFIER)); + defparam->children[0]->str = design->twines().str(param.first); + if ((param.second.flags & RTLIL::CONST_FLAG_STRING) != 0) + defparam->children.push_back(AstNode::mkconst_str(loc, param.second.decode_string())); + else + defparam->children.push_back(AstNode::mkconst_bits(loc, param.second.to_bits(), (param.second.flags & RTLIL::CONST_FLAG_SIGNED) != 0)); + new_ast->children.push_back(std::move(defparam)); + } + + new_ast->fixup_hierarchy_flags(true); + new_ast_out->reset(new_ast.release()); + return modname; +} + +RTLIL::Module *AstModule::clone() const +{ + AstModule *new_mod = new AstModule(design); + new_mod->name = name; + cloneInto(new_mod); + copy_config_into(new_mod); + + return new_mod; +} + +RTLIL::Module *AstModule::clone(RTLIL::Design *dst) const +{ + return clone(dst, dst->twines().copy_from(design->twines(), name)); +} + +RTLIL::Module *AstModule::clone(RTLIL::Design *dst, IdString target_name) const +{ + AstModule *new_mod = new AstModule(dst); + new_mod->name = target_name; + cloneInto(new_mod); + dst->add(new_mod); + copy_config_into(new_mod); + + return new_mod; +} + +void AstModule::copy_config_into(AstModule *new_mod) const +{ + DesignScope design_scope(new_mod->design); + new_mod->ast = ast->clone(); + new_mod->nolatches = nolatches; + new_mod->nomeminit = nomeminit; + new_mod->nomem2reg = nomem2reg; + new_mod->mem2reg = mem2reg; + new_mod->noblackbox = noblackbox; + new_mod->lib = lib; + new_mod->nowb = nowb; + new_mod->noopt = noopt; + new_mod->icells = icells; + new_mod->pwires = pwires; + new_mod->autowire = autowire; +} + +void AstModule::loadconfig() const +{ + current_ast = NULL; + flag_dump_ast1 = false; + flag_dump_ast2 = false; + flag_dump_vlog1 = false; + flag_dump_vlog2 = false; + flag_nolatches = nolatches; + flag_nomeminit = nomeminit; + flag_nomem2reg = nomem2reg; + flag_mem2reg = mem2reg; + flag_noblackbox = noblackbox; + flag_lib = lib; + flag_nowb = nowb; + flag_noopt = noopt; + flag_icells = icells; + flag_pwires = pwires; + flag_autowire = autowire; +} + +void AstNode::formatted_input_error(std::string_view format, std::string str) const +{ + logger().formatted_error(location.to_loc(), "ERROR:", format, std::move(str)); +} + +YOSYS_NAMESPACE_END diff --git a/chips/yosys/frontends/ast/ast.h b/chips/yosys/frontends/ast/ast.h new file mode 100644 index 0000000000000000000000000000000000000000..0f4f2fcbea05c64c793c6b2e247678bf2f2d6768 --- /dev/null +++ b/chips/yosys/frontends/ast/ast.h @@ -0,0 +1,501 @@ +/* -*- c++ -*- + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * --- + * + * The AST frontend library is not a frontend on its own but provides an + * abstract syntax tree (AST) abstraction for the open source Verilog frontend + * at frontends/verilog. + * + */ + +#ifndef AST_H +#define AST_H + +#include "kernel/rtlil.h" +#include "kernel/fmt.h" +#include "frontends/verilog/verilog_location.h" +#include +#include + +YOSYS_NAMESPACE_BEGIN + +namespace AST +{ + TwinePool &ast_name_pool(); + inline IdString intern_attr_name(std::string_view name) { return ast_name_pool().add(name); } + inline std::string attr_name_str(IdString id) { return ast_name_pool().str(id); } + + struct DesignScope { + explicit DesignScope(RTLIL::Design *design); + ~DesignScope(); + private: + RTLIL::Design *prev; + }; + int ast_autoidx(); + + // all node types, type2str() must be extended + // whenever a new node type is added here + enum AstNodeType + { + AST_NONE, + AST_DESIGN, + AST_MODULE, + AST_TASK, + AST_FUNCTION, + AST_DPI_FUNCTION, + + AST_WIRE, + AST_MEMORY, + AST_AUTOWIRE, + AST_PARAMETER, + AST_LOCALPARAM, + AST_DEFPARAM, + AST_PARASET, + AST_ARGUMENT, + AST_RANGE, + AST_MULTIRANGE, + AST_CONSTANT, + AST_REALVALUE, + AST_CELLTYPE, + AST_IDENTIFIER, + AST_PREFIX, + AST_ASSERT, + AST_ASSUME, + AST_LIVE, + AST_FAIR, + AST_COVER, + AST_ENUM, + AST_ENUM_ITEM, + + AST_FCALL, + AST_TO_BITS, + AST_TO_SIGNED, + AST_TO_UNSIGNED, + AST_SELFSZ, + AST_CAST_SIZE, + AST_CONCAT, + AST_REPLICATE, + AST_ASSIGN_PATTERN, + AST_BIT_NOT, + AST_BIT_AND, + AST_BIT_OR, + AST_BIT_XOR, + AST_BIT_XNOR, + AST_REDUCE_AND, + AST_REDUCE_OR, + AST_REDUCE_XOR, + AST_REDUCE_XNOR, + AST_REDUCE_BOOL, + AST_SHIFT_LEFT, + AST_SHIFT_RIGHT, + AST_SHIFT_SLEFT, + AST_SHIFT_SRIGHT, + AST_SHIFTX, + AST_SHIFT, + AST_LT, + AST_LE, + AST_EQ, + AST_NE, + AST_EQX, + AST_NEX, + AST_GE, + AST_GT, + AST_ADD, + AST_SUB, + AST_MUL, + AST_DIV, + AST_MOD, + AST_POW, + AST_POS, + AST_NEG, + AST_LOGIC_AND, + AST_LOGIC_OR, + AST_LOGIC_NOT, + AST_TERNARY, + AST_MEMRD, + AST_MEMWR, + AST_MEMINIT, + + AST_TCALL, + AST_ASSIGN, + AST_CELL, + AST_PRIMITIVE, + AST_CELLARRAY, + AST_ALWAYS, + AST_INITIAL, + AST_BLOCK, + AST_ASSIGN_EQ, + AST_ASSIGN_LE, + AST_CASE, + AST_COND, + AST_CONDX, + AST_CONDZ, + AST_DEFAULT, + AST_FOR, + AST_WHILE, + AST_REPEAT, + + AST_GENVAR, + AST_GENFOR, + AST_GENIF, + AST_GENCASE, + AST_GENBLOCK, + AST_TECALL, + + AST_POSEDGE, + AST_NEGEDGE, + AST_EDGE, + + AST_INTERFACE, + AST_INTERFACEPORT, + AST_INTERFACEPORTTYPE, + AST_MODPORT, + AST_MODPORTMEMBER, + AST_PACKAGE, + AST_IMPORT, + + AST_WIRETYPE, + AST_TYPEDEF, + AST_STRUCT, + AST_UNION, + AST_STRUCT_ITEM + }; + + using AstSrcLocType = Location; + + // convert an node type to a string (e.g. for debug output) + std::string type2str(AstNodeType type); + + // The AST is built using instances of this struct + struct AstNode + { + // for dict<> and pool<> + unsigned int hashidx_; + [[nodiscard]] Hasher hash_into(Hasher h) const { h.eat(hashidx_); return h; } + + // this nodes type + AstNodeType type; + + // the list of child nodes for this node + std::vector> children; + + // The list of attributes assigned to this node. Keys are IdStrings + std::map> attributes; + bool get_bool_attribute(IdString id); + bool get_bool_attribute(const std::string &id) { return get_bool_attribute(intern_attr_name(id)); } + + // node content - most of it is unused in most node types + std::string str; + std::vector bits; + bool is_input, is_output, is_reg, is_logic, is_signed, is_string, is_wand, is_wor, range_valid, range_swapped, was_checked, is_unsized, is_custom_type; + int port_id, range_left, range_right; + uint32_t integer; + double realvalue; + // set for IDs typed to an enumeration, not used + bool is_enum; + + // Declared range for array dimension. + struct dimension_t { + int range_right; // lsb in [msb:lsb] + int range_width; // msb - lsb + 1 + bool range_swapped; // if the declared msb < lsb, msb and lsb above are swapped + }; + // Packed and unpacked dimensions for arrays. + // Unpacked dimensions go first, to follow the order of indexing. + std::vector dimensions; + // Number of unpacked dimensions. + int unpacked_dimensions; + + // this is set by simplify and used during RTLIL generation + AstNode* id2ast; + + // this is used by simplify to detect if basic analysis has been performed already on the node + bool basic_prep; + + // this is used for ID references in RHS expressions that should use the "new" value for non-blocking assignments + bool lookahead; + + // this is the original sourcecode location that resulted in this AST node + // it is automatically set by the constructor using AST::current_filename and + // the AST::get_line_num() callback function. + AstSrcLocType location; + + // are we embedded in an lvalue, param? + // (see fixup_hierarchy_flags) + bool in_lvalue; + bool in_param; + bool in_lvalue_from_above; + bool in_param_from_above; + + // creating and deleting nodes + AstNode(AstSrcLocType loc, AstNodeType type = AST_NONE, std::unique_ptr child1 = nullptr, std::unique_ptr child2 = nullptr, std::unique_ptr child3 = nullptr, std::unique_ptr child4 = nullptr); + std::unique_ptr clone() const; + void cloneInto(AstNode &other) const; + void delete_children(); + ~AstNode(); + + enum mem2reg_flags + { + /* status flags */ + MEM2REG_FL_ALL = 0x00000001, + MEM2REG_FL_ASYNC = 0x00000002, + MEM2REG_FL_INIT = 0x00000004, + + /* candidate flags */ + MEM2REG_FL_FORCED = 0x00000100, + MEM2REG_FL_SET_INIT = 0x00000200, + MEM2REG_FL_SET_ELSE = 0x00000400, + MEM2REG_FL_SET_ASYNC = 0x00000800, + MEM2REG_FL_EQ2 = 0x00001000, + MEM2REG_FL_CMPLX_LHS = 0x00002000, + MEM2REG_FL_CONST_LHS = 0x00004000, + MEM2REG_FL_VAR_LHS = 0x00008000, + + /* proc flags */ + MEM2REG_FL_EQ1 = 0x01000000, + }; + + // simplify() creates a simpler AST by unrolling for-loops, expanding generate blocks, etc. + // it also sets the id2ast pointers so that identifier lookups are fast in genRTLIL() + bool simplify(bool const_fold, int stage, int width_hint, bool sign_hint); + void replace_result_wire_name_in_function(const std::string &from, const std::string &to); + std::unique_ptr readmem(bool is_readmemh, std::string mem_filename, AstNode *memory, int start_addr, int finish_addr, bool unconditional_init); + void expand_genblock(const std::string &prefix); + void label_genblks(std::set& existing, int &counter); + void mem2reg_as_needed_pass1(dict> &mem2reg_places, + dict &mem2reg_flags, dict &proc_flags, uint32_t &status_flags); + bool mem2reg_as_needed_pass2(pool &mem2reg_set, AstNode *mod, AstNode *block, AstNode* async_block); + bool mem2reg_check(pool &mem2reg_set); + void mem2reg_remove(pool &mem2reg_set); + void meminfo(int &mem_width, int &mem_size, int &addr_bits); + bool detect_latch(const std::string &var); + const RTLIL::Module* lookup_cell_module(); + + // additional functionality for evaluating constant functions + struct varinfo_t { + RTLIL::Const val; + int offset; + bool range_swapped; + bool is_signed; + AstNode *arg = nullptr; + bool explicitly_sized; + }; + bool has_const_only_constructs(); + bool replace_variables(std::map &variables, AstNode *fcall, bool must_succeed); + std::unique_ptr eval_const_function(AstNode *fcall, bool must_succeed); + bool is_simple_const_expr(); + bool is_in_unconditional_init(); + + // helper for parsing format strings + Fmt processFormat(int stage, bool sformat_like, int default_base = 10, size_t first_arg_at = 0, bool may_fail = false); + + bool is_recursive_function() const; + std::pair get_tern_choice(); + + // create a human-readable text representation of the AST (for debugging) + void dumpAst(FILE *f, std::string indent) const; + void dumpVlog(FILE *f, std::string indent) const; + + // used by genRTLIL() for detecting expression width and sign + void detectSignWidthWorker(int &width_hint, bool &sign_hint, bool *found_real = nullptr); + void detectSignWidth(int &width_hint, bool &sign_hint, bool *found_real = nullptr); + + // create RTLIL code for this AST node + // for expressions the resulting signal vector is returned + // all generated cell instances, etc. are written to the RTLIL::Module pointed to by AST_INTERNAL::current_module + RTLIL::SigSpec genRTLIL(int width_hint = -1, bool sign_hint = false); + RTLIL::SigSpec genWidthRTLIL(int width, bool sgn, const dict *new_subst_ptr = nullptr); + + // compare AST nodes + bool operator==(const AstNode &other) const; + bool operator!=(const AstNode &other) const; + bool contains(const AstNode *other) const; + AstNode operator=(AstNode) = delete; + + // helper functions for creating AST nodes for constants + static std::unique_ptr mkconst_int(AstSrcLocType loc, uint32_t v, bool is_signed, int width = 32); + static std::unique_ptr mkconst_bits(AstSrcLocType loc, const std::vector &v, bool is_signed, bool is_unsized); + static std::unique_ptr mkconst_bits(AstSrcLocType loc, const std::vector &v, bool is_signed); + static std::unique_ptr mkconst_str(AstSrcLocType loc, const std::vector &v); + static std::unique_ptr mkconst_str(AstSrcLocType loc, const std::string &str); + + // helper function to create an AST node for a temporary register + std::unique_ptr mktemp_logic(AstSrcLocType loc, const std::string &name, AstNode *mod, bool nosync, int range_left, int range_right, bool is_signed); + + // helper function for creating sign-extended const objects + RTLIL::Const bitsAsConst(int width, bool is_signed); + RTLIL::Const bitsAsConst(int width = -1); + RTLIL::Const bitsAsUnsizedConst(int width); + RTLIL::Const asAttrConst() const; + RTLIL::Const asParaConst() const; + uint64_t asInt(bool is_signed); + bool bits_only_01() const; + bool asBool() const; + + // helper functions for real valued const eval + int isConst() const; // return '1' for AST_CONSTANT and '2' for AST_REALVALUE + double asReal(bool is_signed); + RTLIL::Const realAsConst(int width); + RTLIL::Const valueAsConst(int width); + + // helpers for enum + void allocateDefaultEnumValues(); + void annotateTypedEnums(AstNode *template_node); + + // helpers for locations + std::string loc_string() const; + + // Helper for looking up identifiers which are prefixed with the current module name + std::string try_pop_module_prefix() const; + + // helper to clone the node with some of its subexpressions replaced with zero (this is used + // to evaluate widths of dynamic ranges) + std::unique_ptr clone_at_zero(); + + void set_attribute(RTLIL::IdString key, std::unique_ptr node) + { + node->set_in_param_flag(true); + attributes[key] = std::move(node); + } + void set_attribute(const std::string &key, std::unique_ptr node) + { + set_attribute(intern_attr_name(key), std::move(node)); + } + + // helper to set in_lvalue/in_param flags from the hierarchy context (the actual flag + // can be overridden based on the intrinsic properties of this node, i.e. based on its type) + void set_in_lvalue_flag(bool flag, bool no_descend = false); + void set_in_param_flag(bool flag, bool no_descend = false); + + // fix up the hierarchy flags (in_lvalue/in_param) of this node and its children + // + // to keep the flags in sync, fixup_hierarchy_flags(true) needs to be called once after + // parsing the AST to walk the full tree, then plain fixup_hierarchy_flags() performs + // localized fixups after modifying children/attributes of a particular node + void fixup_hierarchy_flags(bool force_descend = false); + + // helpers for indexing + std::unique_ptr make_index_range(AstNode *node, bool unpacked_range = false); + AstNode *get_struct_member() const; + + // helper to print errors from simplify/genrtlil code + [[noreturn]] void formatted_input_error(std::string_view format, std::string str) const; + template + [[noreturn]] void input_error(FmtString...> fmt, const Args &... args) const + { + formatted_input_error(fmt.format_string(), fmt.format(args...)); + } + }; + + // process an AST tree (ast must point to an AST_DESIGN node) and generate RTLIL code + void process(RTLIL::Design *design, AstNode *ast, bool nodisplay, bool dump_ast1, bool dump_ast2, bool no_dump_ptr, bool dump_vlog1, bool dump_vlog2, bool dump_rtlil, bool nolatches, bool nomeminit, + bool nomem2reg, bool mem2reg, bool noblackbox, bool lib, bool nowb, bool noopt, bool icells, bool pwires, bool nooverwrite, bool overwrite, bool defer, bool autowire, int unroll_limit); + + // parametric modules are supported directly by the AST library + // therefore we need our own derivate of RTLIL::Module with overloaded virtual functions + struct AstModule : RTLIL::Module { + using RTLIL::Module::Module; + + std::unique_ptr ast; + bool nolatches, nomeminit, nomem2reg, mem2reg, noblackbox, lib, nowb, noopt, icells, pwires, autowire; + RTLIL::IdString derive(RTLIL::Design *design, const dict ¶meters, bool mayfail) override; + RTLIL::IdString derive(RTLIL::Design *design, const dict ¶meters, const dict &interfaces, const dict &modports, bool mayfail) override; + std::string derive_common(RTLIL::Design *design, const dict ¶meters, std::unique_ptr* new_ast_out, bool quiet = false); + void expand_interfaces(RTLIL::Design *design, const dict &local_interfaces) override; + bool reprocess_if_necessary(RTLIL::Design *design) override; + RTLIL::Module *clone() const override; + RTLIL::Module *clone(RTLIL::Design *dst) const override; + RTLIL::Module *clone(RTLIL::Design *dst, IdString target_name) const override; + void copy_config_into(AstModule *new_mod) const; + void loadconfig() const; + }; + + // this must be set by the language frontend before parsing the sources + // the AstNode constructor then uses current_filename and get_line_num() + // to initialize the filename and linenum properties of new nodes + // extern std::string current_filename; + // also set by the language frontend to control some AST processing + extern bool sv_mode_but_global_and_used_for_literally_one_condition; + + // for stats + unsigned long long astnode_count(); + + // set set_line_num and get_line_num to internal dummy functions (done by simplify() and AstModule::derive + // to control the filename and linenum properties of new nodes not generated by a frontend parser) + void use_internal_line_num(); + + // call a DPI function + std::unique_ptr dpi_call(AstSrcLocType loc, const std::string &rtype, const std::string &fname, const std::vector &argtypes, const std::vector> &args); + + // Helper functions related to handling SystemVerilog interfaces + std::pair split_modport_from_type(std::string name_type); + AstNode * find_modport(AstNode *intf, std::string name); + void explode_interface_port(AstNode *module_ast, RTLIL::Module * intfmodule, std::string intfname, AstNode *modport); + + IdString intern_hier_name(RTLIL::Design *design, std::string_view escaped); + + IdString intern_src_loc(RTLIL::Design *design, const AstSrcLocType &location); + IdString intern_src_name(RTLIL::Design *design, const AstSrcLocType &location, + std::string_view kind, int idx); + + // Helper for setting the src attribute. + void set_src_attr(RTLIL::AttrObject *obj, const AstNode *ast); + + // generate standard $paramod... derived module name; parameters should be + // in the order they are declared in the instantiated module + std::string derived_module_name(std::string stripped_name, const std::vector> ¶meters); + + // used to provide simplify() access to the current design for looking up + // modules, ports, wires, etc. + void set_simplify_design_context(const RTLIL::Design *design); +} + +namespace AST_INTERNAL +{ + // internal state variables + extern bool flag_nodisplay, flag_dump_ast1, flag_dump_ast2, flag_no_dump_ptr, flag_dump_rtlil, flag_nolatches, flag_nomeminit; + extern bool flag_nomem2reg, flag_mem2reg, flag_lib, flag_noopt, flag_icells, flag_pwires, flag_autowire; + extern int flag_unroll_limit; + extern AST::AstNode *current_ast, *current_ast_mod; + extern std::map current_scope; + extern const dict *genRTLIL_subst_ptr; + extern RTLIL::SigSpec ignoreThisSignalsInInitial; + extern AST::AstNode *current_always, *current_top_block, *current_block, *current_block_child; + extern RTLIL::Module *current_module; + extern bool current_always_clocked; + extern dict current_memwr_count; + extern dict> current_memwr_visible; + struct LookaheadRewriter; + struct ProcessGenerator; + + // Create and add a new AstModule from new_ast, then use it to replace + // old_module in design, renaming old_module to move it out of the way. + // Return the new module. + // + // If original_ast is not null, it will be used as the AST node for the + // new module. Otherwise, new_ast will be used. + RTLIL::Module * + process_and_replace_module(RTLIL::Design *design, + RTLIL::Module *old_module, + AST::AstNode *new_ast, + std::unique_ptr original_ast = nullptr); +} + +YOSYS_NAMESPACE_END + +#endif diff --git a/chips/yosys/frontends/ast/dpicall.cc b/chips/yosys/frontends/ast/dpicall.cc new file mode 100644 index 0000000000000000000000000000000000000000..322873d43586981bd4558e294c73d8bdbd05e196 --- /dev/null +++ b/chips/yosys/frontends/ast/dpicall.cc @@ -0,0 +1,163 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "ast.h" + +#ifdef YOSYS_ENABLE_LIBFFI + +#include +#include + +YOSYS_NAMESPACE_BEGIN + +typedef void (*ffi_fptr) (); + +static ffi_fptr resolve_fn (std::string symbol_name) +{ + if (symbol_name.find(':') != std::string::npos) + { + int pos = symbol_name.find(':'); + std::string plugin_name = symbol_name.substr(0, pos); + std::string real_symbol_name = symbol_name.substr(pos+1); + + while (loaded_plugin_aliases.count(plugin_name)) + plugin_name = loaded_plugin_aliases.at(plugin_name); + + if (loaded_plugins.count(plugin_name) == 0) + log_error("unable to resolve '%s': can't find plugin `%s'\n", symbol_name, plugin_name); + + void *symbol = dlsym(loaded_plugins.at(plugin_name), real_symbol_name.c_str()); + + if (symbol == nullptr) + log_error("unable to resolve '%s': can't find symbol `%s' in plugin `%s'\n", + symbol_name, real_symbol_name, plugin_name); + + return (ffi_fptr) symbol; + } + + for (auto &it : loaded_plugins) { + void *symbol = dlsym(it.second, symbol_name.c_str()); + if (symbol != nullptr) + return (ffi_fptr) symbol; + } + + void *symbol = dlsym(RTLD_DEFAULT, symbol_name.c_str()); + if (symbol != nullptr) + return (ffi_fptr) symbol; + + log_error("unable to resolve '%s'.\n", symbol_name); +} + +std::unique_ptr AST::dpi_call(AstSrcLocType loc, const std::string &rtype, const std::string &fname, const std::vector &argtypes, const std::vector> &args) +{ + std::unique_ptr newNode = nullptr; + union value { double f64; float f32; int32_t i32; void *ptr; }; + std::vector value_store(args.size() + 1); + std::vector types(args.size() + 1); + std::vector values(args.size() + 1); + ffi_cif cif; + int status; + + log("Calling DPI function `%s' and returning `%s':\n", fname, rtype); + + log_assert(GetSize(args) == GetSize(argtypes)); + for (int i = 0; i < GetSize(args); i++) { + if (argtypes[i] == "real") { + log(" arg %d (%s): %f\n", i, argtypes[i], args[i]->asReal(args[i]->is_signed)); + value_store[i].f64 = args[i]->asReal(args[i]->is_signed); + values[i] = &value_store[i].f64; + types[i] = &ffi_type_double; + } else if (argtypes[i] == "shortreal") { + log(" arg %d (%s): %f\n", i, argtypes[i], args[i]->asReal(args[i]->is_signed)); + value_store[i].f32 = args[i]->asReal(args[i]->is_signed); + values[i] = &value_store[i].f32; + types[i] = &ffi_type_double; + } else if (argtypes[i] == "integer") { + log(" arg %d (%s): %lld\n", i, argtypes[i], (long long)args[i]->asInt(args[i]->is_signed)); + value_store[i].i32 = args[i]->asInt(args[i]->is_signed); + values[i] = &value_store[i].i32; + types[i] = &ffi_type_sint32; + } else if (argtypes[i] == "chandle") { + log(" arg %d (%s): %llx\n", i, argtypes[i], (unsigned long long)args[i]->asInt(false)); + value_store[i].ptr = (void *)args[i]->asInt(args[i]->is_signed); + values[i] = &value_store[i].ptr; + types[i] = &ffi_type_pointer; + } else { + log_error("invalid argtype '%s' for argument %d.\n", argtypes[i], i); + } + } + + if (rtype == "integer") { + types[args.size()] = &ffi_type_slong; + values[args.size()] = &value_store[args.size()].i32; + } else if (rtype == "shortreal") { + types[args.size()] = &ffi_type_float; + values[args.size()] = &value_store[args.size()].f32; + } else if (rtype == "real") { + types[args.size()] = &ffi_type_double; + values[args.size()] = &value_store[args.size()].f64; + } else if (rtype == "chandle") { + types[args.size()] = &ffi_type_pointer; + values[args.size()] = &value_store[args.size()].ptr; + } else { + log_error("invalid rtype '%s'.\n", rtype); + } + + if ((status = ffi_prep_cif(&cif, FFI_DEFAULT_ABI, args.size(), types[args.size()], types.data())) != FFI_OK) + log_error("ffi_prep_cif failed: status %d.\n", status); + + ffi_call(&cif, resolve_fn(fname.c_str()), values[args.size()], values.data()); + + if (rtype == "real") { + newNode = std::make_unique(loc, AST_REALVALUE); + newNode->realvalue = value_store[args.size()].f64; + log(" return realvalue: %g\n", newNode->asReal(true)); + } else if (rtype == "shortreal") { + newNode = std::make_unique(loc, AST_REALVALUE); + newNode->realvalue = value_store[args.size()].f32; + log(" return realvalue: %g\n", newNode->asReal(true)); + } else if (rtype == "chandle") { + uint64_t rawval = (uint64_t)value_store[args.size()].ptr; + std::vector bits(64); + for (int i = 0; i < 64; i++) + bits.at(i) = (rawval & (1ULL << i)) ? RTLIL::State::S1 : RTLIL::State::S0; + newNode = AstNode::mkconst_bits(loc, bits, false); + log(" return chandle: %llx\n", (unsigned long long)newNode->asInt(false)); + } else { + newNode = AstNode::mkconst_int(loc, value_store[args.size()].i32, false); + log(" return integer: %lld\n", (long long)newNode->asInt(true)); + } + + return newNode; +} + +YOSYS_NAMESPACE_END + +#else /* YOSYS_ENABLE_LIBFFI */ + +YOSYS_NAMESPACE_BEGIN + +std::unique_ptr AST::dpi_call(AstSrcLocType, const std::string&, const std::string &fname, const std::vector&, const std::vector>&) +{ + log_error("Can't call DPI function `%s': this version of yosys is built without plugin support\n", fname); +} + +YOSYS_NAMESPACE_END + +#endif /* YOSYS_ENABLE_LIBFFI */ diff --git a/chips/yosys/frontends/ast/genrtlil.cc b/chips/yosys/frontends/ast/genrtlil.cc new file mode 100644 index 0000000000000000000000000000000000000000..1225bb1697812119ad6fb31936f393e3af09cb75 --- /dev/null +++ b/chips/yosys/frontends/ast/genrtlil.cc @@ -0,0 +1,2341 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * --- + * + * This is the AST frontend library. + * + * The AST frontend library is not a frontend on it's own but provides a + * generic abstract syntax tree (AST) abstraction for HDL code and can be + * used by HDL frontends. See "ast.h" for an overview of the API and the + * Verilog frontend for an usage example. + * + */ + +#include "kernel/log.h" +#include "kernel/twine.h" +#include "kernel/utils.h" +#include "libs/sha1/sha1.h" +#include "ast.h" + +#include +#include +#include + +YOSYS_NAMESPACE_BEGIN + +using namespace AST; +using namespace AST_INTERNAL; + +// helper function for creating RTLIL code for unary operations +static RTLIL::SigSpec uniop2rtlil(AstNode *that, IdString type, int result_width, const RTLIL::SigSpec &arg, bool gen_attributes = true) +{ + IdString name = intern_src_name(current_module->design, that->location, + current_module->twines().str(type), ast_autoidx()); + RTLIL::Cell *cell = current_module->addCell(name, type); + set_src_attr(cell, that); + + RTLIL::Wire *wire = current_module->addWire(TwineSpec::Suffix{cell->name, "_Y"}, result_width); + set_src_attr(wire, that); + wire->is_signed = that->is_signed; + + if (gen_attributes) + for (auto &attr : that->attributes) { + if (attr.second->type != AST_CONSTANT) + that->input_error("Attribute `%s' with non-constant value!\n", attr_name_str(attr.first)); + cell->attributes[current_module->twines().add(attr_name_str(attr.first))] = attr.second->asAttrConst(); + } + + cell->parameters[ID::A_SIGNED] = RTLIL::Const(that->children[0]->is_signed); + cell->parameters[ID::A_WIDTH] = RTLIL::Const(arg.size()); + cell->setPort(ID::A, arg); + + cell->parameters[ID::Y_WIDTH] = result_width; + cell->setPort(ID::Y, wire); + return wire; +} + +// helper function for extending bit width (preferred over SigSpec::extend() because of correct undef propagation in ConstEval) +static void widthExtend(AstNode *that, RTLIL::SigSpec &sig, int width, bool is_signed) +{ + if (width <= sig.size()) { + sig.extend_u0(width, is_signed); + return; + } + + IdString name = intern_src_name(current_module->design, that->location, "$extend", ast_autoidx()); + RTLIL::Cell *cell = current_module->addCell(name, ID($pos)); + set_src_attr(cell, that); + + RTLIL::Wire *wire = current_module->addWire(cell->name.str() + "_Y", width); + set_src_attr(wire, that); + wire->is_signed = that->is_signed; + + if (that != nullptr) + for (auto &attr : that->attributes) { + if (attr.second->type != AST_CONSTANT) + that->input_error("Attribute `%s' with non-constant value!\n", attr_name_str(attr.first)); + cell->attributes[current_module->twines().add(attr_name_str(attr.first))] = attr.second->asAttrConst(); + } + + cell->parameters[ID::A_SIGNED] = RTLIL::Const(is_signed); + cell->parameters[ID::A_WIDTH] = RTLIL::Const(sig.size()); + cell->setPort(ID::A, sig); + + cell->parameters[ID::Y_WIDTH] = width; + cell->setPort(ID::Y, wire); + sig = wire; +} + +// helper function for creating RTLIL code for binary operations +static RTLIL::SigSpec binop2rtlil(AstNode *that, IdString type, int result_width, const RTLIL::SigSpec &left, const RTLIL::SigSpec &right) +{ + IdString name = intern_src_name(current_module->design, that->location, + current_module->twines().str(type), ast_autoidx()); + RTLIL::Cell *cell = current_module->addCell(name, type); + set_src_attr(cell, that); + + RTLIL::Wire *wire = current_module->addWire(TwineSpec::Suffix{cell->name, "_Y"}, result_width); + set_src_attr(wire, that); + wire->is_signed = that->is_signed; + + for (auto &attr : that->attributes) { + if (attr.second->type != AST_CONSTANT) + that->input_error("Attribute `%s' with non-constant value!\n", attr_name_str(attr.first)); + cell->attributes[current_module->twines().add(attr_name_str(attr.first))] = attr.second->asAttrConst(); + } + + cell->parameters[ID::A_SIGNED] = RTLIL::Const(that->children[0]->is_signed); + cell->parameters[ID::B_SIGNED] = RTLIL::Const(that->children[1]->is_signed); + + cell->parameters[ID::A_WIDTH] = RTLIL::Const(left.size()); + cell->parameters[ID::B_WIDTH] = RTLIL::Const(right.size()); + + cell->setPort(ID::A, left); + cell->setPort(ID::B, right); + + cell->parameters[ID::Y_WIDTH] = result_width; + cell->setPort(ID::Y, wire); + return wire; +} + +// helper function for creating RTLIL code for multiplexers +static RTLIL::SigSpec mux2rtlil(AstNode *that, const RTLIL::SigSpec &cond, const RTLIL::SigSpec &left, const RTLIL::SigSpec &right) +{ + log_assert(cond.size() == 1); + + IdString name = intern_src_name(current_module->design, that->location, "$ternary", ast_autoidx()); + + RTLIL::Cell *cell = current_module->addCell(name, ID($mux)); + set_src_attr(cell, that); + + RTLIL::Wire *wire = current_module->addWire(cell->name.str() + "_Y", left.size()); + set_src_attr(wire, that); + wire->is_signed = that->is_signed; + + for (auto &attr : that->attributes) { + if (attr.second->type != AST_CONSTANT) + that->input_error("Attribute `%s' with non-constant value!\n", attr_name_str(attr.first)); + cell->attributes[current_module->twines().add(attr_name_str(attr.first))] = attr.second->asAttrConst(); + } + + cell->parameters[ID::WIDTH] = RTLIL::Const(left.size()); + + cell->setPort(ID::A, right); + cell->setPort(ID::B, left); + cell->setPort(ID::S, cond); + cell->setPort(ID::Y, wire); + + return wire; +} + +static void check_unique_id(RTLIL::Module *module, IdString id, + const AstNode *node, const char *to_add_kind) +{ + auto already_exists = [&](const RTLIL::AttrObject *existing, const char *existing_kind) { + std::string src = existing->get_string_attribute(ID::src); + std::string location_str = "earlier"; + if (!src.empty()) + location_str = "at " + src; + node->input_error("Cannot add %s `%s' because a %s with the same name was already created %s!\n", + to_add_kind, module->twines().str(id), existing_kind, location_str.c_str()); + }; + + if (const RTLIL::Wire *wire = module->wire(id)) + already_exists(wire, "signal"); + if (const RTLIL::Cell *cell = module->cell(id)) + already_exists(cell, "cell"); + if (module->processes.count(id)) + already_exists(module->processes.at(id), "process"); + if (module->memories.count(id)) + already_exists(module->memories.at(id), "memory"); +} + +static void check_unique_id(RTLIL::Module *module, const std::string &id, + const AstNode *node, const char *to_add_kind) +{ + check_unique_id(module, intern_hier_name(module->design, id), node, to_add_kind); +} + +// helper class for rewriting simple lookahead references in AST always blocks +struct AST_INTERNAL::LookaheadRewriter +{ + dict> lookaheadids; + + void collect_lookaheadids(AstNode *node) + { + if (node->lookahead) { + log_assert(node->type == AST_IDENTIFIER); + if (!lookaheadids.count(node->str)) { + auto wire = std::make_unique(node->location, AST_WIRE); + for (auto& c : node->id2ast->children) + wire->children.push_back(c->clone()); + wire->fixup_hierarchy_flags(); + wire->str = stringf("$lookahead%s$%d", node->str, ast_autoidx()); + wire->set_attribute(ID::nosync, AstNode::mkconst_int(node->location, 1, false)); + wire->is_logic = true; + while (wire->simplify(true, 1, -1, false)) { } + lookaheadids[node->str] = make_pair(node->id2ast, wire.get()); + wire->genRTLIL(); + current_ast_mod->children.push_back(std::move(wire)); + } + } + + for (auto& child : node->children) + collect_lookaheadids(child.get()); + } + + bool has_lookaheadids(AstNode *node) + { + if (node->type == AST_IDENTIFIER && lookaheadids.count(node->str) != 0) + return true; + + for (auto& child : node->children) + if (has_lookaheadids(child.get())) + return true; + + return false; + } + + bool has_nonlookaheadids(AstNode *node) + { + if (node->type == AST_IDENTIFIER && lookaheadids.count(node->str) == 0) + return true; + + for (auto& child : node->children) + if (has_nonlookaheadids(child.get())) + return true; + + return false; + } + + void rewrite_lookaheadids(AstNode *node, bool lhs = false) + { + if (node->type == AST_ASSIGN_LE) + { + if (has_lookaheadids(node->children[0].get())) + { + if (has_nonlookaheadids(node->children[0].get())) + log_error("incompatible mix of lookahead and non-lookahead IDs in LHS expression.\n"); + + rewrite_lookaheadids(node->children[0].get(), true); + node->type = AST_ASSIGN_EQ; + } + + rewrite_lookaheadids(node->children[1].get(), lhs); + return; + } + + if (node->type == AST_IDENTIFIER && (node->lookahead || lhs)) { + AstNode *newwire = lookaheadids.at(node->str).second; + node->str = newwire->str; + node->id2ast = newwire; + lhs = false; + } + + for (auto& child : node->children) + rewrite_lookaheadids(child.get(), lhs); + } + + LookaheadRewriter(AstNode *top) + { + // top->dumpAst(nullptr, "REWRITE-BEFORE> "); + // top->dumpVlog(nullptr, "REWRITE-BEFORE> "); + + AstNode *block = nullptr; + auto loc = top->location; + + for (auto& c : top->children) + if (c->type == AST_BLOCK) { + log_assert(block == nullptr); + block = c.get(); + } + log_assert(block != nullptr); + + collect_lookaheadids(block); + rewrite_lookaheadids(block); + + for (auto it : lookaheadids) + { + auto ref_orig = std::make_unique(loc, AST_IDENTIFIER); + ref_orig->str = it.second.first->str; + ref_orig->id2ast = it.second.first; + ref_orig->was_checked = true; + + auto ref_temp = std::make_unique(loc, AST_IDENTIFIER); + ref_temp->str = it.second.second->str; + ref_temp->id2ast = it.second.second; + ref_temp->was_checked = true; + + auto init_assign = std::make_unique(loc, AST_ASSIGN_EQ, ref_temp->clone(), ref_orig->clone()); + auto final_assign = std::make_unique(loc, AST_ASSIGN_LE, std::move(ref_orig), std::move(ref_temp)); + + block->children.insert(block->children.begin(), std::move(init_assign)); + block->children.push_back(std::move(final_assign)); + } + + // top->dumpAst(nullptr, "REWRITE-AFTER> "); + // top->dumpVlog(nullptr, "REWRITE-AFTER> "); + } +}; + +// helper class for converting AST always nodes to RTLIL processes +struct AST_INTERNAL::ProcessGenerator +{ + // input and output structures + std::unique_ptr always; + RTLIL::SigSpec initSyncSignals; + RTLIL::Process *proc; + RTLIL::SigSpec outputSignals; + + // This always points to the RTLIL::CaseRule being filled at the moment + RTLIL::CaseRule *current_case; + + // This map contains the replacement pattern to be used in the right hand side + // of an assignment. E.g. in the code "foo = bar; foo = func(foo);" the foo in the right + // hand side of the 2nd assignment needs to be replace with the temporary signal holding + // the value assigned in the first assignment. So when the first assignment is processed + // the according information is appended to subst_rvalue_from and subst_rvalue_to. + stackmap subst_rvalue_map; + + // This map contains the replacement pattern to be used in the left hand side + // of an assignment. E.g. in the code "always @(posedge clk) foo <= bar" the signal bar + // should not be connected to the signal foo. Instead it must be connected to the temporary + // signal that is used as input for the register that drives the signal foo. + stackmap subst_lvalue_map; + + // The code here generates a number of temporary signal for each output register. This + // map helps generating nice numbered names for all this temporary signals. + std::map new_temp_count; + + // Buffer for generating the init action + RTLIL::SigSpec init_lvalue, init_rvalue; + + // The most recently assigned $print or $check cell \PRIORITY. + int last_effect_priority; + + // Track which signals have been assigned in current_case to avoid unnecessary removeSignalFromCaseTree calls + pool current_case_assigned_bits; + + ProcessGenerator(std::unique_ptr a, RTLIL::SigSpec initSyncSignalsArg = RTLIL::SigSpec()) : always(std::move(a)), initSyncSignals(initSyncSignalsArg), last_effect_priority(0) + { + // rewrite lookahead references + LookaheadRewriter la_rewriter(always.get()); + + // generate process and simple root case + proc = current_module->addProcess(intern_src_name(current_module->design, always->location, "$proc", ast_autoidx())); + set_src_attr(proc, always.get()); + for (auto &attr : always->attributes) { + if (attr.second->type != AST_CONSTANT) + always->input_error("Attribute `%s' with non-constant value!\n", attr_name_str(attr.first)); + proc->attributes[current_module->twines().add(attr_name_str(attr.first))] = attr.second->asAttrConst(); + } + current_case = &proc->root_case; + + // create initial temporary signal for all output registers + RTLIL::SigSpec subst_lvalue_from, subst_lvalue_to; + collect_lvalues(subst_lvalue_from, always.get(), true, true); + subst_lvalue_to = new_temp_signal(subst_lvalue_from); + subst_lvalue_map = subst_lvalue_from.to_sigbit_map(subst_lvalue_to); + + bool found_global_syncs = false; + bool found_anyedge_syncs = false; + for (auto& child : always->children) + { + if ((child->type == AST_POSEDGE || child->type == AST_NEGEDGE) && GetSize(child->children) == 1 && child->children.at(0)->type == AST_IDENTIFIER && + child->children.at(0)->id2ast && child->children.at(0)->id2ast->type == AST_WIRE && child->children.at(0)->id2ast->get_bool_attribute(ID::gclk)) { + found_global_syncs = true; + } + if (child->type == AST_EDGE) { + if (GetSize(child->children) == 1 && child->children.at(0)->type == AST_IDENTIFIER && child->children.at(0)->str == "\\$global_clock") + found_global_syncs = true; + else + found_anyedge_syncs = true; + } + } + + if (found_anyedge_syncs) { + if (found_global_syncs) + always->input_error("Found non-synthesizable event list!\n"); + log("Note: Assuming pure combinatorial block at %s in\n", always->loc_string()); + log("compliance with IEC 62142(E):2005 / IEEE Std. 1364.1(E):2002. Recommending\n"); + log("use of @* instead of @(...) for better match of synthesis and simulation.\n"); + } + + // create syncs for the process + bool found_clocked_sync = false; + for (auto& child : always->children) + if (child->type == AST_POSEDGE || child->type == AST_NEGEDGE) { + if (GetSize(child->children) == 1 && child->children.at(0)->type == AST_IDENTIFIER && child->children.at(0)->id2ast && + child->children.at(0)->id2ast->type == AST_WIRE && child->children.at(0)->id2ast->get_bool_attribute(ID::gclk)) + continue; + found_clocked_sync = true; + if (found_global_syncs || found_anyedge_syncs) + always->input_error("Found non-synthesizable event list!\n"); + RTLIL::SyncRule *syncrule = new RTLIL::SyncRule; + syncrule->type = child->type == AST_POSEDGE ? RTLIL::STp : RTLIL::STn; + syncrule->signal = child->children[0]->genRTLIL(); + if (GetSize(syncrule->signal) != 1) + always->input_error("Found posedge/negedge event on a signal that is not 1 bit wide!\n"); + addChunkActions(syncrule->actions, subst_lvalue_from, subst_lvalue_to, true); + proc->syncs.push_back(syncrule); + } + if (proc->syncs.empty()) { + RTLIL::SyncRule *syncrule = new RTLIL::SyncRule; + syncrule->type = found_global_syncs ? RTLIL::STg : RTLIL::STa; + syncrule->signal = RTLIL::SigSpec(); + addChunkActions(syncrule->actions, subst_lvalue_from, subst_lvalue_to, true); + proc->syncs.push_back(syncrule); + } + + // create initial assignments for the temporary signals + if ((flag_nolatches || always->get_bool_attribute(ID::nolatches) || current_module->get_bool_attribute(ID::nolatches)) && !found_clocked_sync) { + subst_rvalue_map = subst_lvalue_from.to_sigbit_dict(RTLIL::SigSpec(RTLIL::State::Sx, GetSize(subst_lvalue_from))); + } else { + addChunkActions(current_case->actions, subst_lvalue_to, subst_lvalue_from); + // Track initial assignments + for (auto &bit : subst_lvalue_to) + if (bit.wire != NULL) + current_case_assigned_bits.insert(bit); + } + + // process the AST + for (auto& child : always->children) + if (child->type == AST_BLOCK) + processAst(child.get()); + + for (auto sync: proc->syncs) + processMemWrites(sync); + + if (initSyncSignals.size() > 0) + { + RTLIL::SyncRule *sync = new RTLIL::SyncRule; + sync->type = RTLIL::SyncType::STi; + proc->syncs.push_back(sync); + + log_assert(init_lvalue.size() == init_rvalue.size()); + + int offset = 0; + for (auto &init_lvalue_c : init_lvalue.chunks()) { + RTLIL::SigSpec lhs = init_lvalue_c; + RTLIL::SigSpec rhs = init_rvalue.extract(offset, init_lvalue_c.width); + remove_unwanted_lvalue_bits(lhs, rhs); + sync->actions.push_back({lhs, rhs}); + offset += lhs.size(); + } + } + + outputSignals = RTLIL::SigSpec(subst_lvalue_from); + } + + void remove_unwanted_lvalue_bits(RTLIL::SigSpec &lhs, RTLIL::SigSpec &rhs) + { + RTLIL::SigSpec new_lhs, new_rhs; + + log_assert(GetSize(lhs) == GetSize(rhs)); + for (int i = 0; i < GetSize(lhs); i++) { + if (lhs[i].wire == nullptr) + continue; + new_lhs.append(lhs[i]); + new_rhs.append(rhs[i]); + } + + lhs = new_lhs; + rhs = new_rhs; + } + + // create new temporary signals + RTLIL::SigSpec new_temp_signal(RTLIL::SigSpec sig) + { + std::vector chunks = sig.chunks(); + + for (int i = 0; i < GetSize(chunks); i++) + { + RTLIL::SigChunk &chunk = chunks[i]; + if (chunk.wire == nullptr) + continue; + + std::string wire_name; + do { + wire_name = stringf("$%d%s[%d:%d]", new_temp_count[chunk.wire]++, + chunk.wire->name, chunk.width+chunk.offset-1, chunk.offset);; + if (chunk.wire->name.str().find('$') != std::string::npos) + wire_name += stringf("$%d", ast_autoidx()); + } while (current_module->wire(wire_name) != nullptr); + + RTLIL::Wire *wire = current_module->addWire(wire_name, chunk.width); + set_src_attr(wire, always.get()); + + chunk.wire = wire; + chunk.offset = 0; + } + + return chunks; + } + + // recursively traverse the AST and collect all assigned signals + void collect_lvalues(RTLIL::SigSpec ®, AstNode *ast, bool type_eq, bool type_le, bool run_sort_and_unify = true) + { + switch (ast->type) + { + case AST_CASE: + for (auto& child : ast->children) + if (child != ast->children[0]) { + log_assert(child->type == AST_COND || child->type == AST_CONDX || child->type == AST_CONDZ); + collect_lvalues(reg, child.get(), type_eq, type_le, false); + } + break; + + case AST_COND: + case AST_CONDX: + case AST_CONDZ: + case AST_ALWAYS: + case AST_INITIAL: + for (auto& child : ast->children) + if (child->type == AST_BLOCK) + collect_lvalues(reg, child.get(), type_eq, type_le, false); + break; + + case AST_BLOCK: + for (auto& child : ast->children) { + if (child->type == AST_ASSIGN_EQ && type_eq) + reg.append(child->children[0]->genRTLIL()); + if (child->type == AST_ASSIGN_LE && type_le) + reg.append(child->children[0]->genRTLIL()); + if (child->type == AST_CASE || child->type == AST_BLOCK) + collect_lvalues(reg, child.get(), type_eq, type_le, false); + } + break; + + default: + log_abort(); + } + + if (run_sort_and_unify) { + std::set sorted_reg; + for (auto bit : reg) + if (bit.wire) + sorted_reg.insert(bit); + reg = RTLIL::SigSpec(sorted_reg); + } + } + + // remove all assignments to the given signal pattern in a case and all its children. + // e.g. when the last statement in the code "a = 23; if (b) a = 42; a = 0;" is processed this + // function is called to clean up the first two assignments as they are overwritten by + // the third assignment. + void removeSignalFromCaseTree(const pool &pattern_bits, RTLIL::CaseRule *cs) + { + // Optimization: check actions in reverse order and stop early if we've found all pattern bits + pool remaining_bits = pattern_bits; + + for (auto it = cs->actions.rbegin(); it != cs->actions.rend(); ++it) { + bool has_pattern = false; + for (auto &bit : it->first) { + if (bit.wire != NULL && remaining_bits.count(bit)) { + has_pattern = true; + remaining_bits.erase(bit); + } + } + + if (has_pattern) { + it->first.remove2(pattern_bits, &it->second); + } + + // Early exit if we've processed all bits in pattern + if (remaining_bits.empty()) + break; + } + + for (auto it = cs->switches.begin(); it != cs->switches.end(); it++) + for (auto it2 = (*it)->cases.begin(); it2 != (*it)->cases.end(); it2++) + removeSignalFromCaseTree(pattern_bits, *it2); + } + + void removeSignalFromCaseTree(const RTLIL::SigSpec &pattern, RTLIL::CaseRule *cs) + { + pool pattern_bits; + pattern_bits.reserve(pattern.size()); + for (auto &bit : pattern) + if (bit.wire != NULL) + pattern_bits.insert(bit); + removeSignalFromCaseTree(pattern_bits, cs); + } + + // add an assignment (aka "action") but split it up in chunks. this way huge assignments + // are avoided and the generated $mux cells have a more "natural" size. + void addChunkActions(std::vector &actions, RTLIL::SigSpec lvalue, RTLIL::SigSpec rvalue, bool inSyncRule = false) + { + if (inSyncRule && initSyncSignals.size() > 0) { + init_lvalue.append(lvalue.extract(initSyncSignals)); + init_rvalue.append(lvalue.extract(initSyncSignals, &rvalue)); + lvalue.remove2(initSyncSignals, &rvalue); + } + log_assert(lvalue.size() == rvalue.size()); + + int offset = 0; + for (auto &lvalue_c : lvalue.chunks()) { + RTLIL::SigSpec lhs = lvalue_c; + RTLIL::SigSpec rhs = rvalue.extract(offset, lvalue_c.width); + if (inSyncRule && lvalue_c.wire && lvalue_c.wire->get_bool_attribute(ID::nosync)) + rhs = RTLIL::SigSpec(RTLIL::State::Sx, rhs.size()); + remove_unwanted_lvalue_bits(lhs, rhs); + actions.push_back(RTLIL::SigSig(lhs, rhs)); + offset += lhs.size(); + } + } + + // recursively process the AST and fill the RTLIL::Process + void processAst(AstNode *ast) + { + switch (ast->type) + { + case AST_BLOCK: + for (auto& child : ast->children) + processAst(child.get()); + break; + + case AST_ASSIGN_EQ: + case AST_ASSIGN_LE: + { + RTLIL::SigSpec unmapped_lvalue = ast->children[0]->genRTLIL(), lvalue = unmapped_lvalue; + RTLIL::SigSpec rvalue = ast->children[1]->genWidthRTLIL(lvalue.size(), true, &subst_rvalue_map.stdmap()); + + pool lvalue_sigbits; + for (int i = 0; i < GetSize(lvalue); i++) { + if (lvalue_sigbits.count(lvalue[i]) > 0) { + unmapped_lvalue.remove(i); + lvalue.remove(i); + rvalue.remove(i--); + } else + lvalue_sigbits.insert(lvalue[i]); + } + + lvalue.replace(subst_lvalue_map.stdmap()); + + if (ast->type == AST_ASSIGN_EQ) { + for (int i = 0; i < GetSize(unmapped_lvalue); i++) + subst_rvalue_map.set(unmapped_lvalue[i], rvalue[i]); + } + + // Check if any bits in lvalue have been assigned before in current_case + bool has_overlap = false; + for (auto &bit : lvalue) { + if (bit.wire != NULL && current_case_assigned_bits.count(bit)) { + has_overlap = true; + break; + } + } + + if (has_overlap) + removeSignalFromCaseTree(lvalue, current_case); + + // Track newly assigned bits + for (auto &bit : lvalue) + if (bit.wire != NULL) + current_case_assigned_bits.insert(bit); + + remove_unwanted_lvalue_bits(lvalue, rvalue); + current_case->actions.push_back({lvalue, rvalue}); + } + break; + + case AST_CASE: + { + int width_hint; + bool sign_hint; + ast->detectSignWidth(width_hint, sign_hint); + + RTLIL::SwitchRule *sw = new RTLIL::SwitchRule; + set_src_attr(sw, ast); + sw->signal = ast->children[0]->genWidthRTLIL(width_hint, sign_hint, &subst_rvalue_map.stdmap()); + current_case->switches.push_back(sw); + + for (auto &attr : ast->attributes) { + if (attr.second->type != AST_CONSTANT) + ast->input_error("Attribute `%s' with non-constant value!\n", attr_name_str(attr.first)); + sw->attributes[current_module->twines().add(attr_name_str(attr.first))] = attr.second->asAttrConst(); + } + + RTLIL::SigSpec this_case_eq_lvalue; + collect_lvalues(this_case_eq_lvalue, ast, true, false); + + RTLIL::SigSpec this_case_eq_ltemp = new_temp_signal(this_case_eq_lvalue); + + RTLIL::SigSpec this_case_eq_rvalue = this_case_eq_lvalue; + this_case_eq_rvalue.replace(subst_rvalue_map.stdmap()); + + RTLIL::CaseRule *default_case = nullptr; + RTLIL::CaseRule *last_generated_case = nullptr; + for (auto& child : ast->children) + { + if (child == ast->children[0]) + continue; + log_assert(child->type == AST_COND || child->type == AST_CONDX || child->type == AST_CONDZ); + + subst_lvalue_map.save(); + subst_rvalue_map.save(); + + for (int i = 0; i < GetSize(this_case_eq_lvalue); i++) + subst_lvalue_map.set(this_case_eq_lvalue[i], this_case_eq_ltemp[i]); + + RTLIL::CaseRule *backup_case = current_case; + current_case = new RTLIL::CaseRule; + pool backup_assigned_bits = std::move(current_case_assigned_bits); + current_case_assigned_bits.clear(); + set_src_attr(current_case, child.get()); + last_generated_case = current_case; + addChunkActions(current_case->actions, this_case_eq_ltemp, this_case_eq_rvalue); + // Track temp assignments + for (auto &bit : this_case_eq_ltemp) + if (bit.wire != NULL) + current_case_assigned_bits.insert(bit); + for (auto& node : child->children) { + if (node->type == AST_DEFAULT) + default_case = current_case; + else if (node->type == AST_BLOCK) + processAst(node.get()); + else + current_case->compare.push_back(node->genWidthRTLIL(width_hint, sign_hint, &subst_rvalue_map.stdmap())); + } + if (default_case != current_case) + sw->cases.push_back(current_case); + else + log_assert(current_case->compare.size() == 0); + current_case = backup_case; + auto child_bits = std::move(current_case_assigned_bits); + current_case_assigned_bits = std::move(backup_assigned_bits); + // collapse bits assigned in child nodes of AST into current case + for (auto bit : child_bits) + current_case_assigned_bits.insert(bit); + + subst_lvalue_map.restore(); + subst_rvalue_map.restore(); + } + + if (last_generated_case != nullptr && ast->get_bool_attribute(ID::full_case) && default_case == nullptr) { + #if 0 + // this is a valid transformation, but as optimization it is premature. + // better: add a default case that assigns 'x' to everything, and let later + // optimizations take care of the rest + last_generated_case->compare.clear(); + #else + default_case = new RTLIL::CaseRule; + addChunkActions(default_case->actions, this_case_eq_ltemp, SigSpec(State::Sx, GetSize(this_case_eq_rvalue))); + sw->cases.push_back(default_case); + #endif + } else { + if (default_case == nullptr) { + default_case = new RTLIL::CaseRule; + addChunkActions(default_case->actions, this_case_eq_ltemp, this_case_eq_rvalue); + } + sw->cases.push_back(default_case); + } + + for (int i = 0; i < GetSize(this_case_eq_lvalue); i++) + subst_rvalue_map.set(this_case_eq_lvalue[i], this_case_eq_ltemp[i]); + + this_case_eq_lvalue.replace(subst_lvalue_map.stdmap()); + + // Check if any bits in lvalue have been assigned before in current_case + bool has_overlap = false; + for (auto &bit : this_case_eq_lvalue) { + if (bit.wire != NULL && current_case_assigned_bits.count(bit)) { + has_overlap = true; + break; + } + } + + if (has_overlap) + removeSignalFromCaseTree(this_case_eq_lvalue, current_case); + + addChunkActions(current_case->actions, this_case_eq_lvalue, this_case_eq_ltemp); + // Track newly assigned bits + for (auto &bit : this_case_eq_lvalue) + if (bit.wire != NULL) + current_case_assigned_bits.insert(bit); + } + break; + + case AST_WIRE: + ast->input_error("Found reg declaration in block without label!\n"); + break; + + case AST_ASSIGN: + ast->input_error("Found continuous assignment in always/initial block!\n"); + break; + + case AST_PARAMETER: + case AST_LOCALPARAM: + ast->input_error("Found parameter declaration in block without label!\n"); + break; + + case AST_TCALL: + if (ast->str == "$display" || ast->str == "$displayb" || ast->str == "$displayh" || ast->str == "$displayo" || + ast->str == "$write" || ast->str == "$writeb" || ast->str == "$writeh" || ast->str == "$writeo") { + IdString name = intern_src_name(current_module->design, ast->location, ast->str, ast_autoidx()); + + Wire *en = current_module->addWire(TwineSpec::Suffix{name, "_EN"}, 1); + set_src_attr(en, ast); + proc->root_case.actions.push_back({en, SigSpec(false)}); + current_case->actions.push_back({en, SigSpec(true)}); + + RTLIL::SigSpec triggers; + RTLIL::Const::Builder polarity_builder; + for (auto sync : proc->syncs) { + if (sync->type == RTLIL::STp) { + triggers.append(sync->signal); + polarity_builder.push_back(RTLIL::S1); + } else if (sync->type == RTLIL::STn) { + triggers.append(sync->signal); + polarity_builder.push_back(RTLIL::S0); + } + } + RTLIL::Const polarity = polarity_builder.build(); + + RTLIL::Cell *cell = current_module->addCell(name, ID($print)); + set_src_attr(cell, ast); + cell->setParam(ID::TRG_WIDTH, triggers.size()); + cell->setParam(ID::TRG_ENABLE, (always->type == AST_INITIAL) || !triggers.empty()); + cell->setParam(ID::TRG_POLARITY, polarity); + cell->setParam(ID::PRIORITY, --last_effect_priority); + cell->setPort(ID::TRG, triggers); + cell->setPort(ID::EN, en); + + int default_base = 10; + if (ast->str.back() == 'b') + default_base = 2; + else if (ast->str.back() == 'o') + default_base = 8; + else if (ast->str.back() == 'h') + default_base = 16; + + std::vector args; + for (auto& node : ast->children) { + int width; + bool is_signed; + node->detectSignWidth(width, is_signed, nullptr); + + VerilogFmtArg arg = {}; + arg.src = node->location.to_loc(); + if (node->type == AST_CONSTANT && node->is_string) { + arg.type = VerilogFmtArg::STRING; + arg.str = node->bitsAsConst().decode_string(); + // and in case this will be used as an argument... + arg.sig = node->bitsAsConst(); + arg.signed_ = false; + } else if (node->type == AST_IDENTIFIER && node->str == "$time") { + arg.type = VerilogFmtArg::TIME; + } else if (node->type == AST_IDENTIFIER && node->str == "$realtime") { + arg.type = VerilogFmtArg::TIME; + arg.realtime = true; + } else { + arg.type = VerilogFmtArg::INTEGER; + arg.sig = node->genWidthRTLIL(-1, false, &subst_rvalue_map.stdmap()); + arg.signed_ = is_signed; + } + args.push_back(arg); + } + + Fmt fmt; + fmt.parse_verilog(args, /*sformat_like=*/false, default_base, /*task_name=*/ast->str, current_module->name); + if (ast->str.substr(0, 8) == "$display") + fmt.append_literal("\n"); + fmt.emit_rtlil(cell); + } else if (!ast->str.empty()) { + log_file_error(ast->location.to_loc(), "Found unsupported invocation of system task `%s'!\n", ast->str); + } + break; + + // generate $check cells + case AST_ASSERT: + case AST_ASSUME: + case AST_LIVE: + case AST_FAIR: + case AST_COVER: + { + std::string flavor, desc; + if (ast->type == AST_ASSERT) { flavor = "assert"; desc = "assert ()"; } + if (ast->type == AST_ASSUME) { flavor = "assume"; desc = "assume ()"; } + if (ast->type == AST_LIVE) { flavor = "live"; desc = "assert (eventually)"; } + if (ast->type == AST_FAIR) { flavor = "fair"; desc = "assume (eventually)"; } + if (ast->type == AST_COVER) { flavor = "cover"; desc = "cover ()"; } + + IdString cellname; + if (ast->str.empty()) + cellname = intern_src_name(current_module->design, ast->location, + stringf("$%s", flavor), ast_autoidx()); + else + cellname = current_module->twines().add(ast->str); + check_unique_id(current_module, cellname, ast, "procedural assertion"); + + RTLIL::SigSpec check = ast->children[0]->genWidthRTLIL(-1, false, &subst_rvalue_map.stdmap()); + if (GetSize(check) != 1) + check = current_module->ReduceBool(NEW_ID, check); + + Wire *en = current_module->addWire(TwineSpec::Suffix{cellname, "_EN"}, 1); + set_src_attr(en, ast); + proc->root_case.actions.push_back({en, SigSpec(false)}); + current_case->actions.push_back({en, SigSpec(true)}); + + RTLIL::SigSpec triggers; + RTLIL::Const::Builder polarity_builder; + for (auto sync : proc->syncs) { + if (sync->type == RTLIL::STp) { + triggers.append(sync->signal); + polarity_builder.push_back(RTLIL::S1); + } else if (sync->type == RTLIL::STn) { + triggers.append(sync->signal); + polarity_builder.push_back(RTLIL::S0); + } + } + RTLIL::Const polarity = polarity_builder.build(); + + RTLIL::Cell *cell = current_module->addCell(cellname, ID($check)); + set_src_attr(cell, ast); + cell->set_bool_attribute(ID(keep)); + for (auto &attr : ast->attributes) { + if (attr.second->type != AST_CONSTANT) + log_file_error(ast->location.to_loc(), "Attribute `%s' with non-constant value!\n", attr_name_str(attr.first)); + cell->attributes[attr.first] = attr.second->asAttrConst(); + } + cell->setParam(ID::FLAVOR, flavor); + cell->setParam(ID::TRG_WIDTH, triggers.size()); + cell->setParam(ID::TRG_ENABLE, (always->type == AST_INITIAL) || !triggers.empty()); + cell->setParam(ID::TRG_POLARITY, polarity); + cell->setParam(ID::PRIORITY, --last_effect_priority); + cell->setPort(ID::TRG, triggers); + cell->setPort(ID::EN, en); + cell->setPort(ID::A, check); + + // No message is emitted to ensure Verilog code roundtrips correctly. + Fmt fmt; + fmt.emit_rtlil(cell); + break; + } + + case AST_NONE: + case AST_FOR: + break; + + default: + // ast->dumpAst(nullptr, "ast> "); + // current_ast_mod->dumpAst(nullptr, "mod> "); + log_abort(); + } + } + + void processMemWrites(RTLIL::SyncRule *sync) + { + // Maps per-memid AST_MEMWR IDs to indices in the mem_write_actions array. + dict, int> port_map; + for (auto& child : always->children) + if (child->type == AST_MEMWR) + { + std::string memid_str = child->str; + int portid = child->children[3]->asInt(false); + int cur_idx = GetSize(sync->mem_write_actions); + RTLIL::MemWriteAction action; + set_src_attr(&action, child.get()); + action.memid = current_module->twines().add(memid_str); + action.address = child->children[0]->genWidthRTLIL(-1, true, &subst_rvalue_map.stdmap()); + action.data = child->children[1]->genWidthRTLIL(current_module->memories[action.memid]->width, true, &subst_rvalue_map.stdmap()); + action.enable = child->children[2]->genWidthRTLIL(-1, true, &subst_rvalue_map.stdmap()); + RTLIL::Const orig_priority_mask = child->children[4]->bitsAsConst(); + RTLIL::Const priority_mask = RTLIL::Const(0, cur_idx); + for (int i = 0; i < portid; i++) { + int new_bit = port_map[std::make_pair(memid_str, i)]; + priority_mask.set(new_bit, orig_priority_mask[i]); + } + action.priority_mask = priority_mask; + sync->mem_write_actions.push_back(action); + port_map[std::make_pair(memid_str, portid)] = cur_idx; + } + } +}; + +// detect sign and width of an expression +void AstNode::detectSignWidthWorker(int &width_hint, bool &sign_hint, bool *found_real) +{ + std::string type_name; + bool sub_sign_hint = true; + int sub_width_hint = -1; + int this_width = 0; + AstNode *range = nullptr; + AstNode *id_ast = nullptr; + + bool local_found_real = false; + if (found_real == nullptr) + found_real = &local_found_real; + + switch (type) + { + case AST_NONE: + // unallocated enum, ignore + break; + case AST_CONSTANT: + width_hint = max(width_hint, GetSize(bits)); + if (!is_signed) + sign_hint = false; + break; + + case AST_REALVALUE: + *found_real = true; + width_hint = max(width_hint, 32); + break; + + case AST_IDENTIFIER: + id_ast = id2ast; + if (!id_ast) { + if (current_scope.count(str)) + id_ast = current_scope[str]; + else { + std::string alt = try_pop_module_prefix(); + if (current_scope.count(alt)) + id_ast = current_scope[alt]; + } + } + if (!id_ast) + input_error("Failed to resolve identifier %s for width detection!\n", str); + if (id_ast->type == AST_PARAMETER || id_ast->type == AST_LOCALPARAM || id_ast->type == AST_ENUM_ITEM) { + if (id_ast->children.size() > 1 && id_ast->children[1]->range_valid) { + this_width = id_ast->children[1]->range_left - id_ast->children[1]->range_right + 1; + } else { + if (id_ast->children[0]->type != AST_CONSTANT) + while (id_ast->simplify(true, 1, -1, false)) { } + if (id_ast->children[0]->type == AST_CONSTANT) + this_width = id_ast->children[0]->bits.size(); + else + input_error("Failed to detect width for parameter %s!\n", str); + } + if (children.size() != 0) + range = children[0].get(); + } else if (id_ast->type == AST_WIRE || id_ast->type == AST_AUTOWIRE) { + if (!id_ast->range_valid) { + if (id_ast->type == AST_AUTOWIRE) + this_width = 1; + else { + // current_ast_mod->dumpAst(nullptr, "mod> "); + // log("---\n"); + // id_ast->dumpAst(nullptr, "decl> "); + // dumpAst(nullptr, "ref> "); + input_error("Failed to detect width of signal access `%s'!\n", str); + } + } else { + this_width = id_ast->range_left - id_ast->range_right + 1; + if (children.size() != 0) + range = children[0].get(); + } + } else if (id_ast->type == AST_GENVAR) { + this_width = 32; + } else if (id_ast->type == AST_MEMORY) { + if (!id_ast->children[0]->range_valid) + input_error("Failed to detect width of memory access `%s'!\n", str); + this_width = id_ast->children[0]->range_left - id_ast->children[0]->range_right + 1; + if (children.size() > 1) + range = children[1].get(); + } else if (id_ast->type == AST_STRUCT_ITEM || id_ast->type == AST_STRUCT || id_ast->type == AST_UNION) { + auto tmp_range = make_index_range(id_ast); + this_width = tmp_range->range_left - tmp_range->range_right + 1; + } else + input_error("Failed to detect width for identifier %s!\n", str); + if (range) { + if (range->children.size() == 1) + this_width = 1; + else if (!range->range_valid) { + auto left_at_zero_ast = children[0]->children[0]->clone_at_zero(); + auto right_at_zero_ast = children[0]->children.size() >= 2 ? children[0]->children[1]->clone_at_zero() : left_at_zero_ast->clone(); + while (left_at_zero_ast->simplify(true, 1, -1, false)) { } + while (right_at_zero_ast->simplify(true, 1, -1, false)) { } + if (left_at_zero_ast->type != AST_CONSTANT || right_at_zero_ast->type != AST_CONSTANT) + input_error("Unsupported expression on dynamic range select on signal `%s'!\n", str); + this_width = abs(int(left_at_zero_ast->integer - right_at_zero_ast->integer)) + 1; + } else + this_width = range->range_left - range->range_right + 1; + sign_hint = false; + } + width_hint = max(width_hint, this_width); + if (!id_ast->is_signed) + sign_hint = false; + break; + + case AST_TO_BITS: + while (children[0]->simplify(true, 1, -1, false) == true) { } + if (children[0]->type != AST_CONSTANT) + input_error("Left operand of tobits expression is not constant!\n"); + children[1]->detectSignWidthWorker(sub_width_hint, sign_hint); + width_hint = max(width_hint, children[0]->bitsAsConst().as_int()); + break; + + case AST_TO_SIGNED: + children.at(0)->detectSignWidthWorker(width_hint, sub_sign_hint); + break; + + case AST_TO_UNSIGNED: + children.at(0)->detectSignWidthWorker(width_hint, sub_sign_hint); + sign_hint = false; + break; + + case AST_SELFSZ: + sub_width_hint = 0; + children.at(0)->detectSignWidthWorker(sub_width_hint, sign_hint); + break; + + case AST_CAST_SIZE: + while (children.at(0)->simplify(true, 1, -1, false)) { } + if (children.at(0)->type != AST_CONSTANT) + input_error("Static cast with non constant expression!\n"); + children.at(1)->detectSignWidthWorker(sub_width_hint, sign_hint); + this_width = children.at(0)->bitsAsConst().as_int(); + width_hint = max(width_hint, this_width); + if (width_hint <= 0) + input_error("Static cast with zero or negative size!\n"); + break; + + case AST_CONCAT: + for (auto& child : children) { + sub_width_hint = 0; + sub_sign_hint = true; + child->detectSignWidthWorker(sub_width_hint, sub_sign_hint); + this_width += sub_width_hint; + } + width_hint = max(width_hint, this_width); + sign_hint = false; + break; + + case AST_REPLICATE: + while (children[0]->simplify(true, 1, -1, false) == true) { } + if (children[0]->type != AST_CONSTANT) + input_error("Left operand of replicate expression is not constant!\n"); + children[1]->detectSignWidthWorker(sub_width_hint, sub_sign_hint); + width_hint = max(width_hint, children[0]->bitsAsConst().as_int() * sub_width_hint); + sign_hint = false; + break; + + case AST_ASSIGN_PATTERN: + for (auto& child : children) { + sub_width_hint = 0; + sub_sign_hint = true; + child->detectSignWidthWorker(sub_width_hint, sub_sign_hint); + } + sign_hint = false; + break; + + case AST_NEG: + case AST_BIT_NOT: + case AST_POS: + children[0]->detectSignWidthWorker(width_hint, sign_hint, found_real); + break; + + case AST_BIT_AND: + case AST_BIT_OR: + case AST_BIT_XOR: + case AST_BIT_XNOR: + for (auto& child : children) + child->detectSignWidthWorker(width_hint, sign_hint, found_real); + break; + + case AST_REDUCE_AND: + case AST_REDUCE_OR: + case AST_REDUCE_XOR: + case AST_REDUCE_XNOR: + case AST_REDUCE_BOOL: + width_hint = max(width_hint, 1); + sign_hint = false; + break; + + case AST_SHIFT_LEFT: + case AST_SHIFT_RIGHT: + case AST_SHIFT_SLEFT: + case AST_SHIFT_SRIGHT: + case AST_SHIFTX: + case AST_SHIFT: + case AST_POW: + children[0]->detectSignWidthWorker(width_hint, sign_hint, found_real); + break; + + case AST_LT: + case AST_LE: + case AST_EQ: + case AST_NE: + case AST_EQX: + case AST_NEX: + case AST_GE: + case AST_GT: + width_hint = max(width_hint, 1); + sign_hint = false; + break; + + case AST_ADD: + case AST_SUB: + case AST_MUL: + case AST_DIV: + case AST_MOD: + for (auto& child : children) + child->detectSignWidthWorker(width_hint, sign_hint, found_real); + break; + + case AST_LOGIC_AND: + case AST_LOGIC_OR: + case AST_LOGIC_NOT: + width_hint = max(width_hint, 1); + sign_hint = false; + break; + + case AST_TERNARY: + children.at(1)->detectSignWidthWorker(width_hint, sign_hint, found_real); + children.at(2)->detectSignWidthWorker(width_hint, sign_hint, found_real); + break; + + case AST_MEMRD: + if (!id2ast->is_signed) + sign_hint = false; + if (!id2ast->children[0]->range_valid) + input_error("Failed to detect width of memory access `%s'!\n", str); + this_width = id2ast->children[0]->range_left - id2ast->children[0]->range_right + 1; + width_hint = max(width_hint, this_width); + break; + + case AST_CASE: + { + // This detects the _overall_ sign and width to be used for comparing + // the case expression with the case item expressions. The case + // expression and case item expressions are extended to the maximum + // width among them, and are only interpreted as signed if all of them + // are signed. + width_hint = -1; + sign_hint = true; + auto visit_case_expr = [&width_hint, &sign_hint] (AstNode *node) { + int sub_width_hint = -1; + bool sub_sign_hint = true; + node->detectSignWidth(sub_width_hint, sub_sign_hint); + width_hint = max(width_hint, sub_width_hint); + sign_hint &= sub_sign_hint; + }; + visit_case_expr(children[0].get()); + for (size_t i = 1; i < children.size(); i++) { + AstNode *child = children[i].get(); + for (auto& v : child->children) { + if (v->type != AST_DEFAULT && v->type != AST_BLOCK) + visit_case_expr(v.get()); + } + } + break; + } + + case AST_PREFIX: + // Prefix nodes always resolve to identifiers in generate loops, so we + // can simply perform the resolution to determine the sign and width. + simplify(true, 1, -1, false); + log_assert(type == AST_IDENTIFIER); + detectSignWidthWorker(width_hint, sign_hint, found_real); + break; + + case AST_FCALL: + if (str == "\\$anyconst" || str == "\\$anyseq" || str == "\\$allconst" || str == "\\$allseq") { + if (GetSize(children) == 1) { + while (children[0]->simplify(true, 1, -1, false) == true) { } + if (children[0]->type != AST_CONSTANT) + input_error("System function %s called with non-const argument!\n", + RTLIL::unescape_id(str)); + width_hint = max(width_hint, int(children[0]->asInt(true))); + } + break; + } + if (str == "\\$past") { + if (GetSize(children) > 0) { + sub_width_hint = 0; + sub_sign_hint = true; + children.at(0)->detectSignWidthWorker(sub_width_hint, sub_sign_hint); + width_hint = max(width_hint, sub_width_hint); + sign_hint &= sub_sign_hint; + } + break; + } + if (str == "\\$size" || str == "\\$bits" || str == "\\$high" || str == "\\$low" || str == "\\$left" || str == "\\$right") { + width_hint = max(width_hint, 32); + break; + } + if (current_scope.count(str)) + { + // This width detection is needed for function calls which are + // unelaborated, which currently applies to calls to functions + // reached via unevaluated ternary branches or used in case or case + // item expressions. + const AstNode *func = current_scope.at(str); + if (func->type != AST_FUNCTION) + input_error("Function call to %s resolved to something that isn't a function!\n", RTLIL::unescape_id(str)); + const AstNode *wire = nullptr; + for (const auto& child : func->children) + if (child->str == func->str) { + wire = child.get(); + break; + } + log_assert(wire && wire->type == AST_WIRE); + sign_hint &= wire->is_signed; + int result_width = 1; + if (!wire->children.empty()) + { + log_assert(wire->children.size() == 1); + const AstNode *range = wire->children.at(0).get(); + log_assert(range->type == AST_RANGE && range->children.size() == 2); + auto left = range->children.at(0)->clone(); + auto right = range->children.at(1)->clone(); + left->set_in_param_flag(true); + right->set_in_param_flag(true); + while (left->simplify(true, 1, -1, false)) { } + while (right->simplify(true, 1, -1, false)) { } + if (left->type != AST_CONSTANT || right->type != AST_CONSTANT) + input_error("Function %s has non-constant width!", + RTLIL::unescape_id(str)); + result_width = abs(int(left->asInt(true) - right->asInt(true))); + } + width_hint = max(width_hint, result_width); + break; + } + YS_FALLTHROUGH + + // everything should have been handled above -> print error if not. + default: + AstNode *current_scope_ast = current_ast_mod == nullptr ? current_ast : current_ast_mod; + logger().for_each_sink([&](LogSink &sink) { + FILE *f = sink.file_handle(); + if (f) + current_scope_ast->dumpAst(f, "verilog-ast> "); + }); + input_error("Don't know how to detect sign and width for %s node!\n", type2str(type)); + + } + + if (*found_real) + sign_hint = true; +} + +// detect sign and width of an expression +void AstNode::detectSignWidth(int &width_hint, bool &sign_hint, bool *found_real) +{ + width_hint = -1; + sign_hint = true; + if (found_real) + *found_real = false; + detectSignWidthWorker(width_hint, sign_hint, found_real); + + constexpr int kWidthLimit = 1 << 24; + if (width_hint >= kWidthLimit) + input_error("Expression width %d exceeds implementation limit of %d!\n", + width_hint, kWidthLimit); +} + +// create RTLIL from an AST node +// all generated cells, wires and processes are added to the module pointed to by 'current_module' +// when the AST node is an expression (AST_ADD, AST_BIT_XOR, etc.), the result signal is returned. +// +// note that this function is influenced by a number of global variables that might be set when +// called from genWidthRTLIL(). also note that this function recursively calls itself to transform +// larger expressions into a netlist of cells. +RTLIL::SigSpec AstNode::genRTLIL(int width_hint, bool sign_hint) +{ + // in the following big switch() statement there are some uses of + // Clifford's Device (http://www.clifford.at/cfun/cliffdev/). In this + // cases this variable is used to hold the type of the cell that should + // be instantiated for this type of AST node. + IdString type_name; + + switch (type) + { + // simply ignore this nodes. + // they are either leftovers from simplify() or are referenced by other nodes + // and are only accessed here thru this references + case AST_NONE: + case AST_TASK: + case AST_FUNCTION: + case AST_DPI_FUNCTION: + case AST_AUTOWIRE: + case AST_DEFPARAM: + case AST_GENVAR: + case AST_GENFOR: + case AST_GENBLOCK: + case AST_GENIF: + case AST_GENCASE: + case AST_PACKAGE: + case AST_IMPORT: + case AST_ENUM: + case AST_MODPORT: + case AST_MODPORTMEMBER: + case AST_TYPEDEF: + case AST_STRUCT: + case AST_UNION: + break; + case AST_INTERFACEPORT: { + // If a port in a module with unknown type is found, mark it with the attribute 'is_interface' + // This is used by the hierarchy pass to know when it can replace interface connection with the individual + // signals. + const std::string &id = str; + check_unique_id(current_module, id, this, "interface port"); + RTLIL::Wire *wire = current_module->addWire(intern_hier_name(current_module->design, id), 1); + set_src_attr(wire, this); + wire->start_offset = 0; + wire->port_id = port_id; + wire->port_input = true; + wire->port_output = true; + wire->set_bool_attribute(ID::is_interface); + if (children.size() > 0) { + for(size_t i=0; itype == AST_INTERFACEPORTTYPE) { + std::pair res = AST::split_modport_from_type(children[i]->str); + wire->attributes[ID::interface_type] = res.first; + if (res.second != "") + wire->attributes[ID::interface_modport] = res.second; + break; + } + } + } + wire->upto = 0; + } + break; + case AST_INTERFACEPORTTYPE: + break; + + // remember the parameter, needed for example in techmap + case AST_PARAMETER: + current_module->avail_parameters(current_module->twines().add(str)); + if (GetSize(children) >= 1 && children[0]->type == AST_CONSTANT) { + current_module->parameter_default_values[current_module->twines().add(str)] = children[0]->asParaConst(); + } + YS_FALLTHROUGH + case AST_LOCALPARAM: + if (flag_pwires) + { + if (GetSize(children) < 1 || children[0]->type != AST_CONSTANT) + input_error("Parameter `%s' with non-constant value!\n", str); + + RTLIL::Const val = children[0]->bitsAsConst(); + const std::string &id = str; + check_unique_id(current_module, id, this, "pwire"); + RTLIL::Wire *wire = current_module->addWire(intern_hier_name(current_module->design, id), GetSize(val)); + current_module->connect(wire, val); + wire->is_signed = children[0]->is_signed; + + set_src_attr(wire, this); + wire->attributes[type == AST_PARAMETER ? ID::parameter : ID::localparam] = 1; + + for (auto &attr : attributes) { + if (attr.second->type != AST_CONSTANT) + input_error("Attribute `%s' with non-constant value!\n", attr_name_str(attr.first)); + wire->attributes[current_module->twines().add(attr_name_str(attr.first))] = attr.second->asAttrConst(); + } + } + break; + + // create an RTLIL::Wire for an AST_WIRE node + case AST_WIRE: { + if (!range_valid) + input_error("Signal `%s' with non-constant width!\n", str); + + if (!(range_left + 1 >= range_right)) + input_error("Signal `%s' with invalid width range %d!\n", str, range_left - range_right + 1); + + const std::string &id = str; + check_unique_id(current_module, id, this, "signal"); + RTLIL::Wire *wire = current_module->addWire(intern_hier_name(current_module->design, id), range_left - range_right + 1); + set_src_attr(wire, this); + wire->start_offset = range_right; + wire->port_id = port_id; + wire->port_input = is_input; + wire->port_output = is_output; + wire->upto = range_swapped; + + wire->is_signed = is_signed; + + for (auto &attr : attributes) { + if (attr.second->type != AST_CONSTANT) + input_error("Attribute `%s' with non-constant value!\n", attr_name_str(attr.first)); + wire->attributes[current_module->twines().add(attr_name_str(attr.first))] = attr.second->asAttrConst(); + } + + if (is_wand) wire->set_bool_attribute(ID::wand); + if (is_wor) wire->set_bool_attribute(ID::wor); + } + break; + + // create an RTLIL::Memory for an AST_MEMORY node + case AST_MEMORY: { + log_assert(children.size() >= 2); + log_assert(children[0]->type == AST_RANGE); + log_assert(children[1]->type == AST_RANGE); + + if (!children[0]->range_valid || !children[1]->range_valid) + input_error("Memory `%s' with non-constant width or size!\n", str); + + check_unique_id(current_module, str, this, "memory"); + RTLIL::Memory *memory = current_module->addMemory(intern_hier_name(current_module->design, str)); + set_src_attr(memory, this); + memory->width = children[0]->range_left - children[0]->range_right + 1; + if (children[1]->range_right < children[1]->range_left) { + memory->start_offset = children[1]->range_right; + memory->size = children[1]->range_left - children[1]->range_right + 1; + } else { + memory->start_offset = children[1]->range_left; + memory->size = children[1]->range_right - children[1]->range_left + 1; + } + + for (auto &attr : attributes) { + if (attr.second->type != AST_CONSTANT) + input_error("Attribute `%s' with non-constant value!\n", attr_name_str(attr.first)); + memory->attributes[current_module->twines().add(attr_name_str(attr.first))] = attr.second->asAttrConst(); + } + } + break; + + // simply return the corresponding RTLIL::SigSpec for an AST_CONSTANT node + case AST_CONSTANT: + case AST_REALVALUE: + { + if (width_hint < 0) + detectSignWidth(width_hint, sign_hint); + is_signed = sign_hint; + + if (type == AST_CONSTANT) { + if (is_unsized) { + return RTLIL::SigSpec(bitsAsUnsizedConst(width_hint)); + } else { + return RTLIL::SigSpec(bitsAsConst()); + } + } + + RTLIL::SigSpec sig = realAsConst(width_hint); + log_file_warning(location.to_loc(), "converting real value %e to binary %s.\n", realvalue, log_signal(sig)); + return sig; + } + + // simply return the corresponding RTLIL::SigSpec for an AST_IDENTIFIER node + // for identifiers with dynamic bit ranges (e.g. "foo[bar]" or "foo[bar+3:bar]") a + // shifter cell is created and the output signal of this cell is returned + case AST_IDENTIFIER: + { + RTLIL::Wire *wire = nullptr; + RTLIL::SigChunk chunk; + bool is_interface = false; + + AST::AstNode *member_node = nullptr; + int add_undef_bits_msb = 0; + int add_undef_bits_lsb = 0; + + log_assert(id2ast != nullptr); + + IdString str_ref = intern_hier_name(current_module->design, str); + + if (id2ast->type == AST_AUTOWIRE && current_module->wire(str_ref) == nullptr) { + RTLIL::Wire *wire = current_module->addWire(str_ref); + str_ref = wire->name; + set_src_attr(wire, this); + + if (flag_autowire) + log_file_warning(location.to_loc(), "Identifier `%s' is implicitly declared.\n", str); + else + input_error("Identifier `%s' is implicitly declared and `default_nettype is set to none.\n", str); + } + else if (id2ast->type == AST_PARAMETER || id2ast->type == AST_LOCALPARAM || id2ast->type == AST_ENUM_ITEM) { + if (id2ast->children[0]->type != AST_CONSTANT) + input_error("Parameter %s does not evaluate to constant value!\n", str); + chunk = RTLIL::Const(id2ast->children[0]->bits); + goto use_const_chunk; + } + else if ((id2ast->type == AST_WIRE || id2ast->type == AST_AUTOWIRE || id2ast->type == AST_MEMORY) && current_module->wire(str_ref) != nullptr) { + RTLIL::Wire *current_wire = current_module->wire(str_ref); + if (current_wire->get_bool_attribute(ID::is_interface)) + is_interface = true; + // Ignore + } + // If an identifier is found that is not already known, assume that it is an interface: + else if (1) { // FIXME: Check if sv_mode first? + is_interface = true; + } + else { + input_error("Identifier `%s' doesn't map to any signal!\n", str); + } + + if (id2ast->type == AST_MEMORY) + input_error("Identifier `%s' does map to an unexpanded memory!\n", str); + + // If identifier is an interface, create a RTLIL::SigSpec with a dummy wire with a attribute called 'is_interface' + // This makes it possible for the hierarchy pass to see what are interface connections and then replace them + // with the individual signals: + if (is_interface) { + IdString dummy_wire_name = current_module->twines().add(stringf("$dummywireforinterface%s", str)); + RTLIL::Wire *dummy_wire = current_module->wire(dummy_wire_name); + if (!dummy_wire) { + dummy_wire = current_module->addWire(dummy_wire_name); + dummy_wire->set_bool_attribute(ID::is_interface); + } + return dummy_wire; + } + + wire = current_module->wire(str_ref); + chunk.wire = wire; + chunk.width = wire->width; + chunk.offset = 0; + + if ((member_node = get_struct_member())) { + // Clamp wire chunk to range of member within struct/union. + chunk.width = member_node->range_left - member_node->range_right + 1; + chunk.offset = member_node->range_right; + } + + use_const_chunk: + if (children.size() != 0) { + if (children[0]->type != AST_RANGE) + input_error("Single range expected.\n"); + int source_width = id2ast->range_left - id2ast->range_right + 1; + int source_offset = id2ast->range_right; + int chunk_left = source_width - 1; + int chunk_right = 0; + + if (member_node) { + // Clamp wire chunk to range of member within struct/union. + log_assert(!source_offset && !id2ast->range_swapped); + chunk_left = chunk.offset + chunk.width - 1; + chunk_right = chunk.offset; + } + + if (!children[0]->range_valid) { + auto left_at_zero_ast = children[0]->children[0]->clone_at_zero(); + auto right_at_zero_ast = children[0]->children.size() >= 2 ? children[0]->children[1]->clone_at_zero() : left_at_zero_ast->clone(); + while (left_at_zero_ast->simplify(true, 1, -1, false)) { } + while (right_at_zero_ast->simplify(true, 1, -1, false)) { } + if (left_at_zero_ast->type != AST_CONSTANT || right_at_zero_ast->type != AST_CONSTANT) + input_error("Unsupported expression on dynamic range select on signal `%s'!\n", str); + int width = abs(int(left_at_zero_ast->integer - right_at_zero_ast->integer)) + 1; + auto fake_ast = std::make_unique(children[0]->location, AST_NONE, clone(), children[0]->children.size() >= 2 ? + children[0]->children[1]->clone() : children[0]->children[0]->clone()); + fake_ast->children[0]->delete_children(); + if (member_node) + fake_ast->children[0]->set_attribute(ID::wiretype, member_node->clone()); + + int fake_ast_width = 0; + bool fake_ast_sign = true; + fake_ast->children[1]->detectSignWidth(fake_ast_width, fake_ast_sign); + RTLIL::SigSpec shift_val = fake_ast->children[1]->genRTLIL(fake_ast_width, fake_ast_sign); + + if (source_offset != 0) { + shift_val = current_module->Sub(NEW_ID, shift_val, source_offset, fake_ast_sign); + fake_ast->children[1]->is_signed = true; + } + if (id2ast->range_swapped) { + shift_val = current_module->Sub(NEW_ID, RTLIL::SigSpec(source_width - width), shift_val, fake_ast_sign); + fake_ast->children[1]->is_signed = true; + } + if (GetSize(shift_val) >= 32) + fake_ast->children[1]->is_signed = true; + RTLIL::SigSpec sig = binop2rtlil(fake_ast.get(), ID($shiftx), width, fake_ast->children[0]->genRTLIL(), shift_val); + return sig; + } else { + chunk.width = children[0]->range_left - children[0]->range_right + 1; + chunk.offset += children[0]->range_right - source_offset; + if (id2ast->range_swapped) + chunk.offset = source_width - (chunk.offset + chunk.width); + if (chunk.offset > chunk_left || chunk.offset + chunk.width < chunk_right) { + if (chunk.width == 1) + log_file_warning(location.to_loc(), "Range select out of bounds on signal `%s': Setting result bit to undef.\n", + str); + else + log_file_warning(location.to_loc(), "Range select [%d:%d] out of bounds on signal `%s': Setting all %d result bits to undef.\n", + children[0]->range_left, children[0]->range_right, str, chunk.width); + chunk = RTLIL::SigChunk(RTLIL::State::Sx, chunk.width); + } else { + if (chunk.offset + chunk.width - 1 > chunk_left) { + add_undef_bits_msb = (chunk.offset + chunk.width - 1) - chunk_left; + chunk.width -= add_undef_bits_msb; + } + if (chunk.offset < chunk_right) { + add_undef_bits_lsb = chunk_right - chunk.offset; + chunk.width -= add_undef_bits_lsb; + chunk.offset += add_undef_bits_lsb; + } + if (add_undef_bits_lsb) + log_file_warning(location.to_loc(), "Range [%d:%d] select out of bounds on signal `%s': Setting %d LSB bits to undef.\n", + children[0]->range_left, children[0]->range_right, str, add_undef_bits_lsb); + if (add_undef_bits_msb) + log_file_warning(location.to_loc(), "Range [%d:%d] select out of bounds on signal `%s': Setting %d MSB bits to undef.\n", + children[0]->range_left, children[0]->range_right, str, add_undef_bits_msb); + } + } + } + + RTLIL::SigSpec sig = { RTLIL::SigSpec(RTLIL::State::Sx, add_undef_bits_msb), chunk, RTLIL::SigSpec(RTLIL::State::Sx, add_undef_bits_lsb) }; + + if (genRTLIL_subst_ptr) + sig.replace(*genRTLIL_subst_ptr); + + is_signed = children.size() > 0 ? false : id2ast->is_signed && sign_hint; + return sig; + } + + // just pass thru the signal. the parent will evaluate the is_signed property and interpret the SigSpec accordingly + case AST_TO_SIGNED: + case AST_TO_UNSIGNED: + case AST_SELFSZ: { + RTLIL::SigSpec sig = children[0]->genRTLIL(); + if (sig.size() < width_hint) + sig.extend_u0(width_hint, sign_hint); + is_signed = sign_hint; + return sig; + } + + // changing the size of signal can be done directly using RTLIL::SigSpec + case AST_CAST_SIZE: { + RTLIL::SigSpec size = children[0]->genRTLIL(); + if (!size.is_fully_const()) + input_error("Static cast with non constant expression!\n"); + int width = size.as_int(); + if (width <= 0) + input_error("Static cast with zero or negative size!\n"); + // determine the *signedness* of the expression + int sub_width_hint = -1; + bool sub_sign_hint = true; + children[1]->detectSignWidth(sub_width_hint, sub_sign_hint); + // generate the signal given the *cast's* size and the + // *expression's* signedness + RTLIL::SigSpec sig = children[1]->genWidthRTLIL(width, sub_sign_hint); + // context may effect this node's signedness, but not that of the + // casted expression + is_signed = sign_hint; + return sig; + } + + // concatenation of signals can be done directly using RTLIL::SigSpec + case AST_CONCAT: { + RTLIL::SigSpec sig; + for (auto it = children.begin(); it != children.end(); it++) + sig.append((*it)->genRTLIL()); + if (sig.size() < width_hint) + sig.extend_u0(width_hint, false); + return sig; + } + + // replication of signals can be done directly using RTLIL::SigSpec + case AST_REPLICATE: { + RTLIL::SigSpec left = children[0]->genRTLIL(); + RTLIL::SigSpec right = children[1]->genRTLIL(); + if (!left.is_fully_const()) + input_error("Left operand of replicate expression is not constant!\n"); + int count = left.as_int(); + RTLIL::SigSpec sig; + for (int i = 0; i < count; i++) + sig.append(right); + if (sig.size() < width_hint) + sig.extend_u0(width_hint, false); + is_signed = false; + return sig; + } + + case AST_ASSIGN_PATTERN: + input_error("Assignment pattern is only supported for whole unpacked array assignments.\n"); + + // generate cells for unary operations: $not, $pos, $neg + if (0) { case AST_BIT_NOT: type_name = ID($not); } + if (0) { case AST_POS: type_name = ID($pos); } + if (0) { case AST_NEG: type_name = ID($neg); } + { + RTLIL::SigSpec arg = children[0]->genRTLIL(width_hint, sign_hint); + is_signed = children[0]->is_signed; + int width = arg.size(); + if (width_hint > 0) { + width = width_hint; + widthExtend(this, arg, width, is_signed); + } + return uniop2rtlil(this, type_name, width, arg); + } + + // generate cells for binary operations: $and, $or, $xor, $xnor + if (0) { case AST_BIT_AND: type_name = ID($and); } + if (0) { case AST_BIT_OR: type_name = ID($or); } + if (0) { case AST_BIT_XOR: type_name = ID($xor); } + if (0) { case AST_BIT_XNOR: type_name = ID($xnor); } + { + if (width_hint < 0) + detectSignWidth(width_hint, sign_hint); + RTLIL::SigSpec left = children[0]->genRTLIL(width_hint, sign_hint); + RTLIL::SigSpec right = children[1]->genRTLIL(width_hint, sign_hint); + int width = max(left.size(), right.size()); + if (width_hint > 0) + width = width_hint; + is_signed = children[0]->is_signed && children[1]->is_signed; + return binop2rtlil(this, type_name, width, left, right); + } + + // generate cells for unary operations: $reduce_and, $reduce_or, $reduce_xor, $reduce_xnor + if (0) { case AST_REDUCE_AND: type_name = ID($reduce_and); } + if (0) { case AST_REDUCE_OR: type_name = ID($reduce_or); } + if (0) { case AST_REDUCE_XOR: type_name = ID($reduce_xor); } + if (0) { case AST_REDUCE_XNOR: type_name = ID($reduce_xnor); } + { + RTLIL::SigSpec arg = children[0]->genRTLIL(); + RTLIL::SigSpec sig = uniop2rtlil(this, type_name, max(width_hint, 1), arg); + return sig; + } + + // generate cells for unary operations: $reduce_bool + // (this is actually just an $reduce_or, but for clarity a different cell type is used) + if (0) { case AST_REDUCE_BOOL: type_name = ID($reduce_bool); } + { + RTLIL::SigSpec arg = children[0]->genRTLIL(); + RTLIL::SigSpec sig = arg.size() > 1 ? uniop2rtlil(this, type_name, max(width_hint, 1), arg) : arg; + return sig; + } + + // generate cells for binary operations: $shl, $shr, $sshl, $sshr + if (0) { case AST_SHIFT_LEFT: type_name = ID($shl); } + if (0) { case AST_SHIFT_RIGHT: type_name = ID($shr); } + if (0) { case AST_SHIFT_SLEFT: type_name = ID($sshl); } + if (0) { case AST_SHIFT_SRIGHT: type_name = ID($sshr); } + if (0) { case AST_SHIFTX: type_name = ID($shiftx); } + if (0) { case AST_SHIFT: type_name = ID($shift); } + { + if (width_hint < 0) + detectSignWidth(width_hint, sign_hint); + RTLIL::SigSpec left = children[0]->genRTLIL(width_hint, sign_hint); + // for $shift and $shiftx, the second operand can be negative + RTLIL::SigSpec right = children[1]->genRTLIL(-1, type == AST_SHIFT || type == AST_SHIFTX); + int width = width_hint > 0 ? width_hint : left.size(); + is_signed = children[0]->is_signed; + return binop2rtlil(this, type_name, width, left, right); + } + + // generate cells for binary operations: $pow + case AST_POW: + { + int right_width; + bool right_signed; + children[1]->detectSignWidth(right_width, right_signed); + if (width_hint < 0) + detectSignWidth(width_hint, sign_hint); + RTLIL::SigSpec left = children[0]->genRTLIL(width_hint, sign_hint); + RTLIL::SigSpec right = children[1]->genRTLIL(right_width, right_signed); + int width = width_hint > 0 ? width_hint : left.size(); + is_signed = children[0]->is_signed; + if (!flag_noopt && left.is_fully_const() && left.as_int() == 2 && !right_signed) + return binop2rtlil(this, ID($shl), width, RTLIL::SigSpec(1, left.size()), right); + return binop2rtlil(this, ID($pow), width, left, right); + } + + // generate cells for binary operations: $lt, $le, $eq, $ne, $ge, $gt + if (0) { case AST_LT: type_name = ID($lt); } + if (0) { case AST_LE: type_name = ID($le); } + if (0) { case AST_EQ: type_name = ID($eq); } + if (0) { case AST_NE: type_name = ID($ne); } + if (0) { case AST_EQX: type_name = ID($eqx); } + if (0) { case AST_NEX: type_name = ID($nex); } + if (0) { case AST_GE: type_name = ID($ge); } + if (0) { case AST_GT: type_name = ID($gt); } + { + int width = max(width_hint, 1); + width_hint = -1, sign_hint = true; + children[0]->detectSignWidthWorker(width_hint, sign_hint); + children[1]->detectSignWidthWorker(width_hint, sign_hint); + RTLIL::SigSpec left = children[0]->genRTLIL(width_hint, sign_hint); + RTLIL::SigSpec right = children[1]->genRTLIL(width_hint, sign_hint); + RTLIL::SigSpec sig = binop2rtlil(this, type_name, width, left, right); + return sig; + } + + // generate cells for binary operations: $add, $sub, $mul, $div, $mod + if (0) { case AST_ADD: type_name = ID($add); } + if (0) { case AST_SUB: type_name = ID($sub); } + if (0) { case AST_MUL: type_name = ID($mul); } + if (0) { case AST_DIV: type_name = ID($div); } + if (0) { case AST_MOD: type_name = ID($mod); } + { + if (width_hint < 0) + detectSignWidth(width_hint, sign_hint); + RTLIL::SigSpec left = children[0]->genRTLIL(width_hint, sign_hint); + RTLIL::SigSpec right = children[1]->genRTLIL(width_hint, sign_hint); + #if 0 + int width = max(left.size(), right.size()); + if (width > width_hint && width_hint > 0) + width = width_hint; + if (width < width_hint) { + if (type == AST_ADD || type == AST_SUB || type == AST_DIV) + width++; + if (type == AST_SUB && (!children[0]->is_signed || !children[1]->is_signed)) + width = width_hint; + if (type == AST_MUL) + width = min(left.size() + right.size(), width_hint); + } + #else + int width = max(max(left.size(), right.size()), width_hint); + #endif + is_signed = children[0]->is_signed && children[1]->is_signed; + return binop2rtlil(this, type_name, width, left, right); + } + + // generate cells for binary operations: $logic_and, $logic_or + if (0) { case AST_LOGIC_AND: type_name = ID($logic_and); } + if (0) { case AST_LOGIC_OR: type_name = ID($logic_or); } + { + RTLIL::SigSpec left = children[0]->genRTLIL(); + RTLIL::SigSpec right = children[1]->genRTLIL(); + return binop2rtlil(this, type_name, max(width_hint, 1), left, right); + } + + // generate cells for unary operations: $logic_not + case AST_LOGIC_NOT: + { + RTLIL::SigSpec arg = children[0]->genRTLIL(); + return uniop2rtlil(this, ID($logic_not), max(width_hint, 1), arg); + } + + // generate multiplexer for ternary operator (aka ?:-operator) + case AST_TERNARY: + { + if (width_hint < 0) + detectSignWidth(width_hint, sign_hint); + is_signed = sign_hint; + + RTLIL::SigSpec cond = children[0]->genRTLIL(); + RTLIL::SigSpec sig; + + if (cond.is_fully_def()) + { + if (cond.as_bool()) { + sig = children[1]->genRTLIL(width_hint, sign_hint); + log_assert(is_signed == children[1]->is_signed); + } else { + sig = children[2]->genRTLIL(width_hint, sign_hint); + log_assert(is_signed == children[2]->is_signed); + } + + widthExtend(this, sig, sig.size(), is_signed); + } + else + { + RTLIL::SigSpec val1 = children[1]->genRTLIL(width_hint, sign_hint); + RTLIL::SigSpec val2 = children[2]->genRTLIL(width_hint, sign_hint); + + if (cond.size() > 1) + cond = uniop2rtlil(this, ID($reduce_bool), 1, cond, false); + + int width = max(val1.size(), val2.size()); + log_assert(is_signed == children[1]->is_signed); + log_assert(is_signed == children[2]->is_signed); + widthExtend(this, val1, width, is_signed); + widthExtend(this, val2, width, is_signed); + + sig = mux2rtlil(this, cond, val1, val2); + } + + if (sig.size() < width_hint) + sig.extend_u0(width_hint, sign_hint); + return sig; + } + + // generate $memrd cells for memory read ports + case AST_MEMRD: + { + IdString name = current_module->twines().add(TwineSpec::Suffix{ + intern_src_name(current_module->design, location, "$memrd", ast_autoidx()), + stringf("$%s", str)}); + + RTLIL::Cell *cell = current_module->addCell(name, ID($memrd)); + set_src_attr(cell, this); + + IdString mem_tw = current_module->twines().find(str); + RTLIL::Wire *wire = current_module->addWire(cell->name.str() + "_DATA", current_module->memories[mem_tw]->width); + set_src_attr(wire, this); + + int mem_width, mem_size, addr_bits; + is_signed = id2ast->is_signed; + wire->is_signed = is_signed; + id2ast->meminfo(mem_width, mem_size, addr_bits); + + RTLIL::SigSpec addr_sig = children[0]->genRTLIL(); + + cell->setPort(ID::CLK, RTLIL::SigSpec(RTLIL::State::Sx, 1)); + cell->setPort(ID::EN, RTLIL::SigSpec(RTLIL::State::Sx, 1)); + cell->setPort(ID::ADDR, addr_sig); + cell->setPort(ID::DATA, RTLIL::SigSpec(wire)); + + cell->parameters[ID::MEMID] = RTLIL::Const(str); + cell->parameters[ID::ABITS] = RTLIL::Const(GetSize(addr_sig)); + cell->parameters[ID::WIDTH] = RTLIL::Const(wire->width); + + cell->parameters[ID::CLK_ENABLE] = RTLIL::Const(0); + cell->parameters[ID::CLK_POLARITY] = RTLIL::Const(0); + cell->parameters[ID::TRANSPARENT] = RTLIL::Const(0); + + if (!sign_hint) + is_signed = false; + + return RTLIL::SigSpec(wire); + } + + // generate $meminit cells + case AST_MEMINIT: + { + IdString name = current_module->twines().add(TwineSpec::Suffix{ + intern_src_name(current_module->design, location, "$meminit", ast_autoidx()), + stringf("$%s", str)}); + + SigSpec en_sig = children[2]->genRTLIL(); + + RTLIL::Cell *cell = current_module->addCell(name, ID($meminit_v2)); + set_src_attr(cell, this); + + int mem_width, mem_size, addr_bits; + id2ast->meminfo(mem_width, mem_size, addr_bits); + + if (children[3]->type != AST_CONSTANT) + input_error("Memory init with non-constant word count!\n"); + int num_words = int(children[3]->asInt(false)); + cell->parameters[ID::WORDS] = RTLIL::Const(num_words); + + SigSpec addr_sig = children[0]->genRTLIL(); + + IdString mem_tw = current_module->twines().find(str); + cell->setPort(ID::ADDR, addr_sig); + cell->setPort(ID::DATA, children[1]->genWidthRTLIL(current_module->memories[mem_tw]->width * num_words, true)); + cell->setPort(ID::EN, en_sig); + + cell->parameters[ID::MEMID] = RTLIL::Const(str); + cell->parameters[ID::ABITS] = RTLIL::Const(GetSize(addr_sig)); + cell->parameters[ID::WIDTH] = RTLIL::Const(current_module->memories[mem_tw]->width); + + cell->parameters[ID::PRIORITY] = RTLIL::Const(current_module->twines().autoidx()-1); + } + break; + + // generate $check cells + case AST_ASSERT: + case AST_ASSUME: + case AST_LIVE: + case AST_FAIR: + case AST_COVER: + { + std::string flavor, desc; + if (type == AST_ASSERT) { flavor = "assert"; desc = "assert property ()"; } + if (type == AST_ASSUME) { flavor = "assume"; desc = "assume property ()"; } + if (type == AST_LIVE) { flavor = "live"; desc = "assert property (eventually)"; } + if (type == AST_FAIR) { flavor = "fair"; desc = "assume property (eventually)"; } + if (type == AST_COVER) { flavor = "cover"; desc = "cover property ()"; } + + IdString cellname; + if (str.empty()) + cellname = intern_src_name(current_module->design, location, + stringf("$%s", flavor), ast_autoidx()); + else + cellname = current_module->twines().add(str); + check_unique_id(current_module, cellname, this, "procedural assertion"); + + RTLIL::SigSpec check = children[0]->genRTLIL(); + if (GetSize(check) != 1) + check = current_module->ReduceBool(NEW_ID, check); + + RTLIL::Cell *cell = current_module->addCell(cellname, ID($check)); + set_src_attr(cell, this); + for (auto &attr : attributes) { + if (attr.second->type != AST_CONSTANT) + input_error("Attribute `%s' with non-constant value!\n", attr_name_str(attr.first)); + cell->attributes[current_module->twines().add(attr_name_str(attr.first))] = attr.second->asAttrConst(); + } + cell->setParam(ID(FLAVOR), flavor); + cell->parameters[ID::TRG_WIDTH] = 0; + cell->parameters[ID::TRG_ENABLE] = 0; + cell->parameters[ID::TRG_POLARITY] = 0; + cell->parameters[ID::PRIORITY] = 0; + cell->setPort(ID::TRG, RTLIL::SigSpec()); + cell->setPort(ID::EN, RTLIL::S1); + cell->setPort(ID::A, check); + + // No message is emitted to ensure Verilog code roundtrips correctly. + Fmt fmt; + fmt.emit_rtlil(cell); + } + break; + + // add entries to current_module->connections for assignments (outside of always blocks) + case AST_ASSIGN: + { + RTLIL::SigSpec left = children[0]->genRTLIL(); + RTLIL::SigSpec right = children[1]->genWidthRTLIL(left.size(), true); + if (left.has_const()) { + RTLIL::SigSpec new_left, new_right; + for (int i = 0; i < GetSize(left); i++) + if (left[i].wire) { + new_left.append(left[i]); + new_right.append(right[i]); + } + log_file_warning(location.to_loc(), "Ignoring assignment to constant bits:\n" + " old assignment: %s = %s\n new assignment: %s = %s.\n", + log_signal(left), log_signal(right), + log_signal(new_left), log_signal(new_right)); + left = new_left; + right = new_right; + } + current_module->connect(RTLIL::SigSig(left, right)); + } + break; + + // create an RTLIL::Cell for an AST_CELL + case AST_CELL: + { + int port_counter = 0, para_counter = 0; + + const std::string &id = str; + check_unique_id(current_module, id, this, "cell"); + RTLIL::Cell *cell = current_module->addCell(intern_hier_name(current_module->design, id), IdString::Null); + set_src_attr(cell, this); + + for (auto it = children.begin(); it != children.end(); it++) { + auto* child = it->get(); + if (child->type == AST_CELLTYPE) { + std::string type_str = child->str; + if (flag_icells && type_str.size() >= 2 && type_str[0] == '\\' && type_str[1] == '$') + type_str = type_str.substr(1); + cell->type = current_module->twines().add(type_str); + continue; + } + if (child->type == AST_PARASET) { + IdString paraname = current_module->twines().add(child->str.empty() ? stringf("$%d", ++para_counter) : child->str); + const auto* value = child->children[0].get(); + if (value->type == AST_REALVALUE) + log_file_warning(location.to_loc(), "Replacing floating point parameter %s.%s = %f with string.\n", + cell, PooledName(current_module->design, paraname).unescape(), value->realvalue); + else if (value->type != AST_CONSTANT) + input_error("Parameter %s.%s with non-constant value!\n", + cell, PooledName(current_module->design, paraname).unescape()); + cell->parameters[paraname] = value->asParaConst(); + continue; + } + if (child->type == AST_ARGUMENT) { + RTLIL::SigSpec sig; + if (child->children.size() > 0) { + auto* arg = child->children[0].get(); + int local_width_hint = -1; + bool local_sign_hint = false; + // don't inadvertently attempt to detect the width of interfaces + if (arg->type != AST_IDENTIFIER || !arg->id2ast || arg->id2ast->type != AST_CELL) + arg->detectSignWidth(local_width_hint, local_sign_hint); + sig = arg->genRTLIL(local_width_hint, local_sign_hint); + log_assert(local_sign_hint == arg->is_signed); + if (sig.is_wire()) { + // if the resulting SigSpec is a wire, its + // signedness should match that of the AstNode + if (arg->type == AST_IDENTIFIER && arg->id2ast && arg->id2ast->is_signed && !arg->is_signed) + // fully-sliced signed wire will be resolved + // once the module becomes available + log_assert(attributes.count(ID::reprocess_after)); + else + log_assert(arg->is_signed == sig.as_wire()->is_signed); + } else if (arg->is_signed) { + // non-trivial signed nodes are indirected through + // signed wires to enable sign extension + IdString wire_name = current_module->twines().add(NEW_ID); + RTLIL::Wire *wire = current_module->addWire(wire_name, GetSize(sig)); + wire->is_signed = true; + current_module->connect(wire, sig); + sig = wire; + } + } + if (child->str.size() == 0) { + char buf[100]; + snprintf(buf, 100, "$%d", ++port_counter); + cell->setPort(current_module->twines().add(buf), sig); + } else { + cell->setPort(current_module->twines().add(child->str), sig); + } + continue; + } + log_abort(); + } + + // Set attribute 'module_not_derived' which will be cleared again after the hierarchy pass + if (cell->type.isPublic()) + cell->set_bool_attribute(ID::module_not_derived); + + for (auto &attr : attributes) { + if (attr.second->type != AST_CONSTANT) + input_error("Attribute `%s' with non-constant value.\n", attr_name_str(attr.first)); + cell->attributes[current_module->twines().add(attr_name_str(attr.first))] = attr.second->asAttrConst(); + } + if (cell->type == ID($specify2)) { + int src_width = GetSize(cell->getPort(ID::SRC)); + int dst_width = GetSize(cell->getPort(ID::DST)); + bool full = cell->getParam(ID::FULL).as_bool(); + if (!full && src_width != dst_width) + input_error("Parallel specify SRC width does not match DST width.\n"); + cell->setParam(ID::SRC_WIDTH, Const(src_width)); + cell->setParam(ID::DST_WIDTH, Const(dst_width)); + } + else if (cell->type == ID($specify3)) { + int dat_width = GetSize(cell->getPort(ID::DAT)); + int dst_width = GetSize(cell->getPort(ID::DST)); + if (dat_width != dst_width) + input_error("Specify DAT width does not match DST width.\n"); + int src_width = GetSize(cell->getPort(ID::SRC)); + cell->setParam(ID::SRC_WIDTH, Const(src_width)); + cell->setParam(ID::DST_WIDTH, Const(dst_width)); + } + else if (cell->type == ID($specrule)) { + int src_width = GetSize(cell->getPort(ID::SRC)); + int dst_width = GetSize(cell->getPort(ID::DST)); + cell->setParam(ID::SRC_WIDTH, Const(src_width)); + cell->setParam(ID::DST_WIDTH, Const(dst_width)); + } + } + break; + + // use ProcessGenerator for always blocks + case AST_ALWAYS: { + ProcessGenerator generator(this->clone()); + ignoreThisSignalsInInitial.append(generator.outputSignals); + } break; + + case AST_INITIAL: { + auto always = this->clone(); + ProcessGenerator generator(this->clone(), ignoreThisSignalsInInitial); + } break; + + case AST_TECALL: { + int sz = children.size(); + if (str == "$info") { + if (sz > 0) + log_file_info(location.to_loc(), "%s.\n", children[0]->str); + else + log_file_info(location.to_loc(), "\n"); + } else if (str == "$warning") { + if (sz > 0) + log_file_warning(location.to_loc(), "%s.\n", children[0]->str); + else + log_file_warning(location.to_loc(), "\n"); + } else if (str == "$error") { + if (sz > 0) + input_error("%s.\n", children[0]->str); + else + input_error("\n"); + } else if (str == "$fatal") { + // TODO: 1st parameter, if exists, is 0,1 or 2, and passed to $finish() + // if no parameter is given, default value is 1 + // dollar_finish(sz ? children[0] : 1); + // perhaps create & use log_file_fatal() + if (sz > 0) + input_error("FATAL: %s.\n", children[0]->str); + else + input_error("FATAL.\n"); + } else { + input_error("Unknown elaboration system task '%s'.\n", str); + } + } break; + + case AST_FCALL: { + if (str == "\\$anyconst" || str == "\\$anyseq" || str == "\\$allconst" || str == "\\$allseq") + { + string myid = stringf("%s$%d", str.substr(1), ast_autoidx()); + int width = width_hint; + + if (GetSize(children) > 1) + input_error("System function %s got %d arguments, expected 1 or 0.\n", + RTLIL::unescape_id(str), GetSize(children)); + + if (GetSize(children) == 1) { + if (children[0]->type != AST_CONSTANT) + input_error("System function %s called with non-const argument!\n", + RTLIL::unescape_id(str)); + width = children[0]->asInt(true); + } + + if (width <= 0) + input_error("Failed to detect width of %s!\n", RTLIL::unescape_id(str)); + + IdString _type = current_module->twines().add(str.substr(1)); + Cell *cell = current_module->addCell(myid, _type); + set_src_attr(cell, this); + cell->parameters[ID::WIDTH] = width; + + if (attributes.count(ID::reg)) { + auto &attr = attributes.at(ID::reg); + if (attr->type != AST_CONSTANT) + input_error("Attribute `reg' with non-constant value!\n"); + cell->attributes[ID::reg] = attr->asAttrConst(); + } + + Wire *wire = current_module->addWire(myid + "_wire", width); + set_src_attr(wire, this); + cell->setPort(ID::Y, wire); + + is_signed = sign_hint; + return SigSpec(wire); + } + } + YS_FALLTHROUGH + + // everything should have been handled above -> print error if not. + default: + logger().for_each_sink([&](LogSink &sink) { + FILE *f = sink.file_handle(); + if (f) + current_ast_mod->dumpAst(f, "verilog-ast> "); + }); + input_error("Don't know how to generate RTLIL code for %s node!\n", type2str(type)); + } + + return RTLIL::SigSpec(); +} + +// this is a wrapper for AstNode::genRTLIL() when a specific signal width is requested and/or +// signals must be substituted before being used as input values (used by ProcessGenerator) +// note that this is using some global variables to communicate this special settings to AstNode::genRTLIL(). +RTLIL::SigSpec AstNode::genWidthRTLIL(int width, bool sgn, const dict *new_subst_ptr) +{ + const dict *backup_subst_ptr = genRTLIL_subst_ptr; + + if (new_subst_ptr) + genRTLIL_subst_ptr = new_subst_ptr; + + bool sign_hint = sgn; + int width_hint = width; + detectSignWidthWorker(width_hint, sign_hint); + RTLIL::SigSpec sig = genRTLIL(width_hint, sign_hint); + + genRTLIL_subst_ptr = backup_subst_ptr; + + if (width >= 0) + sig.extend_u0(width, is_signed); + + return sig; +} + +YOSYS_NAMESPACE_END diff --git a/chips/yosys/frontends/ast/simplify.cc b/chips/yosys/frontends/ast/simplify.cc new file mode 100644 index 0000000000000000000000000000000000000000..f705a96bcf30eecbe127ec7e0a91becf4af2fd9c --- /dev/null +++ b/chips/yosys/frontends/ast/simplify.cc @@ -0,0 +1,6379 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * --- + * + * This is the AST frontend library. + * + * The AST frontend library is not a frontend on it's own but provides a + * generic abstract syntax tree (AST) abstraction for HDL code and can be + * used by HDL frontends. See "ast.h" for an overview of the API and the + * Verilog frontend for an usage example. + * + */ + +#include "kernel/log.h" +#include "libs/sha1/sha1.h" +#include "frontends/verilog/verilog_frontend.h" +#include "ast.h" +#include "kernel/io.h" + +#include +#include +#include +#include +#include +#include + +YOSYS_NAMESPACE_BEGIN + +using namespace AST; +using namespace AST_INTERNAL; + +void AstNode::set_in_lvalue_flag(bool flag, bool no_descend) +{ + if (flag != in_lvalue_from_above) { + in_lvalue_from_above = flag; + if (!no_descend) + fixup_hierarchy_flags(); + } +} + +void AstNode::set_in_param_flag(bool flag, bool no_descend) +{ + if (flag != in_param_from_above) { + in_param_from_above = flag; + if (!no_descend) + fixup_hierarchy_flags(); + } +} + +void AstNode::fixup_hierarchy_flags(bool force_descend) +{ + // With forced descend, we disable the implicit + // descend from within the set_* functions, instead + // we do an explicit descend at the end of this function + + in_param = in_param_from_above; + + switch (type) { + case AST_PARAMETER: + case AST_LOCALPARAM: + case AST_DEFPARAM: + case AST_PARASET: + case AST_PREFIX: + in_param = true; + for (auto& child : children) + child->set_in_param_flag(true, force_descend); + break; + + case AST_REPLICATE: + case AST_WIRE: + case AST_GENIF: + case AST_GENCASE: + for (auto& child : children) + child->set_in_param_flag(in_param, force_descend); + if (children.size() >= 1) + children[0]->set_in_param_flag(true, force_descend); + break; + + case AST_ASSIGN_PATTERN: + for (auto& child : children) + child->set_in_param_flag(in_param, force_descend); + break; + + case AST_GENFOR: + case AST_FOR: + for (auto& child : children) { + log_assert((bool)child); + child->set_in_param_flag(in_param, force_descend); + } + if (children.size() >= 2) + children[1]->set_in_param_flag(true, force_descend); + break; + + default: + in_param = in_param_from_above; + for (auto& child : children) + child->set_in_param_flag(in_param, force_descend); + } + + for (auto& attr : attributes) + attr.second->set_in_param_flag(true, force_descend); + + in_lvalue = in_lvalue_from_above; + + switch (type) { + case AST_ASSIGN: + case AST_ASSIGN_EQ: + case AST_ASSIGN_LE: + if (children.size() >= 1) + children[0]->set_in_lvalue_flag(true, force_descend); + if (children.size() >= 2) + children[1]->set_in_lvalue_flag(in_lvalue, force_descend); + break; + + default: + for (auto& child : children) + child->set_in_lvalue_flag(in_lvalue, force_descend); + } + + if (force_descend) { + for (auto& child : children) + child->fixup_hierarchy_flags(true); + for (auto& attr : attributes) + attr.second->fixup_hierarchy_flags(true); + } +} + +// Process a format string and arguments for $display, $write, $sprintf, etc + +Fmt AstNode::processFormat(int stage, bool sformat_like, int default_base, size_t first_arg_at, bool may_fail) { + std::vector args; + for (size_t index = first_arg_at; index < children.size(); index++) { + AstNode *node_arg = children[index].get(); + while (node_arg->simplify(true, stage, -1, false)) { } + + VerilogFmtArg arg = {}; + arg.src = location.to_loc(); + if (node_arg->type == AST_CONSTANT && node_arg->is_string) { + arg.type = VerilogFmtArg::STRING; + arg.str = node_arg->bitsAsConst().decode_string(); + // and in case this will be used as an argument... + arg.sig = node_arg->bitsAsConst(); + arg.signed_ = false; + } else if (node_arg->type == AST_IDENTIFIER && node_arg->str == "$time") { + arg.type = VerilogFmtArg::TIME; + } else if (node_arg->type == AST_IDENTIFIER && node_arg->str == "$realtime") { + arg.type = VerilogFmtArg::TIME; + arg.realtime = true; + } else if (node_arg->type == AST_CONSTANT) { + arg.type = VerilogFmtArg::INTEGER; + arg.sig = node_arg->bitsAsConst(); + arg.signed_ = node_arg->is_signed; + } else if (may_fail) { + log_file_info(arg.src, "Skipping system task `%s' with non-constant argument at position %zu.\n", str, index + 1); + return Fmt(); + } else { + log_file_error(arg.src, "Failed to evaluate system task `%s' with non-constant argument at position %zu.\n", str, index + 1); + } + args.push_back(arg); + } + + Fmt fmt; + fmt.parse_verilog(args, sformat_like, default_base, /*task_name=*/str, current_module->name); + return fmt; +} + +void AstNode::annotateTypedEnums(AstNode *template_node) +{ + //check if enum + if (template_node->attributes.count(ID::enum_type)) { + //get reference to enum node: + std::string enum_type = template_node->attributes[ID::enum_type]->str.c_str(); + // log("enum_type=%s (count=%lu)\n", enum_type, current_scope.count(enum_type)); + // log("current scope:\n"); + // for (auto &it : current_scope) + // log(" %s\n", it.first); + log_assert(current_scope.count(enum_type) == 1); + AstNode *enum_node = current_scope.at(enum_type); + log_assert(enum_node->type == AST_ENUM); + while (enum_node->simplify(true, 1, -1, false)) { } + //get width from 1st enum item: + log_assert(enum_node->children.size() >= 1); + AstNode *enum_item0 = enum_node->children[0].get(); + log_assert(enum_item0->type == AST_ENUM_ITEM); + int width; + if (!enum_item0->range_valid) + width = 1; + else if (enum_item0->range_swapped) + width = enum_item0->range_right - enum_item0->range_left + 1; + else + width = enum_item0->range_left - enum_item0->range_right + 1; + log_assert(width > 0); + //add declared enum items: + for (auto& enum_item : enum_node->children){ + log_assert(enum_item->type == AST_ENUM_ITEM); + //get is_signed + bool is_signed; + if (enum_item->children.size() == 1){ + is_signed = false; + } else if (enum_item->children.size() == 2){ + log_assert(enum_item->children[1]->type == AST_RANGE); + is_signed = enum_item->children[1]->is_signed; + } else { + log_error("enum_item children size==%zu, expected 1 or 2 for %s (%s)\n", + (size_t) enum_item->children.size(), + enum_item->str, enum_node->str + ); + } + //start building attribute string + std::string enum_item_str = "\\enum_value_"; + //get enum item value + if(enum_item->children[0]->type != AST_CONSTANT){ + log_error("expected const, got %s for %s (%s)\n", + type2str(enum_item->children[0]->type), + enum_item->str, enum_node->str + ); + } + RTLIL::Const val = enum_item->children[0]->bitsAsConst(width, is_signed); + enum_item_str.append(val.as_string()); + //set attribute for available val to enum item name mappings + set_attribute(enum_item_str.c_str(), mkconst_str(location, enum_item->str)); + } + } +} + +static std::unique_ptr make_range(AstSrcLocType loc, int left, int right, bool is_signed = false) +{ + // generate a pre-validated range node for a fixed signal range. + auto range = std::make_unique(loc, AST_RANGE); + range->range_left = left; + range->range_right = right; + range->range_valid = true; + range->children.push_back(AstNode::mkconst_int(loc, left, true)); + range->children.push_back(AstNode::mkconst_int(loc, right, true)); + range->is_signed = is_signed; + return range; +} + +static int range_width(AstNode *node, AstNode *rnode) +{ + log_assert(rnode->type==AST_RANGE); + if (!rnode->range_valid) { + node->input_error("Non-constant range in declaration of %s\n", node->str); + } + // note: range swapping has already been checked for + return rnode->range_left - rnode->range_right + 1; +} + +static int add_dimension(AstNode *node, AstNode *rnode) +{ + int width = range_width(node, rnode); + node->dimensions.push_back({ rnode->range_right, width, rnode->range_swapped }); + return width; +} + +[[noreturn]] static void struct_array_packing_error(AstNode *node) +{ + node->input_error("Unpacked array in packed struct/union member %s\n", node->str); +} + +// Check if node is an unexpanded array reference (AST_IDENTIFIER -> AST_MEMORY without indexing) +static bool is_unexpanded_array_ref(AstNode *node) +{ + if (node->type != AST_IDENTIFIER) + return false; + if (node->id2ast == nullptr || node->id2ast->type != AST_MEMORY) + return false; + // No indexing children = whole array reference + return node->children.empty(); +} + +// Check if two memories have compatible unpacked dimensions for array assignment +static bool arrays_have_compatible_dims(AstNode *mem_a, AstNode *mem_b) +{ + if (mem_a->unpacked_dimensions != mem_b->unpacked_dimensions) + return false; + for (int i = 0; i < mem_a->unpacked_dimensions; i++) { + if (mem_a->dimensions[i].range_width != mem_b->dimensions[i].range_width) + return false; + } + // Also check packed dimensions (element width) + int a_width, a_size, a_bits; + int b_width, b_size, b_bits; + mem_a->meminfo(a_width, a_size, a_bits); + mem_b->meminfo(b_width, b_size, b_bits); + return a_width == b_width; +} + +// Check if mem_b matches mem_a's unpacked dimensions starting at first_dim. +static bool arrays_have_compatible_dims_from(AstNode *mem_a, int first_dim, AstNode *mem_b) +{ + if (mem_b->unpacked_dimensions != mem_a->unpacked_dimensions - first_dim) + return false; + for (int i = 0; i < mem_b->unpacked_dimensions; i++) { + if (mem_a->dimensions[first_dim + i].range_width != mem_b->dimensions[i].range_width) + return false; + } + // Also check packed dimensions (element width) + int a_width, a_size, a_bits; + int b_width, b_size, b_bits; + mem_a->meminfo(a_width, a_size, a_bits); + mem_b->meminfo(b_width, b_size, b_bits); + return a_width == b_width; +} + +// Convert per-dimension element positions to declared index values. +// Position 0 is the first declared element for each unpacked dimension. +static std::vector array_indices_from_position(AstNode *mem, const std::vector &position) +{ + int num_dims = mem->unpacked_dimensions; + log_assert(GetSize(position) == num_dims); + + std::vector indices(num_dims); + for (int d = 0; d < num_dims; d++) { + int low = mem->dimensions[d].range_right; + int high = low + mem->dimensions[d].range_width - 1; + indices[d] = mem->dimensions[d].range_swapped ? (low + position[d]) : (high - position[d]); + } + return indices; +} + +// Convert per-dimension element positions to a flattened, 1D array position. +// This reproduces all the quirks of array flattening wrt. indexing. Oh well... +static int flattened_array_index_from_position(AstNode *mem, const std::vector &position) +{ + int num_dims = mem->unpacked_dimensions; + log_assert(GetSize(position) == num_dims); + + int index = 0; + for (int d = 0; d < num_dims; d++) { + if (d > 0) + index *= mem->dimensions[d].range_width; + int width = mem->dimensions[d].range_width; + bool swap = mem->dimensions[d].range_swapped || num_dims > 1; + index += swap ? position[d] : width - position[d] - 1; + } + + return index; +} + +// Generate all element positions for a multi-dimensional unpacked array and +// call callback once for each combination. +static void foreach_array_position(AstNode *mem, std::function&)> callback) +{ + int num_dims = mem->unpacked_dimensions; + if (num_dims == 0) { + callback({}); + return; + } + + std::vector position(num_dims, 0); + std::vector sizes(num_dims); + + for (int d = 0; d < num_dims; d++) + sizes[d] = mem->dimensions[d].range_width; + + // Iterate through all position combinations (rightmost dimension fastest). + while (true) { + callback(position); + + int d = num_dims - 1; + while (d >= 0) { + position[d]++; + if (position[d] < sizes[d]) + break; + position[d] = 0; + d--; + } + if (d < 0) + break; + } +} + +static int size_packed_struct(AstNode *snode, int base_offset) +{ + // Struct members will be laid out in the structure contiguously from left to right. + // Union members all have zero offset from the start of the union. + // Determine total packed size and assign offsets. Store these in the member node. + bool is_union = (snode->type == AST_UNION); + int offset = 0; + int packed_width = -1; + // examine members from last to first + for (auto it = snode->children.rbegin(); it != snode->children.rend(); ++it) { + auto node = it->get(); + int width; + if (node->type == AST_STRUCT || node->type == AST_UNION) { + // embedded struct or union + width = size_packed_struct(node, base_offset + offset); + } + else { + log_assert(node->type == AST_STRUCT_ITEM); + if (node->children.size() > 0 && node->children[0]->type == AST_RANGE) { + // member width e.g. bit [7:0] a + width = range_width(node, node->children[0].get()); + if (node->children.size() == 2) { + // Unpacked array. Note that this is a Yosys extension; only packed data types + // and integer data types are allowed in packed structs / unions in SystemVerilog. + if (node->children[1]->type == AST_RANGE) { + // Unpacked array, e.g. bit [63:0] a [0:3] + // Pretend it's declared as a packed array, e.g. bit [0:3][63:0] a + auto rnode = node->children[1].get(); + if (rnode->children.size() == 1) { + // C-style array size, e.g. bit [63:0] a [4] + node->dimensions.push_back({ 0, rnode->range_left, true }); + width *= rnode->range_left; + } else { + width *= add_dimension(node, rnode); + } + add_dimension(node, node->children[0].get()); + } + else { + // The Yosys extension for unpacked arrays in packed structs / unions + // only supports memories, i.e. e.g. logic [7:0] a [256] - see above. + struct_array_packing_error(node); + } + } else { + // Vector + add_dimension(node, node->children[0].get()); + } + // range nodes are now redundant + node->children.clear(); + } + else if (node->children.size() > 0 && node->children[0]->type == AST_MULTIRANGE) { + // Packed array, e.g. bit [3:0][63:0] a + if (node->children.size() != 1) { + // The Yosys extension for unpacked arrays in packed structs / unions + // only supports memories, i.e. e.g. logic [7:0] a [256] - see above. + struct_array_packing_error(node); + } + width = 1; + for (auto& rnode : node->children[0]->children) { + width *= add_dimension(node, rnode.get()); + } + // range nodes are now redundant + node->children.clear(); + } + else if (node->range_left < 0) { + // 1 bit signal: bit, logic or reg + width = 1; + node->dimensions.push_back({ 0, width, false }); + } + else { + // already resolved and compacted + width = node->range_left - node->range_right + 1; + } + if (is_union) { + node->range_right = base_offset; + node->range_left = base_offset + width - 1; + } + else { + node->range_right = base_offset + offset; + node->range_left = base_offset + offset + width - 1; + } + node->range_valid = true; + } + if (is_union) { + // check that all members have the same size + if (packed_width == -1) { + // first member + packed_width = width; + } + else { + if (packed_width != width) + node->input_error("member %s of a packed union has %d bits, expecting %d\n", node->str, width, packed_width); + } + } + else { + offset += width; + } + } + + int width = is_union ? packed_width : offset; + + snode->range_right = base_offset; + snode->range_left = base_offset + width - 1; + snode->range_valid = true; + snode->dimensions.push_back({ 0, width, false }); + + return width; +} + +static std::unique_ptr node_int(AstSrcLocType loc, int ival) +{ + return AstNode::mkconst_int(loc, ival, true); +} + +static std::unique_ptr multiply_by_const(std::unique_ptr expr_node, int stride) +{ + auto loc = expr_node->location; + return std::make_unique(loc, AST_MUL, std::move(expr_node), node_int(loc, stride)); +} + +static std::unique_ptr normalize_index(AstNode *expr, AstNode *decl_node, int dimension) +{ + auto new_expr = expr->clone(); + auto loc = expr->location; + + int offset = decl_node->dimensions[dimension].range_right; + if (offset) { + new_expr = std::make_unique(loc, AST_SUB, std::move(new_expr), node_int(loc, offset)); + } + + // Packed dimensions are normally indexed by lsb, while unpacked dimensions are normally indexed by msb. + if ((dimension < decl_node->unpacked_dimensions) ^ decl_node->dimensions[dimension].range_swapped) { + // Swap the index if the dimension is declared the "wrong" way. + int left = decl_node->dimensions[dimension].range_width - 1; + new_expr = std::make_unique(loc, AST_SUB, node_int(loc, left), std::move(new_expr)); + } + + return new_expr; +} + +static std::unique_ptr index_offset(std::unique_ptr offset, AstNode *rnode, AstNode *decl_node, int dimension, int &stride) +{ + stride /= decl_node->dimensions[dimension].range_width; + auto right = normalize_index(rnode->children.back().get(), decl_node, dimension); + auto add_offset = stride > 1 ? multiply_by_const(std::move(right), stride) : std::move(right); + return offset ? std::make_unique(rnode->location, AST_ADD, std::move(offset), std::move(add_offset)) : std::move(add_offset); +} + +static std::unique_ptr index_msb_offset(std::unique_ptr lsb_offset, AstNode *rnode, AstNode *decl_node, int dimension, int stride) +{ + log_assert(rnode->children.size() <= 2); + auto loc = rnode->location; + + // Offset to add to LSB + std::unique_ptr add_offset; + if (rnode->children.size() == 1) { + // Index, e.g. s.a[i] + add_offset = node_int(rnode->location, stride - 1); + } + else { + // rnode->children.size() == 2 + // Slice, e.g. s.a[i:j] + auto left = normalize_index(rnode->children[0].get(), decl_node, dimension); + auto right = normalize_index(rnode->children[1].get(), decl_node, dimension); + add_offset = std::make_unique(loc, AST_SUB, std::move(left), std::move(right)); + if (stride > 1) { + // offset = (msb - lsb + 1)*stride - 1 + auto slice_width = std::make_unique(loc, AST_ADD, std::move(add_offset), node_int(loc, 1)); + add_offset = std::make_unique(loc, AST_SUB, multiply_by_const(std::move(slice_width), stride), node_int(loc, 1)); + } + } + + return std::make_unique(loc, AST_ADD, std::move(lsb_offset), std::move(add_offset)); +} + + +std::unique_ptr AstNode::make_index_range(AstNode *decl_node, bool unpacked_range) +{ + // Work out the range in the packed array that corresponds to a struct member + // taking into account any range operations applicable to the current node + // such as array indexing or slicing + if (children.empty()) { + // no range operations apply, return the whole width + return make_range(decl_node->location, decl_node->range_left - decl_node->range_right, 0); + } + + log_assert(children.size() == 1); + + // Range operations + AstNode *rnode = children[0].get(); + std::unique_ptr offset = nullptr; + int dim = unpacked_range ? 0 : decl_node->unpacked_dimensions; + int max_dim = unpacked_range ? decl_node->unpacked_dimensions : GetSize(decl_node->dimensions); + + int stride = 1; + for (int i = dim; i < max_dim; i++) { + stride *= decl_node->dimensions[i].range_width; + } + + // Calculate LSB offset for the final index / slice + if (rnode->type == AST_RANGE) { + offset = index_offset(std::move(offset), rnode, decl_node, dim, stride); + } + else if (rnode->type == AST_MULTIRANGE) { + // Add offset for each dimension + AstNode *mrnode = rnode; + int stop_dim = std::min(GetSize(mrnode->children), max_dim); + for (; dim < stop_dim; dim++) { + rnode = mrnode->children[dim].get(); + offset = index_offset(std::move(offset), rnode, decl_node, dim, stride); + } + dim--; // Step back to the final index / slice + } + else { + input_error("Unsupported range operation for %s\n", str); + } + + std::unique_ptr index_range = std::make_unique(rnode->location, AST_RANGE); + + if (!unpacked_range && (stride > 1 || GetSize(rnode->children) == 2)) { + // Calculate MSB offset for the final index / slice of packed dimensions. + std::unique_ptrmsb_offset = index_msb_offset(offset->clone(), rnode, decl_node, dim, stride); + index_range->children.push_back(std::move(msb_offset)); + } + + index_range->children.push_back(std::move(offset)); + + return index_range; +} + +AstNode *AstNode::get_struct_member() const +{ + AstNode *member_node; + if (attributes.count(ID::wiretype) && (member_node = attributes.at(ID::wiretype).get()) && + (member_node->type == AST_STRUCT_ITEM || member_node->type == AST_STRUCT || member_node->type == AST_UNION)) + { + return member_node; + } + return nullptr; +} + +static void add_members_to_scope(AstNode *snode, std::string name) +{ + // add all the members in a struct or union to local scope + // in case later referenced in assignments + log_assert(snode->type==AST_STRUCT || snode->type==AST_UNION); + for (auto &node : snode->children) { + auto member_name = name + "." + node->str; + current_scope[member_name] = node.get(); + if (node->type != AST_STRUCT_ITEM) { + // embedded struct or union + add_members_to_scope(node.get(), name + "." + node->str); + } + } +} + +std::unique_ptr make_packed_struct(AstNode *template_node, std::string &name, decltype(AstNode::attributes) &attributes) +{ + // create a wire for the packed struct + auto loc = template_node->location; + auto wnode = std::make_unique(loc, AST_WIRE, make_range(loc, template_node->range_left, 0)); + wnode->str = name; + wnode->is_logic = true; + wnode->range_valid = true; + wnode->is_signed = template_node->is_signed; + for (auto &pair : attributes) { + wnode->set_attribute(pair.first, pair.second->clone()); + } + // resolve packed dimension + while (wnode->simplify(true, 1, -1, false)) {} + // make sure this node is the one in scope for this name + current_scope[name] = wnode.get(); + // add all the struct members to scope under the wire's name + add_members_to_scope(template_node, name); + return wnode; +} + +static void prepend_ranges(std::unique_ptr &range, AstNode *range_add) +{ + // Convert range to multirange. + auto loc = range->location; + if (range->type == AST_RANGE) + range = std::make_unique(loc, AST_MULTIRANGE, std::move(range)); + + // Add range or ranges. + if (range_add->type == AST_RANGE) + range->children.insert(range->children.begin(), range_add->clone()); + else { + int i = 0; + for (auto& child : range_add->children) + range->children.insert(range->children.begin() + i++, child->clone()); + } +} + +// check if a node or its children contains an assignment to the given variable +static bool node_contains_assignment_to(const AstNode* node, const AstNode* var) +{ + if (node->type == AST_ASSIGN_EQ || node->type == AST_ASSIGN_LE) { + // current node is iteslf an assignment + log_assert(node->children.size() >= 2); + const AstNode* lhs = node->children[0].get(); + if (lhs->type == AST_IDENTIFIER && lhs->str == var->str) + return false; + } + for (auto& child : node->children) { + // if this child shadows the given variable + if (child.get() != var && child->str == var->str && child->type == AST_WIRE) + break; // skip the remainder of this block/scope + // depth-first short circuit + if (!node_contains_assignment_to(child.get(), var)) + return false; + } + return true; +} + +static std::string prefix_id(const std::string &prefix, const std::string &str) +{ + log_assert(!prefix.empty() && (prefix.front() == '$' || prefix.front() == '\\')); + log_assert(!str.empty() && (str.front() == '$' || str.front() == '\\')); + log_assert(prefix.back() == '.'); + if (str.front() == '\\') + return prefix + str.substr(1); + return prefix + str; +} + +// direct access to this global should be limited to the following two functions +static const RTLIL::Design *simplify_design_context = nullptr; +static dict simplify_design_modules; +static size_t simplify_design_modules_size = 0; + +void AST::set_simplify_design_context(const RTLIL::Design *design) +{ + log_assert(!simplify_design_context || !design); + simplify_design_context = design; + simplify_design_modules.clear(); + simplify_design_modules_size = 0; +} + +// lookup the module with the given name in the current design context +static const RTLIL::Module* lookup_module(const std::string &name) +{ + const RTLIL::Design *design = simplify_design_context; + if (const RTLIL::Module *module = design->module(name)) + return module; + + if (simplify_design_modules_size != design->modules_.size()) { + simplify_design_modules.clear(); + for (const auto &it : design->modules_) + simplify_design_modules[design->twines().str(it.first)] = it.first; + simplify_design_modules_size = design->modules_.size(); + } + auto it = simplify_design_modules.find(name); + return it == simplify_design_modules.end() ? nullptr : design->module(it->second); +} + +const RTLIL::Module* AstNode::lookup_cell_module() +{ + log_assert(type == AST_CELL); + + auto reprocess_after = [this] (const std::string &modname) { + if (!attributes.count(ID::reprocess_after)) + set_attribute(ID::reprocess_after, AstNode::mkconst_str(location, modname)); + }; + + const AstNode *celltype = nullptr; + for (auto& child : children) + if (child->type == AST_CELLTYPE) { + celltype = child.get(); + break; + } + log_assert(celltype != nullptr); + + const RTLIL::Module *module = lookup_module(celltype->str); + if (!module) + module = lookup_module("$abstract" + celltype->str); + if (!module) { + if (celltype->str.at(0) != '$') + reprocess_after(celltype->str); + return nullptr; + } + + // build a mapping from true param name to param value + size_t para_counter = 0; + dict cell_params_map; + for (auto& child : children) { + if (child->type != AST_PARASET) + continue; + + if (child->str.empty() && para_counter >= module->avail_parameters.size()) + return nullptr; // let hierarchy handle this error + IdString paraname = child->str.empty() ? module->avail_parameters[para_counter++] + : module->twines().add(child->str); + + const AstNode *value = child->children[0].get(); + if (value->type != AST_REALVALUE && value->type != AST_CONSTANT) + return nullptr; // let genrtlil handle this error + cell_params_map[paraname] = value->asParaConst(); + } + + // put the parameters in order and generate the derived module name + std::vector> named_parameters; + for (RTLIL::IdString param : module->avail_parameters) { + auto it = cell_params_map.find(param); + if (it != cell_params_map.end()) + named_parameters.emplace_back(module->twines().str(it->first), it->second); + } + std::string modname = celltype->str; + if (cell_params_map.size()) // not named_parameters to cover hierarchical defparams + modname = derived_module_name(celltype->str, named_parameters); + + // try to find the resolved module + module = lookup_module(modname); + if (!module) { + reprocess_after(modname); + return nullptr; + } + return module; +} + +// returns whether an expression contains an unbased unsized literal; does not +// check the literal exists in a self-determined context +static bool contains_unbased_unsized(const AstNode *node) +{ + if (node->type == AST_CONSTANT) + return node->is_unsized; + for (auto& child : node->children) + if (contains_unbased_unsized(child.get())) + return true; + return false; +} + +// adds a wire to the current module with the given name that matches the +// dimensions of the given wire reference +void add_wire_for_ref(Location loc, const RTLIL::Wire *ref, const std::string &str) +{ + auto left = AstNode::mkconst_int(loc, ref->width - 1 + ref->start_offset, true); + auto right = AstNode::mkconst_int(loc, ref->start_offset, true); + if (ref->upto) + std::swap(left, right); + auto range = std::make_unique(loc, AST_RANGE, std::move(left), std::move(right)); + + auto wire = std::make_unique(loc, AST_WIRE, std::move(range)); + wire->is_signed = ref->is_signed; + wire->is_logic = true; + wire->str = str; + + current_scope[str] = wire.get(); + current_ast_mod->children.push_back(std::move(wire)); +} + +enum class IdentUsage { + NotReferenced, // target variable is neither read or written in the block + Assigned, // target variable is always assigned before use + SyncRequired, // target variable may be used before it has been assigned +}; + +// determines whether a local variable a block is always assigned before it is +// used, meaning the nosync attribute can automatically be added to that +// variable +static IdentUsage always_asgn_before_use(const AstNode *node, const std::string &target) +{ + // This variable has been referenced before it has necessarily been assigned + // a value in this procedure. + if (node->type == AST_IDENTIFIER && node->str == target) + return IdentUsage::SyncRequired; + + // For case statements (which are also used for if/else), we check each + // possible branch. If the variable is assigned in all branches, then it is + // assigned, and a sync isn't required. If it used before assignment in any + // branch, then a sync is required. + if (node->type == AST_CASE) { + bool all_defined = true; + bool any_used = false; + bool has_default = false; + for (auto& child : node->children) { + if (child->type == AST_COND && child->children.at(0)->type == AST_DEFAULT) + has_default = true; + IdentUsage nested = always_asgn_before_use(child.get(), target); + if (nested != IdentUsage::Assigned && child->type == AST_COND) + all_defined = false; + if (nested == IdentUsage::SyncRequired) + any_used = true; + } + if (any_used) + return IdentUsage::SyncRequired; + else if (all_defined && has_default) + return IdentUsage::Assigned; + else + return IdentUsage::NotReferenced; + } + + // Check if this is an assignment to the target variable. For simplicity, we + // don't analyze sub-ranges of the variable. + if (node->type == AST_ASSIGN_EQ) { + auto& ident = node->children.at(0); + if (ident->type == AST_IDENTIFIER && ident->str == target) + return IdentUsage::Assigned; + } + + for (auto& child : node->children) { + IdentUsage nested = always_asgn_before_use(child.get(), target); + if (nested != IdentUsage::NotReferenced) + return nested; + } + return IdentUsage::NotReferenced; +} + +std::unique_ptr AstNode::clone_at_zero() +{ + int width_hint; + bool sign_hint; + AstNode *pointee; + + switch (type) { + case AST_IDENTIFIER: + if (id2ast) + pointee = id2ast; + else if (current_scope.count(str)) + pointee = current_scope[str]; + else + break; + + if (pointee->type != AST_WIRE && + pointee->type != AST_AUTOWIRE && + pointee->type != AST_MEMORY) + break; + + YS_FALLTHROUGH + case AST_MEMRD: + detectSignWidth(width_hint, sign_hint); + return mkconst_int(location, 0, sign_hint, width_hint); + + default: + break; + } + + auto that = clone(); + for (auto &it : that->children) + it = it->clone_at_zero(); + for (auto &it : that->attributes) + it.second = it.second->clone(); + + that->set_in_lvalue_flag(false); + that->set_in_param_flag(false); + that->fixup_hierarchy_flags(); + + return that; +} + +static bool try_determine_range_width(AstNode *range, int &result_width) +{ + log_assert(range->type == AST_RANGE); + + if (range->children.size() == 1) { + result_width = 1; + return true; + } + + auto left_at_zero_ast = range->children[0]->clone_at_zero(); + auto right_at_zero_ast = range->children[1]->clone_at_zero(); + + while (left_at_zero_ast->simplify(true, 1, -1, false)) {} + while (right_at_zero_ast->simplify(true, 1, -1, false)) {} + + bool ok = false; + if (left_at_zero_ast->type == AST_CONSTANT + && right_at_zero_ast->type == AST_CONSTANT) { + ok = true; + result_width = abs(int(left_at_zero_ast->integer - right_at_zero_ast->integer)) + 1; + } + + return ok; +} + +static const std::string auto_nosync_prefix = "\\AutoNosync"; + +// mark a local variable in an always_comb block for automatic nosync +// consideration +static void mark_auto_nosync(AstNode *block, const AstNode *wire) +{ + log_assert(block->type == AST_BLOCK); + log_assert(wire->type == AST_WIRE); + block->set_attribute(auto_nosync_prefix + wire->str, AstNode::mkconst_int(block->location, 1, false)); +} + +// block names can be prefixed with an explicit scope during elaboration +static bool is_autonamed_block(const std::string &str) { + size_t last_dot = str.rfind('.'); + // unprefixed names: autonamed if the first char is a dollar sign + if (last_dot == std::string::npos) + return str.at(0) == '$'; // e.g., `$fordecl_block$1` + // prefixed names: autonamed if the final chunk begins with a dollar sign + return str.rfind(".$") == last_dot; // e.g., `\foo.bar.$fordecl_block$1` +} + +// check a procedural block for auto-nosync markings, remove them, and add +// nosync to local variables as necessary +static void check_auto_nosync(AstNode *node) +{ + std::vector attrs_to_drop; + for (const auto& elem : node->attributes) { + std::string attr_str = attr_name_str(elem.first); + // skip attributes that don't begin with the prefix + if (attr_str.compare(0, auto_nosync_prefix.size(), + auto_nosync_prefix.c_str())) + continue; + + // delete and remove the attribute once we're done iterating + attrs_to_drop.push_back(elem.first); + + // find the wire based on the attribute + std::string wire_name = attr_str.substr(auto_nosync_prefix.size()); + auto it = current_scope.find(wire_name); + if (it == current_scope.end()) + continue; + + // analyze the usage of the local variable in this block + IdentUsage ident_usage = always_asgn_before_use(node, wire_name); + if (ident_usage != IdentUsage::Assigned) + continue; + + // mark the wire with `nosync` + AstNode *wire = it->second; + log_assert(wire->type == AST_WIRE); + wire->set_attribute(ID::nosync, AstNode::mkconst_int(wire->location, 1, false)); + } + + // remove the attributes we've "consumed" + for (IdString id : attrs_to_drop) { + auto it = node->attributes.find(id); + node->attributes.erase(it); + } + + // check local variables in any nested blocks + for (auto& child : node->children) + check_auto_nosync(child.get()); +} + +class PackageImporter { + std::set import_items; + bool is_wildcard; + const AstNode* node; +public: + PackageImporter(const AstNode* n, const AstNode* child) : node(n) { + is_wildcard = child->children.empty(); + // For specific imports, collect the list of items to import + if (!is_wildcard) { + for (auto& item : child->children) { + import_items.insert(item->str); + } + } + } + + void import(std::map& scope, AstNode* to_import) const { + // Check if this is a specific import and if this item should be imported + if (!is_wildcard && import_items.count(to_import->str) == 0) + return; + + if (to_import->type == AST_PARAMETER || to_import->type == AST_LOCALPARAM || + to_import->type == AST_TYPEDEF || to_import->type == AST_FUNCTION || + to_import->type == AST_TASK || to_import->type == AST_ENUM) { + // For wildcard imports, check if item already exists (from specific import) + if (is_wildcard && scope.count(to_import->str) > 0) + return; + scope[to_import->str] = to_import; + } + if (to_import->type == AST_ENUM) { + for (auto& enode : to_import->children) { + log_assert(enode->type==AST_ENUM_ITEM); + // Check if this enum item should be imported + if (!is_wildcard && import_items.count(enode->str) == 0) + continue; + // For wildcard imports, check if item already exists (from specific import) + if (is_wildcard && scope.count(enode->str) > 0) + continue; + if (scope.count(enode->str) == 0) + scope[enode->str] = enode.get(); + else + node->input_error("enum item %s already exists in current scope\n", enode->str); + } + } + } +}; + +// convert the AST into a simpler AST that has all parameters substituted by their +// values, unrolled for-loops, expanded generate blocks, etc. when this function +// is done with an AST it can be converted into RTLIL using genRTLIL(). +// +// this function also does all name resolving and sets the id2ast member of all +// nodes that link to a different node using names and lexical scoping. +bool AstNode::simplify(bool const_fold, int stage, int width_hint, bool sign_hint) +{ + static int recursion_counter = 0; + static bool deep_recursion_warning = false; + + if (recursion_counter++ == 1000 && deep_recursion_warning) { + log_warning("Deep recursion in AST simplifier.\nDoes this design contain overly long or deeply nested expressions, or excessive recursion?\n"); + deep_recursion_warning = false; + } + + static bool unevaluated_tern_branch = false; + + std::unique_ptr newNode = nullptr; + bool did_something = false; + +#if 0 + log("-------------\n"); + log("AST simplify[%d] depth %d at %s on %s %p:\n", stage, recursion_counter, location.to_string(), type2str(type), this); + log("const_fold=%d, stage=%d, width_hint=%d, sign_hint=%d\n", + int(const_fold), int(stage), int(width_hint), int(sign_hint)); + // dumpAst(nullptr, "> "); +#endif + + if (stage == 0) + { + log_assert(type == AST_MODULE || type == AST_INTERFACE); + + deep_recursion_warning = true; + while (simplify(const_fold, 1, width_hint, sign_hint)) { } + + if (!flag_nomem2reg && !get_bool_attribute(ID::nomem2reg)) + { + dict> mem2reg_places; + dict mem2reg_candidates, dummy_proc_flags; + uint32_t flags = flag_mem2reg ? AstNode::MEM2REG_FL_ALL : 0; + mem2reg_as_needed_pass1(mem2reg_places, mem2reg_candidates, dummy_proc_flags, flags); + + pool mem2reg_set; + for (auto &it : mem2reg_candidates) + { + AstNode *mem = it.first; + uint32_t memflags = it.second; + bool this_nomeminit = flag_nomeminit; + log_assert((memflags & ~0x00ffff00) == 0); + + if (mem->get_bool_attribute(ID::nomem2reg)) + continue; + + if (mem->get_bool_attribute(ID::nomeminit) || get_bool_attribute(ID::nomeminit)) + this_nomeminit = true; + + if (memflags & AstNode::MEM2REG_FL_FORCED) + goto silent_activate; + + if (memflags & AstNode::MEM2REG_FL_EQ2) + goto verbose_activate; + + if (memflags & AstNode::MEM2REG_FL_SET_ASYNC) + goto verbose_activate; + + if ((memflags & AstNode::MEM2REG_FL_SET_INIT) && (memflags & AstNode::MEM2REG_FL_SET_ELSE) && this_nomeminit) + goto verbose_activate; + + if (memflags & AstNode::MEM2REG_FL_CMPLX_LHS) + goto verbose_activate; + + if ((memflags & AstNode::MEM2REG_FL_CONST_LHS) && !(memflags & AstNode::MEM2REG_FL_VAR_LHS)) + goto verbose_activate; + + // log("Note: Not replacing memory %s with list of registers (flags=0x%08lx).\n", mem->str, long(memflags)); + continue; + + verbose_activate: + if (mem2reg_set.count(mem) == 0) { + std::string message = stringf("Replacing memory %s with list of registers.", mem->str); + bool first_element = true; + for (auto &place : mem2reg_places[it.first]) { + message += stringf("%s%s", first_element ? " See " : ", ", place); + first_element = false; + } + log_warning("%s\n", message); + } + + silent_activate: + // log("Note: Replacing memory %s with list of registers (flags=0x%08lx).\n", mem->str, long(memflags)); + mem2reg_set.insert(mem); + } + + for (auto node : mem2reg_set) + { + int mem_width, mem_size, addr_bits; + node->meminfo(mem_width, mem_size, addr_bits); + + int data_range_left = node->children[0]->range_left; + int data_range_right = node->children[0]->range_right; + + if (node->children[0]->range_swapped) + std::swap(data_range_left, data_range_right); + + auto loc = node->location; + for (int i = 0; i < mem_size; i++) { + auto reg = std::make_unique(loc, AST_WIRE, std::make_unique(loc, AST_RANGE, + mkconst_int(loc, data_range_left, true), mkconst_int(loc, data_range_right, true))); + reg->str = stringf("%s[%d]", node->str, i); + reg->is_reg = true; + reg->is_signed = node->is_signed; + for (auto &it : node->attributes) + if (it.first != ID::mem2reg) + reg->set_attribute(it.first, it.second->clone()); + reg->location.begin.filename = node->location.begin.filename; + reg->location = node->location; + while (reg->simplify(true, 1, -1, false)) { } + children.push_back(std::move(reg)); + } + } + + AstNode* async_block = nullptr; + while (mem2reg_as_needed_pass2(mem2reg_set, this, nullptr, async_block)) { } + + mem2reg_remove(mem2reg_set); + } + + while (simplify(const_fold, 2, width_hint, sign_hint)) { } + recursion_counter--; + return false; + } + + // we do not look inside a task or function + // (but as soon as a task or function is instantiated we process the generated AST as usual) + if (type == AST_FUNCTION || type == AST_TASK) { + recursion_counter--; + return false; + } + + // deactivate all calls to non-synthesis system tasks + // note that $display, $finish, and $stop are used for synthesis-time DRC so they're not in this list + if ((type == AST_FCALL || type == AST_TCALL) && (str == "$strobe" || str == "$monitor" || str == "$time" || + str == "$dumpfile" || str == "$dumpvars" || str == "$dumpon" || str == "$dumpoff" || str == "$dumpall")) { + log_file_warning(location.to_loc(), "Ignoring call to system %s %s.\n", type == AST_FCALL ? "function" : "task", str); + delete_children(); + str = std::string(); + } + + if ((type == AST_TCALL) && + (str == "$display" || str == "$displayb" || str == "$displayh" || str == "$displayo" || + str == "$write" || str == "$writeb" || str == "$writeh" || str == "$writeo")) + { + if (!current_always) { + log_file_warning(location.to_loc(), "System task `%s' outside initial or always block is unsupported.\n", str); + delete_children(); + str = std::string(); + } else { + // simplify the expressions and convert them to a special cell later in genrtlil + for (auto& node : children) + while (node->simplify(true, stage, -1, false)) {} + + if (current_always->type == AST_INITIAL && !flag_nodisplay && stage == 2) { + int default_base = 10; + if (str.back() == 'b') + default_base = 2; + else if (str.back() == 'o') + default_base = 8; + else if (str.back() == 'h') + default_base = 16; + + // when $display()/$write() functions are used in an initial block, print them during synthesis + Fmt fmt = processFormat(stage, /*sformat_like=*/false, default_base, /*first_arg_at=*/0, /*may_fail=*/true); + if (str.substr(0, 8) == "$display") + fmt.append_literal("\n"); + log("%s", fmt.render()); + } + + return false; + } + } + + // activate const folding if this is anything that must be evaluated statically (ranges, parameters, attributes, etc.) + if (type == AST_WIRE || type == AST_PARAMETER || type == AST_LOCALPARAM || type == AST_ENUM_ITEM || type == AST_DEFPARAM || type == AST_PARASET || type == AST_RANGE || type == AST_PREFIX || type == AST_TYPEDEF) + const_fold = true; + if (type == AST_IDENTIFIER && current_scope.count(str) > 0 && (current_scope[str]->type == AST_PARAMETER || current_scope[str]->type == AST_LOCALPARAM || current_scope[str]->type == AST_ENUM_ITEM)) + const_fold = true; + + std::map backup_scope; + + // create name resolution entries for all objects with names + // also merge multiple declarations for the same wire (e.g. "output foobar; reg foobar;") + if (type == AST_MODULE || type == AST_INTERFACE) { + current_scope.clear(); + std::set existing; + int counter = 0; + label_genblks(existing, counter); + std::map this_wire_scope; + + // Process package imports after clearing the scope but before processing module declarations + for (size_t i = 0; i < children.size(); i++) { + AstNode *child = children[i].get(); + if (child->type == AST_IMPORT) { + // Find the package in the design + AstNode *package_node = nullptr; + + // First look in current_ast->children (for packages in same file) + if (current_ast != nullptr) { + for (auto &design_child : current_ast->children) { + if (design_child->type == AST_PACKAGE) { + if (design_child->str == child->str) { + package_node = design_child.get(); + break; + } + } + } + } + + // If not found, look in design->verilog_packages (for packages from other files) + if (!package_node && simplify_design_context != nullptr) { + for (auto &design_package : simplify_design_context->verilog_packages) { + // Handle both with and without leading backslash + std::string package_name = design_package->str; + if (package_name[0] == '\\') { + package_name = package_name.substr(1); + } + if (package_name == child->str || design_package->str == child->str) { + package_node = design_package.get(); + break; + } + } + } + + if (package_node) { + PackageImporter importer(this, child); + // Import names from the package into current scope + for (auto& pkg_child : package_node->children) { + importer.import(current_scope, pkg_child.get()); + } + // Remove the import node since it's been processed + children.erase(children.begin() + i); + i--; // Adjust index since we removed an element + } else { + // If we can't find the package, just remove the import node to avoid errors later + log_warning("Package `%s' not found for import, removing import statement\n", child->str); + children.erase(children.begin() + i); + i--; // Adjust index since we removed an element + } + } + } + for (size_t i = 0; i < children.size(); i++) { + AstNode* node = children[i].get(); + + if (node->type == AST_WIRE) { + if (node->children.size() == 1 && node->children[0]->type == AST_RANGE) { + for (auto& c : node->children[0]->children) { + if (!c->is_simple_const_expr()) + set_attribute(ID::dynports, AstNode::mkconst_int(c->location, 1, true)); + } + } + if (this_wire_scope.count(node->str) > 0) { + AstNode *first_node = this_wire_scope[node->str]; + if (first_node->is_input && node->is_reg) + goto wires_are_incompatible; + if (!node->is_input && !node->is_output && node->is_reg && node->children.size() == 0) + goto wires_are_compatible; + if (first_node->children.size() == 0 && node->children.size() == 1 && node->children[0]->type == AST_RANGE) { + AstNode* r = node->children[0].get(); + if (r->range_valid && r->range_left == 0 && r->range_right == 0) { + node->children.pop_back(); + } + } + if (first_node->children.size() != node->children.size()) + goto wires_are_incompatible; + for (size_t j = 0; j < node->children.size(); j++) { + auto &n1 = first_node->children[j], &n2 = node->children[j]; + if (n1->type == AST_RANGE && n2->type == AST_RANGE && n1->range_valid && n2->range_valid) { + if (n1->range_left != n2->range_left) + goto wires_are_incompatible; + if (n1->range_right != n2->range_right) + goto wires_are_incompatible; + } else if (*n1 != *n2) + goto wires_are_incompatible; + } + if (first_node->range_left != node->range_left) + goto wires_are_incompatible; + if (first_node->range_right != node->range_right) + goto wires_are_incompatible; + if (first_node->port_id == 0 && (node->is_input || node->is_output)) + goto wires_are_incompatible; + wires_are_compatible: + if (node->is_input) + first_node->is_input = true; + if (node->is_output) + first_node->is_output = true; + if (node->is_reg) + first_node->is_reg = true; + if (node->is_logic) + first_node->is_logic = true; + if (node->is_signed) + first_node->is_signed = true; + for (auto &it : node->attributes) { + first_node->set_attribute(it.first, it.second->clone()); + } + children.erase(children.begin()+(i--)); + did_something = true; + continue; + wires_are_incompatible: + if (stage > 1) + input_error("Incompatible re-declaration of wire %s.\n", node->str); + continue; + } + this_wire_scope[node->str] = node; + } + // these nodes appear at the top level in a module and can define names + if (node->type == AST_PARAMETER || node->type == AST_LOCALPARAM || node->type == AST_WIRE || node->type == AST_AUTOWIRE || node->type == AST_GENVAR || + node->type == AST_MEMORY || node->type == AST_FUNCTION || node->type == AST_TASK || node->type == AST_DPI_FUNCTION || node->type == AST_CELL || + node->type == AST_TYPEDEF) { + backup_scope[node->str] = current_scope[node->str]; + current_scope[node->str] = node; + } + if (node->type == AST_ENUM) { + current_scope[node->str] = node; + for (auto& enode : node->children) { + log_assert(enode->type==AST_ENUM_ITEM); + if (current_scope.count(enode->str) == 0) + current_scope[enode->str] = enode.get(); + else + input_error("enum item %s already exists\n", enode->str); + } + } + } + for (size_t i = 0; i < children.size(); i++) { + auto& node = children[i]; + if (node->type == AST_PARAMETER || node->type == AST_LOCALPARAM || node->type == AST_WIRE || node->type == AST_AUTOWIRE || node->type == AST_MEMORY || node->type == AST_TYPEDEF) + while (node->simplify(true, 1, -1, false)) + did_something = true; + if (node->type == AST_ENUM) { + for (auto& enode : node->children){ + log_assert(enode->type==AST_ENUM_ITEM); + while (node->simplify(true, 1, -1, false)) + did_something = true; + } + } + } + + for (auto& child : children) + if (child->type == AST_ALWAYS && + child->attributes.count(ID::always_comb)) + check_auto_nosync(child.get()); + } + + // create name resolution entries for all objects with names + if (type == AST_PACKAGE) { + //add names to package scope + for (size_t i = 0; i < children.size(); i++) { + auto& node = children[i]; + // these nodes appear at the top level in a package and can define names + if (node->type == AST_PARAMETER || node->type == AST_LOCALPARAM || node->type == AST_TYPEDEF || node->type == AST_FUNCTION || node->type == AST_TASK) { + current_scope[node->str] = node.get(); + } + if (node->type == AST_ENUM) { + current_scope[node->str] = node.get(); + for (auto& enode : node->children) { + log_assert(enode->type==AST_ENUM_ITEM); + if (current_scope.count(enode->str) == 0) + current_scope[enode->str] = enode.get(); + else + input_error("enum item %s already exists in package\n", enode->str); + } + } + } + } + + + auto backup_current_block = current_block; + auto backup_current_block_child = current_block_child; + auto backup_current_top_block = current_top_block; + auto backup_current_always = current_always; + auto backup_current_always_clocked = current_always_clocked; + + if (type == AST_ALWAYS || type == AST_INITIAL) + { + if (current_always != nullptr) + input_error("Invalid nesting of always blocks and/or initializations.\n"); + + current_always = this; + current_always_clocked = false; + + if (type == AST_ALWAYS) + for (auto& child : children) { + if (child->type == AST_POSEDGE || child->type == AST_NEGEDGE) + current_always_clocked = true; + if (child->type == AST_EDGE && GetSize(child->children) == 1 && + child->children[0]->type == AST_IDENTIFIER && child->children[0]->str == "\\$global_clock") + current_always_clocked = true; + } + } + + if (type == AST_CELL) { + bool lookup_suggested = false; + + for (auto& child : children) { + // simplify any parameters to constants + if (child->type == AST_PARASET) + while (child->simplify(true, 1, -1, false)) { } + + // look for patterns which _may_ indicate ambiguity requiring + // resolution of the underlying module + if (child->type == AST_ARGUMENT) { + if (child->children.size() != 1) + continue; + const auto& value = child->children[0]; + if (value->type == AST_IDENTIFIER) { + const AstNode *elem = value->id2ast; + if (elem == nullptr) { + if (current_scope.count(value->str)) + elem = current_scope.at(value->str); + else + continue; + } + if (elem->type == AST_MEMORY) + // need to determine is the is a read or wire + lookup_suggested = true; + else if (elem->type == AST_WIRE && elem->is_signed && !value->children.empty()) + // this may be a fully sliced signed wire which needs + // to be indirected to produce an unsigned connection + lookup_suggested = true; + } + else if (contains_unbased_unsized(value.get())) + // unbased unsized literals extend to width of the context + lookup_suggested = true; + } + } + + const RTLIL::Module *module = nullptr; + if (lookup_suggested) + module = lookup_cell_module(); + if (module) { + size_t port_counter = 0; + dict ports_by_name; + for (auto port : module->ports) + ports_by_name[module->twines().str(port)] = port; + for (auto& child : children) { + if (child->type != AST_ARGUMENT) + continue; + + // determine the full name of port this argument is connected to + RTLIL::IdString port_name; + if (child->str.size()) { + auto it = ports_by_name.find(child->str); + if (it != ports_by_name.end()) + port_name = it->second; + } + else { + if (port_counter >= module->ports.size()) + input_error("Cell instance has more ports than the module!\n"); + port_name = module->ports[port_counter++]; + } + + // find the port's wire in the underlying module + const RTLIL::Wire *ref = module->wire(port_name); + if (ref == nullptr) + input_error("Cell instance refers to port %s which does not exist in module %s!.\n", + child->str.size() ? RTLIL::unescape_id(child->str) + : module->twines().unescaped_str(port_name), + module->name.unescape()); + + // select the argument, if present + log_assert(child->children.size() <= 1); + if (child->children.empty()) + continue; + + { + auto arg_check = child->children[0].get(); + + // plain identifiers never need indirection; this also prevents + // adding infinite levels of indirection + if (arg_check->type == AST_IDENTIFIER && arg_check->children.empty()) + continue; + + // only add indirection for standard inputs or outputs + if (ref->port_input == ref->port_output) + continue; + } + + auto arg = std::move(child->children[0]); + did_something = true; + + // create the indirection wire + std::stringstream sstr; + sstr << "$indirect$" << ref->name.str() << "$" << RTLIL::encode_filename(*location.begin.filename) << ":" << location.begin.line << "$" << ast_autoidx(); + std::string tmp_str = sstr.str(); + add_wire_for_ref(location, ref, tmp_str); + + auto asgn_owned = std::make_unique(child->location, AST_ASSIGN); + auto* asgn = asgn_owned.get(); + current_ast_mod->children.push_back(std::move(asgn_owned)); + + auto ident = std::make_unique(child->location, AST_IDENTIFIER); + ident->str = tmp_str; + child->children[0] = ident->clone(); + + if (ref->port_input && !ref->port_output) { + asgn->children.push_back(std::move(ident)); + asgn->children.push_back(std::move(arg)); + } else { + log_assert(!ref->port_input && ref->port_output); + asgn->children.push_back(std::move(arg)); + asgn->children.push_back(std::move(ident)); + } + asgn->fixup_hierarchy_flags(); + } + + + } + } + + int backup_width_hint = width_hint; + bool backup_sign_hint = sign_hint; + + bool detect_width_simple = false; + bool child_0_is_self_determined = false; + bool child_1_is_self_determined = false; + bool child_2_is_self_determined = false; + bool children_are_self_determined = false; + bool reset_width_after_children = false; + + switch (type) + { + case AST_ASSIGN_EQ: + case AST_ASSIGN_LE: + case AST_ASSIGN: + while (!children[0]->basic_prep && children[0]->simplify(false, stage, -1, false) == true) + did_something = true; + while (!children[1]->basic_prep && children[1]->simplify(false, stage, -1, false) == true) + did_something = true; + children[0]->detectSignWidth(backup_width_hint, backup_sign_hint); + children[1]->detectSignWidth(width_hint, sign_hint); + width_hint = max(width_hint, backup_width_hint); + child_0_is_self_determined = true; + // test only once, before optimizations and memory mappings but after assignment LHS was mapped to an identifier + if (children[0]->id2ast && !children[0]->was_checked) { + if ((type == AST_ASSIGN_LE || type == AST_ASSIGN_EQ) && children[0]->id2ast->is_logic) + children[0]->id2ast->is_reg = true; // if logic type is used in a block asignment + if ((type == AST_ASSIGN_LE || type == AST_ASSIGN_EQ) && !children[0]->id2ast->is_reg) + log_warning("wire '%s' is assigned in a block at %s.\n", children[0]->str, loc_string()); + if (type == AST_ASSIGN && children[0]->id2ast->is_reg) { + bool is_rand_reg = false; + if (children[1]->type == AST_FCALL) { + if (children[1]->str == "\\$anyconst") + is_rand_reg = true; + if (children[1]->str == "\\$anyseq") + is_rand_reg = true; + if (children[1]->str == "\\$allconst") + is_rand_reg = true; + if (children[1]->str == "\\$allseq") + is_rand_reg = true; + } + if (!is_rand_reg) + log_warning("reg '%s' is assigned in a continuous assignment at %s.\n", children[0]->str, loc_string()); + } + children[0]->was_checked = true; + } + break; + + case AST_STRUCT: + case AST_UNION: + if (!basic_prep) { + for (auto& node : children) { + // resolve any ranges + while (!node->basic_prep && node->simplify(true, stage, -1, false)) { + did_something = true; + } + } + // determine member offsets and widths + size_packed_struct(this, 0); + + // instance rather than just a type in a typedef or outer struct? + if (!str.empty() && str[0] == '\\') { + // instance so add a wire for the packed structure + auto wnode = make_packed_struct(this, str, attributes); + log_assert(current_ast_mod); + current_ast_mod->children.push_back(std::move(wnode)); + } + basic_prep = true; + is_custom_type = false; + } + break; + + case AST_STRUCT_ITEM: + if (is_custom_type) { + log_assert(children.size() >= 1); + log_assert(children[0]->type == AST_WIRETYPE); + + // Pretend it's just a wire in order to resolve the type. + type = AST_WIRE; + while (is_custom_type && simplify(const_fold, stage, width_hint, sign_hint)) {}; + if (type == AST_WIRE) + type = AST_STRUCT_ITEM; + + did_something = true; + } + log_assert(!is_custom_type); + break; + + case AST_ENUM: + //log("\nENUM %s: %d child %d\n", str, basic_prep, children[0]->basic_prep); + if (!basic_prep) { + for (auto& item_node : children) { + while (!item_node->basic_prep && item_node->simplify(false, stage, -1, false)) + did_something = true; + } + // allocate values (called more than once) + allocateDefaultEnumValues(); + } + break; + + case AST_PARAMETER: + case AST_LOCALPARAM: + // if parameter is implicit type which is the typename of a struct or union, + // save information about struct in wiretype attribute + if (children[0]->type == AST_IDENTIFIER && current_scope.count(children[0]->str) > 0) { + auto item_node = current_scope[children[0]->str]; + if (item_node->type == AST_STRUCT || item_node->type == AST_UNION) { + set_attribute(ID::wiretype, item_node->clone()); + size_packed_struct(attributes[ID::wiretype].get(), 0); + add_members_to_scope(attributes[ID::wiretype].get(), str); + } + } + while (!children[0]->basic_prep && children[0]->simplify(false, stage, -1, false) == true) + did_something = true; + children[0]->detectSignWidth(width_hint, sign_hint); + if (children.size() > 1 && children[1]->type == AST_RANGE) { + while (!children[1]->basic_prep && children[1]->simplify(false, stage, -1, false) == true) + did_something = true; + if (!children[1]->range_valid) + input_error("Non-constant width range on parameter decl.\n"); + width_hint = max(width_hint, children[1]->range_left - children[1]->range_right + 1); + } + break; + case AST_ENUM_ITEM: + while (!children[0]->basic_prep && children[0]->simplify(false, stage, -1, false)) + did_something = true; + children[0]->detectSignWidth(width_hint, sign_hint); + if (children.size() > 1 && children[1]->type == AST_RANGE) { + while (!children[1]->basic_prep && children[1]->simplify(false, stage, -1, false)) + did_something = true; + if (!children[1]->range_valid) + input_error("Non-constant width range on enum item decl.\n"); + width_hint = max(width_hint, children[1]->range_left - children[1]->range_right + 1); + } + break; + + case AST_CAST_SIZE: { + bool is_type_cast = children[0]->type == AST_WIRE; + if (children[0]->type == AST_WIRE) { + int width = 1; + std::unique_ptr node; + auto* child = children[0].get(); + if (child->children.size() == 0) { + // Base type (e.g., int) + width = child->range_left - child->range_right +1; + node = mkconst_int(child->location, width, child->is_signed); + } else { + // User defined type + log_assert(child->children[0]->type == AST_WIRETYPE); + + const std::string &type_name = child->children[0]->str; + if (!current_scope.count(type_name)) + input_error("Unknown identifier `%s' used as type name\n", type_name); + AstNode *resolved_type_node = current_scope.at(type_name); + if (resolved_type_node->type != AST_TYPEDEF) + input_error("`%s' does not name a type\n", type_name); + log_assert(resolved_type_node->children.size() == 1); + auto* template_node = resolved_type_node->children[0].get(); + + // Ensure typedef itself is fully simplified + while (template_node->simplify(const_fold, stage, width_hint, sign_hint)) {}; + + switch (template_node->type) + { + case AST_WIRE: { + if (template_node->children.size() > 0 && template_node->children[0]->type == AST_RANGE) + width = range_width(this, template_node->children[0].get()); + child->delete_children(); + node = mkconst_int(child->location, width, template_node->is_signed); + break; + } + + case AST_STRUCT: + case AST_UNION: { + child->delete_children(); + width = size_packed_struct(template_node, 0); + node = mkconst_int(child->location, width, template_node->is_signed); + break; + } + + default: + log_error("Don't know how to translate static cast of type %s\n", type2str(template_node->type)); + } + } + + children.erase(children.begin()); + children.insert(children.begin(), std::move(node)); + } + + while (!children[0]->basic_prep && children[0]->simplify(true, stage, -1, false)) + did_something = true; + if (children[0]->type == AST_CONSTANT) { + while (!children[1]->basic_prep && children[1]->simplify(false, stage, -1, false)) + did_something = true; + children[1]->detectSignWidth(width_hint, sign_hint); + width_hint = max(width_hint, children[0]->bitsAsConst().as_int()); + child_0_is_self_determined = true; + reset_width_after_children = true; + } else + children_are_self_determined = true; + + detect_width_simple = true; + // if is typecast, grab signedness from the signedness of the type + if (is_type_cast) { + type = children[0]->is_signed ? AST_TO_SIGNED : AST_TO_UNSIGNED; + auto cast = std::make_unique(location, AST_CAST_SIZE); + cast->children.swap(children); + children.push_back(std::move(cast)); + fixup_hierarchy_flags(); + children_are_self_determined = true; + did_something = true; + } + break; + } + + case AST_TO_BITS: + case AST_TO_SIGNED: + case AST_TO_UNSIGNED: + case AST_SELFSZ: + case AST_CONCAT: + case AST_REPLICATE: + case AST_REDUCE_AND: + case AST_REDUCE_OR: + case AST_REDUCE_XOR: + case AST_REDUCE_XNOR: + case AST_REDUCE_BOOL: + detect_width_simple = true; + children_are_self_determined = true; + break; + + case AST_ASSIGN_PATTERN: + // Assignment pattern elements are context-determined by the target element type. + // Keep child width context intact until whole-array assignment expansion creates scalar assignments. + detect_width_simple = true; + break; + + case AST_NEG: + case AST_BIT_NOT: + case AST_POS: + case AST_BIT_AND: + case AST_BIT_OR: + case AST_BIT_XOR: + case AST_BIT_XNOR: + case AST_ADD: + case AST_SUB: + case AST_MUL: + case AST_DIV: + case AST_MOD: + detect_width_simple = true; + break; + + case AST_SHIFT_LEFT: + case AST_SHIFT_RIGHT: + case AST_SHIFT_SLEFT: + case AST_SHIFT_SRIGHT: + case AST_POW: + detect_width_simple = true; + child_1_is_self_determined = true; + break; + + case AST_LT: + case AST_LE: + case AST_EQ: + case AST_NE: + case AST_EQX: + case AST_NEX: + case AST_GE: + case AST_GT: + width_hint = -1; + sign_hint = true; + for (auto& child : children) { + while (!child->basic_prep && child->simplify(false, stage, -1, false) == true) + did_something = true; + child->detectSignWidthWorker(width_hint, sign_hint); + } + reset_width_after_children = true; + break; + + case AST_LOGIC_AND: + case AST_LOGIC_OR: + case AST_LOGIC_NOT: + detect_width_simple = true; + children_are_self_determined = true; + break; + + case AST_TERNARY: + child_0_is_self_determined = true; + break; + + case AST_MEMRD: + detect_width_simple = true; + children_are_self_determined = true; + break; + + case AST_FCALL: + case AST_TCALL: + children_are_self_determined = true; + break; + + default: + width_hint = -1; + sign_hint = false; + } + + if (detect_width_simple && width_hint < 0) { + if (type == AST_REPLICATE) + while (children[0]->simplify(true, stage, -1, false) == true) + did_something = true; + for (auto& child : children) + while (!child->basic_prep && child->simplify(false, stage, -1, false) == true) + did_something = true; + detectSignWidth(width_hint, sign_hint); + } + + if (type == AST_FCALL && str == "\\$past") + detectSignWidth(width_hint, sign_hint); + + if (type == AST_TERNARY) { + if (width_hint < 0) { + while (!children[0]->basic_prep && children[0]->simplify(true, stage, -1, false)) + did_something = true; + + bool backup_unevaluated_tern_branch = unevaluated_tern_branch; + AstNode *chosen = get_tern_choice().first; + + unevaluated_tern_branch = backup_unevaluated_tern_branch || chosen == children[2].get(); + while (!children[1]->basic_prep && children[1]->simplify(false, stage, -1, false)) + did_something = true; + + unevaluated_tern_branch = backup_unevaluated_tern_branch || chosen == children[1].get(); + while (!children[2]->basic_prep && children[2]->simplify(false, stage, -1, false)) + did_something = true; + + unevaluated_tern_branch = backup_unevaluated_tern_branch; + detectSignWidth(width_hint, sign_hint); + } + int width_hint_left, width_hint_right; + bool sign_hint_left, sign_hint_right; + bool found_real_left, found_real_right; + children[1]->detectSignWidth(width_hint_left, sign_hint_left, &found_real_left); + children[2]->detectSignWidth(width_hint_right, sign_hint_right, &found_real_right); + if (found_real_left || found_real_right) { + child_1_is_self_determined = true; + child_2_is_self_determined = true; + } + } + + if (type == AST_CONDX && children.size() > 0 && children.at(0)->type == AST_CONSTANT) { + for (auto &bit : children.at(0)->bits) + if (bit == State::Sz || bit == State::Sx) + bit = State::Sa; + } + + if (type == AST_CONDZ && children.size() > 0 && children.at(0)->type == AST_CONSTANT) { + for (auto &bit : children.at(0)->bits) + if (bit == State::Sz) + bit = State::Sa; + } + + if (const_fold && type == AST_CASE) + { + detectSignWidth(width_hint, sign_hint); + while (children[0]->simplify(const_fold, stage, width_hint, sign_hint)) { } + if (children[0]->type == AST_CONSTANT && children[0]->bits_only_01()) { + children[0]->is_signed = sign_hint; + RTLIL::Const case_expr = children[0]->bitsAsConst(width_hint, sign_hint); + std::vector> new_children; + new_children.push_back(std::move(children[0])); + for (int i = 1; i < GetSize(children); i++) { + auto& child = children[i]; + log_assert(child->type == AST_COND || child->type == AST_CONDX || child->type == AST_CONDZ); + for (auto& v : child->children) { + if (v->type == AST_DEFAULT) + goto keep_const_cond; + if (v->type == AST_BLOCK) + continue; + while (v->simplify(const_fold, stage, width_hint, sign_hint)) { } + if (v->type == AST_CONSTANT && v->bits_only_01()) { + RTLIL::Const case_item_expr = v->bitsAsConst(width_hint, sign_hint); + RTLIL::Const match = const_eq(case_expr, case_item_expr, sign_hint, sign_hint, 1); + log_assert(match.size() == 1); + if (match.front() == RTLIL::State::S1) { + // This is the only reachable case. Skip to the end + i = GetSize(children); + goto keep_const_cond; + } + continue; + } + goto keep_const_cond; + } + if (0) + keep_const_cond: + new_children.push_back(std::move(child)); + } + new_children.swap(children); + } + } + + dict> backup_memwr_visible; + dict> final_memwr_visible; + + if (type == AST_CASE && stage == 2) { + backup_memwr_visible = current_memwr_visible; + final_memwr_visible = current_memwr_visible; + } + + // simplify all children first + // (iterate by index as e.g. auto wires can add new children in the process) + for (size_t i = 0; i < children.size(); i++) { + bool did_something_here = true; + bool backup_flag_autowire = flag_autowire; + bool backup_unevaluated_tern_branch = unevaluated_tern_branch; + if ((type == AST_GENFOR || type == AST_FOR) && i >= 3) + break; + if ((type == AST_GENIF || type == AST_GENCASE) && i >= 1) + break; + if (type == AST_GENBLOCK) + break; + if (type == AST_CELLARRAY && (children[i]->type == AST_CELL || children[i]->type == AST_PRIMITIVE)) + continue; + if (type == AST_BLOCK && !str.empty()) + break; + if (type == AST_PREFIX && i >= 1) + break; + if (type == AST_DEFPARAM && i == 0) + flag_autowire = true; + if (type == AST_TERNARY && i > 0 && !unevaluated_tern_branch) { + AstNode *chosen = get_tern_choice().first; + unevaluated_tern_branch = chosen && chosen != children[i].get(); + } + while (did_something_here && i < children.size()) { + bool const_fold_here = const_fold; + int width_hint_here = width_hint; + bool sign_hint_here = sign_hint; + if (i == 0 && (type == AST_REPLICATE || type == AST_WIRE)) + const_fold_here = true; + if (type == AST_PARAMETER || type == AST_LOCALPARAM) + const_fold_here = true; + if (type == AST_BLOCK) { + current_block = this; + current_block_child = children[i].get(); + } + if ((type == AST_ALWAYS || type == AST_INITIAL) && children[i]->type == AST_BLOCK) + current_top_block = children[i].get(); + if (i == 0 && child_0_is_self_determined) + width_hint_here = -1, sign_hint_here = false; + if (i == 1 && child_1_is_self_determined) + width_hint_here = -1, sign_hint_here = false; + if (i == 2 && child_2_is_self_determined) + width_hint_here = -1, sign_hint_here = false; + if (children_are_self_determined) + width_hint_here = -1, sign_hint_here = false; + if (type == AST_ASSIGN_PATTERN) { + // It's unlikely for this simplify to run, but just to be sure + while (!children[i]->basic_prep && children[i]->simplify(false, stage, -1, false)) + did_something = true; + // Undo signedness inheritance of the children from the parent AST_ASSIGN_PATTERN + // but widen as needed + int child_width_hint; + bool child_sign_hint; + children[i]->detectSignWidth(child_width_hint, child_sign_hint); + width_hint_here = max(width_hint, child_width_hint); + sign_hint_here = child_sign_hint; + } + did_something_here = children[i]->simplify(const_fold_here, stage, width_hint_here, sign_hint_here); + if (did_something_here) + did_something = true; + } + if (stage == 2 && children[i]->type == AST_INITIAL && current_ast_mod != this) { + current_ast_mod->children.push_back(std::move(children[i])); + children.erase(children.begin() + (i--)); + did_something = true; + } + flag_autowire = backup_flag_autowire; + unevaluated_tern_branch = backup_unevaluated_tern_branch; + if (stage == 2 && type == AST_CASE) { + for (auto &x : current_memwr_visible) { + for (int y : x.second) + final_memwr_visible[x.first].insert(y); + } + current_memwr_visible = backup_memwr_visible; + } + } + for (auto &attr : attributes) { + while (attr.second->simplify(true, stage, -1, false)) + did_something = true; + } + if (type == AST_CASE && stage == 2) { + current_memwr_visible = final_memwr_visible; + } + if (type == AST_ALWAYS && stage == 2) { + current_memwr_visible.clear(); + current_memwr_count.clear(); + } + + if (reset_width_after_children) { + width_hint = backup_width_hint; + sign_hint = backup_sign_hint; + if (width_hint < 0) + detectSignWidth(width_hint, sign_hint); + } + + current_block = backup_current_block; + current_block_child = backup_current_block_child; + current_top_block = backup_current_top_block; + current_always = backup_current_always; + current_always_clocked = backup_current_always_clocked; + + for (auto it = backup_scope.begin(); it != backup_scope.end(); it++) { + if (it->second == nullptr) + current_scope.erase(it->first); + else + current_scope[it->first] = it->second; + } + + if (type == AST_MODULE || type == AST_INTERFACE) + current_scope.clear(); + + // convert defparam nodes to cell parameters + if (type == AST_DEFPARAM && !children.empty()) + { + if (children[0]->type != AST_IDENTIFIER) + input_error("Module name in defparam contains non-constant expressions!\n"); + + string modname, paramname = children[0]->str; + + size_t pos = paramname.rfind('.'); + + while (pos != 0 && pos != std::string::npos) + { + modname = paramname.substr(0, pos); + + if (current_scope.count(modname)) + break; + + pos = paramname.rfind('.', pos - 1); + } + + if (pos == std::string::npos) + input_error("Can't find object for defparam `%s`!\n", RTLIL::unescape_id(paramname)); + + paramname = "\\" + paramname.substr(pos+1); + + if (current_scope.at(modname)->type != AST_CELL) + input_error("Defparam argument `%s . %s` does not match a cell!\n", + RTLIL::unescape_id(modname), RTLIL::unescape_id(paramname)); + + auto paraset = std::make_unique(location, AST_PARASET, children[1]->clone(), GetSize(children) > 2 ? children[2]->clone() : nullptr); + paraset->str = paramname; + + AstNode *cell = current_scope.at(modname); + cell->children.insert(cell->children.begin() + 1, std::move(paraset)); + delete_children(); + } + + // resolve typedefs + if (type == AST_TYPEDEF) { + log_assert(children.size() == 1); + auto& type_node = children[0]; + log_assert(type_node->type == AST_WIRE || type_node->type == AST_MEMORY || type_node->type == AST_STRUCT || type_node->type == AST_UNION); + while (type_node->simplify(const_fold, stage, width_hint, sign_hint)) { + did_something = true; + } + log_assert(!type_node->is_custom_type); + } + + // resolve types of wires + if (type == AST_WIRE || type == AST_MEMORY) { + if (is_custom_type) { + log_assert(children.size() >= 1); + log_assert(children[0]->type == AST_WIRETYPE); + auto type_name = children[0]->str; + if (!current_scope.count(type_name)) { + input_error("Unknown identifier `%s' used as type name\n", type_name); + } + AstNode *resolved_type_node = current_scope.at(type_name); + if (resolved_type_node->type != AST_TYPEDEF) + input_error("`%s' does not name a type\n", type_name); + log_assert(resolved_type_node->children.size() == 1); + auto& template_node = resolved_type_node->children[0]; + + // Resolve the typedef from the bottom up, recursing within the current + // block of code. Defer further simplification until the complete type is + // resolved. + while (template_node->is_custom_type && template_node->simplify(const_fold, stage, width_hint, sign_hint)) {}; + + if (!str.empty() && str[0] == '\\' && (template_node->type == AST_STRUCT || template_node->type == AST_UNION)) { + // replace instance with wire representing the packed structure + newNode = make_packed_struct(template_node.get(), str, attributes); + newNode->set_attribute(ID::wiretype, mkconst_str(newNode->location, resolved_type_node->str)); + // add original input/output attribute to resolved wire + newNode->is_input = this->is_input; + newNode->is_output = this->is_output; + current_scope[str] = this; + goto apply_newNode; + } + + // Prepare replacement node. + newNode = template_node->clone(); + newNode->str = str; + newNode->set_attribute(ID::wiretype, mkconst_str(newNode->location, resolved_type_node->str)); + newNode->is_input = is_input; + newNode->is_output = is_output; + newNode->is_wand = is_wand; + newNode->is_wor = is_wor; + for (auto &pair : attributes) + newNode->set_attribute(pair.first, pair.second->clone()); + + // if an enum then add attributes to support simulator tracing + newNode->annotateTypedEnums(template_node.get()); + + bool add_packed_dimensions = (type == AST_WIRE && GetSize(children) > 1) || (type == AST_MEMORY && GetSize(children) > 2); + + // Cannot add packed dimensions if unpacked dimensions are already specified. + if (add_packed_dimensions && newNode->type == AST_MEMORY) + input_error("Cannot extend unpacked type `%s' with packed dimensions\n", type_name); + + // Add packed dimensions. + if (add_packed_dimensions) { + auto& packed = children[1]; + if (newNode->children.empty()) + newNode->children.insert(newNode->children.begin(), packed->clone()); + else + prepend_ranges(newNode->children[0], packed.get()); + } + + // Add unpacked dimensions. + if (type == AST_MEMORY) { + auto& unpacked = children.back(); + if (GetSize(newNode->children) < 2) + newNode->children.push_back(unpacked->clone()); + else + prepend_ranges(newNode->children[1], unpacked.get()); + newNode->type = type; + } + + // Prepare to generate dimensions metadata for the resolved type. + newNode->dimensions.clear(); + newNode->unpacked_dimensions = 0; + + goto apply_newNode; + } + } + + // resolve types of parameters + if (type == AST_LOCALPARAM || type == AST_PARAMETER) { + if (is_custom_type) { + log_assert(children.size() >= 2); + log_assert(children[1]->type == AST_WIRETYPE); + + // Pretend it's just a wire in order to resolve the type in the code block above. + AstNodeType param_type = type; + type = AST_WIRE; + auto expr = std::move(children.front()); + children.erase(children.begin()); + while (is_custom_type && simplify(const_fold, stage, width_hint, sign_hint)) {}; + type = param_type; + children.insert(children.begin(), std::move(expr)); + + if (children[1]->type == AST_MEMORY) + input_error("unpacked array type `%s' cannot be used for a parameter\n", children[1]->str); + fixup_hierarchy_flags(); + did_something = true; + } + log_assert(!is_custom_type); + } + + // resolve constant prefixes + if (type == AST_PREFIX) { + if (children[0]->type != AST_CONSTANT) { + // dumpAst(nullptr, "> "); + input_error("Index in generate block prefix syntax is not constant!\n"); + } + if (children[1]->type == AST_PREFIX) + children[1]->simplify(const_fold, stage, width_hint, sign_hint); + log_assert(children[1]->type == AST_IDENTIFIER); + newNode = children[1]->clone(); + const char *second_part = children[1]->str.c_str(); + if (second_part[0] == '\\') + second_part++; + newNode->str = stringf("%s[%d].%s", str, children[0]->integer, second_part); + goto apply_newNode; + } + + // evaluate TO_BITS nodes + if (type == AST_TO_BITS) { + if (children[0]->type != AST_CONSTANT) + input_error("Left operand of to_bits expression is not constant!\n"); + if (children[1]->type != AST_CONSTANT) + input_error("Right operand of to_bits expression is not constant!\n"); + RTLIL::Const new_value = children[1]->bitsAsConst(children[0]->bitsAsConst().as_int(), children[1]->is_signed); + newNode = mkconst_bits(location, new_value.to_bits(), children[1]->is_signed); + goto apply_newNode; + } + + // annotate constant ranges + if (type == AST_RANGE) { + bool old_range_valid = range_valid; + range_valid = false; + range_swapped = false; + range_left = -1; + range_right = 0; + log_assert(children.size() >= 1); + if (children[0]->type == AST_CONSTANT) { + range_valid = true; + range_left = children[0]->integer; + if (children.size() == 1) + range_right = range_left; + } + if (children.size() >= 2) { + if (children[1]->type == AST_CONSTANT) + range_right = children[1]->integer; + else + range_valid = false; + } + if (old_range_valid != range_valid) + did_something = true; + if (range_valid && range_right > range_left) { + std::swap(range_left, range_right); + range_swapped = true; + } + } + + // annotate wires with their ranges + if (type == AST_WIRE) { + if (children.size() > 0) { + if (children[0]->range_valid) { + if (!range_valid) + did_something = true; + range_valid = true; + range_swapped = children[0]->range_swapped; + range_left = children[0]->range_left; + range_right = children[0]->range_right; + bool force_upto = false, force_downto = false; + if (attributes.count(ID::force_upto)) { + auto* val = attributes[ID::force_upto].get(); + if (val->type != AST_CONSTANT) + input_error("Attribute `force_upto' with non-constant value!\n"); + force_upto = val->asAttrConst().as_bool(); + } + if (attributes.count(ID::force_downto)) { + auto* val = attributes[ID::force_downto].get(); + if (val->type != AST_CONSTANT) + input_error("Attribute `force_downto' with non-constant value!\n"); + force_downto = val->asAttrConst().as_bool(); + } + if (force_upto && force_downto) + input_error("Attributes `force_downto' and `force_upto' cannot be both set!\n"); + if ((force_upto && !range_swapped) || (force_downto && range_swapped)) { + std::swap(range_left, range_right); + range_swapped = force_upto; + } + if (range_left == range_right && !attributes.count(ID::single_bit_vector)) + set_attribute(ID::single_bit_vector, mkconst_int(location, 1, false)); + } + } else { + if (!range_valid) + did_something = true; + range_valid = true; + range_swapped = false; + range_left = 0; + range_right = 0; + attributes.erase(ID::single_bit_vector); + } + } + + // Resolve packed and unpacked ranges in declarations. + if ((type == AST_WIRE || type == AST_MEMORY) && dimensions.empty()) { + if (!children.empty()) { + // Unpacked ranges first, then packed ranges. + for (int i = std::min(GetSize(children), 2) - 1; i >= 0; i--) { + if (children[i]->type == AST_MULTIRANGE) { + int width = 1; + for (auto& range : children[i]->children) { + width *= add_dimension(this, range.get()); + if (i) unpacked_dimensions++; + } + int left = width - 1, right = 0; + if (i) + std::swap(left, right); + auto loc = children[i]->location; + children[i] = std::make_unique(loc, AST_RANGE, mkconst_int(loc, left, true), mkconst_int(loc, right, true)); + fixup_hierarchy_flags(); + did_something = true; + } else if (children[i]->type == AST_RANGE) { + add_dimension(this, children[i].get()); + if (i) unpacked_dimensions++; + } + } + } else { + // 1 bit signal: bit, logic or reg + dimensions.push_back({ 0, 1, false }); + } + } + + // Resolve multidimensional array access. + if (type == AST_IDENTIFIER && !basic_prep && id2ast && (id2ast->type == AST_WIRE || id2ast->type == AST_MEMORY) && + children.size() > 0 && (children[0]->type == AST_RANGE || children[0]->type == AST_MULTIRANGE)) + { + int dims_sel = children[0]->type == AST_MULTIRANGE ? children[0]->children.size() : 1; + // Save original number of dimensions for $size() etc. + integer = dims_sel; + + // Split access into unpacked and packed parts. + std::unique_ptr unpacked_range = nullptr; + std::unique_ptr packed_range = nullptr; + + if (id2ast->unpacked_dimensions) { + if (id2ast->unpacked_dimensions > 1) { + // Flattened range for access to unpacked dimensions. + unpacked_range = make_index_range(id2ast, true); + } else { + // Index into one-dimensional unpacked part; unlink simple range node. + auto& range = children[0]->type == AST_MULTIRANGE ? children[0]->children[0] : children[0]; + unpacked_range = std::move(range); + range = nullptr; + } + } + + if (dims_sel > id2ast->unpacked_dimensions) { + if (GetSize(id2ast->dimensions) - id2ast->unpacked_dimensions > 1) { + // Flattened range for access to packed dimensions. + packed_range = make_index_range(id2ast, false); + } else { + // Index into one-dimensional packed part; unlink simple range node. + auto& range = children[0]->type == AST_MULTIRANGE ? children[0]->children[dims_sel - 1] : children[0]; + packed_range = std::move(range); + range = nullptr; + } + } + + children.clear(); + + if (unpacked_range) + children.push_back(std::move(unpacked_range)); + + if (packed_range) + children.push_back(std::move(packed_range)); + + fixup_hierarchy_flags(); + basic_prep = true; + did_something = true; + } + + // trim/extend parameters + if (type == AST_PARAMETER || type == AST_LOCALPARAM || type == AST_ENUM_ITEM) { + if (children.size() > 1 && children[1]->type == AST_RANGE) { + if (!children[1]->range_valid) + input_error("Non-constant width range on parameter decl.\n"); + int width = std::abs(children[1]->range_left - children[1]->range_right) + 1; + if (children[0]->type == AST_REALVALUE) { + RTLIL::Const constvalue = children[0]->realAsConst(width); + log_file_warning(location.to_loc(), "converting real value %e to binary %s.\n", + children[0]->realvalue, log_signal(constvalue)); + children[0] = mkconst_bits(location, constvalue.to_bits(), sign_hint); + fixup_hierarchy_flags(); + did_something = true; + } + if (children[0]->type == AST_CONSTANT) { + if (width != int(children[0]->bits.size())) { + RTLIL::Const val; + if (children[0]->is_unsized) { + val = children[0]->bitsAsUnsizedConst(width); + } else { + val = children[0]->bitsAsConst(width); + } + children[0] = mkconst_bits(location, val.to_bits(), is_signed); + fixup_hierarchy_flags(); + } + children[0]->is_signed = is_signed; + } + range_valid = true; + range_swapped = children[1]->range_swapped; + range_left = children[1]->range_left; + range_right = children[1]->range_right; + } else + if (children.size() > 1 && children[1]->type == AST_REALVALUE && children[0]->type == AST_CONSTANT) { + double as_realvalue = children[0]->asReal(sign_hint); + children[0] = std::make_unique(location, AST_REALVALUE); + children[0]->realvalue = as_realvalue; + fixup_hierarchy_flags(); + did_something = true; + } + } + + if (type == AST_IDENTIFIER && !basic_prep) { + // check if a plausible struct member sss.mmmm + if (!str.empty() && str[0] == '\\' && current_scope.count(str)) { + auto item_node = current_scope[str]; + if (item_node->type == AST_STRUCT_ITEM || item_node->type == AST_STRUCT || item_node->type == AST_UNION) { + // Traverse any hierarchical path until the full name for the referenced struct/union is found. + std::string sname; + bool found_sname = false; + for (std::string::size_type pos = 0; (pos = str.find('.', pos)) != std::string::npos; pos++) { + sname = str.substr(0, pos); + if (current_scope.count(sname)) { + auto stype = current_scope[sname]->type; + if (stype == AST_WIRE || stype == AST_PARAMETER || stype == AST_LOCALPARAM) { + found_sname = true; + break; + } + } + } + + if (found_sname) { + // structure member, rewrite this node to reference the packed struct wire + auto range = make_index_range(item_node); + newNode = std::make_unique(location, AST_IDENTIFIER, std::move(range)); + newNode->str = sname; + // save type and original number of dimensions for $size() etc. + newNode->set_attribute(ID::wiretype, item_node->clone()); + if (!item_node->dimensions.empty() && children.size() > 0) { + if (children[0]->type == AST_RANGE) + newNode->integer = 1; + else if (children[0]->type == AST_MULTIRANGE) + newNode->integer = children[0]->children.size(); + } + newNode->basic_prep = true; + if (item_node->is_signed) + newNode = std::make_unique(location, AST_TO_SIGNED, std::move(newNode)); + goto apply_newNode; + } + } + } + } + // annotate identifiers using scope resolution and create auto-wires as needed + if (type == AST_IDENTIFIER) { + if (current_scope.count(str) == 0) { + AstNode *current_scope_ast = (current_ast_mod == nullptr) ? current_ast : current_ast_mod; + str = try_pop_module_prefix(); + for (auto& node : current_scope_ast->children) { + //log("looking at mod scope child %s\n", type2str(node->type)); + switch (node->type) { + case AST_PARAMETER: + case AST_LOCALPARAM: + case AST_WIRE: + case AST_AUTOWIRE: + case AST_GENVAR: + case AST_MEMORY: + case AST_FUNCTION: + case AST_TASK: + case AST_DPI_FUNCTION: + //log("found child %s, %s\n", type2str(node->type), node->str); + if (str == node->str) { + //log("add %s, type %s to scope\n", str, type2str(node->type)); + current_scope[node->str] = node.get(); + } + break; + case AST_ENUM: + current_scope[node->str] = node.get(); + for (auto& enum_node : node->children) { + log_assert(enum_node->type==AST_ENUM_ITEM); + if (str == enum_node->str) { + //log("\nadding enum item %s to scope\n", str); + current_scope[str] = enum_node.get(); + } + } + break; + default: + break; + } + } + } + if (current_scope.count(str) == 0) { + if (current_ast_mod == nullptr) { + input_error("Identifier `%s' is implicitly declared outside of a module.\n", str); + } else if (flag_autowire || str == "\\$global_clock") { + auto auto_wire = std::make_unique(location, AST_AUTOWIRE); + auto_wire->str = str; + current_scope[str] = auto_wire.get(); + current_ast_mod->children.push_back(std::move(auto_wire)); + did_something = true; + } else { + input_error("Identifier `%s' is implicitly declared and `default_nettype is set to none.\n", str); + } + } + if (id2ast != current_scope[str]) { + id2ast = current_scope[str]; + did_something = true; + } + } + + // split memory access with bit select to individual statements + if (type == AST_IDENTIFIER && children.size() == 2 && children[0]->type == AST_RANGE && children[1]->type == AST_RANGE && !in_lvalue && stage == 2) + { + if (id2ast == nullptr || id2ast->type != AST_MEMORY || children[0]->children.size() != 1) + input_error("Invalid bit-select on memory access!\n"); + + int mem_width, mem_size, addr_bits; + id2ast->meminfo(mem_width, mem_size, addr_bits); + + int data_range_left = id2ast->children[0]->range_left; + int data_range_right = id2ast->children[0]->range_right; + + if (id2ast->children[0]->range_swapped) + std::swap(data_range_left, data_range_right); + + std::stringstream sstr; + sstr << "$mem2bits$" << str << "$" << RTLIL::encode_filename(*location.begin.filename) << ":" << location.begin.line << "$" << ast_autoidx(); + std::string wire_id = sstr.str(); + + auto wire_owned = std::make_unique(location, AST_WIRE, std::make_unique(location, AST_RANGE, mkconst_int(location, data_range_left, true), mkconst_int(location, data_range_right, true))); + auto* wire = wire_owned.get(); + current_ast_mod->children.push_back(std::move(wire_owned)); + wire->str = wire_id; + if (current_block) + wire->set_attribute(ID::nosync, AstNode::mkconst_int(location, 1, false)); + while (wire->simplify(true, 1, -1, false)) { } + + auto data = clone(); + data->children.pop_back(); + + auto assign = std::make_unique(location, AST_ASSIGN_EQ, std::make_unique(location, AST_IDENTIFIER), std::move(data)); + assign->children[0]->str = wire_id; + assign->children[0]->was_checked = true; + + if (current_block) + { + size_t assign_idx = 0; + while (assign_idx < current_block->children.size() && current_block->children[assign_idx].get() != current_block_child) + assign_idx++; + log_assert(assign_idx < current_block->children.size()); + current_block->children.insert(current_block->children.begin()+assign_idx, std::move(assign)); + wire->is_reg = true; + } + else + { + auto proc = std::make_unique(location, AST_ALWAYS, std::make_unique(location, AST_BLOCK)); + proc->children[0]->children.push_back(std::move(assign)); + current_ast_mod->children.push_back(std::move(proc)); + } + + newNode = std::make_unique(location, AST_IDENTIFIER, children[1]->clone()); + newNode->str = wire_id; + newNode->integer = integer; // save original number of dimensions for $size() etc. + newNode->id2ast = wire; + goto apply_newNode; + } + + if (type == AST_WHILE) + input_error("While loops are only allowed in constant functions!\n"); + + if (type == AST_REPEAT) + { + auto count = std::move(children[0]); + auto body = std::move(children[1]); + + // eval count expression + while (count->simplify(true, stage, 32, true)) { } + + if (count->type != AST_CONSTANT) + input_error("Repeat loops outside must have constant repeat counts!\n"); + + // convert to a block with the body repeated n times + type = AST_BLOCK; + children.clear(); + for (int i = 0; i < count->bitsAsConst().as_int(); i++) + children.insert(children.begin(), body->clone()); + + did_something = true; + } + + // unroll for loops and generate-for blocks + if ((type == AST_GENFOR || type == AST_FOR) && children.size() != 0) + { + auto& init_ast = children[0]; + auto& while_ast = children[1]; + auto& next_ast = children[2]; + auto* body_ast = children[3].get(); + + while (body_ast->type == AST_GENBLOCK && body_ast->str.empty() && + body_ast->children.size() == 1 && body_ast->children.at(0)->type == AST_GENBLOCK) + body_ast = body_ast->children.at(0).get(); + + const char* loop_type_str = "procedural"; + const char* var_type_str = "register"; + AstNodeType var_type = AST_WIRE; + if (type == AST_GENFOR) { + loop_type_str = "generate"; + var_type_str = "genvar"; + var_type = AST_GENVAR; + } + + if (init_ast->type != AST_ASSIGN_EQ) + input_error("Unsupported 1st expression of %s for-loop!\n", loop_type_str); + if (next_ast->type != AST_ASSIGN_EQ) + input_error("Unsupported 3rd expression of %s for-loop!\n", loop_type_str); + + if (init_ast->children[0]->id2ast == nullptr || init_ast->children[0]->id2ast->type != var_type) + input_error("Left hand side of 1st expression of %s for-loop is not a %s!\n", loop_type_str, var_type_str); + if (next_ast->children[0]->id2ast == nullptr || next_ast->children[0]->id2ast->type != var_type) + input_error("Left hand side of 3rd expression of %s for-loop is not a %s!\n", loop_type_str, var_type_str); + + if (init_ast->children[0]->id2ast != next_ast->children[0]->id2ast) + input_error("Incompatible left-hand sides in 1st and 3rd expression of %s for-loop!\n", loop_type_str); + + // eval 1st expression + auto varbuf = init_ast->children[1]->clone(); + { + int expr_width_hint = -1; + bool expr_sign_hint = true; + varbuf->detectSignWidth(expr_width_hint, expr_sign_hint); + while (varbuf->simplify(true, stage, 32, true)) { } + } + + if (varbuf->type != AST_CONSTANT) + input_error("Right hand side of 1st expression of %s for-loop is not constant!\n", loop_type_str); + + auto resolved = current_scope.at(init_ast->children[0]->str); + auto apply_loop_var_type = [&resolved](std::unique_ptr &value) { + if (resolved->range_valid) { + int const_size = value->range_left - value->range_right; + int resolved_size = resolved->range_left - resolved->range_right; + if (const_size < resolved_size) { + for (int i = const_size; i < resolved_size; i++) + value->bits.push_back(resolved->is_signed ? value->bits.back() : State::S0); + value->range_left = resolved->range_left; + value->range_right = resolved->range_right; + value->range_swapped = resolved->range_swapped; + value->range_valid = resolved->range_valid; + } + } + value->is_signed = resolved->is_signed; + }; + + apply_loop_var_type(varbuf); + + varbuf = std::make_unique(location, AST_LOCALPARAM, std::move(varbuf)); + varbuf->str = init_ast->children[0]->str; + varbuf->is_signed = resolved->is_signed; + + AstNode *backup_scope_varbuf = current_scope[varbuf->str]; + current_scope[varbuf->str] = varbuf.get(); + + size_t current_block_idx = 0; + if (type == AST_FOR) { + while (current_block_idx < current_block->children.size() && + current_block->children[current_block_idx].get() != current_block_child) + current_block_idx++; + } + + while (1) + { + // eval 2nd expression + auto buf = while_ast->clone(); + { + int expr_width_hint = -1; + bool expr_sign_hint = true; + buf->detectSignWidth(expr_width_hint, expr_sign_hint); + while (buf->simplify(true, stage, expr_width_hint, expr_sign_hint)) { } + } + + if (buf->type != AST_CONSTANT) + input_error("2nd expression of %s for-loop is not constant!\n", loop_type_str); + + if (buf->integer == 0) { + break; + } + + // expand body + int index = varbuf->children[0]->integer; + log_assert(body_ast->type == AST_GENBLOCK || body_ast->type == AST_BLOCK); + log_assert(!body_ast->str.empty()); + buf = body_ast->clone(); + + if (index > flag_unroll_limit) { + input_error("loop variable %s exceeds unroll limit %d\n", varbuf->str.c_str(), flag_unroll_limit); + } + + std::stringstream sstr; + sstr << buf->str << "[" << index << "]."; + std::string prefix = sstr.str(); + + // create a scoped localparam for the current value of the loop variable + auto local_index = varbuf->clone(); + size_t pos = local_index->str.rfind('.'); + if (pos != std::string::npos) // remove outer prefix + local_index->str = "\\" + local_index->str.substr(pos + 1); + local_index->str = prefix_id(prefix, local_index->str); + current_scope[local_index->str] = local_index.get(); + current_ast_mod->children.push_back(std::move(local_index)); + + buf->expand_genblock(prefix); + + if (type == AST_GENFOR) { + for (size_t i = 0; i < buf->children.size(); i++) { + buf->children[i]->simplify(const_fold, stage, -1, false); + current_ast_mod->children.push_back(std::move(buf->children[i])); + } + } else { + for (size_t i = 0; i < buf->children.size(); i++) + current_block->children.insert(current_block->children.begin() + current_block_idx++, std::move(buf->children[i])); + } + buf->children.clear(); + + // eval 3rd expression + buf = next_ast->children[1]->clone(); + buf->set_in_param_flag(true); + { + int expr_width_hint = -1; + bool expr_sign_hint = true; + buf->detectSignWidth(expr_width_hint, expr_sign_hint); + while (buf->simplify(true, stage, expr_width_hint, expr_sign_hint)) { } + } + + if (buf->type != AST_CONSTANT) + input_error("Right hand side of 3rd expression of %s for-loop is not constant (%s)!\n", loop_type_str, type2str(buf->type)); + + apply_loop_var_type(buf); + varbuf->children[0] = std::move(buf); + } + + if (type == AST_FOR) { + auto buf = next_ast->clone(); + buf->children[1] = varbuf->children[0]->clone(); + current_block->children.insert(current_block->children.begin() + current_block_idx++, std::move(buf)); + } + + current_scope[varbuf->str] = backup_scope_varbuf; + delete_children(); + did_something = true; + } + + // check for local objects in unnamed block + if (type == AST_BLOCK && str.empty()) + { + for (size_t i = 0; i < children.size(); i++) + if (children[i]->type == AST_WIRE || children[i]->type == AST_MEMORY || children[i]->type == AST_PARAMETER || children[i]->type == AST_LOCALPARAM || children[i]->type == AST_TYPEDEF) + { + log_assert(!sv_mode_but_global_and_used_for_literally_one_condition); + children[i]->input_error("Local declaration in unnamed block is only supported in SystemVerilog mode!\n"); + } + } + + // transform block with name + if (type == AST_BLOCK && !str.empty()) + { + expand_genblock(str + "."); + + // if this is an autonamed block is in an always_comb + if (current_always && current_always->attributes.count(ID::always_comb) + && is_autonamed_block(str)) + // track local variables in this block so we can consider adding + // nosync once the block has been fully elaborated + for (auto& child : children) + if (child->type == AST_WIRE && + !child->attributes.count(ID::nosync)) + mark_auto_nosync(this, child.get()); + + std::vector> new_children; + for (size_t i = 0; i < children.size(); i++) + if (children[i]->type == AST_WIRE || children[i]->type == AST_MEMORY || children[i]->type == AST_PARAMETER || children[i]->type == AST_LOCALPARAM || children[i]->type == AST_TYPEDEF) { + children[i]->simplify(false, stage, -1, false); + current_scope[children[i]->str] = children[i].get(); + current_ast_mod->children.push_back(std::move(children[i])); + } else + new_children.push_back(std::move(children[i])); + + children.swap(new_children); + did_something = true; + str.clear(); + } + + // simplify unconditional generate block + if (type == AST_GENBLOCK && children.size() != 0) + { + if (!str.empty()) { + expand_genblock(str + "."); + } + + for (size_t i = 0; i < children.size(); i++) { + children[i]->simplify(const_fold, stage, -1, false); + current_ast_mod->children.push_back(std::move(children[i])); + } + + children.clear(); + did_something = true; + } + + // simplify generate-if blocks + if (type == AST_GENIF && children.size() != 0) + { + auto buf = children[0]->clone(); + while (buf->simplify(true, stage, width_hint, sign_hint)) { } + if (!buf->isConst()) { + //logger().for_each_sink([&](LogSink &sink) { + // FILE *f = sink.file_handle(); + // if (f) + // dumpAst(f, "verilog-ast> "); + //}); + input_error("Condition for generate if is not constant!\n"); + } + if (buf->asBool() != 0) { + buf = children[1]->clone(); + } else { + buf = children.size() > 2 ? children[2]->clone() : nullptr; + } + + if (buf) + { + if (buf->type != AST_GENBLOCK) + buf = std::make_unique(location, AST_GENBLOCK, std::move(buf)); + + if (!buf->str.empty()) { + buf->expand_genblock(buf->str + "."); + } + + for (size_t i = 0; i < buf->children.size(); i++) { + buf->children[i]->simplify(const_fold, stage, -1, false); + current_ast_mod->children.push_back(std::move(buf->children[i])); + } + + buf->children.clear(); + } + + delete_children(); + did_something = true; + } + + // simplify generate-case blocks + if (type == AST_GENCASE && children.size() != 0) + { + auto buf = children[0]->clone(); + while (buf->simplify(true, stage, width_hint, sign_hint)) { } + if (buf->type != AST_CONSTANT) { + //logger().for_each_sink([&](LogSink &sink) { + // FILE *f = sink.file_handle(); + // if (f) + // dumpAst(f, "verilog-ast> "); + //}); + input_error("Condition for generate case is not constant!\n"); + } + + bool ref_signed = buf->is_signed; + RTLIL::Const ref_value = buf->bitsAsConst(); + + AstNode *selected_case = nullptr; + for (size_t i = 1; i < children.size(); i++) + { + log_assert(children.at(i)->type == AST_COND || children.at(i)->type == AST_CONDX || children.at(i)->type == AST_CONDZ); + + AstNode *this_genblock = nullptr; + for (auto& child : children.at(i)->children) { + log_assert(this_genblock == nullptr); + if (child->type == AST_GENBLOCK) + this_genblock = child.get(); + } + + for (auto& child : children.at(i)->children) + { + if (child->type == AST_DEFAULT) { + if (selected_case == nullptr) + selected_case = this_genblock; + continue; + } + if (child->type == AST_GENBLOCK) + continue; + + buf = child->clone(); + buf->set_in_param_flag(true); + while (buf->simplify(true, stage, width_hint, sign_hint)) { } + if (buf->type != AST_CONSTANT) { + //logger().for_each_sink([&](LogSink &sink) { + // FILE *f = sink.file_handle(); + // if (f) + // dumpAst(f, "verilog-ast> "); + //}); + input_error("Expression in generate case is not constant!\n"); + } + + bool is_selected = RTLIL::const_eq(ref_value, buf->bitsAsConst(), ref_signed && buf->is_signed, ref_signed && buf->is_signed, 1).as_bool(); + + if (is_selected) { + selected_case = this_genblock; + i = children.size(); + break; + } + } + } + + if (selected_case != nullptr) + { + log_assert(selected_case->type == AST_GENBLOCK); + buf = selected_case->clone(); + + if (!buf->str.empty()) { + buf->expand_genblock(buf->str + "."); + } + + for (size_t i = 0; i < buf->children.size(); i++) { + buf->children[i]->simplify(const_fold, stage, -1, false); + current_ast_mod->children.push_back(std::move(buf->children[i])); + } + + buf->children.clear(); + } + + delete_children(); + did_something = true; + } + + // unroll cell arrays + if (type == AST_CELLARRAY) + { + if (!children.at(0)->range_valid) + input_error("Non-constant array range on cell array.\n"); + + newNode = std::make_unique(location, AST_GENBLOCK); + int num = max(children.at(0)->range_left, children.at(0)->range_right) - min(children.at(0)->range_left, children.at(0)->range_right) + 1; + + if (this->children.at(1)->type == AST_PRIMITIVE) { + // Move the range to the AST_PRIMITIVE node and replace this with the AST_PRIMITIVE node handled below + newNode = std::move(this->children.at(1)); + newNode->range_left = this->children.at(0)->range_left; + newNode->range_right = this->children.at(0)->range_right; + newNode->range_valid = true; + goto apply_newNode; + } + + for (int i = 0; i < num; i++) { + int idx = children.at(0)->range_left > children.at(0)->range_right ? children.at(0)->range_right + i : children.at(0)->range_right - i; + auto new_cell_owned = children.at(1)->clone(); + auto* new_cell = new_cell_owned.get(); + newNode->children.push_back(std::move(new_cell_owned)); + new_cell->str += stringf("[%d]", idx); + + log_assert(new_cell->children.at(0)->type == AST_CELLTYPE); + new_cell->children.at(0)->str = stringf("$array:%d:%d:%s", i, num, new_cell->children.at(0)->str); + } + + goto apply_newNode; + } + + // replace primitives with assignments + if (type == AST_PRIMITIVE) + { + if (children.size() < 2) + input_error("Insufficient number of arguments for primitive `%s'!\n", str); + + std::vector> children_list; + for (auto& child : children) { + log_assert(child->type == AST_ARGUMENT); + log_assert(child->children.size() == 1); + children_list.push_back(std::move(child->children[0])); + child->children.clear(); + } + children.clear(); + + // TODO handle bit-widths of primitives and support cell arrays for more primitives + + if (range_valid && str != "tran") + input_error("Cell arrays of primitives are currently not supported.\n"); + + if (str == "bufif0" || str == "bufif1" || str == "notif0" || str == "notif1") + { + if (children_list.size() != 3) + input_error("Invalid number of arguments for primitive `%s'!\n", str); + + std::vector z_const(1, RTLIL::State::Sz); + + auto& mux_input = children_list.at(1); + if (str == "notif0" || str == "notif1") { + mux_input = std::make_unique(location, AST_BIT_NOT, std::move(mux_input)); + } + auto node = std::make_unique(location, AST_TERNARY, std::move(children_list.at(2))); + if (str == "bufif0") { + node->children.push_back(AstNode::mkconst_bits(location, z_const, false)); + node->children.push_back(std::move(mux_input)); + } else { + node->children.push_back(std::move(mux_input)); + node->children.push_back(AstNode::mkconst_bits(location, z_const, false)); + } + + str.clear(); + type = AST_ASSIGN; + children.push_back(std::move(children_list.at(0))); + children.back()->was_checked = true; + children.push_back(std::move(node)); + fixup_hierarchy_flags(); + did_something = true; + } + else if (str == "buf" || str == "not" || str == "tran") + { + auto& input = children_list.back(); + if (str == "not") + input = std::make_unique(location, AST_BIT_NOT, std::move(input)); + + newNode = std::make_unique(location, AST_GENBLOCK); + for (auto it = children_list.begin(); it != std::prev(children_list.end()); it++) { + newNode->children.push_back(std::make_unique(location, AST_ASSIGN, std::move(*it), input->clone())); + newNode->children.back()->was_checked = true; + } + + did_something = true; + } + else + { + AstNodeType op_type = AST_NONE; + bool invert_results = false; + + if (str == "and") + op_type = AST_BIT_AND; + if (str == "nand") + op_type = AST_BIT_AND, invert_results = true; + if (str == "or") + op_type = AST_BIT_OR; + if (str == "nor") + op_type = AST_BIT_OR, invert_results = true; + if (str == "xor") + op_type = AST_BIT_XOR; + if (str == "xnor") + op_type = AST_BIT_XOR, invert_results = true; + log_assert(op_type != AST_NONE); + + auto& node = children_list[1]; + if (op_type != AST_POS) + for (size_t i = 2; i < children_list.size(); i++) { + node = std::make_unique(location, op_type, std::move(node), std::move(children_list[i])); + node->location = location; + } + if (invert_results) + node = std::make_unique(location, AST_BIT_NOT, std::move(node)); + + str.clear(); + type = AST_ASSIGN; + children.push_back(std::move(children_list[0])); + children.back()->was_checked = true; + children.push_back(std::move(node)); + fixup_hierarchy_flags(); + did_something = true; + } + } + + // replace dynamic ranges in left-hand side expressions (e.g. "foo[bar] <= 1'b1;") with + // either a big case block that selects the correct single-bit assignment, or mask and + // shift operations. + if (type == AST_ASSIGN_EQ || type == AST_ASSIGN_LE) + { + if (children[0]->type != AST_IDENTIFIER || children[0]->children.size() == 0) + goto skip_dynamic_range_lvalue_expansion; + if (children[0]->children[0]->range_valid || did_something) + goto skip_dynamic_range_lvalue_expansion; + if (children[0]->id2ast == nullptr || children[0]->id2ast->type != AST_WIRE) + goto skip_dynamic_range_lvalue_expansion; + if (!children[0]->id2ast->range_valid) + goto skip_dynamic_range_lvalue_expansion; + + AST::AstNode *member_node = children[0]->get_struct_member(); + int wire_width = member_node ? + member_node->range_left - member_node->range_right + 1 : + children[0]->id2ast->range_left - children[0]->id2ast->range_right + 1; + int wire_offset = children[0]->id2ast->range_right; + int result_width = 1; + + std::unique_ptr shift_expr = nullptr; + auto& range = children[0]->children[0]; + + if (!try_determine_range_width(range.get(), result_width)) + input_error("Unsupported expression on dynamic range select on signal `%s'!\n", str); + + if (range->children.size() >= 2) + shift_expr = range->children[1]->clone(); + else + shift_expr = range->children[0]->clone(); + + bool use_case_method = children[0]->id2ast->get_bool_attribute(ID::nowrshmsk); + + if (!use_case_method && current_always->detect_latch(children[0]->str)) + use_case_method = true; + + if (use_case_method) { + // big case block + + int stride = 1; + long long bitno_div = stride; + + int case_width_hint; + bool case_sign_hint; + shift_expr->detectSignWidth(case_width_hint, case_sign_hint); + int max_width = case_width_hint; + + if (member_node) { // Member in packed struct/union + // Clamp chunk to range of member within struct/union. + log_assert(!wire_offset && !children[0]->id2ast->range_swapped); + + // When the (* nowrshmsk *) attribute is set, a CASE block is generated below + // to select the indexed bit slice. When a multirange array is indexed, the + // start of each possible slice is separated by the bit stride of the last + // index dimension, and we can optimize the CASE block accordingly. + // The dimension of the original array expression is saved in the 'integer' field. + int dims = children[0]->integer; + stride = wire_width; + for (int dim = 0; dim < dims; dim++) { + stride /= member_node->dimensions[dim].range_width; + } + bitno_div = stride; + } else { + // Extract (index)*(width) from non_opt_range pattern ((@selfsz@((index)*(width)))+(0)). + AstNode *lsb_expr = + shift_expr->type == AST_ADD && shift_expr->children[0]->type == AST_SELFSZ && + shift_expr->children[1]->type == AST_CONSTANT && shift_expr->children[1]->integer == 0 ? + shift_expr->children[0]->children[0].get() : + shift_expr.get(); + + // Extract stride from indexing of two-dimensional packed arrays and + // variable slices on the form dst[i*stride +: width] = src. + if (lsb_expr->type == AST_MUL && + (lsb_expr->children[0]->type == AST_CONSTANT || + lsb_expr->children[1]->type == AST_CONSTANT)) + { + int stride_ix = lsb_expr->children[1]->type == AST_CONSTANT; + stride = (int)lsb_expr->children[stride_ix]->integer; + bitno_div = stride != 0 ? stride : 1; + + // Check whether i*stride can overflow. + int i_width; + bool i_sign; + lsb_expr->children[1 - stride_ix]->detectSignWidth(i_width, i_sign); + int stride_width; + bool stride_sign; + lsb_expr->children[stride_ix]->detectSignWidth(stride_width, stride_sign); + max_width = std::max(i_width, stride_width); + // Stride width calculated from actual stride value. + if (stride == 0) + stride_width = 0; + else + stride_width = std::ceil(std::log2(std::abs(stride))); + + if (i_width + stride_width > max_width) { + // For (truncated) i*stride to be within the range of dst, the following must hold: + // i*stride ≡ bitno (mod shift_mod), i.e. + // i*stride = k*shift_mod + bitno + // + // The Diophantine equation on the form ax + by = c: + // stride*i - shift_mod*k = bitno + // has solutions iff c is a multiple of d = gcd(a, b), i.e. + // bitno mod gcd(stride, shift_mod) = 0 + // + // long long is at least 64 bits in C++11 + long long shift_mod = 1ll << (max_width - case_sign_hint); + bitno_div = std::gcd((long long)stride, shift_mod); + } + } + } + + // long long is at least 64 bits in C++11 + long long max_offset = (1ll << (max_width - case_sign_hint)) - 1; + long long min_offset = case_sign_hint ? -(1ll << (max_width - 1)) : 0; + + // A temporary register holds the result of the (possibly complex) rvalue expression, + // avoiding repetition in each AST_COND below. + int rvalue_width; + bool rvalue_sign; + children[1]->detectSignWidth(rvalue_width, rvalue_sign); + auto rvalue = mktemp_logic(location, "$bitselwrite$rvalue$", current_ast_mod, true, rvalue_width - 1, 0, rvalue_sign); + auto* rvalue_leaky = rvalue.get(); + log("make 1\n"); + auto case_node_owned = std::make_unique(location, AST_CASE, std::move(shift_expr)); + auto* case_node = case_node_owned.get(); + newNode = std::make_unique(location, AST_BLOCK, + std::make_unique(location, AST_ASSIGN_EQ, std::move(rvalue), children[1]->clone()), + std::move(case_node_owned)); + + did_something = true; + for (int i = 1 - result_width; i < wire_width; i++) { + // Out of range indexes are handled in genrtlil.cc + int start_bit = wire_offset + i; + int end_bit = start_bit + result_width - 1; + // Check whether the current index can be generated by shift_expr. + if (start_bit < min_offset || start_bit > max_offset) + continue; + if (start_bit%bitno_div != 0 || (stride == 0 && start_bit != 0)) + continue; + + auto cond = std::make_unique(location, AST_COND, mkconst_int(location, start_bit, case_sign_hint, max_width)); + auto lvalue = children[0]->clone(); + lvalue->delete_children(); + if (member_node) + lvalue->set_attribute(ID::wiretype, member_node->clone()); + lvalue->children.push_back(std::make_unique(location, AST_RANGE, + mkconst_int(location, end_bit, true), mkconst_int(location, start_bit, true))); + cond->children.push_back(std::make_unique(location, AST_BLOCK, std::make_unique(location, std::move(type), std::move(lvalue), rvalue_leaky->clone()))); + case_node->children.push_back(std::move(cond)); + } + } else { + // mask and shift operations + // dst = (dst & ~(width'1 << lsb)) | unsigned'(width'(src)) << lsb) + + auto lvalue = children[0]->clone(); + lvalue->delete_children(); + if (member_node) + lvalue->set_attribute(ID::wiretype, member_node->clone()); + + auto old_data = lvalue->clone(); + if (type == AST_ASSIGN_LE) + old_data->lookahead = true; + + int shift_width_hint; + bool shift_sign_hint; + shift_expr->detectSignWidth(shift_width_hint, shift_sign_hint); + + // All operations are carried out in a new block. + newNode = std::make_unique(location, AST_BLOCK); + + // Temporary register holding the result of the bit- or part-select position expression. + auto pos = mktemp_logic(location, "$bitselwrite$pos$", current_ast_mod, true, shift_width_hint - 1, 0, shift_sign_hint); + // Calculate lsb from position. + auto shift_val = pos->clone(); + + newNode->children.push_back(std::make_unique(location, AST_ASSIGN_EQ, std::move(pos), std::move(shift_expr))); + + // If the expression is signed, we must add an extra bit for possible negation of the most negative number. + // If the expression is unsigned, we must add an extra bit for sign. + shift_val = std::make_unique(location, AST_CAST_SIZE, mkconst_int(location, shift_width_hint + 1, true), std::move(shift_val)); + if (!shift_sign_hint) + shift_val = std::make_unique(location, AST_TO_SIGNED, std::move(shift_val)); + + // offset the shift amount by the lower bound of the dimension + if (wire_offset != 0) + shift_val = std::make_unique(location, AST_SUB, std::move(shift_val), mkconst_int(location, wire_offset, true)); + + // reflect the shift amount if the dimension is swapped + if (children[0]->id2ast->range_swapped) + shift_val = std::make_unique(location, AST_SUB, mkconst_int(location, wire_width - result_width, true), std::move(shift_val)); + + // AST_SHIFT uses negative amounts for shifting left + shift_val = std::make_unique(location, AST_NEG, std::move(shift_val)); + auto also_shift_val = shift_val->clone(); + + // dst = (dst & ~(width'1 << lsb)) | unsigned'(width'(src)) << lsb) + did_something = true; + auto bitmask = mkconst_bits(location, std::vector(result_width, State::S1), false); + newNode->children.push_back( + std::make_unique(location, std::move(type), + std::move(lvalue), + std::make_unique(location, AST_BIT_OR, + std::make_unique(location, AST_BIT_AND, + std::move(old_data), + std::make_unique(location, AST_BIT_NOT, + std::make_unique(location, AST_SHIFT, + std::move(bitmask), + std::move(shift_val)))), + std::make_unique(location, AST_SHIFT, + std::make_unique(location, AST_TO_UNSIGNED, + std::make_unique(location, AST_CAST_SIZE, + mkconst_int(location, result_width, true), + children[1]->clone())), + std::move(also_shift_val))))); + + newNode->fixup_hierarchy_flags(true); + } + + goto apply_newNode; + } +skip_dynamic_range_lvalue_expansion:; + + // found right-hand side identifier for memory -> replace with memory read port + if (stage > 1 && type == AST_IDENTIFIER && id2ast != nullptr && id2ast->type == AST_MEMORY && !in_lvalue && + children.size() == 1 && children[0]->type == AST_RANGE && children[0]->children.size() == 1) { + if (integer < (unsigned)id2ast->unpacked_dimensions) + input_error("Insufficient number of array indices for %s.\n", RTLIL::unescape_id(str)); + newNode = std::make_unique(location, AST_MEMRD, children[0]->children[0]->clone()); + newNode->str = str; + newNode->id2ast = id2ast; + goto apply_newNode; + } + + // assignment with nontrivial member in left-hand concat expression -> split assignment + if ((type == AST_ASSIGN_EQ || type == AST_ASSIGN_LE) && children[0]->type == AST_CONCAT && width_hint > 0) + { + bool found_nontrivial_member = false; + + for (auto& child : children[0]->children) { + if (child->type == AST_IDENTIFIER && child->id2ast != nullptr && child->id2ast->type == AST_MEMORY) + found_nontrivial_member = true; + } + + if (found_nontrivial_member) + { + newNode = std::make_unique(location, AST_BLOCK); + + auto wire_tmp_owned = std::make_unique(location, AST_WIRE, std::make_unique(location, AST_RANGE, mkconst_int(location, width_hint-1, true), mkconst_int(location, 0, true))); + auto wire_tmp = wire_tmp_owned.get(); + wire_tmp->str = stringf("$splitcmplxassign$%s:%d$%d", RTLIL::encode_filename(*location.begin.filename), location.begin.line, ast_autoidx()); + current_scope[wire_tmp->str] = wire_tmp; + current_ast_mod->children.push_back(std::move(wire_tmp_owned)); + wire_tmp->set_attribute(ID::nosync, AstNode::mkconst_int(location, 1, false)); + while (wire_tmp->simplify(true, 1, -1, false)) { } + wire_tmp->is_logic = true; + + auto wire_tmp_id_owned = std::make_unique(location, AST_IDENTIFIER); + auto* wire_tmp_id = wire_tmp_id_owned.get(); + wire_tmp_id->str = wire_tmp->str; + + newNode->children.push_back(std::make_unique(location, AST_ASSIGN_EQ, std::move(wire_tmp_id_owned), children[1]->clone())); + newNode->children.back()->was_checked = true; + + int cursor = 0; + for (auto& child : children[0]->children) + { + int child_width_hint = -1; + bool child_sign_hint = true; + child->detectSignWidth(child_width_hint, child_sign_hint); + + auto rhs = wire_tmp_id->clone(); + rhs->children.push_back(std::make_unique(location, AST_RANGE, AstNode::mkconst_int(location, cursor+child_width_hint-1, true), AstNode::mkconst_int(location, cursor, true))); + newNode->children.push_back(std::make_unique(location, type, child->clone(), std::move(rhs))); + + cursor += child_width_hint; + } + + goto apply_newNode; + } + } + + // Expand array assignment: arr_out = arr_in OR arr_out = cond ? arr_a : arr_b OR arr_out = '{a, b} + // Supports multi-dimensional unpacked arrays + if ((type == AST_ASSIGN_EQ || type == AST_ASSIGN_LE || type == AST_ASSIGN) && + is_unexpanded_array_ref(children[0].get())) + { + AstNode *lhs = children[0].get(); + AstNode *rhs = children[1].get(); + AstNode *lhs_mem = lhs->id2ast; + + // Case 1: Direct array assignment (b = a) + bool is_direct_assign = is_unexpanded_array_ref(rhs); + + // Case 2: Ternary array assignment (out = sel ? a : b) + bool is_ternary_assign = (rhs->type == AST_TERNARY && + is_unexpanded_array_ref(rhs->children[1].get()) && + is_unexpanded_array_ref(rhs->children[2].get())); + + // Case 3: Positional assignment pattern (out = '{a, b}) + bool is_pattern_assign = rhs->type == AST_ASSIGN_PATTERN; + + if (is_direct_assign || is_ternary_assign || is_pattern_assign) + { + AstNode *direct_rhs_mem = nullptr; + AstNode *true_mem = nullptr; + AstNode *false_mem = nullptr; + + int num_dims = lhs_mem->unpacked_dimensions; + int total_elements = 1; + for (int d = 0; d < num_dims; d++) + total_elements *= lhs_mem->dimensions[d].range_width; + int element_width, mem_size, addr_bits; + lhs_mem->meminfo(element_width, mem_size, addr_bits); + bool pattern_is_flat = false; + + // Helper to add indices to an array identifier clone. + auto add_indices_to_id = [&](std::unique_ptr id, const std::vector& indices) { + int indexed_dims = GetSize(indices); + if (indexed_dims == 1) { + // Single dimension: use AST_RANGE + id->children.push_back(std::make_unique(location, AST_RANGE, + mkconst_int(location, indices[0], true))); + } else { + // Multiple dimensions: use AST_MULTIRANGE + auto multirange = std::make_unique(location, AST_MULTIRANGE); + for (int idx : indices) { + multirange->children.push_back(std::make_unique(location, AST_RANGE, + mkconst_int(location, idx, true))); + } + id->children.push_back(std::move(multirange)); + } + id->integer = indexed_dims; + // Reset basic_prep so multirange gets resolved during subsequent simplify passes + id->basic_prep = false; + return id; + }; + + auto add_position_to_id = [&](std::unique_ptr id, AstNode *mem, const std::vector& position) { + return add_indices_to_id(std::move(id), array_indices_from_position(mem, position)); + }; + + // Validate nested assignment pattern shape against unpacked dimensions. + std::function validate_pattern_shape = [&](AstNode *pattern, int dim) { + log_assert(pattern->type == AST_ASSIGN_PATTERN); + + int expected = lhs_mem->dimensions[dim].range_width; + if (GetSize(pattern->children) != expected) + input_error("Assignment pattern element count mismatch at dimension %d: got %d, expected %d\n", + dim + 1, GetSize(pattern->children), expected); + + if (dim + 1 == num_dims) + return; + + for (auto& child : pattern->children) { + if (child->type == AST_ASSIGN_PATTERN) { + validate_pattern_shape(child.get(), dim + 1); + } else if (is_unexpanded_array_ref(child.get()) && + arrays_have_compatible_dims_from(lhs_mem, dim + 1, child->id2ast)) { + continue; + } else { + input_error("Nested assignment pattern or compatible array expression required for dimension %d\n", dim + 2); + } + } + }; + + // Select the assignment pattern element for an unpacked array position. + auto pattern_element_at_position = [&](const std::vector& position, int flat_index) { + if (pattern_is_flat) + return rhs->children[flat_index]->clone(); + + AstNode *pattern = rhs; + for (int d = 0; d < num_dims; d++) { + log_assert(pattern->type == AST_ASSIGN_PATTERN); + AstNode *element = pattern->children[position[d]].get(); + + if (d + 1 == num_dims) + return element->clone(); + + if (element->type == AST_ASSIGN_PATTERN) { + pattern = element; + } else { + std::vector subposition(position.begin() + d + 1, position.end()); + return add_position_to_id(element->clone(), element->id2ast, subposition); + } + } + log_abort(); + }; + + // Validate array compatibility + if (is_direct_assign) { + direct_rhs_mem = rhs->id2ast; + if (!arrays_have_compatible_dims(lhs_mem, direct_rhs_mem)) + input_error("Array dimension mismatch in assignment\n"); + } else if (is_ternary_assign) { + true_mem = rhs->children[1]->id2ast; + false_mem = rhs->children[2]->id2ast; + if (!arrays_have_compatible_dims(lhs_mem, true_mem) || + !arrays_have_compatible_dims(lhs_mem, false_mem)) + input_error("Array dimension mismatch in ternary expression\n"); + } else { + if (num_dims > 1 && GetSize(rhs->children) == lhs_mem->dimensions[0].range_width) { + validate_pattern_shape(rhs, 0); + } else if (num_dims == 1 && GetSize(rhs->children) == total_elements) { + pattern_is_flat = true; + } else { + if (num_dims > 1 && GetSize(rhs->children) == lhs_mem->dimensions[0].range_width) + validate_pattern_shape(rhs, 0); + int expected = num_dims > 1 ? lhs_mem->dimensions[0].range_width : total_elements; + input_error("Assignment pattern element count mismatch: got %d, expected %d\n", GetSize(rhs->children), expected); + } + } + + // Build a single AST_MEMINIT if all elements have folded to constants before this point + bool use_meminit = is_pattern_assign && this->is_in_unconditional_init() && rhs->is_simple_const_expr(); + vector meminit_bits(total_elements * element_width); + + if (use_meminit) { + int iter_idx = 0; + + foreach_array_position(lhs_mem, [&](const std::vector& position) { + if (!use_meminit) + return; + + auto elem = pattern_element_at_position(position, iter_idx++); + + if (!elem->isConst()) { + use_meminit = false; + return; + } + + vector bits = elem->valueAsConst(element_width).to_bits(); + int linear_idx = element_width * flattened_array_index_from_position(lhs_mem, position); + + for (int b = 0; b < element_width; b++) + meminit_bits[linear_idx + b] = bits[b]; + }); + } + + if (use_meminit) { + int start = lhs_mem->unpacked_dimensions == 1 + ? lhs_mem->dimensions[0].range_right + : 0; + + vector en_bits(element_width, State::S1); + auto meminit_owned = std::make_unique( + location, + AST_MEMINIT, + AstNode::mkconst_int(location, start, false), + AstNode::mkconst_bits(location, meminit_bits, false), + AstNode::mkconst_bits(location, en_bits, false), + AstNode::mkconst_int(location, total_elements, false) + ); + + auto meminit = meminit_owned.get(); + meminit->str = lhs_mem->str; + meminit->id2ast = lhs_mem; + + current_ast_mod->children.push_back(std::move(meminit_owned)); + newNode = std::make_unique(location, AST_BLOCK); + } else { + // Warn if array assignment expansion is large. + if (total_elements > 10000) + log_warning("Expanding array assignment with %d elements at %s, this may be slow.\n", + total_elements, location.to_string()); + + // Collect all assignments + std::vector> assignments; + std::vector> pattern_temp_assignments; + + foreach_array_position(lhs_mem, [&](const std::vector& position) { + auto lhs_idx = add_position_to_id(lhs->clone(), lhs_mem, position); + + std::unique_ptr rhs_expr; + if (is_direct_assign) { + rhs_expr = add_position_to_id(rhs->clone(), direct_rhs_mem, position); + } else if (is_ternary_assign) { + // Ternary case + AstNode *cond = rhs->children[0].get(); + AstNode *true_val = rhs->children[1].get(); + AstNode *false_val = rhs->children[2].get(); + + auto true_idx = add_position_to_id(true_val->clone(), true_mem, position); + auto false_idx = add_position_to_id(false_val->clone(), false_mem, position); + + rhs_expr = std::make_unique(location, AST_TERNARY, + cond->clone(), std::move(true_idx), std::move(false_idx)); + } else { + auto pattern_rhs = pattern_element_at_position(position, GetSize(assignments)); + + if (type == AST_ASSIGN_EQ) { + auto wire_tmp_owned = std::make_unique(location, AST_WIRE, + std::make_unique(location, AST_RANGE, + mkconst_int(location, element_width - 1, true), + mkconst_int(location, 0, true))); + auto wire_tmp = wire_tmp_owned.get(); + wire_tmp->str = stringf("$assignpattern$%s:%d$%d", + RTLIL::encode_filename(*location.begin.filename), location.begin.line, ast_autoidx()); + current_scope[wire_tmp->str] = wire_tmp; + current_ast_mod->children.push_back(std::move(wire_tmp_owned)); + wire_tmp->set_attribute(ID::nosync, AstNode::mkconst_int(location, 1, false)); + while (wire_tmp->simplify(true, 1, -1, false)) { } + wire_tmp->is_logic = true; + wire_tmp->is_signed = lhs_mem->is_signed; + + auto tmp_id = std::make_unique(location, AST_IDENTIFIER); + tmp_id->str = wire_tmp->str; + pattern_temp_assignments.push_back(std::make_unique(location, AST_ASSIGN_EQ, + tmp_id->clone(), std::move(pattern_rhs))); + rhs_expr = std::move(tmp_id); + } else { + rhs_expr = std::move(pattern_rhs); + } + } + + auto assign = std::make_unique(location, type, + std::move(lhs_idx), std::move(rhs_expr)); + assign->was_checked = true; + assignments.push_back(std::move(assign)); + }); + + // For continuous assignments, add to module; for procedural, use block + if (type == AST_ASSIGN) { + // Add all but last to module + for (size_t i = 0; i + 1 < assignments.size(); i++) + current_ast_mod->children.push_back(std::move(assignments[i])); + // Last one replaces current node + newNode = std::move(assignments.back()); + } else { + // Wrap in AST_BLOCK for procedural + newNode = std::make_unique(location, AST_BLOCK); + for (auto& assign : pattern_temp_assignments) + newNode->children.push_back(std::move(assign)); + for (auto& assign : assignments) + newNode->children.push_back(std::move(assign)); + } + } + + goto apply_newNode; + } + } + + // assignment with memory in left-hand side expression -> replace with memory write port + if (stage > 1 && (type == AST_ASSIGN_EQ || type == AST_ASSIGN_LE) && children[0]->type == AST_IDENTIFIER && + children[0]->id2ast && children[0]->id2ast->type == AST_MEMORY && children[0]->id2ast->children.size() >= 2 && + children[0]->id2ast->children[0]->range_valid && children[0]->id2ast->children[1]->range_valid && + (children[0]->children.size() == 1 || children[0]->children.size() == 2) && children[0]->children[0]->type == AST_RANGE) + { + if (children[0]->integer < (unsigned)children[0]->id2ast->unpacked_dimensions) + input_error("Insufficient number of array indices for %s.\n", RTLIL::unescape_id(str)); + + std::stringstream sstr; + sstr << "$memwr$" << children[0]->str << "$" << RTLIL::encode_filename(*location.begin.filename) << ":" << location.begin.line << "$" << ast_autoidx(); + std::string id_addr = sstr.str() + "_ADDR", id_data = sstr.str() + "_DATA", id_en = sstr.str() + "_EN"; + + int mem_width, mem_size, addr_bits; + bool mem_signed = children[0]->id2ast->is_signed; + children[0]->id2ast->meminfo(mem_width, mem_size, addr_bits); + + newNode = std::make_unique(location, AST_BLOCK); + auto defNode = std::make_unique(location, AST_BLOCK); + + int data_range_left = children[0]->id2ast->children[0]->range_left; + int data_range_right = children[0]->id2ast->children[0]->range_right; + int mem_data_range_offset = std::min(data_range_left, data_range_right); + + int addr_width_hint = -1; + bool addr_sign_hint = true; + children[0]->children[0]->children[0]->detectSignWidthWorker(addr_width_hint, addr_sign_hint); + addr_bits = std::max(addr_bits, addr_width_hint); + + std::vector x_bits_addr, x_bits_data, set_bits_en; + for (int i = 0; i < addr_bits; i++) + x_bits_addr.push_back(RTLIL::State::Sx); + for (int i = 0; i < mem_width; i++) + x_bits_data.push_back(RTLIL::State::Sx); + for (int i = 0; i < mem_width; i++) + set_bits_en.push_back(RTLIL::State::S1); + + std::unique_ptr node_addr = nullptr; + if (children[0]->children[0]->children[0]->isConst()) { + node_addr = children[0]->children[0]->children[0]->clone(); + } else { + auto wire_addr_owned = std::make_unique(location, AST_WIRE, std::make_unique(location, AST_RANGE, mkconst_int(location, addr_bits-1, true), mkconst_int(location, 0, true))); + auto* wire_addr = wire_addr_owned.get(); + wire_addr->str = id_addr; + wire_addr->was_checked = true; + current_ast_mod->children.push_back(std::move(wire_addr_owned)); + current_scope[wire_addr->str] = wire_addr; + while (wire_addr->simplify(true, 1, -1, false)) { } + + auto assign_addr = std::make_unique(location, AST_ASSIGN_EQ, std::make_unique(location, AST_IDENTIFIER), mkconst_bits(location, x_bits_addr, false)); + assign_addr->children[0]->str = id_addr; + assign_addr->children[0]->was_checked = true; + defNode->children.push_back(std::move(assign_addr)); + + assign_addr = std::make_unique(location, AST_ASSIGN_EQ, std::make_unique(location, AST_IDENTIFIER), children[0]->children[0]->children[0]->clone()); + assign_addr->children[0]->str = id_addr; + assign_addr->children[0]->was_checked = true; + newNode->children.push_back(std::move(assign_addr)); + + node_addr = std::make_unique(location, AST_IDENTIFIER); + node_addr->str = id_addr; + } + + std::unique_ptr node_data = nullptr; + if (children[0]->children.size() == 1 && children[1]->isConst()) { + node_data = children[1]->clone(); + } else { + auto wire_data_owned = std::make_unique(location, AST_WIRE, std::make_unique(location, AST_RANGE, mkconst_int(location, mem_width-1, true), mkconst_int(location, 0, true))); + auto* wire_data = wire_data_owned.get(); + wire_data->str = id_data; + wire_data->was_checked = true; + wire_data->is_signed = mem_signed; + current_scope[wire_data->str] = wire_data; + current_ast_mod->children.push_back(std::move(wire_data_owned)); + while (wire_data->simplify(true, 1, -1, false)) { } + + auto assign_data = std::make_unique(location, AST_ASSIGN_EQ, std::make_unique(location, AST_IDENTIFIER), mkconst_bits(location, x_bits_data, false)); + assign_data->children[0]->str = id_data; + assign_data->children[0]->was_checked = true; + defNode->children.push_back(std::move(assign_data)); + + node_data = std::make_unique(location, AST_IDENTIFIER); + node_data->str = id_data; + } + + auto wire_en_owned = std::make_unique(location, AST_WIRE, std::make_unique(location, AST_RANGE, mkconst_int(location, mem_width-1, true), mkconst_int(location, 0, true))); + auto* wire_en = wire_en_owned.get(); + wire_en->str = id_en; + wire_en->was_checked = true; + current_scope[wire_en->str] = wire_en; + current_ast_mod->children.push_back(std::move(wire_en_owned)); + while (wire_en->simplify(true, 1, -1, false)) { } + + auto assign_en_first = std::make_unique(location, AST_ASSIGN_EQ, std::make_unique(location, AST_IDENTIFIER), mkconst_int(location, 0, false, mem_width)); + assign_en_first->children[0]->str = id_en; + assign_en_first->children[0]->was_checked = true; + defNode->children.push_back(std::move(assign_en_first)); + + auto node_en = std::make_unique(location, AST_IDENTIFIER); + node_en->str = id_en; + + if (!defNode->children.empty()) + current_top_block->children.insert(current_top_block->children.begin(), std::move(defNode)); + + std::unique_ptr assign_data = nullptr; + std::unique_ptr assign_en = nullptr; + if (children[0]->children.size() == 2) + { + if (children[0]->children[1]->range_valid) + { + int offset = children[0]->children[1]->range_right; + int width = children[0]->children[1]->range_left - offset + 1; + offset -= mem_data_range_offset; + + std::vector padding_x(offset, RTLIL::State::Sx); + + assign_data = std::make_unique(location, AST_ASSIGN_EQ, std::make_unique(location, AST_IDENTIFIER), + std::make_unique(location, AST_CONCAT, mkconst_bits(location, padding_x, false), children[1]->clone())); + assign_data->children[0]->str = id_data; + assign_data->children[0]->was_checked = true; + + for (int i = 0; i < mem_width; i++) + set_bits_en[i] = offset <= i && i < offset+width ? RTLIL::State::S1 : RTLIL::State::S0; + assign_en = std::make_unique(location, AST_ASSIGN_EQ, std::make_unique(location, AST_IDENTIFIER), mkconst_bits(location, set_bits_en, false)); + assign_en->children[0]->str = id_en; + assign_en->children[0]->was_checked = true; + } + else + { + auto& the_range = children[0]->children[1]; + std::unique_ptr offset_ast; + int width; + + if (!try_determine_range_width(the_range.get(), width)) + input_error("Unsupported expression on dynamic range select on signal `%s'!\n", str); + + if (the_range->children.size() >= 2) + offset_ast = the_range->children[1]->clone(); + else + offset_ast = the_range->children[0]->clone(); + + if (mem_data_range_offset) + offset_ast = std::make_unique(location, AST_SUB, std::move(offset_ast), mkconst_int(location, mem_data_range_offset, true)); + + assign_data = std::make_unique(location, AST_ASSIGN_EQ, std::make_unique(location, AST_IDENTIFIER), + std::make_unique(location, AST_SHIFT_LEFT, children[1]->clone(), offset_ast->clone())); + assign_data->children[0]->str = id_data; + assign_data->children[0]->was_checked = true; + + for (int i = 0; i < mem_width; i++) + set_bits_en[i] = i < width ? RTLIL::State::S1 : RTLIL::State::S0; + assign_en = std::make_unique(location, AST_ASSIGN_EQ, std::make_unique(location, AST_IDENTIFIER), + std::make_unique(location, AST_SHIFT_LEFT, mkconst_bits(location, set_bits_en, false), offset_ast->clone())); + assign_en->children[0]->str = id_en; + assign_en->children[0]->was_checked = true; + } + } + else + { + if (!(children[0]->children.size() == 1 && children[1]->isConst())) { + assign_data = std::make_unique(location, AST_ASSIGN_EQ, std::make_unique(location, AST_IDENTIFIER), children[1]->clone()); + assign_data->children[0]->str = id_data; + assign_data->children[0]->was_checked = true; + } + + assign_en = std::make_unique(location, AST_ASSIGN_EQ, std::make_unique(location, AST_IDENTIFIER), mkconst_bits(location, set_bits_en, false)); + assign_en->children[0]->str = id_en; + assign_en->children[0]->was_checked = true; + } + if (assign_data) + newNode->children.push_back(std::move(assign_data)); + if (assign_en) + newNode->children.push_back(std::move(assign_en)); + + std::unique_ptr wrnode; + if (current_always->type == AST_INITIAL) + wrnode = std::make_unique(location, AST_MEMINIT, std::move(node_addr), std::move(node_data), std::move(node_en), mkconst_int(location, 1, false)); + else + wrnode = std::make_unique(location, AST_MEMWR, std::move(node_addr), std::move(node_data), std::move(node_en)); + wrnode->str = children[0]->str; + wrnode->id2ast = children[0]->id2ast; + wrnode->location = location; + if (wrnode->type == AST_MEMWR) { + int portid = current_memwr_count[wrnode->str]++; + wrnode->children.push_back(mkconst_int(location, portid, false)); + std::vector priority_mask; + for (int i = 0; i < portid; i++) { + bool has_prio = current_memwr_visible[wrnode->str].count(i); + priority_mask.push_back(State(has_prio)); + } + wrnode->children.push_back(mkconst_bits(location, priority_mask, false)); + current_memwr_visible[wrnode->str].insert(portid); + current_always->children.push_back(std::move(wrnode)); + } else { + current_ast_mod->children.push_back(std::move(wrnode)); + } + + if (newNode->children.empty()) { + newNode = std::make_unique(location); + } + goto apply_newNode; + } + + // replace function and task calls with the code from the function or task + if ((type == AST_FCALL || type == AST_TCALL) && !str.empty()) + { + if (type == AST_FCALL) + { + if (str == "\\$initstate") + { + int myidx = ast_autoidx(); + + auto wire_owned = std::make_unique(location, AST_WIRE); + auto* wire = wire_owned.get(); + current_ast_mod->children.push_back(std::move(wire_owned)); + wire->str = stringf("$initstate$%d_wire", myidx); + while (wire->simplify(true, 1, -1, false)) { } + + auto cell_owned = std::make_unique(location, AST_CELL, std::make_unique(location, AST_CELLTYPE), std::make_unique(location, AST_ARGUMENT, std::make_unique(location, AST_IDENTIFIER))); + auto* cell = cell_owned.get(); + cell->str = stringf("$initstate$%d", myidx); + cell->children[0]->str = "$initstate"; + cell->children[1]->str = "\\Y"; + cell->children[1]->children[0]->str = wire->str; + cell->children[1]->children[0]->id2ast = wire; + current_ast_mod->children.push_back(std::move(cell_owned)); + while (cell->simplify(true, 1, -1, false)) { } + + newNode = std::make_unique(location, AST_IDENTIFIER); + newNode->str = wire->str; + newNode->id2ast = wire; + goto apply_newNode; + } + + if (str == "\\$past") + { + if (width_hint < 0) + goto replace_fcall_later; + + int num_steps = 1; + + if (GetSize(children) != 1 && GetSize(children) != 2) + input_error("System function %s got %d arguments, expected 1 or 2.\n", + RTLIL::unescape_id(str), int(children.size())); + + if (!current_always_clocked) + input_error("System function %s is only allowed in clocked blocks.\n", + RTLIL::unescape_id(str)); + + if (GetSize(children) == 2) + { + auto buf = children[1]->clone(); + while (buf->simplify(true, stage, -1, false)) { } + if (buf->type != AST_CONSTANT) + input_error("Failed to evaluate system function `%s' with non-constant value.\n", str); + + num_steps = buf->asInt(true); + } + + AstNode *block = nullptr; + + for (auto& child : current_always->children) + if (child->type == AST_BLOCK) + block = child.get(); + + log_assert(block != nullptr); + + if (num_steps == 0) { + newNode = children[0]->clone(); + goto apply_newNode; + } + + int myidx = ast_autoidx(); + AstNode* outreg = nullptr; + + for (int i = 0; i < num_steps; i++) + { + auto reg_owned = std::make_unique(location, AST_WIRE, std::make_unique(location, AST_RANGE, + mkconst_int(location, width_hint-1, true), mkconst_int(location, 0, true))); + auto* reg = reg_owned.get(); + current_ast_mod->children.push_back(std::move(reg_owned)); + + reg->str = stringf("$past$%s:%d$%d$%d", RTLIL::encode_filename(*location.begin.filename), location.begin.line, myidx, i); + reg->is_reg = true; + reg->is_signed = sign_hint; + + + while (reg->simplify(true, 1, -1, false)) { } + + auto regid = std::make_unique(location, AST_IDENTIFIER); + regid->str = reg->str; + regid->id2ast = reg; + regid->was_checked = true; + + std::unique_ptr rhs = nullptr; + + if (outreg == nullptr) { + rhs = children.at(0)->clone(); + } else { + rhs = std::make_unique(location, AST_IDENTIFIER); + rhs->str = outreg->str; + rhs->id2ast = outreg; + } + + block->children.push_back(std::make_unique(location, AST_ASSIGN_LE, std::move(regid), std::move(rhs))); + outreg = reg; + } + + newNode = std::make_unique(location, AST_IDENTIFIER); + newNode->str = outreg->str; + newNode->id2ast = outreg; + goto apply_newNode; + } + + if (str == "\\$stable" || str == "\\$rose" || str == "\\$fell" || str == "\\$changed") + { + if (GetSize(children) != 1) + input_error("System function %s got %d arguments, expected 1.\n", + RTLIL::unescape_id(str), int(children.size())); + + if (!current_always_clocked) + input_error("System function %s is only allowed in clocked blocks.\n", + RTLIL::unescape_id(str)); + + auto present = children.at(0)->clone(); + auto past = clone(); + past->str = "\\$past"; + + if (str == "\\$stable") + newNode = std::make_unique(location, AST_EQ, std::move(past), std::move(present)); + + else if (str == "\\$changed") + newNode = std::make_unique(location, AST_NE, std::move(past), std::move(present)); + + else if (str == "\\$rose") + newNode = std::make_unique(location, AST_LOGIC_AND, + std::make_unique(location, AST_LOGIC_NOT, std::make_unique(location, AST_BIT_AND, std::move(past), mkconst_int(location, 1, false))), + std::make_unique(location, AST_BIT_AND, std::move(present), mkconst_int(location, 1, false))); + + else if (str == "\\$fell") + newNode = std::make_unique(location, AST_LOGIC_AND, + std::make_unique(location, AST_BIT_AND, std::move(past), mkconst_int(location, 1, false)), + std::make_unique(location, AST_LOGIC_NOT, std::make_unique(location, AST_BIT_AND, std::move(present), mkconst_int(location, 1, false)))); + + else + log_abort(); + + goto apply_newNode; + } + + // $anyconst and $anyseq are mapped in AstNode::genRTLIL() + if (str == "\\$anyconst" || str == "\\$anyseq" || str == "\\$allconst" || str == "\\$allseq") { + recursion_counter--; + return false; + } + + if (str == "\\$clog2") + { + if (children.size() != 1) + input_error("System function %s got %d arguments, expected 1.\n", + RTLIL::unescape_id(str), int(children.size())); + + auto buf = children[0]->clone(); + while (buf->simplify(true, stage, width_hint, sign_hint)) { } + if (buf->type != AST_CONSTANT) + input_error("Failed to evaluate system function `%s' with non-constant value.\n", str); + + RTLIL::Const arg_value = buf->bitsAsConst(); + if (arg_value.as_bool()) + arg_value = const_sub(arg_value, 1, false, false, GetSize(arg_value)); + + uint32_t result = 0; + for (auto i = 0; i < arg_value.size(); i++) + if (arg_value.at(i) == RTLIL::State::S1) + result = i + 1; + + newNode = mkconst_int(location, result, true); + goto apply_newNode; + } + + if (str == "\\$dimensions" || str == "\\$unpacked_dimensions" || + str == "\\$increment" || str == "\\$size" || str == "\\$bits" || str == "\\$high" || str == "\\$low" || str == "\\$left" || str == "\\$right") + { + int dim = 1; + if (str == "\\$dimensions" || str == "\\$unpacked_dimensions" || str == "\\$bits") { + if (children.size() != 1) + input_error("System function %s got %d arguments, expected 1.\n", + RTLIL::unescape_id(str), int(children.size())); + } else { + if (children.size() != 1 && children.size() != 2) + input_error("System function %s got %d arguments, expected 1 or 2.\n", + RTLIL::unescape_id(str), int(children.size())); + if (children.size() == 2) { + auto buf = children[1]->clone(); + // Evaluate constant expression + while (buf->simplify(true, stage, width_hint, sign_hint)) { } + dim = buf->asInt(false); + } + } + auto buf = children[0]->clone(); + int mem_depth = 1; + int result, high = 0, low = 0, left = 0, right = 0, width = 1; // defaults for a simple wire + int expr_dimensions = 0, expr_unpacked_dimensions = 0; + AstNode *id_ast = nullptr; + + buf->detectSignWidth(width_hint, sign_hint); + + if (buf->type == AST_IDENTIFIER) { + id_ast = buf->id2ast; + if (id_ast == nullptr && current_scope.count(buf->str)) + id_ast = current_scope.at(buf->str); + if (!id_ast) + input_error("Failed to resolve identifier %s for width detection!\n", buf->str); + + if (id_ast->type == AST_WIRE || id_ast->type == AST_MEMORY) { + // Check for item in packed struct / union + AstNode *item_node = buf->get_struct_member(); + if (item_node) + id_ast = item_node; + + // The dimension of the original array expression is saved in the 'integer' field + dim += buf->integer; + + int dims = GetSize(id_ast->dimensions); + // TODO: IEEE Std 1800-2017 20.7: "If the first argument to an array query function would cause $dimensions to return 0 + // or if the second argument is out of range, then 'x shall be returned." + if (dim < 1 || dim > dims) + input_error("Dimension %d out of range in `%s', as it only has %d dimensions!\n", dim, id_ast->str, dims); + + expr_dimensions = dims - dim + 1; + expr_unpacked_dimensions = std::max(id_ast->unpacked_dimensions - dim + 1, 0); + + right = low = id_ast->dimensions[dim - 1].range_right; + left = high = low + id_ast->dimensions[dim - 1].range_width - 1; + if (id_ast->dimensions[dim - 1].range_swapped) { + std::swap(left, right); + } + for (int i = dim; i < dims; i++) { + mem_depth *= id_ast->dimensions[i].range_width; + } + } + width = high - low + 1; + } else { + width = width_hint; + right = low = 0; + left = high = width - 1; + expr_dimensions = 1; + } + if (str == "\\$dimensions") + result = expr_dimensions; + else if (str == "\\$unpacked_dimensions") + result = expr_unpacked_dimensions; + else if (str == "\\$high") + result = high; + else if (str == "\\$low") + result = low; + else if (str == "\\$left") + result = left; + else if (str == "\\$right") + result = right; + else if (str == "\\$increment") + result = left >= right ? 1 : -1; + else if (str == "\\$size") + result = width; + else { // str == "\\$bits" + result = width * mem_depth; + } + newNode = mkconst_int(location, result, true); + goto apply_newNode; + } + + if (str == "\\$ln" || str == "\\$log10" || str == "\\$exp" || str == "\\$sqrt" || str == "\\$pow" || + str == "\\$floor" || str == "\\$ceil" || str == "\\$sin" || str == "\\$cos" || str == "\\$tan" || + str == "\\$asin" || str == "\\$acos" || str == "\\$atan" || str == "\\$atan2" || str == "\\$hypot" || + str == "\\$sinh" || str == "\\$cosh" || str == "\\$tanh" || str == "\\$asinh" || str == "\\$acosh" || str == "\\$atanh" || + str == "\\$rtoi" || str == "\\$itor") + { + bool func_with_two_arguments = str == "\\$pow" || str == "\\$atan2" || str == "\\$hypot"; + double x = 0, y = 0; + + if (func_with_two_arguments) { + if (children.size() != 2) + input_error("System function %s got %d arguments, expected 2.\n", + RTLIL::unescape_id(str), int(children.size())); + } else { + if (children.size() != 1) + input_error("System function %s got %d arguments, expected 1.\n", + RTLIL::unescape_id(str), int(children.size())); + } + + if (children.size() >= 1) { + while (children[0]->simplify(true, stage, width_hint, sign_hint)) { } + if (!children[0]->isConst()) + input_error("Failed to evaluate system function `%s' with non-constant argument.\n", + RTLIL::unescape_id(str)); + int child_width_hint = width_hint; + bool child_sign_hint = sign_hint; + children[0]->detectSignWidth(child_width_hint, child_sign_hint); + x = children[0]->asReal(child_sign_hint); + } + + if (children.size() >= 2) { + while (children[1]->simplify(true, stage, width_hint, sign_hint)) { } + if (!children[1]->isConst()) + input_error("Failed to evaluate system function `%s' with non-constant argument.\n", + RTLIL::unescape_id(str)); + int child_width_hint = width_hint; + bool child_sign_hint = sign_hint; + children[1]->detectSignWidth(child_width_hint, child_sign_hint); + y = children[1]->asReal(child_sign_hint); + } + + if (str == "\\$rtoi") { + if (!(x > -2147483649.0 && x < 2147483648.0)) + log_file_warning(location.to_loc(), "$rtoi argument %e does not fit in a 32-bit integer.\n", x); + // Like most commercial tools, wrap a finite value and map infinity and NaN to 0. + newNode = AstNode::mkconst_int(location, std::isfinite(x) ? (int64_t)fmod(x, 4294967296.0) : 0, true); + } else { + newNode = std::make_unique(location, AST_REALVALUE); + if (str == "\\$ln") newNode->realvalue = ::log(x); + else if (str == "\\$log10") newNode->realvalue = ::log10(x); + else if (str == "\\$exp") newNode->realvalue = ::exp(x); + else if (str == "\\$sqrt") newNode->realvalue = ::sqrt(x); + else if (str == "\\$pow") newNode->realvalue = ::pow(x, y); + else if (str == "\\$floor") newNode->realvalue = ::floor(x); + else if (str == "\\$ceil") newNode->realvalue = ::ceil(x); + else if (str == "\\$sin") newNode->realvalue = ::sin(x); + else if (str == "\\$cos") newNode->realvalue = ::cos(x); + else if (str == "\\$tan") newNode->realvalue = ::tan(x); + else if (str == "\\$asin") newNode->realvalue = ::asin(x); + else if (str == "\\$acos") newNode->realvalue = ::acos(x); + else if (str == "\\$atan") newNode->realvalue = ::atan(x); + else if (str == "\\$atan2") newNode->realvalue = ::atan2(x, y); + else if (str == "\\$hypot") newNode->realvalue = ::hypot(x, y); + else if (str == "\\$sinh") newNode->realvalue = ::sinh(x); + else if (str == "\\$cosh") newNode->realvalue = ::cosh(x); + else if (str == "\\$tanh") newNode->realvalue = ::tanh(x); + else if (str == "\\$asinh") newNode->realvalue = ::asinh(x); + else if (str == "\\$acosh") newNode->realvalue = ::acosh(x); + else if (str == "\\$atanh") newNode->realvalue = ::atanh(x); + else if (str == "\\$itor") newNode->realvalue = x; + else log_abort(); + } + goto apply_newNode; + } + + if (str == "\\$sformatf") { + Fmt fmt = processFormat(stage, /*sformat_like=*/true); + newNode = AstNode::mkconst_str(location, fmt.render()); + goto apply_newNode; + } + + if (str == "\\$countbits") { + if (children.size() < 2) + input_error("System function %s got %d arguments, expected at least 2.\n", + RTLIL::unescape_id(str), int(children.size())); + + std::vector control_bits; + + // Determine which bits to count + for (size_t i = 1; i < children.size(); i++) { + auto& node = children[i]; + while (node->simplify(true, stage, -1, false)) { } + if (node->type != AST_CONSTANT) + input_error("Failed to evaluate system function `%s' with non-constant control bit argument.\n", str); + if (node->bits.size() != 1) + input_error("Failed to evaluate system function `%s' with control bit width != 1.\n", str); + control_bits.push_back(node->bits[0]); + } + + // Detect width of exp (first argument of $countbits) + int exp_width = -1; + bool exp_sign = false; + auto& exp = children[0]; + exp->detectSignWidth(exp_width, exp_sign, nullptr); + + newNode = mkconst_int(location, 0, false); + + for (int i = 0; i < exp_width; i++) { + // Generate nodes for: exp << i >> ($size(exp) - 1) + // ^^ ^^ + auto lsh_node = std::make_unique(location, AST_SHIFT_LEFT, exp->clone(), mkconst_int(location, i, false)); + auto rsh_node = std::make_unique(location, AST_SHIFT_RIGHT, std::move(lsh_node), mkconst_int(location, exp_width - 1, false)); + + std::unique_ptr or_node = nullptr; + + for (RTLIL::State control_bit : control_bits) { + // Generate node for: (exp << i >> ($size(exp) - 1)) === control_bit + // ^^^ + auto eq_node = std::make_unique(location, AST_EQX, rsh_node->clone(), mkconst_bits(location, {control_bit}, false)); + + // Or the result for each checked bit value + if (or_node) + or_node = std::make_unique(location, AST_LOGIC_OR, std::move(or_node), std::move(eq_node)); + else + or_node = std::move(eq_node); + } + + // We should have at least one element in control_bits, + // because we checked for the number of arguments above + log_assert(or_node != nullptr); + + // Generate node for adding with result of previous bit + newNode = std::make_unique(location, AST_ADD, std::move(newNode), std::move(or_node)); + } + + goto apply_newNode; + } + + if (str == "\\$countones" || str == "\\$isunknown" || str == "\\$onehot" || str == "\\$onehot0") { + if (children.size() != 1) + input_error("System function %s got %d arguments, expected 1.\n", + RTLIL::unescape_id(str), int(children.size())); + + auto countbits = clone(); + countbits->str = "\\$countbits"; + + if (str == "\\$countones") { + countbits->children.push_back(mkconst_bits(location, {RTLIL::State::S1}, false)); + newNode = std::move(countbits); + } else if (str == "\\$isunknown") { + countbits->children.push_back(mkconst_bits(location, {RTLIL::Sx}, false)); + countbits->children.push_back(mkconst_bits(location, {RTLIL::Sz}, false)); + newNode = std::make_unique(location, AST_GT, std::move(countbits), mkconst_int(location, 0, false)); + } else if (str == "\\$onehot") { + countbits->children.push_back(mkconst_bits(location, {RTLIL::State::S1}, false)); + newNode = std::make_unique(location, AST_EQ, std::move(countbits), mkconst_int(location, 1, false)); + } else if (str == "\\$onehot0") { + countbits->children.push_back(mkconst_bits(location, {RTLIL::State::S1}, false)); + newNode = std::make_unique(location, AST_LE, std::move(countbits), mkconst_int(location, 1, false)); + } else { + log_abort(); + } + + goto apply_newNode; + } + + if (current_scope.count(str) != 0 && current_scope[str]->type == AST_DPI_FUNCTION) + { + AstNode *dpi_decl = current_scope[str]; + + std::string rtype, fname; + std::vector argtypes; + std::vector> args; + + rtype = RTLIL::unescape_id(dpi_decl->children.at(0)->str); + fname = RTLIL::unescape_id(dpi_decl->children.at(1)->str); + + for (int i = 2; i < GetSize(dpi_decl->children); i++) + { + if (i-2 >= GetSize(children)) + input_error("Insufficient number of arguments in DPI function call.\n"); + + argtypes.push_back(RTLIL::unescape_id(dpi_decl->children.at(i)->str)); + args.push_back(children.at(i-2)->clone()); + while (args.back()->simplify(true, stage, -1, false)) { } + + if (args.back()->type != AST_CONSTANT && args.back()->type != AST_REALVALUE) + input_error("Failed to evaluate DPI function with non-constant argument.\n"); + } + + newNode = dpi_call(dpi_decl->location, rtype, fname, argtypes, args); + + goto apply_newNode; + } + + if (current_scope.count(str) == 0) + str = try_pop_module_prefix(); + if (current_scope.count(str) == 0 || current_scope[str]->type != AST_FUNCTION) + input_error("Can't resolve function name `%s'.\n", str); + } + + if (type == AST_TCALL) + { + if (str == "$finish" || str == "$stop") + { + if (!current_always || current_always->type != AST_INITIAL) + input_error("System task `%s' outside initial block is unsupported.\n", str); + + input_error("System task `%s' executed.\n", str); + } + + if (str == "\\$readmemh" || str == "\\$readmemb") + { + if (GetSize(children) < 2 || GetSize(children) > 4) + input_error("System function %s got %d arguments, expected 2-4.\n", + RTLIL::unescape_id(str), int(children.size())); + + auto node_filename = children[0]->clone(); + while (node_filename->simplify(true, stage, width_hint, sign_hint)) { } + if (node_filename->type != AST_CONSTANT) + input_error("Failed to evaluate system function `%s' with non-constant 1st argument.\n", str); + + auto node_memory = children[1]->clone(); + while (node_memory->simplify(true, stage, width_hint, sign_hint)) { } + if (node_memory->type != AST_IDENTIFIER || node_memory->id2ast == nullptr || node_memory->id2ast->type != AST_MEMORY) + input_error("Failed to evaluate system function `%s' with non-memory 2nd argument.\n", str); + + int start_addr = -1, finish_addr = -1; + + if (GetSize(children) > 2) { + auto node_addr = children[2]->clone(); + while (node_addr->simplify(true, stage, width_hint, sign_hint)) { } + if (node_addr->type != AST_CONSTANT) + input_error("Failed to evaluate system function `%s' with non-constant 3rd argument.\n", str); + start_addr = int(node_addr->asInt(false)); + } + + if (GetSize(children) > 3) { + auto node_addr = children[3]->clone(); + while (node_addr->simplify(true, stage, width_hint, sign_hint)) { } + if (node_addr->type != AST_CONSTANT) + input_error("Failed to evaluate system function `%s' with non-constant 4th argument.\n", str); + finish_addr = int(node_addr->asInt(false)); + } + + newNode = readmem(str == "\\$readmemh", node_filename->bitsAsConst().decode_string(), node_memory->id2ast, start_addr, finish_addr, this->is_in_unconditional_init()); + goto apply_newNode; + } + + if (current_scope.count(str) == 0) + str = try_pop_module_prefix(); + if (current_scope.count(str) == 0 || current_scope[str]->type != AST_TASK) + input_error("Can't resolve task name `%s'.\n", str); + } + + + std::stringstream sstr; + sstr << str << "$func$" << RTLIL::encode_filename(*location.begin.filename) << ":" << location.begin.line << "$" << ast_autoidx() << '.'; + std::string prefix = sstr.str(); + + auto* decl = current_scope[str]; + if (unevaluated_tern_branch && decl->is_recursive_function()) + goto replace_fcall_later; + auto decl_clone = decl->clone(); + decl = decl_clone.get(); // sketchy? + decl->replace_result_wire_name_in_function(str, "$result"); // enables recursion + decl->expand_genblock(prefix); + + if (decl->type == AST_FUNCTION && !decl->attributes.count(ID::via_celltype)) + { + bool require_const_eval = decl->has_const_only_constructs(); + bool all_args_const = true; + for (auto& child : children) { + while (child->simplify(true, 1, -1, false)) { } + if (child->type != AST_CONSTANT && child->type != AST_REALVALUE) + all_args_const = false; + } + + if (all_args_const) { + auto func_workspace = decl->clone(); + func_workspace->set_in_param_flag(true); + func_workspace->str = prefix_id(prefix, "$result"); + // func_workspace->dumpAst(stdout, "func_workspace "); + newNode = func_workspace->eval_const_function(this, in_param || require_const_eval); + if (newNode) { + goto apply_newNode; + } + } + + if (in_param) + input_error("Non-constant function call in constant expression.\n"); + if (require_const_eval) + input_error("Function %s can only be called with constant arguments.\n", str); + } + + size_t arg_count = 0; + dict wire_cache; + vector> new_stmts; + vector> output_assignments; + + if (current_block == nullptr) + { + log_assert(type == AST_FCALL); + + std::unique_ptr wire = nullptr; + std::string res_name = prefix_id(prefix, "$result"); + for (auto& child : decl->children) + if (child->type == AST_WIRE && child->str == res_name) + wire = child->clone(); + log_assert(wire != nullptr); + + wire->port_id = 0; + wire->is_input = false; + wire->is_output = false; + + auto* wire_leaky = wire.get(); + current_scope[wire->str] = wire_leaky; + current_ast_mod->children.push_back(std::move(wire)); + while (wire_leaky->simplify(true, 1, -1, false)) { } + + auto lvalue = std::make_unique(location, AST_IDENTIFIER); + lvalue->str = wire_leaky->str; + + auto always = std::make_unique(location, AST_ALWAYS, std::make_unique(location, AST_BLOCK, + std::make_unique(location, AST_ASSIGN_EQ, std::move(lvalue), clone()))); + always->children[0]->children[0]->was_checked = true; + + current_ast_mod->children.push_back(std::move(always)); + + goto replace_fcall_with_id; + } + + if (decl->attributes.count(ID::via_celltype)) + { + std::string celltype = decl->attributes.at(ID::via_celltype)->asAttrConst().decode_string(); + std::string outport = str; + + if (celltype.find(' ') != std::string::npos) { + int pos = celltype.find(' '); + outport = RTLIL::escape_id(celltype.substr(pos+1)); + celltype = RTLIL::escape_id(celltype.substr(0, pos)); + } else + celltype = RTLIL::escape_id(celltype); + + auto cell = std::make_unique(location, AST_CELL, std::make_unique(location, AST_CELLTYPE)); + cell->str = prefix.substr(0, GetSize(prefix)-1); + cell->children[0]->str = celltype; + + for (auto& attr : decl->attributes) { + std::string attr_str = attr_name_str(attr.first); + if (attr_str.rfind("\\via_celltype_defparam_", 0) == 0) + { + auto cell_arg = std::make_unique(location, AST_PARASET, attr.second->clone()); + cell_arg->str = RTLIL::escape_id(attr_str.substr(strlen("\\via_celltype_defparam_"))); + cell->children.push_back(std::move(cell_arg)); + } + } + + for (auto& child : decl->children) + if (child->type == AST_WIRE && (child->is_input || child->is_output || (type == AST_FCALL && child->str == str))) + { + auto wire = child->clone(); + wire->port_id = 0; + wire->is_input = false; + wire->is_output = false; + current_ast_mod->children.push_back(std::move(wire)); + while (wire->simplify(true, 1, -1, false)) { } + + auto wire_id = std::make_unique(location, AST_IDENTIFIER); + wire_id->str = wire->str; + + if ((child->is_input || child->is_output) && arg_count < children.size()) + { + auto arg = children[arg_count++]->clone(); + auto assign = child->is_input ? + std::make_unique(location, AST_ASSIGN_EQ, wire_id->clone(), std::move(arg)) : + std::make_unique(location, AST_ASSIGN_EQ, std::move(arg), wire_id->clone()); + assign->children[0]->was_checked = true; + + for (auto it = current_block->children.begin(); it != current_block->children.end(); it++) { + if (it->get() != current_block_child) + continue; + current_block->children.insert(it, std::move(assign)); + break; + } + } + + auto cell_arg = std::make_unique(location, AST_ARGUMENT, std::move(wire_id)); + cell_arg->str = child->str == str ? outport : child->str; + cell->children.push_back(std::move(cell_arg)); + } + + current_ast_mod->children.push_back(std::move(cell)); + goto replace_fcall_with_id; + } + + for (auto& child : decl->children) + if (child->type == AST_WIRE || child->type == AST_MEMORY || child->type == AST_PARAMETER || child->type == AST_LOCALPARAM || child->type == AST_ENUM_ITEM) + { + AstNode *wire = nullptr; + + if (wire_cache.count(child->str)) + { + wire = wire_cache.at(child->str); + bool contains_value = wire->type == AST_LOCALPARAM; + if (wire->children.size() == contains_value) { + for (auto& c : child->children) + wire->children.push_back(c->clone()); + } else if (!child->children.empty()) { + while (child->simplify(true, stage, -1, false)) { } + if (GetSize(child->children) == GetSize(wire->children) - contains_value) { + for (int i = 0; i < GetSize(child->children); i++) + if (*child->children.at(i) != *wire->children.at(i + contains_value)) + goto tcall_incompatible_wires; + } else { + tcall_incompatible_wires: + input_error("Incompatible re-declaration of wire %s.\n", child->str); + } + } + } + else + { + current_ast_mod->children.push_back(child->clone()); + wire = current_ast_mod->children.back().get(); + wire->port_id = 0; + wire->is_input = false; + wire->is_output = false; + wire->is_reg = true; + wire->set_attribute(ID::nosync, AstNode::mkconst_int(location, 1, false)); + if (child->type == AST_ENUM_ITEM) + wire->set_attribute(ID::enum_base_type, std::move(child->attributes[ID::enum_base_type])); + + wire_cache[child->str] = wire; + + current_scope[wire->str] = wire; + } + + while (wire->simplify(true, 1, -1, false)) { } + + if ((child->is_input || child->is_output) && arg_count < children.size()) + { + auto arg = children[arg_count++]->clone(); + // convert purely constant arguments into localparams + if (child->is_input && child->type == AST_WIRE && arg->type == AST_CONSTANT && node_contains_assignment_to(decl, child.get())) { + wire->type = AST_LOCALPARAM; + wire->attributes.erase(ID::nosync); + wire->children.insert(wire->children.begin(), arg->clone()); + // args without a range implicitly have width 1 + if (wire->children.back()->type != AST_RANGE) { + // check if this wire is redeclared with an explicit size + bool uses_explicit_size = false; + for (auto& other_child : decl->children) + if (other_child->type == AST_WIRE && child->str == other_child->str + && !other_child->children.empty() + && other_child->children.back()->type == AST_RANGE) { + uses_explicit_size = true; + break; + } + if (!uses_explicit_size) { + auto range = std::make_unique(location); + range->type = AST_RANGE; + range->children.push_back(mkconst_int(location, 0, true)); + range->children.push_back(mkconst_int(location, 0, true)); + wire->children.push_back(std::move(range)); + } + } + wire->fixup_hierarchy_flags(); + // updates the sizing + while (wire->simplify(true, 1, -1, false)) { } + continue; + } + + auto wire_id = std::make_unique(location, AST_IDENTIFIER); + wire_id->str = wire->str; + if (child->is_input) { + auto assign = std::make_unique(location, AST_ASSIGN_EQ, wire_id->clone(), arg->clone()); + assign->children[0]->was_checked = true; + new_stmts.push_back(std::move(assign)); + } + + if (child->is_output) { + auto assign = std::make_unique(location, AST_ASSIGN_EQ, arg->clone(), wire_id->clone()); + assign->children[0]->was_checked = true; + output_assignments.push_back(std::move(assign)); + } + } + } + + for (auto& child : decl->children) + if (child->type != AST_WIRE && child->type != AST_MEMORY && child->type != AST_PARAMETER && child->type != AST_LOCALPARAM) + new_stmts.push_back(child->clone()); + + new_stmts.reserve(new_stmts.size() + output_assignments.size()); + std::move(output_assignments.begin(), output_assignments.end(), std::back_inserter(new_stmts)); + + for (auto it = current_block->children.begin(); ; it++) { + log_assert(it != current_block->children.end()); + if (it->get() == current_block_child) { + current_block->children.insert(it, + std::make_move_iterator(new_stmts.begin()), + std::make_move_iterator(new_stmts.end())); + break; + } + } + + replace_fcall_with_id: + if (type == AST_FCALL) { + delete_children(); + type = AST_IDENTIFIER; + str = prefix_id(prefix, "$result"); + } + if (type == AST_TCALL) + str = ""; + did_something = true; + } + +replace_fcall_later:; + + // perform const folding when activated + if (const_fold) + { + bool string_op; + std::vector tmp_bits; + RTLIL::Const (*const_func)(const RTLIL::Const&, const RTLIL::Const&, bool, bool, int); + RTLIL::Const dummy_arg; + + switch (type) + { + case AST_IDENTIFIER: + if (current_scope.count(str) > 0 && (current_scope[str]->type == AST_PARAMETER || current_scope[str]->type == AST_LOCALPARAM || current_scope[str]->type == AST_ENUM_ITEM)) { + if (current_scope[str]->children[0]->type == AST_CONSTANT) { + if (children.size() != 0 && children[0]->type == AST_RANGE && children[0]->range_valid) { + std::vector data; + bool param_upto = current_scope[str]->range_valid && current_scope[str]->range_swapped; + int param_offset = current_scope[str]->range_valid ? current_scope[str]->range_right : 0; + int param_width = current_scope[str]->range_valid ? current_scope[str]->range_left - current_scope[str]->range_right + 1 : + GetSize(current_scope[str]->children[0]->bits); + int tmp_range_left = children[0]->range_left, tmp_range_right = children[0]->range_right; + if (param_upto) { + tmp_range_left = (param_width + 2*param_offset) - children[0]->range_right - 1; + tmp_range_right = (param_width + 2*param_offset) - children[0]->range_left - 1; + } + AstNode *member_node = get_struct_member(); + int chunk_offset = member_node ? member_node->range_right : 0; + log_assert(!(chunk_offset && param_upto)); + for (int i = tmp_range_right; i <= tmp_range_left; i++) { + int index = i - param_offset; + if (0 <= index && index < param_width) + data.push_back(current_scope[str]->children[0]->bits[chunk_offset + index]); + else + data.push_back(RTLIL::State::Sx); + } + newNode = mkconst_bits(location, data, false); + } else + if (children.size() == 0) + newNode = current_scope[str]->children[0]->clone(); + } else + if (current_scope[str]->children[0]->isConst()) + newNode = current_scope[str]->children[0]->clone(); + } + break; + case AST_BIT_NOT: + if (children[0]->type == AST_CONSTANT) { + RTLIL::Const y = RTLIL::const_not(children[0]->bitsAsConst(width_hint, sign_hint), dummy_arg, sign_hint, false, width_hint); + newNode = mkconst_bits(location, y.to_bits(), sign_hint); + } + break; + case AST_TO_SIGNED: + case AST_TO_UNSIGNED: + if (children[0]->type == AST_CONSTANT) { + RTLIL::Const y = children[0]->bitsAsConst(width_hint, sign_hint); + newNode = mkconst_bits(location, y.to_bits(), type == AST_TO_SIGNED); + } + break; + if (0) { case AST_BIT_AND: const_func = RTLIL::const_and; } + if (0) { case AST_BIT_OR: const_func = RTLIL::const_or; } + if (0) { case AST_BIT_XOR: const_func = RTLIL::const_xor; } + if (0) { case AST_BIT_XNOR: const_func = RTLIL::const_xnor; } + if (children[0]->type == AST_CONSTANT && children[1]->type == AST_CONSTANT) { + RTLIL::Const y = const_func(children[0]->bitsAsConst(width_hint, sign_hint), + children[1]->bitsAsConst(width_hint, sign_hint), sign_hint, sign_hint, width_hint); + newNode = mkconst_bits(location, y.to_bits(), sign_hint); + } + break; + if (0) { case AST_REDUCE_AND: const_func = RTLIL::const_reduce_and; } + if (0) { case AST_REDUCE_OR: const_func = RTLIL::const_reduce_or; } + if (0) { case AST_REDUCE_XOR: const_func = RTLIL::const_reduce_xor; } + if (0) { case AST_REDUCE_XNOR: const_func = RTLIL::const_reduce_xnor; } + if (0) { case AST_REDUCE_BOOL: const_func = RTLIL::const_reduce_bool; } + if (children[0]->type == AST_CONSTANT) { + RTLIL::Const y = const_func(RTLIL::Const(children[0]->bits), dummy_arg, false, false, -1); + newNode = mkconst_bits(location, y.to_bits(), false); + } else + if (type == AST_REDUCE_BOOL && children[0]->type == AST_REALVALUE) { + newNode = mkconst_int(location, children[0]->asReal(sign_hint) != 0, false, 1); + } + break; + case AST_LOGIC_NOT: + if (children[0]->type == AST_CONSTANT) { + RTLIL::Const y = RTLIL::const_logic_not(RTLIL::Const(children[0]->bits), dummy_arg, children[0]->is_signed, false, -1); + newNode = mkconst_bits(location, y.to_bits(), false); + } else + if (children[0]->isConst()) { + newNode = mkconst_int(location, children[0]->asReal(sign_hint) == 0, false, 1); + } + break; + if (0) { case AST_LOGIC_AND: const_func = RTLIL::const_logic_and; } + if (0) { case AST_LOGIC_OR: const_func = RTLIL::const_logic_or; } + if (children[0]->type == AST_CONSTANT && children[1]->type == AST_CONSTANT) { + RTLIL::Const y = const_func(RTLIL::Const(children[0]->bits), RTLIL::Const(children[1]->bits), + children[0]->is_signed, children[1]->is_signed, -1); + newNode = mkconst_bits(location, y.to_bits(), false); + } else + if (children[0]->isConst() && children[1]->isConst()) { + if (type == AST_LOGIC_AND) + newNode = mkconst_int(location, (children[0]->asReal(sign_hint) != 0) && (children[1]->asReal(sign_hint) != 0), false, 1); + else + newNode = mkconst_int(location, (children[0]->asReal(sign_hint) != 0) || (children[1]->asReal(sign_hint) != 0), false, 1); + } + break; + if (0) { case AST_SHIFT_LEFT: const_func = RTLIL::const_shl; } + if (0) { case AST_SHIFT_RIGHT: const_func = RTLIL::const_shr; } + if (0) { case AST_SHIFT_SLEFT: const_func = RTLIL::const_sshl; } + if (0) { case AST_SHIFT_SRIGHT: const_func = RTLIL::const_sshr; } + if (0) { case AST_POW: const_func = RTLIL::const_pow; } + if (children[0]->type == AST_CONSTANT && children[1]->type == AST_CONSTANT) { + RTLIL::Const y = const_func(children[0]->bitsAsConst(width_hint, sign_hint), + RTLIL::Const(children[1]->bits), sign_hint, type == AST_POW ? children[1]->is_signed : false, width_hint); + newNode = mkconst_bits(location, y.to_bits(), sign_hint); + } else + if (type == AST_POW && children[0]->isConst() && children[1]->isConst()) { + newNode = std::make_unique(location, AST_REALVALUE); + newNode->realvalue = pow(children[0]->asReal(sign_hint), children[1]->asReal(sign_hint)); + } + break; + if (0) { case AST_LT: const_func = RTLIL::const_lt; } + if (0) { case AST_LE: const_func = RTLIL::const_le; } + if (0) { case AST_EQ: const_func = RTLIL::const_eq; } + if (0) { case AST_NE: const_func = RTLIL::const_ne; } + if (0) { case AST_EQX: const_func = RTLIL::const_eqx; } + if (0) { case AST_NEX: const_func = RTLIL::const_nex; } + if (0) { case AST_GE: const_func = RTLIL::const_ge; } + if (0) { case AST_GT: const_func = RTLIL::const_gt; } + if (children[0]->type == AST_CONSTANT && children[1]->type == AST_CONSTANT) { + int cmp_width = max(children[0]->bits.size(), children[1]->bits.size()); + bool cmp_signed = children[0]->is_signed && children[1]->is_signed; + RTLIL::Const y = const_func(children[0]->bitsAsConst(cmp_width, cmp_signed), + children[1]->bitsAsConst(cmp_width, cmp_signed), cmp_signed, cmp_signed, 1); + newNode = mkconst_bits(location, y.to_bits(), false); + } else + if (children[0]->isConst() && children[1]->isConst()) { + bool cmp_signed = (children[0]->type == AST_REALVALUE || children[0]->is_signed) && (children[1]->type == AST_REALVALUE || children[1]->is_signed); + switch (type) { + case AST_LT: newNode = mkconst_int(location, children[0]->asReal(cmp_signed) < children[1]->asReal(cmp_signed), false, 1); break; + case AST_LE: newNode = mkconst_int(location, children[0]->asReal(cmp_signed) <= children[1]->asReal(cmp_signed), false, 1); break; + case AST_EQ: newNode = mkconst_int(location, children[0]->asReal(cmp_signed) == children[1]->asReal(cmp_signed), false, 1); break; + case AST_NE: newNode = mkconst_int(location, children[0]->asReal(cmp_signed) != children[1]->asReal(cmp_signed), false, 1); break; + case AST_EQX: newNode = mkconst_int(location, children[0]->asReal(cmp_signed) == children[1]->asReal(cmp_signed), false, 1); break; + case AST_NEX: newNode = mkconst_int(location, children[0]->asReal(cmp_signed) != children[1]->asReal(cmp_signed), false, 1); break; + case AST_GE: newNode = mkconst_int(location, children[0]->asReal(cmp_signed) >= children[1]->asReal(cmp_signed), false, 1); break; + case AST_GT: newNode = mkconst_int(location, children[0]->asReal(cmp_signed) > children[1]->asReal(cmp_signed), false, 1); break; + default: log_abort(); + } + } + break; + if (0) { case AST_ADD: const_func = RTLIL::const_add; } + if (0) { case AST_SUB: const_func = RTLIL::const_sub; } + if (0) { case AST_MUL: const_func = RTLIL::const_mul; } + if (0) { case AST_DIV: const_func = RTLIL::const_div; } + if (0) { case AST_MOD: const_func = RTLIL::const_mod; } + if (children[0]->type == AST_CONSTANT && children[1]->type == AST_CONSTANT) { + RTLIL::Const y = const_func(children[0]->bitsAsConst(width_hint, sign_hint), + children[1]->bitsAsConst(width_hint, sign_hint), sign_hint, sign_hint, width_hint); + newNode = mkconst_bits(location, y.to_bits(), sign_hint); + } else + if (children[0]->isConst() && children[1]->isConst()) { + newNode = std::make_unique(location, AST_REALVALUE); + switch (type) { + case AST_ADD: newNode->realvalue = children[0]->asReal(sign_hint) + children[1]->asReal(sign_hint); break; + case AST_SUB: newNode->realvalue = children[0]->asReal(sign_hint) - children[1]->asReal(sign_hint); break; + case AST_MUL: newNode->realvalue = children[0]->asReal(sign_hint) * children[1]->asReal(sign_hint); break; + case AST_DIV: newNode->realvalue = children[0]->asReal(sign_hint) / children[1]->asReal(sign_hint); break; + case AST_MOD: newNode->realvalue = fmod(children[0]->asReal(sign_hint), children[1]->asReal(sign_hint)); break; + default: log_abort(); + } + } + break; + if (0) { case AST_SELFSZ: const_func = RTLIL::const_pos; } + if (0) { case AST_POS: const_func = RTLIL::const_pos; } + if (0) { case AST_NEG: const_func = RTLIL::const_neg; } + if (children[0]->type == AST_CONSTANT) { + RTLIL::Const y = const_func(children[0]->bitsAsConst(width_hint, sign_hint), dummy_arg, sign_hint, false, width_hint); + newNode = mkconst_bits(location, y.to_bits(), sign_hint); + } else + if (children[0]->isConst()) { + newNode = std::make_unique(location, AST_REALVALUE); + if (type == AST_NEG) + newNode->realvalue = -children[0]->asReal(sign_hint); + else + newNode->realvalue = +children[0]->asReal(sign_hint); + } + break; + case AST_TERNARY: + if (children[0]->isConst()) + { + auto pair = get_tern_choice(); + AstNode *choice = pair.first; + AstNode *not_choice = pair.second; + + if (choice != nullptr) { + if (choice->type == AST_CONSTANT) { + int other_width_hint = width_hint; + bool other_sign_hint = sign_hint, other_real = false; + not_choice->detectSignWidth(other_width_hint, other_sign_hint, &other_real); + if (other_real) { + newNode = std::make_unique(location, AST_REALVALUE); + choice->detectSignWidth(width_hint, sign_hint); + newNode->realvalue = choice->asReal(sign_hint); + } else { + RTLIL::Const y = choice->bitsAsConst(width_hint, sign_hint); + if (choice->is_string && y.size() % 8 == 0 && sign_hint == false) + newNode = mkconst_str(location, y.to_bits()); + else + newNode = mkconst_bits(location, y.to_bits(), sign_hint); + } + } else + if (choice->isConst()) { + newNode = choice->clone(); + } + } else if (children[1]->type == AST_CONSTANT && children[2]->type == AST_CONSTANT) { + RTLIL::Const a = children[1]->bitsAsConst(width_hint, sign_hint); + RTLIL::Const b = children[2]->bitsAsConst(width_hint, sign_hint); + log_assert(a.size() == b.size()); + for (auto i = 0; i < a.size(); i++) + if (a[i] != b[i]) + a.set(i, RTLIL::State::Sx); + newNode = mkconst_bits(location, a.to_bits(), sign_hint); + } else if (children[1]->isConst() && children[2]->isConst()) { + newNode = std::make_unique(location, AST_REALVALUE); + if (children[1]->asReal(sign_hint) == children[2]->asReal(sign_hint)) + newNode->realvalue = children[1]->asReal(sign_hint); + else + // IEEE Std 1800-2012 Sec. 11.4.11 states that the entry in Table 7-1 for + // the data type in question should be returned if the ?: is ambiguous. The + // value in Table 7-1 for the 'real' type is 0.0. + newNode->realvalue = 0.0; + } + } + break; + case AST_CAST_SIZE: + if (children.at(0)->type == AST_CONSTANT && children.at(1)->type == AST_CONSTANT) { + int width = children[0]->bitsAsConst().as_int(); + if (width <= 0) + input_error("Static cast with zero or negative size!\n"); + RTLIL::Const val; + if (children[1]->is_unsized) + val = children[1]->bitsAsUnsizedConst(width); + else + val = children[1]->bitsAsConst(width); + newNode = mkconst_bits(location, val.to_bits(), children[1]->is_signed); + } + break; + case AST_CONCAT: + string_op = !children.empty(); + for (auto it = children.begin(); it != children.end(); it++) { + if ((*it)->type != AST_CONSTANT) + goto not_const; + if (!(*it)->is_string) + string_op = false; + tmp_bits.insert(tmp_bits.end(), (*it)->bits.begin(), (*it)->bits.end()); + } + newNode = string_op ? mkconst_str(location, tmp_bits) : mkconst_bits(location, tmp_bits, false); + break; + case AST_REPLICATE: + if (children.at(0)->type != AST_CONSTANT || children.at(1)->type != AST_CONSTANT) + goto not_const; + for (int i = 0; i < children[0]->bitsAsConst().as_int(); i++) + tmp_bits.insert(tmp_bits.end(), children.at(1)->bits.begin(), children.at(1)->bits.end()); + newNode = children.at(1)->is_string ? mkconst_str(location, tmp_bits) : mkconst_bits(location, tmp_bits, false); + break; + case AST_ASSIGN_PATTERN: + goto not_const; + default: + not_const: + break; + } + } + + // if any of the above set 'newNode' -> use 'newNode' as template to update 'this' + if (newNode) { +apply_newNode: + // fprintf(stderr, "----\n"); + // dumpAst(stderr, "- "); + // newNode->dumpAst(stderr, "+ "); + log_assert(newNode != nullptr); + newNode->location.begin.filename = location.begin.filename; + newNode->location = location; + newNode->cloneInto(*this); + fixup_hierarchy_flags(); + did_something = true; + } + + if (!did_something) + basic_prep = true; + + recursion_counter--; + return did_something; +} + +void AstNode::replace_result_wire_name_in_function(const std::string &from, const std::string &to) +{ + for (auto& child : children) + child->replace_result_wire_name_in_function(from, to); + if (str == from && type != AST_FCALL && type != AST_TCALL) + str = to; +} + +// replace a readmem[bh] TCALL ast node with a block of memory assignments +std::unique_ptr AstNode::readmem(bool is_readmemh, std::string mem_filename, AstNode *memory, int start_addr, int finish_addr, bool unconditional_init) +{ + int mem_width, mem_size, addr_bits; + memory->meminfo(mem_width, mem_size, addr_bits); + + auto block = std::make_unique(location, AST_BLOCK); + + AstNode* meminit = nullptr; + int next_meminit_cursor=0; + vector meminit_bits; + vector en_bits; + int meminit_size=0; + + for (int i = 0; i < mem_width; i++) + en_bits.push_back(State::S1); + + std::ifstream f; + f.open(mem_filename.c_str()); + if (f.fail()) { + std::string path = parent_from_file_path(*location.begin.filename); + f.open(path + mem_filename.c_str()); + yosys_input_files.insert(path + mem_filename); + } else { + yosys_input_files.insert(mem_filename); + } + if (f.fail() || GetSize(mem_filename) == 0) + input_error("Can not open file `%s` for %s.\n", mem_filename, str); + + log_assert(GetSize(memory->children) == 2 && memory->children[1]->type == AST_RANGE && memory->children[1]->range_valid); + int range_left = memory->children[1]->range_left, range_right = memory->children[1]->range_right; + int range_min = min(range_left, range_right), range_max = max(range_left, range_right); + + if (start_addr < 0) + start_addr = range_min; + + if (finish_addr < 0) + finish_addr = range_max + 1; + + bool in_comment = false; + int increment = start_addr <= finish_addr ? +1 : -1; + int cursor = start_addr; + + while (!f.eof()) + { + std::string line, token; + std::getline(f, line); + + for (int i = 0; i < GetSize(line); i++) { + if (in_comment && line.compare(i, 2, "*/") == 0) { + line[i] = ' '; + line[i+1] = ' '; + in_comment = false; + continue; + } + if (!in_comment && line.compare(i, 2, "/*") == 0) + in_comment = true; + if (in_comment) + line[i] = ' '; + } + + while (1) + { + token = next_token(line, " \t\r\n"); + if (token.empty() || token.compare(0, 2, "//") == 0) + break; + + if (token[0] == '@') { + token = token.substr(1); + const char *nptr = token.c_str(); + char *endptr; + cursor = strtol(nptr, &endptr, 16); + if (!*nptr || *endptr) + input_error("Can not parse address `%s` for %s.\n", nptr, str); + continue; + } + + VERILOG_FRONTEND::ConstParser p{memory->location}; + auto value = p.const2ast(stringf("%d'%c", mem_width, is_readmemh ? 'h' : 'b') + token); + + if (unconditional_init) + { + if (meminit == nullptr || cursor != next_meminit_cursor) + { + if (meminit != nullptr) { + meminit->children[1] = AstNode::mkconst_bits(location, meminit_bits, false); + meminit->children[3] = AstNode::mkconst_int(location, meminit_size, false); + } + + auto meminit_owned = std::make_unique(location, AST_MEMINIT); + meminit = meminit_owned.get(); + meminit->children.push_back(AstNode::mkconst_int(location, cursor, false)); + meminit->children.push_back(nullptr); + meminit->children.push_back(AstNode::mkconst_bits(location, en_bits, false)); + meminit->children.push_back(nullptr); + meminit->str = memory->str; + meminit->id2ast = memory; + meminit_bits.clear(); + meminit_size = 0; + + current_ast_mod->children.push_back(std::move(meminit_owned)); + next_meminit_cursor = cursor; + } + + meminit_size++; + next_meminit_cursor++; + meminit_bits.insert(meminit_bits.end(), value->bits.begin(), value->bits.end()); + } + else + { + block->children.push_back( + std::make_unique(location, + AST_ASSIGN_EQ, std::make_unique(location, + AST_IDENTIFIER, std::make_unique(location, + AST_RANGE, AstNode::mkconst_int(location, + cursor, false))), + std::move(value))); + block->children.back()->children[0]->str = memory->str; + block->children.back()->children[0]->id2ast = memory; + block->children.back()->children[0]->was_checked = true; + } + + cursor += increment; + if ((cursor == finish_addr+increment) || (increment > 0 && cursor > range_max) || (increment < 0 && cursor < range_min)) + break; + } + + if ((cursor == finish_addr+increment) || (increment > 0 && cursor > range_max) || (increment < 0 && cursor < range_min)) + break; + } + + if (meminit != nullptr) { + meminit->children[1] = AstNode::mkconst_bits(location, meminit_bits, false); + meminit->children[3] = AstNode::mkconst_int(location, meminit_size, false); + } + + return block; +} + +// annotate the names of all wires and other named objects in a named generate +// or procedural block; nested blocks are themselves annotated such that the +// prefix is carried forward, but resolution of their children is deferred +void AstNode::expand_genblock(const std::string &prefix) +{ + if (type == AST_IDENTIFIER || type == AST_FCALL || type == AST_TCALL || type == AST_WIRETYPE || type == AST_PREFIX) { + log_assert(!str.empty()); + + // search starting in the innermost scope and then stepping outward + for (size_t ppos = prefix.size() - 1; ppos; --ppos) { + if (prefix.at(ppos) != '.') continue; + + std::string new_prefix = prefix.substr(0, ppos + 1); + auto attempt_resolve = [&new_prefix](const std::string &ident) -> std::string { + std::string new_name = prefix_id(new_prefix, ident); + if (current_scope.count(new_name)) + return new_name; + return {}; + }; + + // attempt to resolve the full identifier + std::string resolved = attempt_resolve(str); + if (!resolved.empty()) { + str = resolved; + break; + } + + // attempt to resolve hierarchical prefixes within the identifier, + // as the prefix could refer to a local scope which exists but + // hasn't yet been elaborated + for (size_t spos = str.size() - 1; spos; --spos) { + if (str.at(spos) != '.') continue; + resolved = attempt_resolve(str.substr(0, spos)); + if (!resolved.empty()) { + str = resolved + str.substr(spos); + ppos = 1; // break outer loop + break; + } + } + + } + } + + auto prefix_node = [&prefix](AstNode* child) { + if (child->str.empty()) return; + std::string new_name = prefix_id(prefix, child->str); + if (child->type == AST_FUNCTION) + child->replace_result_wire_name_in_function(child->str, new_name); + else + child->str = new_name; + current_scope[new_name] = child; + }; + + for (size_t i = 0; i < children.size(); i++) { + auto* child = children[i].get(); + + switch (child->type) { + case AST_WIRE: + case AST_AUTOWIRE: + case AST_MEMORY: + case AST_STRUCT: + case AST_UNION: + case AST_PARAMETER: + case AST_LOCALPARAM: + case AST_FUNCTION: + case AST_TASK: + case AST_CELL: + case AST_TYPEDEF: + case AST_ENUM_ITEM: + case AST_GENVAR: + prefix_node(child); + break; + + case AST_BLOCK: + case AST_GENBLOCK: + if (!child->str.empty()) + prefix_node(child); + break; + + case AST_ENUM: + current_scope[child->str] = child; + for (auto& enode : child->children){ + log_assert(enode->type == AST_ENUM_ITEM); + prefix_node(enode.get()); + } + break; + + case AST_IDENTIFIER: + if (!child->str.empty() && prefix.size() > 0) { + bool is_resolved = false; + std::string identifier_str = child->str; + if (current_ast_mod != nullptr && identifier_str.size() > current_ast_mod->str.size() && identifier_str.compare(0, current_ast_mod->str.size(), current_ast_mod->str) == 0) { + if (identifier_str.at(current_ast_mod->str.size()) == '.') { + identifier_str = '\\' + identifier_str.substr(current_ast_mod->str.size()+1, identifier_str.size()); + } + } + // search starting in the innermost scope and then stepping outward + for (size_t ppos = prefix.size() - 1; ppos; --ppos) { + if (prefix.at(ppos) != '.') continue; + + std::string new_prefix = prefix.substr(0, ppos + 1); + auto attempt_resolve = [&new_prefix](const std::string &ident) -> std::string { + std::string new_name = prefix_id(new_prefix, ident); + if (current_scope.count(new_name)) + return new_name; + return {}; + }; + + // attempt to resolve the full identifier + std::string resolved = attempt_resolve(identifier_str); + if (!resolved.empty()) { + is_resolved = true; + break; + } + // attempt to resolve hierarchical prefixes within the identifier, + // as the prefix could refer to a local scope which exists but + // hasn't yet been elaborated + for (size_t spos = identifier_str.size() - 1; spos; --spos) { + if (identifier_str.at(spos) != '.') continue; + resolved = attempt_resolve(identifier_str.substr(0, spos)); + if (!resolved.empty()) { + is_resolved = true; + identifier_str = resolved + identifier_str.substr(spos); + ppos = 1; // break outer loop + break; + } + } + if (current_scope.count(identifier_str) == 0) { + AstNode *current_scope_ast = (current_ast_mod == nullptr) ? current_ast : current_ast_mod; + for (auto& node : current_scope_ast->children) { + switch (node->type) { + case AST_PARAMETER: + case AST_LOCALPARAM: + case AST_WIRE: + case AST_AUTOWIRE: + case AST_GENVAR: + case AST_MEMORY: + case AST_FUNCTION: + case AST_TASK: + case AST_DPI_FUNCTION: + if (prefix_id(new_prefix, identifier_str) == node->str) { + is_resolved = true; + current_scope[node->str] = node.get(); + } + break; + case AST_ENUM: + current_scope[node->str] = node.get(); + for (auto& enum_node : node->children) { + log_assert(enum_node->type==AST_ENUM_ITEM); + if (prefix_id(new_prefix, identifier_str) == enum_node->str) { + is_resolved = true; + current_scope[enum_node->str] = enum_node.get(); + } + } + break; + default: + break; + } + } + } + } + if ((current_scope.count(identifier_str) == 0) && is_resolved == false) { + if (current_ast_mod == nullptr) { + input_error("Identifier `%s' is implicitly declared outside of a module.\n", child->str.c_str()); + } else if (flag_autowire || identifier_str == "\\$global_clock") { + auto auto_wire = std::make_unique(child->location, AST_AUTOWIRE); + auto_wire->str = identifier_str; + children.push_back(std::move(auto_wire)); + } else { + input_error("Identifier `%s' is implicitly declared and `default_nettype is set to none.\n", identifier_str.c_str()); + } + } + } + break; + default: + break; + } + } + + for (size_t i = 0; i < children.size(); i++) { + auto& child = children[i]; + // AST_PREFIX member names should not be prefixed; we recurse into them + // as normal to ensure indices and ranges are properly resolved, and + // then restore the previous string + if (type == AST_PREFIX && i == 1) { + std::string backup_scope_name = child->str; + child->expand_genblock(prefix); + child->str = backup_scope_name; + continue; + } + // functions/tasks may reference wires, constants, etc. in this scope + if (child->type == AST_FUNCTION || child->type == AST_TASK) + continue; + // named blocks pick up the current prefix and will expanded later + if ((child->type == AST_GENBLOCK || child->type == AST_BLOCK) && !child->str.empty()) + continue; + + child->expand_genblock(prefix); + } +} + +// add implicit AST_GENBLOCK names according to IEEE 1364-2005 Section 12.4.3 or +// IEEE 1800-2017 Section 27.6 +void AstNode::label_genblks(std::set& existing, int &counter) +{ + switch (type) { + case AST_GENIF: + case AST_GENFOR: + case AST_GENCASE: + // seeing a proper generate control flow construct increments the + // counter once + ++counter; + for (auto& child : children) + child->label_genblks(existing, counter); + break; + + case AST_GENBLOCK: { + // if this block is unlabeled, generate its corresponding unique name + for (int padding = 0; str.empty(); ++padding) { + std::string candidate = "\\genblk"; + for (int i = 0; i < padding; ++i) + candidate += '0'; + candidate += std::to_string(counter); + if (!existing.count(candidate)) + str = candidate; + } + // within a genblk, the counter starts fresh + std::set existing_local = existing; + int counter_local = 0; + for (auto& child : children) + child->label_genblks(existing_local, counter_local); + break; + } + + default: + // track names which could conflict with implicit genblk names + if (str.rfind("\\genblk", 0) == 0) + existing.insert(str); + for (auto& child : children) + child->label_genblks(existing, counter); + break; + } +} + +// helper function for mem2reg_as_needed_pass1 +static void mark_memories_assign_lhs_complex(dict> &mem2reg_places, + dict &mem2reg_candidates, AstNode *that) +{ + for (auto &child : that->children) + mark_memories_assign_lhs_complex(mem2reg_places, mem2reg_candidates, child.get()); + + if (that->type == AST_IDENTIFIER && that->id2ast && that->id2ast->type == AST_MEMORY) { + AstNode *mem = that->id2ast; + if (!(mem2reg_candidates[mem] & AstNode::MEM2REG_FL_CMPLX_LHS)) + mem2reg_places[mem].insert(stringf("%s:%d", RTLIL::encode_filename(*that->location.begin.filename), that->location.begin.line)); + mem2reg_candidates[mem] |= AstNode::MEM2REG_FL_CMPLX_LHS; + } +} + +// find memories that should be replaced by registers +void AstNode::mem2reg_as_needed_pass1(dict> &mem2reg_places, + dict &mem2reg_candidates, dict &proc_flags, uint32_t &flags) +{ + uint32_t children_flags = 0; + int lhs_children_counter = 0; + + if (type == AST_TYPEDEF) + return; // don't touch content of typedefs + + if (type == AST_ASSIGN || type == AST_ASSIGN_LE || type == AST_ASSIGN_EQ) + { + // mark all memories that are used in a complex expression on the left side of an assignment + for (auto &lhs_child : children[0]->children) + mark_memories_assign_lhs_complex(mem2reg_places, mem2reg_candidates, lhs_child.get()); + + if (children[0]->type == AST_IDENTIFIER && children[0]->id2ast && children[0]->id2ast->type == AST_MEMORY) + { + AstNode *mem = children[0]->id2ast; + + // activate mem2reg if this is assigned in an async proc + if (flags & AstNode::MEM2REG_FL_ASYNC) { + if (!(mem2reg_candidates[mem] & AstNode::MEM2REG_FL_SET_ASYNC)) + mem2reg_places[mem].insert(stringf("%s:%d", RTLIL::encode_filename(*location.begin.filename), location.begin.line)); + mem2reg_candidates[mem] |= AstNode::MEM2REG_FL_SET_ASYNC; + } + + // remember if this is assigned blocking (=) + if (type == AST_ASSIGN_EQ) { + if (!(proc_flags[mem] & AstNode::MEM2REG_FL_EQ1)) + mem2reg_places[mem].insert(stringf("%s:%d", RTLIL::encode_filename(*location.begin.filename), location.begin.line)); + proc_flags[mem] |= AstNode::MEM2REG_FL_EQ1; + } + + // for proper (non-init) writes: remember if this is a constant index or not + if ((flags & MEM2REG_FL_INIT) == 0) { + if (children[0]->children.size() && children[0]->children[0]->type == AST_RANGE && children[0]->children[0]->children.size()) { + if (children[0]->children[0]->children[0]->type == AST_CONSTANT) + mem2reg_candidates[mem] |= AstNode::MEM2REG_FL_CONST_LHS; + else + mem2reg_candidates[mem] |= AstNode::MEM2REG_FL_VAR_LHS; + } + } + + // remember where this is + if (flags & MEM2REG_FL_INIT) { + if (!(mem2reg_candidates[mem] & AstNode::MEM2REG_FL_SET_INIT)) + mem2reg_places[mem].insert(stringf("%s:%d", RTLIL::encode_filename(*location.begin.filename), location.begin.line)); + mem2reg_candidates[mem] |= AstNode::MEM2REG_FL_SET_INIT; + } else { + if (!(mem2reg_candidates[mem] & AstNode::MEM2REG_FL_SET_ELSE)) + mem2reg_places[mem].insert(stringf("%s:%d", RTLIL::encode_filename(*location.begin.filename), location.begin.line)); + mem2reg_candidates[mem] |= AstNode::MEM2REG_FL_SET_ELSE; + } + } + + lhs_children_counter = 1; + } + + if (type == AST_IDENTIFIER && id2ast && id2ast->type == AST_MEMORY) + { + AstNode *mem = id2ast; + + if (integer < (unsigned)mem->unpacked_dimensions) + input_error("Insufficient number of array indices for %s.\n", RTLIL::unescape_id(str)); + + // flag if used after blocking assignment (in same proc) + if ((proc_flags[mem] & AstNode::MEM2REG_FL_EQ1) && !(mem2reg_candidates[mem] & AstNode::MEM2REG_FL_EQ2)) { + mem2reg_places[mem].insert(stringf("%s:%d", RTLIL::encode_filename(*location.begin.filename), location.begin.line)); + mem2reg_candidates[mem] |= AstNode::MEM2REG_FL_EQ2; + } + } + + // also activate if requested, either by using mem2reg attribute or by declaring array as 'wire' instead of 'reg' or 'logic' + if (type == AST_MEMORY && (get_bool_attribute(ID::mem2reg) || (flags & AstNode::MEM2REG_FL_ALL) || !(is_reg || is_logic))) + mem2reg_candidates[this] |= AstNode::MEM2REG_FL_FORCED; + + if ((type == AST_MODULE || type == AST_INTERFACE) && get_bool_attribute(ID::mem2reg)) + children_flags |= AstNode::MEM2REG_FL_ALL; + + dict *proc_flags_p = nullptr; + + if (type == AST_ALWAYS) { + int count_edge_events = 0; + for (auto& child : children) + if (child->type == AST_POSEDGE || child->type == AST_NEGEDGE) + count_edge_events++; + if (count_edge_events != 1) + children_flags |= AstNode::MEM2REG_FL_ASYNC; + proc_flags_p = new dict; + } + else if (type == AST_INITIAL) { + children_flags |= AstNode::MEM2REG_FL_INIT; + proc_flags_p = new dict; + } + + uint32_t backup_flags = flags; + flags |= children_flags; + log_assert((flags & ~0x000000ff) == 0); + + for (auto& child : children) + { + if (lhs_children_counter > 0) { + lhs_children_counter--; + if (child->children.size() && child->children[0]->type == AST_RANGE && child->children[0]->children.size()) { + for (auto& c : child->children[0]->children) { + if (proc_flags_p) + c->mem2reg_as_needed_pass1(mem2reg_places, mem2reg_candidates, *proc_flags_p, flags); + else + c->mem2reg_as_needed_pass1(mem2reg_places, mem2reg_candidates, proc_flags, flags); + } + } + } else + if (proc_flags_p) + child->mem2reg_as_needed_pass1(mem2reg_places, mem2reg_candidates, *proc_flags_p, flags); + else + child->mem2reg_as_needed_pass1(mem2reg_places, mem2reg_candidates, proc_flags, flags); + } + + flags &= ~children_flags | backup_flags; + + if (proc_flags_p) { +#ifndef NDEBUG + for (auto it : *proc_flags_p) + log_assert((it.second & ~0xff000000) == 0); +#endif + delete proc_flags_p; + } +} + +bool AstNode::mem2reg_check(pool &mem2reg_set) +{ + if (type != AST_IDENTIFIER || !id2ast || !mem2reg_set.count(id2ast)) + return false; + + if (children.empty() || children[0]->type != AST_RANGE || GetSize(children[0]->children) != 1) + input_error("Invalid array access.\n"); + + return true; +} + +void AstNode::mem2reg_remove(pool &mem2reg_set) +{ + log_assert(mem2reg_set.count(this) == 0); + + if (mem2reg_set.count(id2ast)) + id2ast = nullptr; + + for (size_t i = 0; i < children.size(); i++) { + if (mem2reg_set.count(children[i].get()) > 0) { + children.erase(children.begin() + (i--)); + } else { + children[i]->mem2reg_remove(mem2reg_set); + } + } +} + +// actually replace memories with registers +bool AstNode::mem2reg_as_needed_pass2(pool &mem2reg_set, AstNode *mod, AstNode *block, AstNode* async_block) +{ + bool did_something = false; + + if (type == AST_BLOCK) + block = this; + + if (type == AST_FUNCTION || type == AST_TASK) + return false; + + if (type == AST_TYPEDEF) + return false; + + if (type == AST_MEMINIT && id2ast && mem2reg_set.count(id2ast)) + { + log_assert(children[0]->type == AST_CONSTANT); + log_assert(children[1]->type == AST_CONSTANT); + log_assert(children[2]->type == AST_CONSTANT); + log_assert(children[3]->type == AST_CONSTANT); + + int cursor = children[0]->asInt(false); + Const data = children[1]->bitsAsConst(); + Const en = children[2]->bitsAsConst(); + int length = children[3]->asInt(false); + + if (length != 0) + { + auto block_owned = std::make_unique(location, + AST_INITIAL, std::make_unique(location, + AST_BLOCK)); + auto block = block_owned.get(); + mod->children.push_back(std::move(block_owned)); + block = block->children[0].get(); + + int wordsz = GetSize(data) / length; + + for (int i = 0; i < length; i++) { + int pos = 0; + while (pos < wordsz) { + if (en[pos] != State::S1) { + pos++; + } else { + int epos = pos + 1; + while (epos < wordsz && en[epos] == State::S1) + epos++; + int clen = epos - pos; + auto range = std::make_unique(location, + AST_RANGE, AstNode::mkconst_int(location, + cursor+i, false)); + if (pos != 0 || epos != wordsz) { + int left; + int right; + auto& mrange = id2ast->children[0]; + if (mrange->range_left < mrange->range_right) { + right = mrange->range_right - pos; + left = mrange->range_right - epos + 1; + } else { + right = mrange->range_right + pos; + left = mrange->range_right + epos - 1; + } + range = std::make_unique(location, + AST_MULTIRANGE, std::move(range), std::make_unique(location, + AST_RANGE, + AstNode::mkconst_int(location, left, true), + AstNode::mkconst_int(location, right, true))); + } + auto target = std::make_unique(location, AST_IDENTIFIER, std::move(range)); + target->str = str; + target->id2ast = id2ast; + target->was_checked = true; + block->children.push_back(std::make_unique(location, + AST_ASSIGN_EQ, + std::move(target), + mkconst_bits(location, + data.extract(i*wordsz + pos, clen).to_bits(), + false))); + pos = epos; + } + } + } + } + + auto newNode = std::make_unique(location, AST_NONE); + newNode->cloneInto(*this); + did_something = true; + } + + if (type == AST_ASSIGN && block == nullptr && children[0]->mem2reg_check(mem2reg_set)) + { + if (async_block == nullptr) { + auto async_block_owned = std::make_unique(location, AST_ALWAYS, std::make_unique(location, AST_BLOCK)); + async_block = async_block_owned.get(); + mod->children.push_back(std::move(async_block_owned)); + } + + auto newNode = clone(); + newNode->type = AST_ASSIGN_EQ; + newNode->children[0]->was_checked = true; + async_block->children[0]->children.push_back(std::move(newNode)); + + newNode = std::make_unique(location, AST_NONE); + newNode->cloneInto(*this); + did_something = true; + } + + if ((type == AST_ASSIGN_LE || type == AST_ASSIGN_EQ) && children[0]->mem2reg_check(mem2reg_set) && + children[0]->children[0]->children[0]->type != AST_CONSTANT) + { + std::stringstream sstr; + sstr << "$mem2reg_wr$" << children[0]->str << "$" << RTLIL::encode_filename(*location.begin.filename) << ":" << location.begin.line << "$" << ast_autoidx(); + std::string id_addr = sstr.str() + "_ADDR", id_data = sstr.str() + "_DATA"; + + int mem_width, mem_size, addr_bits; + bool mem_signed = children[0]->id2ast->is_signed; + children[0]->id2ast->meminfo(mem_width, mem_size, addr_bits); + + auto wire_addr = std::make_unique(location, AST_WIRE, std::make_unique(location, AST_RANGE, mkconst_int(location, addr_bits-1, true), mkconst_int(location, 0, true))); + wire_addr->str = id_addr; + wire_addr->is_reg = true; + wire_addr->was_checked = true; + wire_addr->set_attribute(ID::nosync, AstNode::mkconst_int(location, 1, false)); + while (wire_addr->simplify(true, 1, -1, false)) { } + mod->children.push_back(std::move(wire_addr)); + + auto wire_data = std::make_unique(location, AST_WIRE, std::make_unique(location, AST_RANGE, mkconst_int(location, mem_width-1, true), mkconst_int(location, 0, true))); + wire_data->str = id_data; + wire_data->is_reg = true; + wire_data->was_checked = true; + wire_data->is_signed = mem_signed; + wire_data->set_attribute(ID::nosync, AstNode::mkconst_int(location, 1, false)); + while (wire_data->simplify(true, 1, -1, false)) { } + mod->children.push_back(std::move(wire_data)); + + log_assert(block != nullptr); + size_t assign_idx = 0; + while (assign_idx < block->children.size() && block->children[assign_idx].get() != this) + assign_idx++; + log_assert(assign_idx < block->children.size()); + + auto assign_addr = std::make_unique(location, AST_ASSIGN_EQ, std::make_unique(location, AST_IDENTIFIER), children[0]->children[0]->children[0]->clone()); + assign_addr->children[0]->str = id_addr; + assign_addr->children[0]->was_checked = true; + block->children.insert(block->children.begin()+assign_idx+1, std::move(assign_addr)); + + auto case_node = std::make_unique(location, AST_CASE, std::make_unique(location, AST_IDENTIFIER)); + case_node->children[0]->str = id_addr; + for (int i = 0; i < mem_size; i++) { + if (children[0]->children[0]->children[0]->type == AST_CONSTANT && int(children[0]->children[0]->children[0]->integer) != i) + continue; + auto cond_node = std::make_unique(location, AST_COND, AstNode::mkconst_int(location, i, false, addr_bits), std::make_unique(location, AST_BLOCK)); + auto assign_reg = std::make_unique(location, type, std::make_unique(location, AST_IDENTIFIER), std::make_unique(location, AST_IDENTIFIER)); + if (children[0]->children.size() == 2) + assign_reg->children[0]->children.push_back(children[0]->children[1]->clone()); + assign_reg->children[0]->str = stringf("%s[%d]", children[0]->str, i); + assign_reg->children[1]->str = id_data; + cond_node->children[1]->children.push_back(std::move(assign_reg)); + case_node->children.push_back(std::move(cond_node)); + } + + // fixup on the full hierarchy below case_node + case_node->fixup_hierarchy_flags(true); + + block->children.insert(block->children.begin()+assign_idx+2, std::move(case_node)); + + children[0]->delete_children(); + children[0]->range_valid = false; + children[0]->id2ast = nullptr; + children[0]->str = id_data; + type = AST_ASSIGN_EQ; + children[0]->was_checked = true; + + fixup_hierarchy_flags(); + did_something = true; + } + + if (mem2reg_check(mem2reg_set)) + { + std::unique_ptr bit_part_sel = nullptr; + if (children.size() == 2) + bit_part_sel = children[1]->clone(); + + if (children[0]->children[0]->type == AST_CONSTANT) + { + int id = children[0]->children[0]->integer; + int left = id2ast->children[1]->children[0]->integer; + int right = id2ast->children[1]->children[1]->integer; + bool valid_const_access = + (left <= id && id <= right) || + (right <= id && id <= left); + if (valid_const_access) + { + str = stringf("%s[%d]", str, id); + delete_children(); + range_valid = false; + id2ast = nullptr; + } + else + { + int width; + if (bit_part_sel) + { + // bit_part_sel->dumpAst(nullptr, "? "); + if (bit_part_sel->children.size() == 1) + width = 0; + else + width = bit_part_sel->children[0]->integer - + bit_part_sel->children[1]->integer; + bit_part_sel = nullptr; + } + else + { + width = id2ast->children[0]->children[0]->integer - + id2ast->children[0]->children[1]->integer; + } + width = abs(width) + 1; + + delete_children(); + + std::vector x_bits; + for (int i = 0; i < width; i++) + x_bits.push_back(RTLIL::State::Sx); + auto constant = AstNode::mkconst_bits(location, x_bits, false); + constant->cloneInto(*this); + } + } + else + { + std::stringstream sstr; + sstr << "$mem2reg_rd$" << str << "$" << RTLIL::encode_filename(*location.begin.filename) << ":" << location.begin.line << "$" << ast_autoidx(); + std::string id_addr = sstr.str() + "_ADDR", id_data = sstr.str() + "_DATA"; + + int mem_width, mem_size, addr_bits; + bool mem_signed = id2ast->is_signed; + id2ast->meminfo(mem_width, mem_size, addr_bits); + + auto wire_addr = std::make_unique(location, AST_WIRE, std::make_unique(location, AST_RANGE, mkconst_int(location, addr_bits-1, true), mkconst_int(location, 0, true))); + wire_addr->str = id_addr; + wire_addr->is_reg = true; + wire_addr->was_checked = true; + if (block) + wire_addr->set_attribute(ID::nosync, AstNode::mkconst_int(location, 1, false)); + while (wire_addr->simplify(true, 1, -1, false)) { } + mod->children.push_back(std::move(wire_addr)); + + auto wire_data = std::make_unique(location, AST_WIRE, std::make_unique(location, AST_RANGE, mkconst_int(location, mem_width-1, true), mkconst_int(location, 0, true))); + wire_data->str = id_data; + wire_data->is_reg = true; + wire_data->was_checked = true; + wire_data->is_signed = mem_signed; + if (block) + wire_data->set_attribute(ID::nosync, AstNode::mkconst_int(location, 1, false)); + while (wire_data->simplify(true, 1, -1, false)) { } + mod->children.push_back(std::move(wire_data)); + + auto assign_addr = std::make_unique(location, block ? AST_ASSIGN_EQ : AST_ASSIGN, std::make_unique(location, AST_IDENTIFIER), children[0]->children[0]->clone()); + assign_addr->children[0]->str = id_addr; + assign_addr->children[0]->was_checked = true; + + auto case_node = std::make_unique(location, AST_CASE, std::make_unique(location, AST_IDENTIFIER)); + case_node->children[0]->str = id_addr; + + for (int i = 0; i < mem_size; i++) { + if (children[0]->children[0]->type == AST_CONSTANT && int(children[0]->children[0]->integer) != i) + continue; + auto cond_node = std::make_unique(location, AST_COND, AstNode::mkconst_int(location, i, false, addr_bits), std::make_unique(location, AST_BLOCK)); + auto assign_reg = std::make_unique(location, AST_ASSIGN_EQ, std::make_unique(location, AST_IDENTIFIER), std::make_unique(location, AST_IDENTIFIER)); + assign_reg->children[0]->str = id_data; + assign_reg->children[0]->was_checked = true; + assign_reg->children[1]->str = stringf("%s[%d]", str, i); + cond_node->children[1]->children.push_back(std::move(assign_reg)); + case_node->children.push_back(std::move(cond_node)); + } + + std::vector x_bits; + for (int i = 0; i < mem_width; i++) + x_bits.push_back(RTLIL::State::Sx); + + auto cond_node = std::make_unique(location, AST_COND, std::make_unique(location, AST_DEFAULT), std::make_unique(location, AST_BLOCK)); + auto assign_reg = std::make_unique(location, AST_ASSIGN_EQ, std::make_unique(location, AST_IDENTIFIER), AstNode::mkconst_bits(location, x_bits, false)); + assign_reg->children[0]->str = id_data; + assign_reg->children[0]->was_checked = true; + cond_node->children[1]->children.push_back(std::move(assign_reg)); + case_node->children.push_back(std::move(cond_node)); + + // fixup on the full hierarchy below case_node + case_node->fixup_hierarchy_flags(true); + + if (block) + { + size_t assign_idx = 0; + while (assign_idx < block->children.size() && !block->children[assign_idx]->contains(this)) + assign_idx++; + log_assert(assign_idx < block->children.size()); + block->children.insert(block->children.begin()+assign_idx, std::move(case_node)); + block->children.insert(block->children.begin()+assign_idx, std::move(assign_addr)); + } + else + { + auto proc = std::make_unique(location, AST_ALWAYS, std::make_unique(location, AST_BLOCK, std::move(case_node))); + mod->children.push_back(std::move(proc)); + mod->children.push_back(std::move(assign_addr)); + mod->fixup_hierarchy_flags(); + } + + delete_children(); + range_valid = false; + id2ast = nullptr; + str = id_data; + } + + if (bit_part_sel) { + children.push_back(std::move(bit_part_sel)); + fixup_hierarchy_flags(); + } + + did_something = true; + } + + log_assert(id2ast == nullptr || mem2reg_set.count(id2ast) == 0); + + std::vector children_list; + for (auto& child : children) + children_list.push_back(child.get()); + + for (size_t i = 0; i < children_list.size(); i++) + if (children_list[i]->mem2reg_as_needed_pass2(mem2reg_set, mod, block, async_block)) + did_something = true; + + return did_something; +} + +// calculate memory dimensions +void AstNode::meminfo(int &mem_width, int &mem_size, int &addr_bits) +{ + log_assert(type == AST_MEMORY); + + mem_width = children[0]->range_left - children[0]->range_right + 1; + mem_size = children[1]->range_left - children[1]->range_right; + + if (mem_size < 0) + mem_size *= -1; + mem_size += min(children[1]->range_left, children[1]->range_right) + 1; + + addr_bits = 1; + while ((1 << addr_bits) < mem_size) + addr_bits++; +} + +bool AstNode::detect_latch(const std::string &var) +{ + switch (type) + { + case AST_ALWAYS: + for (auto &c : children) + { + switch (c->type) + { + case AST_POSEDGE: + case AST_NEGEDGE: + return false; + case AST_EDGE: + break; + case AST_BLOCK: + if (!c->detect_latch(var)) + return false; + break; + default: + log_abort(); + } + } + return true; + case AST_BLOCK: + for (auto &c : children) + if (!c->detect_latch(var)) + return false; + return true; + case AST_CASE: + { + bool r = true; + for (auto &c : children) { + if (c->type == AST_COND) { + if (c->children.at(1)->detect_latch(var)) + return true; + r = false; + } + if (c->type == AST_DEFAULT) { + if (c->children.at(0)->detect_latch(var)) + return true; + r = false; + } + } + return r; + } + case AST_ASSIGN_EQ: + case AST_ASSIGN_LE: + if (children.at(0)->type == AST_IDENTIFIER && + children.at(0)->children.empty() && children.at(0)->str == var) + return false; + return true; + default: + return true; + } +} + +bool AstNode::has_const_only_constructs() +{ + if (type == AST_WHILE || type == AST_REPEAT) + return true; + for (auto& child : children) + if (child->has_const_only_constructs()) + return true; + return false; +} + +bool AstNode::is_simple_const_expr() +{ + if (type == AST_IDENTIFIER) + return false; + for (auto& child : children) + if (!child->is_simple_const_expr()) + return false; + return true; +} + +bool AstNode::is_in_unconditional_init() { + if (current_always && current_always->type == AST_INITIAL) { + pool queue; + log_assert(current_always->children[0]->type == AST_BLOCK); + queue.insert(current_always->children[0].get()); + while (!queue.empty()) { + pool next_queue; + for (auto& n : queue) + for (auto& c : n->children) { + if (c.get() == this) + return true; + next_queue.insert(c.get()); + } + next_queue.swap(queue); + } + } + + return false; +} + +// helper function for AstNode::eval_const_function() +bool AstNode::replace_variables(std::map &variables, AstNode *fcall, bool must_succeed) +{ + if (type == AST_IDENTIFIER && variables.count(str)) { + int offset = variables.at(str).offset, width = variables.at(str).val.size(); + if (!children.empty()) { + if (children.size() != 1 || children.at(0)->type != AST_RANGE) { + if (!must_succeed) + return false; + input_error("Memory access in constant function is not supported\n%s: ...called from here.\n", + fcall->loc_string().c_str()); + } + if (!children.at(0)->replace_variables(variables, fcall, must_succeed)) + return false; + while (simplify(true, 1, -1, false)) { } + if (!children.at(0)->range_valid) { + if (!must_succeed) + return false; + input_error("Non-constant range\n%s: ... called from here.\n", + fcall->loc_string().c_str()); + } + offset = min(children.at(0)->range_left, children.at(0)->range_right); + width = min(std::abs(children.at(0)->range_left - children.at(0)->range_right) + 1, width); + } + offset -= variables.at(str).offset; + if (variables.at(str).range_swapped) + offset = -offset; + const RTLIL::Const &val = variables.at(str).val; + std::vector new_bits; + new_bits.reserve(width); + for (int i = 0; i < width; i++) + new_bits.push_back(val[offset+i]); + auto newNode = mkconst_bits(location, new_bits, variables.at(str).is_signed); + newNode->cloneInto(*this); + return true; + } + + for (auto &child : children) + if (!child->replace_variables(variables, fcall, must_succeed)) + return false; + return true; +} + +// attempt to statically evaluate a functions with all-const arguments +std::unique_ptr AstNode::eval_const_function(AstNode *fcall, bool must_succeed) +{ + std::map backup_scope = current_scope; + std::map variables; + auto block = std::make_unique(location, AST_BLOCK); + std::unique_ptr result = nullptr; + + size_t argidx = 0; + for (auto& child : children) + { + block->children.push_back(child->clone()); + } + block->set_in_param_flag(true); + std::vector> temporary_nodes; + + while (!block->children.empty()) + { + auto& stmt = block->children.front(); + +#if 0 + log("-----------------------------------\n"); + for (auto &it : variables) + log("%20s %40s\n", it.first, log_signal(it.second.val)); + stmt->dumpAst(nullptr, "stmt> "); +#endif + if (stmt->type == AST_WIRE) + { + while (stmt->simplify(true, 1, -1, false)) { } + if (!stmt->range_valid) { + if (!must_succeed) + goto finished; + stmt->input_error("Can't determine size of variable %s\n%s: ... called from here.\n", + stmt->str.c_str(), fcall->loc_string().c_str()); + } + AstNode::varinfo_t &variable = variables[stmt->str]; + int width = abs(stmt->range_left - stmt->range_right) + 1; + // if this variable has already been declared as an input, check the + // sizes match if it already had an explicit size + if (variable.arg && variable.explicitly_sized && variable.val.size() != width) { + input_error("Incompatible re-declaration of constant function wire %s.\n", stmt->str); + } + variable.val = RTLIL::Const(RTLIL::State::Sx, width); + variable.offset = stmt->range_swapped ? stmt->range_left : stmt->range_right; + variable.range_swapped = stmt->range_swapped; + variable.is_signed = stmt->is_signed; + variable.explicitly_sized = stmt->children.size() && + stmt->children.back()->type == AST_RANGE; + // identify the argument corresponding to this wire, if applicable + if (stmt->is_input && argidx < fcall->children.size()) { + variable.arg = fcall->children.at(argidx++).get(); + } + // load the constant arg's value into this variable + if (variable.arg) { + if (variable.arg->type == AST_CONSTANT) { + variable.val = variable.arg->bitsAsConst(width); + } else { + log_assert(variable.arg->type == AST_REALVALUE); + variable.val = variable.arg->realAsConst(width); + } + } + current_scope[stmt->str] = stmt.get(); + temporary_nodes.push_back(std::move(stmt)); + + block->children.erase(block->children.begin()); + continue; + } + + log_assert(variables.count(str) != 0); + + if (stmt->type == AST_LOCALPARAM) + { + while (stmt->simplify(true, 1, -1, false)) { } + + current_scope[stmt->str] = stmt.get(); + temporary_nodes.push_back(std::move(stmt)); + + block->children.erase(block->children.begin()); + continue; + } + + if (stmt->type == AST_ASSIGN_EQ) + { + if (stmt->children.at(0)->type == AST_IDENTIFIER && stmt->children.at(0)->children.size() != 0 && + stmt->children.at(0)->children.at(0)->type == AST_RANGE) + if (!stmt->children.at(0)->children.at(0)->replace_variables(variables, fcall, must_succeed)) + goto finished; + if (!stmt->children.at(1)->replace_variables(variables, fcall, must_succeed)) + goto finished; + while (stmt->simplify(true, 1, -1, false)) { } + + if (stmt->type != AST_ASSIGN_EQ) + continue; + + if (stmt->children.at(1)->type != AST_CONSTANT) { + if (!must_succeed) + goto finished; + stmt->input_error("Non-constant expression in constant function\n%s: ... called from here. X\n", + fcall->loc_string().c_str()); + } + + if (stmt->children.at(0)->type != AST_IDENTIFIER) { + if (!must_succeed) + goto finished; + stmt->input_error("Unsupported composite left hand side in constant function\n%s: ... called from here.\n", + fcall->loc_string().c_str()); + } + + if (!variables.count(stmt->children.at(0)->str)) { + if (!must_succeed) + goto finished; + stmt->input_error("Assignment to non-local variable in constant function\n%s: ... called from here.\n", + fcall->loc_string().c_str()); + } + + if (stmt->children.at(0)->children.empty()) { + variables[stmt->children.at(0)->str].val = stmt->children.at(1)->bitsAsConst(variables[stmt->children.at(0)->str].val.size()); + } else { + AstNode *range = stmt->children.at(0)->children.at(0).get(); + if (!range->range_valid) { + if (!must_succeed) + goto finished; + range->input_error("Non-constant range\n%s: ... called from here.\n", fcall->loc_string()); + } + int offset = min(range->range_left, range->range_right); + int width = std::abs(range->range_left - range->range_right) + 1; + varinfo_t &v = variables[stmt->children.at(0)->str]; + RTLIL::Const r = stmt->children.at(1)->bitsAsConst(v.val.size()); + for (int i = 0; i < width; i++) { + int index = i + offset - v.offset; + if (v.range_swapped) + index = -index; + v.val.set(index, r.at(i)); + } + } + + block->children.erase(block->children.begin()); + continue; + } + + if (stmt->type == AST_FOR) + { + stmt->type = AST_WHILE; + log_assert(stmt->children.size() > 2); + auto yoink0 = std::move(stmt->children.at(0)); + log_assert(stmt->children.size() > 2); + auto yoink2 = std::move(stmt->children.at(2)); + stmt->children.at(3)->children.push_back(std::move(yoink2)); + stmt->children.erase(stmt->children.begin() + 2); + stmt->children.erase(stmt->children.begin()); + block->children.insert(block->children.begin(), std::move(yoink0)); + log_assert(stmt->children.size() == 2); + continue; + } + + if (stmt->type == AST_WHILE) + { + auto cond = stmt->children.at(0)->clone(); + if (!cond->replace_variables(variables, fcall, must_succeed)) + goto finished; + cond->set_in_param_flag(true); + while (cond->simplify(true, 1, -1, false)) { } + + if (!cond->isConst()) { + if (!must_succeed) + goto finished; + stmt->input_error("Non-constant expression in constant function\n%s: ... called from here.\n", + fcall->loc_string().c_str()); + } + + if (cond->asBool()) { + block->children.insert(block->children.begin(), stmt->children.at(1)->clone()); + } else { + block->children.erase(block->children.begin()); + } + continue; + } + + if (stmt->type == AST_REPEAT) + { + auto num = stmt->children.at(0)->clone(); + if (!num->replace_variables(variables, fcall, must_succeed)) + goto finished; + num->set_in_param_flag(true); + while (num->simplify(true, 1, -1, false)) { } + + if (num->type != AST_CONSTANT) { + if (!must_succeed) + goto finished; + stmt->input_error("Non-constant expression in constant function\n%s: ... called from here.\n", + fcall->loc_string().c_str()); + } + + temporary_nodes.push_back(std::move(stmt)); + block->children.erase(block->children.begin()); + for (int i = 0; i < num->bitsAsConst().as_int(); i++) + block->children.insert(block->children.begin(), temporary_nodes.back()->children.at(1)->clone()); + + continue; + } + + if (stmt->type == AST_CASE) + { + auto expr = stmt->children.at(0)->clone(); + if (!expr->replace_variables(variables, fcall, must_succeed)) + goto finished; + expr->set_in_param_flag(true); + while (expr->simplify(true, 1, -1, false)) { } + + AstNode *sel_case = nullptr; + std::unique_ptr sel_case_copy = nullptr; + for (size_t i = 1; i < stmt->children.size(); i++) + { + bool found_match = false; + log_assert(stmt->children.at(i)->type == AST_COND || stmt->children.at(i)->type == AST_CONDX || stmt->children.at(i)->type == AST_CONDZ); + + if (stmt->children.at(i)->children.front()->type == AST_DEFAULT) { + sel_case = stmt->children.at(i)->children.back().get(); + continue; + } + + for (size_t j = 0; j+1 < stmt->children.at(i)->children.size() && !found_match; j++) + { + auto cond = stmt->children.at(i)->children.at(j)->clone(); + if (!cond->replace_variables(variables, fcall, must_succeed)) + goto finished; + + cond = std::make_unique(location, AST_EQ, expr->clone(), std::move(cond)); + cond->set_in_param_flag(true); + while (cond->simplify(true, 1, -1, false)) { } + + if (cond->type != AST_CONSTANT) { + if (!must_succeed) + goto finished; + stmt->input_error("Non-constant expression in constant function\n%s: ... called from here.\n", + fcall->loc_string().c_str()); + } + + found_match = cond->asBool(); + } + + if (found_match) { + sel_case = stmt->children.at(i)->children.back().get(); + break; + } + } + if (sel_case) + sel_case_copy = sel_case->clone(); + + block->children.erase(block->children.begin()); + if (sel_case_copy) + block->children.insert(block->children.begin(), std::move(sel_case_copy)); + continue; + } + + if (stmt->type == AST_BLOCK) + { + if (!stmt->str.empty()) + stmt->expand_genblock(stmt->str + "."); + auto* stmt_leaky = stmt.get(); + temporary_nodes.push_back(std::move(stmt)); + block->children.erase(block->children.begin()); + block->children.reserve(block->children.size() + stmt_leaky->children.size()); + block->children.insert(block->children.begin(), + std::make_move_iterator(stmt_leaky->children.begin()), + std::make_move_iterator(stmt_leaky->children.end())); + stmt_leaky->children.clear(); + block->fixup_hierarchy_flags(); + continue; + } + + // log("C\n"); + if (!must_succeed) + goto finished; + stmt->input_error("Unsupported language construct in constant function\n%s: ... called from here.\n", + fcall->loc_string().c_str()); + log_abort(); + } + + result = AstNode::mkconst_bits(location, variables.at(str).val.to_bits(), variables.at(str).is_signed); + +finished: + current_scope = backup_scope; + return result; +} + +void AstNode::allocateDefaultEnumValues() +{ + log_assert(type==AST_ENUM); + log_assert(children.size() > 0); + if (children.front()->attributes.count(ID::enum_base_type)) + return; // already elaborated + int last_enum_int = -1; + for (auto& node : children) { + log_assert(node->type==AST_ENUM_ITEM); + node->set_attribute(ID::enum_base_type, mkconst_str(node->location, str)); + for (size_t i = 0; i < node->children.size(); i++) { + switch (node->children[i]->type) { + case AST_NONE: + // replace with auto-incremented constant + node->children[i] = AstNode::mkconst_int(node->location, ++last_enum_int, true); + break; + case AST_CONSTANT: + // explicit constant (or folded expression) + // TODO: can't extend 'x or 'z item + last_enum_int = node->children[i]->integer; + break; + default: + // ignore ranges + break; + } + // TODO: range check + } + } +} + +bool AstNode::is_recursive_function() const +{ + std::set visited; + std::function visit = [&](const AstNode *node) { + if (visited.count(node)) + return node == this; + visited.insert(node); + if (node->type == AST_FCALL) { + auto it = current_scope.find(node->str); + if (it != current_scope.end() && visit(it->second)) + return true; + } + for (auto& child : node->children) { + if (visit(child.get())) + return true; + } + return false; + }; + + log_assert(type == AST_FUNCTION); + return visit(this); +} + +std::pair AstNode::get_tern_choice() +{ + if (!children[0]->isConst()) + return {}; + + bool found_sure_true = false; + bool found_maybe_true = false; + + if (children[0]->type == AST_CONSTANT) + for (auto &bit : children[0]->bits) { + if (bit == RTLIL::State::S1) + found_sure_true = true; + if (bit > RTLIL::State::S1) + found_maybe_true = true; + } + else + found_sure_true = children[0]->asReal(true) != 0; + + AstNode *choice = nullptr, *not_choice = nullptr; + if (found_sure_true) + choice = children[1].get(), not_choice = children[2].get(); + else if (!found_maybe_true) + choice = children[2].get(), not_choice = children[1].get(); + + return {choice, not_choice}; +} + +std::string AstNode::try_pop_module_prefix() const +{ + AstNode *current_scope_ast = (current_ast_mod == nullptr) ? current_ast : current_ast_mod; + size_t pos = str.find('.', 1); + if (str[0] == '\\' && pos != std::string::npos) { + std::string new_str = "\\" + str.substr(pos + 1); + if (current_scope.count(new_str)) { + std::string prefix = str.substr(0, pos); + auto it = current_scope_ast->attributes.find(ID::hdlname); + if ((it != current_scope_ast->attributes.end() && it->second->str == prefix.substr(1)) + || prefix == current_scope_ast->str) + return new_str; + } + } + return str; +} + +YOSYS_NAMESPACE_END diff --git a/chips/yosys/frontends/blif/CMakeLists.txt b/chips/yosys/frontends/blif/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..75f2e6356e28042a4ad4a3a8f69a7c1869f9ec72 --- /dev/null +++ b/chips/yosys/frontends/blif/CMakeLists.txt @@ -0,0 +1,8 @@ +yosys_frontend(blif + blifparse.cc + blifparse.h + DATA_DIR + include/frontends/blif + DATA_FILES + blifparse.h +) diff --git a/chips/yosys/frontends/blif/blifparse.cc b/chips/yosys/frontends/blif/blifparse.cc new file mode 100644 index 0000000000000000000000000000000000000000..3ef023e837184b15abb36703f9a5c7b9eeff53e0 --- /dev/null +++ b/chips/yosys/frontends/blif/blifparse.cc @@ -0,0 +1,706 @@ +/* + * yosys -- Yosys Open SYnthesis Suite + * + * Copyright (C) 2012 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#include "blifparse.h" + +YOSYS_NAMESPACE_BEGIN + +const int lut_input_plane_limit = 12; + +static bool read_next_line(char *&buffer, size_t &buffer_size, int &line_count, std::istream &f) +{ + string strbuf; + int buffer_len = 0; + buffer[0] = 0; + + while (1) + { + buffer_len += strlen(buffer + buffer_len); + while (buffer_len > 0 && (buffer[buffer_len-1] == ' ' || buffer[buffer_len-1] == '\t' || + buffer[buffer_len-1] == '\r' || buffer[buffer_len-1] == '\n')) + buffer[--buffer_len] = 0; + + if (buffer_size-buffer_len < 4096) { + buffer_size *= 2; + buffer = (char*)realloc(buffer, buffer_size); + } + + if (buffer_len == 0 || buffer[buffer_len-1] == '\\') { + if (buffer_len > 0 && buffer[buffer_len-1] == '\\') + buffer[--buffer_len] = 0; + line_count++; + if (!std::getline(f, strbuf)) + return false; + while (buffer_size-buffer_len < strbuf.size()+1) { + buffer_size *= 2; + buffer = (char*)realloc(buffer, buffer_size); + } + strcpy(buffer+buffer_len, strbuf.c_str()); + } else + return true; + } +} + +static std::pair wideports_split(std::string name) +{ + int pos = -1; + + if (name.empty() || name.back() != ']') + goto failed; + + for (int i = 0; i+1 < GetSize(name); i++) { + if (name[i] == '[') + pos = i; + else if (name[i] != '-' && (name[i] < '0' || name[i] > '9')) + pos = -1; + else if (name[i] == '-' && ((i != pos+1) || name[i+1] == ']')) + pos = -1; + else if (i == pos+2 && name[i] == '0' && name[i-1] == '-') + pos = -1; + else if (i == pos+1 && name[i] == '0' && name[i+1] != ']') + pos = -1; + } + + if (pos >= 0) + return std::pair("\\" + name.substr(0, pos), atoi(name.c_str() + pos+1)); + +failed: + return std::pair(std::string(), 0); +} + +static std::string blif_new_id(int autoidx_base, int &local_autoidx) +{ + return stringf("$blif$%d$%d", autoidx_base, local_autoidx++); +} + +void parse_blif(RTLIL::Design *design, std::istream &f, IdString dff_name, int autoidx_base, bool run_clean, bool sop_mode, bool wideports) +{ + RTLIL::Module *module = nullptr; + RTLIL::Const *lutptr = NULL; + RTLIL::Cell *sopcell = NULL; + RTLIL::Cell *lastcell = nullptr; + RTLIL::State lut_default_state = RTLIL::State::Sx; + std::string err_reason; + int blif_maxnum = 0, sopmode = -1; + int local_autoidx = 0; + + auto blif_wire = [&](const std::string &wire_name) -> Wire* + { + if (wire_name[0] == '$') + { + for (int i = 0; i+1 < GetSize(wire_name); i++) + { + if (wire_name[i] != '$') + continue; + + int len = 0; + while (i+len+1 < GetSize(wire_name) && '0' <= wire_name[i+len+1] && wire_name[i+len+1] <= '9') + len++; + + if (len > 0) { + string num_str = wire_name.substr(i+1, len); + int num = atoi(num_str.c_str()) & 0x0fffffff; + blif_maxnum = std::max(blif_maxnum, num); + } + } + } + + IdString wire_ref = design->twines().add(RTLIL::escape_id(wire_name)); + Wire *wire = module->wire(wire_ref); + + if (wire == nullptr) + wire = module->addWire(wire_ref); + + return wire; + }; + + dict *obj_attributes = nullptr; + dict *obj_parameters = nullptr; + + dict> wideports_cache; + + size_t buffer_size = 4096; + char *buffer = (char*)malloc(buffer_size); + int line_count = 0; + + while (1) + { + if (!read_next_line(buffer, buffer_size, line_count, f)) { + if (module != nullptr) + goto error; + free(buffer); + return; + } + + continue_without_read: + if (buffer[0] == '#') + continue; + + if (buffer[0] == '.') + { + if (lutptr) { + for (auto bit : *lutptr) + if (bit == RTLIL::State::Sx) + bit = lut_default_state; + lutptr = NULL; + lut_default_state = RTLIL::State::Sx; + } + + if (sopcell) { + sopcell = NULL; + sopmode = -1; + } + + char *cmd = strtok(buffer, " \t\r\n"); + + if (!strcmp(cmd, ".model")) { + if (module != nullptr) + goto error; + module = new RTLIL::Module(design); + lastcell = nullptr; + char *name = strtok(NULL, " \t\r\n"); + if (name == nullptr) + goto error; + module->name = design->twines().add(RTLIL::escape_id(name)); + obj_attributes = &module->attributes; + obj_parameters = nullptr; + if (design->module(module->name)) + log_error("Duplicate definition of module %s in line %d!\n", module, line_count); + design->add(module); + continue; + } + + if (module == nullptr) + goto error; + + if (!strcmp(cmd, ".blackbox")) + { + module->attributes[ID::blackbox] = RTLIL::Const(1); + continue; + } + + if (!strcmp(cmd, ".end")) + { + for (auto &wp : wideports_cache) + { + auto name = wp.first; + int width = wp.second.first; + bool isinput = wp.second.second; + + RTLIL::Wire *wire = module->addWire(name, width); + wire->port_input = isinput; + wire->port_output = !isinput; + + for (int i = 0; i < width; i++) { + std::string other_name = design->twines().str(name) + stringf("[%d]", i); + IdString other_ref = design->twines().find(other_name); + RTLIL::Wire *other_wire = module->wire(other_ref); + if (other_wire) { + other_wire->port_input = false; + other_wire->port_output = false; + if (isinput) + module->connect(other_wire, SigSpec(wire, i)); + else + module->connect(SigSpec(wire, i), other_wire); + } + } + } + + module->fixup_ports(); + wideports_cache.clear(); + + if (run_clean) + { + Const buffer_lut(vector({State::S0, State::S1})); + vector remove_cells; + + for (auto cell : module->cells()) + if (cell->type == ID($lut) && cell->getParam(ID::LUT) == buffer_lut) { + module->connect(cell->getPort(ID::Y), cell->getPort(ID::A)); + remove_cells.push_back(cell); + } + + for (auto cell : remove_cells) + module->remove(cell); + + Wire *true_wire = module->wire(ID::lookup("$true")); + Wire *false_wire = module->wire(ID::lookup("$false")); + Wire *undef_wire = module->wire(ID::lookup("$undef")); + + if (true_wire != nullptr) + module->rename(true_wire, stringf("$true$%d", ++blif_maxnum)); + + if (false_wire != nullptr) + module->rename(false_wire, stringf("$false$%d", ++blif_maxnum)); + + if (undef_wire != nullptr) + module->rename(undef_wire, stringf("$undef$%d", ++blif_maxnum)); + + design->twines().ensure_autoidx(blif_maxnum+1); + blif_maxnum = 0; + } + + module = nullptr; + lastcell = nullptr; + obj_attributes = nullptr; + obj_parameters = nullptr; + continue; + } + + if (!strcmp(cmd, ".area") || !strcmp(cmd, ".delay") || !strcmp(cmd, ".wire_load_slope") || !strcmp(cmd, ".wire") || + !strcmp(cmd, ".input_arrival") || !strcmp(cmd, ".default_input_arrival") || !strcmp(cmd, ".output_required") || + !strcmp(cmd, ".default_output_required") || !strcmp(cmd, ".input_drive") || !strcmp(cmd, ".default_input_drive") || + !strcmp(cmd, ".max_input_load") || !strcmp(cmd, ".default_max_input_load") || !strcmp(cmd, ".output_load") || + !strcmp(cmd, ".default_output_load")) + { + log_warning("Blif delay constraints (%s) are not supported.\n", cmd); + continue; + } + + if (!strcmp(cmd, ".inputs") || !strcmp(cmd, ".outputs")) + { + char *p; + while ((p = strtok(NULL, " \t\r\n")) != NULL) + { + std::string wire_name_str = stringf("\\%s", p); + IdString wire_ref = design->twines().add(wire_name_str); + RTLIL::Wire *wire = module->wire(wire_ref); + if (wire == nullptr) + wire = module->addWire(wire_ref); + if (!strcmp(cmd, ".inputs")) + wire->port_input = true; + else + wire->port_output = true; + + if (wideports) { + std::pair wp = wideports_split(p); + if (!wp.first.empty() && wp.second >= 0) { + IdString wp_ref = design->twines().add(wp.first); + wideports_cache[wp_ref].first = std::max(wideports_cache[wp_ref].first, wp.second + 1); + wideports_cache[wp_ref].second = !strcmp(cmd, ".inputs"); + } + } + } + obj_attributes = nullptr; + obj_parameters = nullptr; + continue; + } + + if (!strcmp(cmd, ".cname")) + { + char *p = strtok(NULL, " \t\r\n"); + if (p == NULL) + goto error; + + if(lastcell == nullptr || module == nullptr) + { + err_reason = stringf("No primitive object to attach .cname %s.", p); + goto error_with_reason; + } + + module->rename(lastcell, RTLIL::escape_id(p)); + continue; + } + + if (!strcmp(cmd, ".attr") || !strcmp(cmd, ".param")) { + char *n = strtok(NULL, " \t\r\n"); + char *v = strtok(NULL, "\r\n"); + IdString id_n = design->twines().add(RTLIL::escape_id(n)); + Const const_v; + if (v[0] == '"') { + std::string str(v+1); + if (str.back() == '"') + str.resize(str.size()-1); + const_v = Const(str); + } else { + int n = strlen(v); + Const::Builder const_v_builder(n); + for (int i = 0; i < n; i++) + const_v_builder.push_back(v[n-i-1] != '0' ? State::S1 : State::S0); + const_v = const_v_builder.build(); + } + if (!strcmp(cmd, ".attr")) { + if (obj_attributes == nullptr) { + err_reason = stringf("No object to attach .attr too."); + goto error_with_reason; + } + (*obj_attributes)[id_n] = const_v; + } else { + if (obj_parameters == nullptr) { + err_reason = stringf("No object to attach .param too."); + goto error_with_reason; + } + (*obj_parameters)[id_n] = const_v; + } + continue; + } + + if (!strcmp(cmd, ".latch")) + { + char *d = strtok(NULL, " \t\r\n"); + char *q = strtok(NULL, " \t\r\n"); + char *edge = strtok(NULL, " \t\r\n"); + char *clock = strtok(NULL, " \t\r\n"); + char *init = strtok(NULL, " \t\r\n"); + RTLIL::Cell *cell = nullptr; + + if (clock == nullptr && edge != nullptr) { + init = edge; + edge = nullptr; + } + + if (init != nullptr && (init[0] == '0' || init[0] == '1')) + blif_wire(q)->attributes[ID::init] = Const(init[0] == '1' ? 1 : 0, 1); + + if (clock == nullptr) + goto no_latch_clock; + + if (!strcmp(edge, "re")) + cell = module->addDffGate(blif_new_id(autoidx_base, local_autoidx), blif_wire(clock), blif_wire(d), blif_wire(q)); + else if (!strcmp(edge, "fe")) + cell = module->addDffGate(blif_new_id(autoidx_base, local_autoidx), blif_wire(clock), blif_wire(d), blif_wire(q), false); + else if (!strcmp(edge, "ah")) + cell = module->addDlatchGate(blif_new_id(autoidx_base, local_autoidx), blif_wire(clock), blif_wire(d), blif_wire(q)); + else if (!strcmp(edge, "al")) + cell = module->addDlatchGate(blif_new_id(autoidx_base, local_autoidx), blif_wire(clock), blif_wire(d), blif_wire(q), false); + else { + no_latch_clock: + if (dff_name == IdString::Null) { + cell = module->addFfGate(blif_new_id(autoidx_base, local_autoidx), blif_wire(d), blif_wire(q)); + } else { + cell = module->addCell(blif_new_id(autoidx_base, local_autoidx), dff_name); + cell->setPort(ID::D, blif_wire(d)); + cell->setPort(ID::Q, blif_wire(q)); + } + } + + lastcell = cell; + obj_attributes = &cell->attributes; + obj_parameters = &cell->parameters; + continue; + } + + if (!strcmp(cmd, ".gate") || !strcmp(cmd, ".subckt")) + { + char *p = strtok(NULL, " \t\r\n"); + if (p == NULL) + goto error; + + IdString celltype = design->twines().add(RTLIL::escape_id(p)); + RTLIL::Cell *cell = module->addCell(blif_new_id(autoidx_base, local_autoidx), celltype); + RTLIL::Module *cell_mod = design->module(cell->type); + + dict> cell_wideports_cache; + + while ((p = strtok(NULL, " \t\r\n")) != NULL) + { + char *q = strchr(p, '='); + if (q == NULL || !q[0]) + goto error; + *(q++) = 0; + + if (wideports) { + std::pair wp = wideports_split(p); + if (wp.first.empty()) { + IdString port_ref = design->twines().add(RTLIL::escape_id(p)); + cell->setPort(port_ref, *q ? blif_wire(q) : SigSpec()); + } else { + IdString wp_ref = design->twines().add(wp.first); + cell_wideports_cache[wp_ref][wp.second] = blif_wire(q); + } + } else { + IdString port_ref = design->twines().add(RTLIL::escape_id(p)); + cell->setPort(port_ref, *q ? blif_wire(q) : SigSpec()); + } + } + + for (auto &it : cell_wideports_cache) + { + int width = 0; + int offset = 0; + bool upto = false; + for (auto &b : it.second) + width = std::max(width, b.first + 1); + + if (cell_mod) { + Wire *cell_port = cell_mod->wire(it.first); + if (cell_port && (cell_port->port_input || cell_port->port_output)) { + offset = cell_port->start_offset; + upto = cell_port->upto; + width = cell_port->width; + } + } + + SigSpec sig; + + for (int i = 0; i < width; i++) { + int idx = offset + (upto ? width - 1 - i: i); + if (it.second.count(idx)) + sig.append(it.second.at(idx)); + else + sig.append(module->addWire(blif_new_id(autoidx_base, local_autoidx))); + } + + cell->setPort(it.first, sig); + } + + lastcell = cell; + obj_attributes = &cell->attributes; + obj_parameters = &cell->parameters; + continue; + } + + obj_attributes = nullptr; + obj_parameters = nullptr; + + if (!strcmp(cmd, ".barbuf") || !strcmp(cmd, ".conn")) + { + char *p = strtok(NULL, " \t\r\n"); + if (p == NULL) + goto error; + + char *q = strtok(NULL, " \t\r\n"); + if (q == NULL) + goto error; + + module->connect(blif_wire(q), blif_wire(p)); + continue; + } + + if (!strcmp(cmd, ".gateinit")) + { + char *p = strtok(NULL, " \t\r\n"); + if (p == NULL) + goto error; + + char *n = strtok(p, "="); + char *init = strtok(NULL, "="); + if (n == NULL || init == NULL) + goto error; + if (init[0] != '0' && init[0] != '1') + goto error; + + if (blif_wire(n)->attributes.find(ID::init) == blif_wire(n)->attributes.end()) + blif_wire(n)->attributes.emplace(ID::init, Const(init[0] == '1' ? 1 : 0, 1)); + else + blif_wire(n)->attributes[ID::init] = Const(init[0] == '1' ? 1 : 0, 1); + + continue; + } + + if (!strcmp(cmd, ".names")) + { + char *p; + RTLIL::SigSpec input_sig, output_sig; + while ((p = strtok(NULL, " \t\r\n")) != NULL) + input_sig.append(blif_wire(p)); + output_sig = input_sig.extract(input_sig.size()-1, 1); + input_sig = input_sig.extract(0, input_sig.size()-1); + + if (input_sig.size() == 0) + { + RTLIL::State state = RTLIL::State::Sa; + while (1) { + if (!read_next_line(buffer, buffer_size, line_count, f)) + goto error; + for (int i = 0; buffer[i]; i++) { + if (buffer[i] == ' ' || buffer[i] == '\t') + continue; + if (i == 0 && buffer[i] == '.') + goto finished_parsing_constval; + if (buffer[i] == '0') { + if (state == RTLIL::State::S1) + goto error; + state = RTLIL::State::S0; + continue; + } + if (buffer[i] == '1') { + if (state == RTLIL::State::S0) + goto error; + state = RTLIL::State::S1; + continue; + } + goto error; + } + } + + finished_parsing_constval: + if (state == RTLIL::State::Sa) + state = RTLIL::State::S0; + if (output_sig.as_wire()->name == ID($undef)) + state = RTLIL::State::Sx; + module->connect(RTLIL::SigSig(output_sig, state)); + goto continue_without_read; + } + + if (sop_mode) + { + sopcell = module->addCell(blif_new_id(autoidx_base, local_autoidx), ID($sop)); + sopcell->parameters[ID::WIDTH] = RTLIL::Const(input_sig.size()); + sopcell->parameters[ID::DEPTH] = 0; + sopcell->parameters[ID::TABLE] = RTLIL::Const(); + sopcell->setPort(ID::A, input_sig); + sopcell->setPort(ID::Y, output_sig); + sopmode = -1; + lastcell = sopcell; + } + else if (input_sig.size() > lut_input_plane_limit) + { + err_reason = stringf("names' input plane must have fewer than %d signals.", lut_input_plane_limit + 1); + goto error_with_reason; + } + else + { + RTLIL::Cell *cell = module->addCell(blif_new_id(autoidx_base, local_autoidx), ID($lut)); + cell->parameters[ID::WIDTH] = RTLIL::Const(input_sig.size()); + cell->parameters[ID::LUT] = RTLIL::Const(RTLIL::State::Sx, 1 << input_sig.size()); + cell->setPort(ID::A, input_sig); + cell->setPort(ID::Y, output_sig); + lutptr = &cell->parameters.at(ID::LUT); + lut_default_state = RTLIL::State::Sx; + lastcell = cell; + } + continue; + } + + goto error; + } + + if (lutptr == NULL && sopcell == NULL) + goto error; + + char *input = strtok(buffer, " \t\r\n"); + char *output = strtok(NULL, " \t\r\n"); + + if (input == NULL || output == NULL || (strcmp(output, "0") && strcmp(output, "1"))) + goto error; + + int input_len = strlen(input); + + if (sopcell) + { + log_assert(sopcell->parameters[ID::WIDTH].as_int() == input_len); + sopcell->parameters[ID::DEPTH] = sopcell->parameters[ID::DEPTH].as_int() + 1; + + Const::Builder table_bits_builder(input_len * 2); + for (int i = 0; i < input_len; i++) + switch (input[i]) { + case '0': + table_bits_builder.push_back(State::S1); + table_bits_builder.push_back(State::S0); + break; + case '1': + table_bits_builder.push_back(State::S0); + table_bits_builder.push_back(State::S1); + break; + default: + table_bits_builder.push_back(State::S0); + table_bits_builder.push_back(State::S0); + break; + } + sopcell->parameters[ID::TABLE].append(table_bits_builder.build()); + + if (sopmode == -1) { + sopmode = (*output == '1'); + if (!sopmode) { + SigSpec outnet = sopcell->getPort(ID::Y); + SigSpec tempnet = module->addWire(blif_new_id(autoidx_base, local_autoidx)); + module->addNotGate(blif_new_id(autoidx_base, local_autoidx), tempnet, outnet); + sopcell->setPort(ID::Y, tempnet); + } + } else + log_assert(sopmode == (*output == '1')); + } + + if (lutptr) + { + if (input_len > lut_input_plane_limit) + goto error; + + for (int i = 0; i < (1 << input_len); i++) { + for (int j = 0; j < input_len; j++) { + char c1 = input[j]; + if (c1 != '-') { + char c2 = (i & (1 << j)) != 0 ? '1' : '0'; + if (c1 != c2) + goto try_next_value; + } + } + log_assert(i < lutptr->size()); + lutptr->set(i, !strcmp(output, "0") ? RTLIL::State::S0 : RTLIL::State::S1); + try_next_value:; + } + + lut_default_state = !strcmp(output, "0") ? RTLIL::State::S1 : RTLIL::State::S0; + } + } + + return; + +error: + log_error("Syntax error in line %d!\n", line_count); +error_with_reason: + log_error("Syntax error in line %d: %s\n", line_count, err_reason); +} + +struct BlifFrontend : public Frontend { + BlifFrontend() : Frontend("blif", "read BLIF file") { } + void help() override + { + // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| + log("\n"); + log(" read_blif [options] [filename]\n"); + log("\n"); + log("Load modules from a BLIF file into the current design.\n"); + log("\n"); + log(" -sop\n"); + log(" Create $sop cells instead of $lut cells\n"); + log("\n"); + log(" -wideports\n"); + log(" Merge ports that match the pattern 'name[int]' into a single\n"); + log(" multi-bit port 'name'.\n"); + log("\n"); + } + void execute(std::istream *&f, std::string filename, std::vector args, RTLIL::Design *design) override + { + bool sop_mode = false; + bool wideports = false; + + log_header(design, "Executing BLIF frontend.\n"); + + size_t argidx; + for (argidx = 1; argidx < args.size(); argidx++) { + std::string arg = args[argidx]; + if (arg == "-sop") { + sop_mode = true; + continue; + } + if (arg == "-wideports") { + wideports = true; + continue; + } + break; + } + extra_args(f, filename, args, argidx); + + parse_blif(design, *f, IdString::Null, design->twines().next_autoidx(), true, sop_mode, wideports); + } +} BlifFrontend; + +YOSYS_NAMESPACE_END