aboutsummaryrefslogtreecommitdiffstats
path: root/misc/yosysjs/demo01.html
blob: 3f9f737e908c51b37ccbe51f8549943bf75bc1c7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
<html><head>
	<title>YosysJS Example Application #01</title>
	<script type="text/javascript" src="yosysjs.js"></script>
</head><body onload="document.getElementById('command').focus()">
	<h1>YosysJS Example Application #01</h1>
	<table width="100%"><tr><td><div id="tabs"></div></td><td align="right"><tt>[ <span onclick="load_example()">load example</span> ]</tt></td></tr></table>
	<svg id="svg" style="display: none; position: absolute; padding: 10px; width: calc(100% - 40px); height: 480px;"></svg>
	<div><textarea id="output" style="width: 100%; height: 500px"></textarea></div>
	<div id="wait" style="display: block"><br/><b><span id="waitmsg">Loading...</span></b></div>
	<div id="input" style="display: none"><form onsubmit="window.setTimeout(run_command); return false"><br/><tt><span id="prompt">
			</span></tt><input id="command" type="text" onkeydown="history(event)" style="font-family: monospace; font-weight: bold;" size="100"></form></div>
	<script type='text/javascript'>
		function print_output(text) {
			var el = document.getElementById('output');
			el.value += text + "\n";
		}

		YosysJS.load_viz();
		var ys = YosysJS.create("", function() {
			print_output(ys.print_buffer);

			document.getElementById('wait').style.display = 'none';
			document.getElementById('input').style.display = 'block';
			document.getElementById('waitmsg').textContent = 'Waiting for yosys.js...';
			document.getElementById('prompt').textContent = ys.prompt();

			update_tabs();
		});

		ys.echo = true;

		var history_log = [];
		var history_index = 0;
		var history_bak = "";

		function history(ev) {
			if (ev.keyCode == 38) {
				el = document.getElementById('command');
				if (history_index == history_log.length)
					history_bak = el.value
				if (history_index > 0)
					el.value = history_log[--history_index];
			}
			if (ev.keyCode == 40) {
				if (history_index < history_log.length) {
					el = document.getElementById('command');
					if (++history_index < history_log.length)
						el.value = history_log[history_index];
					else
						el.value = history_bak;
				}
			}
		}

		var current_file = "";
		var console_messages = "";
		var svg_cache = { };

		function update_tabs() {
			var f, html = "", flist = ys.read_dir('.');
			if (current_file == "") {
				html += '<tt>[ <b>Console</b>';
			} else {
				html += '<tt>[ <span onclick="open_file(\'\')">Console</span>';
			}
			for (i in flist) {
				f = flist[i]
				if (f == "." || f == "..")
					continue;
				if (current_file == f) {
					html += ' | <b>' + f + '</b>';
				} else {
					html += ' | <span onclick="open_file(\'' + f + '\')">' + f + '</span>';
				}
			}
			html += ' | <span onclick="open_file(prompt(\'Filename:\'))">new file</span> ]</tt>';
			document.getElementById('tabs').innerHTML = html;
			if (current_file == "" || /\.dot$/.test(current_file)) {
				var element = document.getElementById('output');
				element.readOnly = true;
				element.scrollTop = element.scrollHeight; // focus on bottom
				document.getElementById('command').focus();
			} else {
				document.getElementById('output').readOnly = false;
				document.getElementById('output').focus();
			}
		}

		function open_file(filename)
		{
			if (current_file == "")
				console_messages = document.getElementById('output').value;
			else if (!/\.dot$/.test(current_file))
				ys.write_file(current_file, document.getElementById('output').value);

			if (filename == "") {
				document.getElementById('output').value = console_messages;
			} else {
				try {
					document.getElementById('output').value = ys.read_file(filename);
				} catch (e) {
					document.getElementById('output').value = "";
					ys.write_file(filename, document.getElementById('output').value);
				}
			}

			if (/\.dot$/.test(filename)) {
				dot = document.getElementById('output').value;
				YosysJS.dot_into_svg(dot, 'svg');
				document.getElementById('svg').style.display = 'block';
				document.getElementById('output').value = '';
			} else {
				document.getElementById('svg').innerHTML = '';
				document.getElementById('svg').style.display = 'none';
			}

			current_file = filename;
			update_tabs()
		}

		function startup() {
		}

		function load_example() {
			open_file('')

			var txt = "";
			txt += "// a simple yosys.js example. run \"script example.ys\".\n";
			txt += "\n";
			txt += "module example(input clk, input rst, input inc, output reg [3:0] cnt);\n";
			txt += "  always @(posedge clk) begin\n";
			txt += "    if (rst)\n";
			txt += "      cnt <= 0;\n";
			txt += "    else if (inc)\n";
			txt += "      cnt <= cnt + 1;\n";
			txt += "  end\n";
			txt += "endmodule\n";
			txt += "\n";
			ys.write_file('example.v', txt);

			var txt = "";
			txt += "# a simple yosys.js example. run \"script example.ys\".\n";
			txt += "\n";
			txt += "design -reset\n";
			txt += "read_verilog example.v\n";
			txt += "proc\n";
			txt += "opt\n";
			txt += "show\n";
			txt += "\n";
			ys.write_file('example.ys', txt);

			open_file('example.ys')
			document.getElementById('command').focus();
		}

		function run_command() {
			var cmd = document.getElementById('command').value;
			document.getElementById('command').value = '';
			if (history_log.length == 0 || history_log[history_log.length-1] != cmd)
				history_log.push(cmd);
			history_index = history_log.length;

			var show_dot_before = "";
			try { show_dot_before = ys.read_file('show.dot'); } catch (e) { }

			open_file('');

			document.getElementById('wait').style.display = 'block';
			document.getElementById('input').style.display = 'none';

			function run_command_bh() {
				try {
					ys.run(cmd);
				} catch (e) {
					ys.write('Caught JavaScript exception. (see JavaScript console for details.)');
					console.log(e);
				}
				print_output(ys.print_buffer);

				document.getElementById('wait').style.display = 'none';
				document.getElementById('input').style.display = 'block';
				document.getElementById('prompt').textContent = ys.prompt();

				var show_dot_after = "";
				try { show_dot_after = ys.read_file('show.dot'); } catch (e) { }

				if (show_dot_before != show_dot_after)
					open_file('show.dot');

				update_tabs();
			}

			window.setTimeout(run_command_bh, 50);
			return false;
		}
	</script>
