aboutsummaryrefslogtreecommitdiffstats
path: root/passes/fsm/fsm_detect.cc
blob: a1c8067b47b6f8b7a35a95af48372d8ad89af827 (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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
/*
 *  yosys -- Yosys Open SYnthesis Suite
 *
 *  Copyright (C) 2012  Clifford Wolf <clifford@clifford.at>
 *
 *  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 "kernel/log.h"
#include "kernel/register.h"
#include "kernel/sigtools.h"
#include "kernel/consteval.h"
#include "kernel/celltypes.h"
#include "fsmdata.h"

USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN

static RTLIL::Module *module;
static SigMap assign_map;
typedef std::pair<RTLIL::Cell*, RTLIL::IdString> sig2driver_entry_t;
static SigSet<sig2driver_entry_t> sig2driver, sig2user;
static std::set<RTLIL::Cell*> muxtree_cells;
static SigPool sig_at_port;

static bool check_state_mux_tree(RTLIL::SigSpec old_sig, RTLIL::SigSpec sig, pool<Cell*> &recursion_monitor, dict<RTLIL::SigSpec, bool> &mux_tree_cache)
{
	if (mux_tree_cache.find(sig) != mux_tree_cache.end())
		return mux_tree_cache.at(sig);

	if (sig.is_fully_const() || old_sig == sig) {
ret_true:
		mux_tree_cache[sig] = true;
		return true;
	}

	if (sig_at_port.check_any(assign_map(sig))) {
ret_false:
		mux_tree_cache[sig] = false;
		return false;
	}

	std::set<sig2driver_entry_t> cellport_list;
	sig2driver.find(sig, cellport_list);
	for (auto &cellport : cellport_list)
	{
		if ((cellport.first->type != "$mux" && cellport.first->type != "$pmux") || cellport.second != "\\Y") {
			goto ret_false;
		}

		if (recursion_monitor.count(cellport.first)) {
			log_warning("logic loop in mux tree at signal %s in module %s.\n",
					log_signal(sig), RTLIL::id2cstr(module->name));
			goto ret_false;
		}

		recursion_monitor.insert(cellport.first);

		RTLIL::SigSpec sig_a = assign_map(cellport.first->getPort("\\A"));
		RTLIL::SigSpec sig_b = assign_map(cellport.first->getPort("\\B"));

		if (!check_state_mux_tree(old_sig, sig_a, recursion_monitor, mux_tree_cache)) {
			recursion_monitor.erase(cellport.first);
			goto ret_false;
		}

		for (int i = 0; i < sig_b.size(); i += sig_a.size())
			if (!check_state_mux_tree(old_sig, sig_b.extract(i, sig_a.size()), recursion_monitor, mux_tree_cache)) {
				recursion_monitor.erase(cellport.first);
				goto ret_false;
			}

		recursion_monitor.erase(cellport.first);
		muxtree_cells.insert(cellport.first);
	}

	goto ret_true;
}

static bool check_state_users(RTLIL::SigSpec sig)
{
	if (sig_at_port.check_any(assign_map(sig)))
		return false;

	std::set<sig2driver_entry_t> cellport_list;
	sig2user.find(sig, cellport_list);
	for (auto &cellport : cellport_list) {
		RTLIL::Cell *cell = cellport.first;
		if (muxtree_cells.count(cell) > 0)
			continue;
		if (cell->type == "$logic_not" && assign_map(cell->getPort("\\A")) == sig)
			continue;
		if (cellport.second != "\\A" && cellport.second != "\\B")
			return false;
		if (!cell->hasPort("\\A") || !cell->hasPort("\\B") || !cell->hasPort("\\Y"))
			return false;
		for (auto &port_it : cell->connections())
			if (port_it.first != "\\A" && port_it.first != "\\B" && port_it.first != "\\Y")
				return false;
		if (assign_map(cell->getPort("\\A")) == sig && cell->getPort("\\B").is_fully_const())
			continue;
		if (assign_map(cell->getPort("\\B")) == sig && cell->getPort("\\A").is_fully_const())
			continue;
		return false;
	}

	return true;
}

static void detect_fsm(RTLIL::Wire *wire)
{
	bool has_fsm_encoding_attr = wire->attributes.count("\\fsm_encoding") > 0 && wire->attributes.at("\\fsm_encoding").decode_string() != "none";
	bool has_fsm_encoding_none = wire->attributes.count("\\fsm_encoding") > 0 && wire->attributes.at("\\fsm_encoding").decode_string() == "none";
	bool has_init_attr = wire->attributes.count("\\init") > 0;
	bool is_module_port = sig_at_port.check_any(assign_map(RTLIL::SigSpec(wire)));
	bool looks_like_state_reg = false, looks_like_good_state_reg = false;
	bool is_self_resetting = false;

	if (has_fsm_encoding_none)
		return;

	if (wire->width <= 1) {
		if (has_fsm_encoding_attr) {
			log_warning("Removing fsm_encoding attribute from 1-bit net: %s.%s\n", log_id(wire->module), log_id(wire));
			wire->attributes.erase("\\fsm_encoding");
		}
		return;
	}

	std::set<sig2driver_entry_t> cellport_list;
	sig2driver.find(RTLIL::SigSpec(wire), cellport_list);

	for (auto &cellport : cellport_list)
	{
		if ((cellport.first->type != "$dff" && cellport.first->type != "$adff") || cellport.second != "\\Q")
			continue;

		muxtree_cells.clear();
		pool<Cell*> recursion_monitor;
		RTLIL::SigSpec sig_q = assign_map(cellport.first->getPort("\\Q"));
		RTLIL::SigSpec sig_d = assign_map(cellport.first->getPort("\\D"));
		dict<RTLIL::SigSpec, bool> mux_tree_cache;

		if (sig_q != assign_map(wire))
			continue;

		looks_like_state_reg = check_state_mux_tree(sig_q, sig_d, recursion_monitor, mux_tree_cache);
		looks_like_good_state_reg = check_state_users(sig_q);

		if (!looks_like_state_reg)
			break;

		ConstEval ce(wire->module);

		std::set<sig2driver_entry_t> cellport_list;
		sig2user.find(sig_q, cellport_list);

		auto sig_q_bits = sig_q.to_sigbit_pool();

		for (auto &cellport : cellport_list)
		{
			RTLIL::Cell *cell = cellport.first;
			bool set_output = false, clr_output = false;

			if (cell->type.in("$ne", "$reduce_or", "$reduce_bool"))
				set_output = true;

			if (cell->type.in("$eq", "$logic_not", "$reduce_and"))
				clr_output = true;

			if (set_output || clr_output) {
				for (auto &port_it : cell->connections())
					if (cell->input(port_it.first))
						for (auto bit : assign_map(port_it.second))
							if (bit.wire != nullptr && !sig_q_bits.count(bit))
								goto next_cellport;
			}

			if (set_output || clr_output) {
				for (auto &port_it : cell->connections())
					if (cell->output(port_it.first)) {
						SigSpec sig = assign_map(port_it.second);
						Const val(set_output ? State::S1 : State::S0, GetSize(sig));
						ce.set(sig, val);
					}
			}
		next_cellport:;
		}

		SigSpec sig_y = sig_d, sig_undef;
		if (ce.eval(sig_y, sig_undef))
			is_self_resetting = true;
	}

	if (has_fsm_encoding_attr)
	{
		vector<string> warnings;

		if (is_module_port)
			warnings.push_back("Forcing FSM recoding on module port might result in larger circuit.\n");

		if (!looks_like_good_state_reg)
			warnings.push_back("Users of state reg look like FSM recoding might result in larger circuit.\n");

		if (has_init_attr)
			warnings.push_back("Initialization value on FSM state register is ignored. Possible simulation-synthesis mismatch!\n");

		if (!looks_like_state_reg)
			warnings.push_back("Doesn't look like a proper FSM. Possible simulation-synthesis mismatch!\n");

		if (is_self_resetting)
			warnings.push_back("FSM seems to be self-resetting. Possible simulation-synthesis mismatch!\n");

		if (!warnings.empty()) {
			string warnmsg = stringf("Regarding the user-specified fsm_encoding attribute on %s.%s:\n", log_id(wire->module), log_id(wire));
			for (auto w : warnings) warnmsg += "    " + w;
			log_warning("%s", warnmsg.c_str());
		} else {
			log("FSM state register %s.%s already has fsm_encoding attribute.\n", log_id(wire->module), log_id(wire));
		}
	}
	else
	if (looks_like_state_reg && looks_like_good_state_reg && !has_init_attr && !is_module_port && !is_self_resetting)
	{
		log("Found FSM state register %s.%s.\n", log_id(wire->module), log_id(wire));
		wire->attributes["\\fsm_encoding"] = RTLIL::Const("auto");
	}
	else
	if (looks_like_state_reg)
	{
		log("Not marking %s.%s as FSM state register:\n", log_id(wire->module), log_id(wire));

		if (is_module_port)
			log("    Register is connected to module port.\n");

		if (!looks_like_good_state_reg)
			log("    Users of register don't seem to benefit from recoding.\n");

		if (has_init_attr)
			log("    Register has an initialization value.\n");

		if (is_self_resetting)
			log("    Circuit seems to be self-resetting.\n");
	}
}

struct FsmDetectPass : public Pass {
	FsmDetectPass() : Pass("fsm_detect", "finding FSMs in design") { }
	void help() YS_OVERRIDE
	{
		//   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
		log("\n");
		log("    fsm_detect [selection]\n");
		log("\n");
		log("This pass detects finite state machines by identifying the state signal.\n");
		log("The state signal is then marked by setting the attribute 'fsm_encoding'\n");
		log("on the state signal to \"auto\".\n");
		log("\n");
		log("Existing 'fsm_encoding' attributes are not changed by this pass.\n");
		log("\n");
		log("Signals can be protected from being detected by this pass by setting the\n");
		log("'fsm_encoding' attribute to \"none\".\n");
		log("\n");
	}
	void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
	{
		log_header(design, "Executing FSM_DETECT pass (finding FSMs in design).\n");
		extra_args(args, 1, design);

		CellTypes ct;
		ct.setup_internals();
		ct.setup_internals_mem();
		ct.setup_stdcells();
		ct.setup_stdcells_mem();

		for (auto &mod_it : design->modules_)
		{
			if (!design->selected(mod_it.second))
				continue;

			module = mod_it.second;
			assign_map.set(module);

			sig2driver.clear();
			sig2user.clear();
			sig_at_port.clear();
			for (auto &cell_it : module->cells_)
				for (auto &conn_it : cell_it.second->connections()) {
					if (ct.cell_output(cell_it.second->type, conn_it.first) || !ct.cell_known(cell_it.second->type)) {
						RTLIL::SigSpec sig = conn_it.second;
						assign_map.apply(sig);
						sig2driver.insert(sig, sig2driver_entry_t(cell_it.second, conn_it.first));
					}
					if (!ct.cell_known(cell_it.second->type) || ct.cell_input(cell_it.second->type, conn_it.first)) {
						RTLIL::SigSpec sig = conn_it.second;
						assign_map.apply(sig);
						sig2user.insert(sig, sig2driver_entry_t(cell_it.second, conn_it.first));
					}
				}

			for (auto &wire_it : module->wires_)
				if (wire_it.second->port_id != 0)
					sig_at_port.add(assign_map(RTLIL::SigSpec(wire_it.second)));

			for (auto &wire_it : module->wires_)
				if (design->selected(module, wire_it.second))
					detect_fsm(wire_it.second);
		}

		assign_map.clear();
		sig2driver.clear();
		sig2user.clear();
		muxtree_cells.clear();
	}
} FsmDetectPass;

PRIVATE_NAMESPACE_END