</body></html>
s="nb">{itemize} \item Any constant value of arbitrary bit-width \\ \null\hskip1em For example: \lstinline[language=Verilog]{1337, 16'b0000010100111001, 1'b1, 1'bx} \item All bits of a wire or a selection of bits from a wire \\ \null\hskip1em For example: \lstinline[language=Verilog]{mywire, mywire[24], mywire[15:8]} \item Concatenations of the above \\ \null\hskip1em For example: \lstinline[language=Verilog]|{16'd1337, mywire[15:8]}| \end{itemize} The RTLIL::SigSpec data type is used to represent signals. 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. \subsection{RTLIL::Process} \label{sec:rtlil_process} When a high-level HDL frontend processes behavioural code it splits it up into data path logic (e.g.~the expression {\tt a + b} is replaced by the output of an adder that takes {\tt a} and {\tt b} as inputs) and an RTLIL::Process that models the control logic of the behavioural code. Let's consider a simple example: \begin{lstlisting}[numbers=left,frame=single,language=Verilog] 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 \end{lstlisting} 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: \begin{lstlisting}[numbers=left,frame=single,language=rtlil] 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 \end{lstlisting} This RTLIL::Process contains two RTLIL::SyncRule objects, two RTLIL::SwitchRule objects and five RTLIL::CaseRule objects. The wire {\tt \$0\textbackslash{}q[0:0]} is an automatically created wire that holds the next value of {\tt \textbackslash{}q}. The lines $2 \dots 12$ describe how {\tt \$0\textbackslash{}q[0:0]} should be calculated. The lines $13 \dots 16$ describe how the value of {\tt \$0\textbackslash{}q[0:0]} is used to update {\tt \textbackslash{}q}. An RTLIL::Process is a container for zero or more RTLIL::SyncRule objects and exactly one RTLIL::CaseRule object, which is called the {\it 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 {\tt 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 \dots 12$ are the root case. Here {\tt \$0\textbackslash{}q[0:0]} is first assigned the old value {\tt \textbackslash{}q} as default value (line 2). The root case also contains an RTLIL::SwitchRule object (lines $3 \dots 12$). Such an object is very similar to the C {\tt switch} statement as it uses a control signal ({\tt \textbackslash{}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\footnote{The syntax {\tt 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'').} for {\tt \textbackslash{}reset == 1} that causes {\tt \$0\textbackslash{}q[0:0]} to be set (lines 4 and 5) and a default case that in turn contains a switch that sets {\tt \$0\textbackslash{}q[0:0]} to the value of {\tt \textbackslash{}d} if {\tt \textbackslash{}enable} is active (lines $6 \dots 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 {\tt parallel\_case} attribute allows passes to assume that no more than one case will match, and {\tt 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 \dots 16$ then cause {\tt \textbackslash{}q} to be updated whenever there is a positive clock edge on {\tt \textbackslash{}clock} or {\tt \textbackslash{}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 {\tt proc\_arst} pass. This pass transforms the above example to the following RTLIL::Process: \begin{lstlisting}[numbers=left,frame=single,language=rtlil] 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 \end{lstlisting} This pass has transformed the outer RTLIL::SwitchRule into a modified RTLIL::SyncRule object for the {\tt \textbackslash{}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: \begin{lstlisting}[numbers=left,frame=single,language=rtlil] 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 \end{lstlisting} Different combinations of passes may yield different results. Note that {\tt \$adff} and {\tt \$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 {\tt proc} pass calls a series of other passes that together perform this conversion in a way that is suitable for most synthesis tasks. \subsection{RTLIL::Memory} \label{sec:rtlil_memory} For every array (memory) in the HDL code an RTLIL::Memory object is created. A memory object has the following properties: \begin{itemize} \item The memory name \item A list of attributes \item The width of an addressable word \item The size of the memory in number of words \end{itemize} All read accesses to the memory are transformed to {\tt \$memrd} cells and all write accesses to {\tt \$memwr} cells by the language frontend. These cells consist of independent read- and write-ports to the memory. Memory initialization is transformed to {\tt \$meminit} cells by the language frontend. The \B{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 {\tt \$memrd} and {\tt \$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 {\tt \$memrd} and {\tt \$memwr} cells to multiport memory blocks after resource sharing is completed. The {\tt 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 {\tt \$mem} cells). See Sec.~\ref{sec:memcells} for details about the memory cell types. \section{Command Interface and Synthesis Scripts} Yosys reads and processes commands from synthesis scripts, command line arguments and an interactive command prompt. Yosys commands consist of a command name and an optional whitespace separated list of arguments. Commands are terminated using the newline character or a semicolon ({\tt ;}). Empty lines and lines starting with the hash sign ({\tt \#}) are ignored. See Sec.~\ref{sec:typusecase} for an example synthesis script. The command {\tt help} can be used to access the command reference manual. Most commands can operate not only on the entire design but also specifically on {\it selected} parts of the design. For example the command {\tt dump} will print all selected objects in the current design while {\tt dump foobar} will only print the module {\tt foobar} and {\tt dump *} will print the entire design regardless of the current selection. The selection mechanism is very powerful. For example the command {\tt dump */t:\$add \%x:+[A] */w:* \%i} will print all wires that are connected to the \B{A} port of a {\tt \$add} cell. Detailed documentation of the select framework can be found in the command reference for the {\tt select} command. \section{Source Tree and Build System} The Yosys source tree is organized into the following top-level directories: \begin{itemize} \item {\tt backends/} \\ This directory contains a subdirectory for each of the backend modules. \item {\tt frontends/} \\ This directory contains a subdirectory for each of the frontend modules. \item {\tt kernel/} \\ This directory contains all the core functionality of Yosys. This includes the functions and definitions for working with the RTLIL data structures ({\tt rtlil.h} and {\tt rtlil.cc}), the main() function ({\tt driver.cc}), the internal framework for generating log messages ({\tt log.h} and {\tt log.cc}), the internal framework for registering and calling passes ({\tt register.h} and {\tt register.cc}), some core commands that are not really passes ({\tt select.cc}, {\tt show.cc}, \dots) and a couple of other small utility libraries. \item {\tt passes/} \\ This directory contains a subdirectory for each pass or group of passes. For example as of this writing the directory {\tt passes/opt/} contains the code for seven passes: {\tt opt}, {\tt opt\_expr}, {\tt opt\_muxtree}, {\tt opt\_reduce}, {\tt opt\_rmdff}, {\tt opt\_rmunused} and {\tt opt\_merge}. \item {\tt techlibs/} \\ This directory contains simulation models and standard implementations for the cells from the internal cell library. \item {\tt tests/} \\ This directory contains a couple of test cases. Most of the smaller tests are executed automatically when {\tt make test} is called. The larger tests must be executed manually. Most of the larger tests require downloading external HDL source code and/or external tools. The tests range from comparing simulation results of the synthesized design to the original sources to logic equivalence checking of entire CPU cores. \end{itemize} \begin{sloppypar} The top-level Makefile includes {\tt frontends/*/Makefile.inc}, {\tt passes/*/Makefile.inc} and {\tt backends/*/Makefile.inc}. So when extending Yosys it is enough to create a new directory in {\tt frontends/}, {\tt passes/} or {\tt backends/} with your sources and a {\tt Makefile.inc}. 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. \end{sloppypar} Good starting points for reading example source code to learn how to write passes are {\tt passes/opt/opt\_rmdff.cc} and {\tt passes/opt/opt\_merge.cc}. See the top-level README file for a quick {\it Getting Started} guide and build instructions. The Yosys build is based solely on Makefiles. Users of the Qt Creator IDE can generate a QT Creator project file using {\tt 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.