Moved smt2 yosys info parsing from smtbmc.py to smtio.py
[yosys.git] / backends / smt2 / smt2.cc
1 /*
2 * yosys -- Yosys Open SYnthesis Suite
3 *
4 * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
5 *
6 * Permission to use, copy, modify, and/or distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 *
18 */
19
20 #include "kernel/rtlil.h"
21 #include "kernel/register.h"
22 #include "kernel/sigtools.h"
23 #include "kernel/celltypes.h"
24 #include "kernel/log.h"
25 #include <string>
26
27 USING_YOSYS_NAMESPACE
28 PRIVATE_NAMESPACE_BEGIN
29
30 struct Smt2Worker
31 {
32 CellTypes ct;
33 SigMap sigmap;
34 RTLIL::Module *module;
35 bool bvmode, memmode, regsmode, wiresmode, verbose;
36 int idcounter;
37
38 std::vector<std::string> decls, trans, hier;
39 std::map<RTLIL::SigBit, RTLIL::Cell*> bit_driver;
40 std::set<RTLIL::Cell*> exported_cells, hiercells;
41 pool<Cell*> recursive_cells, registers;
42
43 std::map<RTLIL::SigBit, std::pair<int, int>> fcache;
44 std::map<Cell*, int> memarrays;
45 std::map<int, int> bvsizes;
46
47 Smt2Worker(RTLIL::Module *module, bool bvmode, bool memmode, bool regsmode, bool wiresmode, bool verbose) :
48 ct(module->design), sigmap(module), module(module), bvmode(bvmode), memmode(memmode),
49 regsmode(regsmode), wiresmode(wiresmode), verbose(verbose), idcounter(0)
50 {
51 decls.push_back(stringf("(declare-sort |%s_s| 0)\n", log_id(module)));
52
53 for (auto cell : module->cells())
54 for (auto &conn : cell->connections()) {
55 bool is_input = ct.cell_input(cell->type, conn.first);
56 bool is_output = ct.cell_output(cell->type, conn.first);
57 if (is_output && !is_input)
58 for (auto bit : sigmap(conn.second)) {
59 if (bit_driver.count(bit))
60 log_error("Found multiple drivers for %s.\n", log_signal(bit));
61 bit_driver[bit] = cell;
62 }
63 else if (is_output || !is_input)
64 log_error("Unsupported or unknown directionality on port %s of cell %s.%s (%s).\n",
65 log_id(conn.first), log_id(module), log_id(cell), log_id(cell->type));
66 }
67 }
68
69 void register_bool(RTLIL::SigBit bit, int id)
70 {
71 if (verbose) log("%*s-> register_bool: %s %d\n", 2+2*GetSize(recursive_cells), "",
72 log_signal(bit), id);
73
74 sigmap.apply(bit);
75 log_assert(fcache.count(bit) == 0);
76 fcache[bit] = std::pair<int, int>(id, -1);
77 }
78
79 void register_bv(RTLIL::SigSpec sig, int id)
80 {
81 if (verbose) log("%*s-> register_bv: %s %d\n", 2+2*GetSize(recursive_cells), "",
82 log_signal(sig), id);
83
84 log_assert(bvmode);
85 sigmap.apply(sig);
86
87 log_assert(bvsizes.count(id) == 0);
88 bvsizes[id] = GetSize(sig);
89
90 for (int i = 0; i < GetSize(sig); i++) {
91 log_assert(fcache.count(sig[i]) == 0);
92 fcache[sig[i]] = std::pair<int, int>(id, i);
93 }
94 }
95
96 void register_boolvec(RTLIL::SigSpec sig, int id)
97 {
98 if (verbose) log("%*s-> register_boolvec: %s %d\n", 2+2*GetSize(recursive_cells), "",
99 log_signal(sig), id);
100
101 log_assert(bvmode);
102 sigmap.apply(sig);
103 register_bool(sig[0], id);
104
105 for (int i = 1; i < GetSize(sig); i++)
106 sigmap.add(sig[i], RTLIL::State::S0);
107 }
108
109 std::string get_bool(RTLIL::SigBit bit, const char *state_name = "state")
110 {
111 sigmap.apply(bit);
112
113 if (bit.wire == nullptr)
114 return bit == RTLIL::State::S1 ? "true" : "false";
115
116 if (bit_driver.count(bit))
117 export_cell(bit_driver.at(bit));
118 sigmap.apply(bit);
119
120 if (fcache.count(bit) == 0) {
121 if (verbose) log("%*s-> external bool: %s\n", 2+2*GetSize(recursive_cells), "",
122 log_signal(bit));
123 decls.push_back(stringf("(declare-fun |%s#%d| (|%s_s|) Bool) ; %s\n",
124 log_id(module), idcounter, log_id(module), log_signal(bit)));
125 register_bool(bit, idcounter++);
126 }
127
128 auto f = fcache.at(bit);
129 if (f.second >= 0)
130 return stringf("(= ((_ extract %d %d) (|%s#%d| %s)) #b1)", f.second, f.second, log_id(module), f.first, state_name);
131 return stringf("(|%s#%d| %s)", log_id(module), f.first, state_name);
132 }
133
134 std::string get_bool(RTLIL::SigSpec sig, const char *state_name = "state")
135 {
136 return get_bool(sig.as_bit(), state_name);
137 }
138
139 std::string get_bv(RTLIL::SigSpec sig, const char *state_name = "state")
140 {
141 log_assert(bvmode);
142 sigmap.apply(sig);
143
144 std::vector<std::string> subexpr;
145
146 SigSpec orig_sig;
147 while (orig_sig != sig) {
148 for (auto bit : sig)
149 if (bit_driver.count(bit))
150 export_cell(bit_driver.at(bit));
151 orig_sig = sig;
152 sigmap.apply(sig);
153 }
154
155 for (int i = 0, j = 1; i < GetSize(sig); i += j, j = 1)
156 {
157 if (sig[i].wire == nullptr) {
158 while (i+j < GetSize(sig) && sig[i+j].wire == nullptr) j++;
159 subexpr.push_back("#b");
160 for (int k = i+j-1; k >= i; k--)
161 subexpr.back() += sig[k] == RTLIL::State::S1 ? "1" : "0";
162 continue;
163 }
164
165 if (fcache.count(sig[i]) && fcache.at(sig[i]).second == -1) {
166 subexpr.push_back(stringf("(ite %s #b1 #b0)", get_bool(sig[i], state_name).c_str()));
167 continue;
168 }
169
170 if (fcache.count(sig[i])) {
171 auto t1 = fcache.at(sig[i]);
172 while (i+j < GetSize(sig)) {
173 if (fcache.count(sig[i+j]) == 0)
174 break;
175 auto t2 = fcache.at(sig[i+j]);
176 if (t1.first != t2.first)
177 break;
178 if (t1.second+j != t2.second)
179 break;
180 j++;
181 }
182 if (t1.second == 0 && j == bvsizes.at(t1.first))
183 subexpr.push_back(stringf("(|%s#%d| %s)", log_id(module), t1.first, state_name));
184 else
185 subexpr.push_back(stringf("((_ extract %d %d) (|%s#%d| %s))",
186 t1.second + j - 1, t1.second, log_id(module), t1.first, state_name));
187 continue;
188 }
189
190 std::set<RTLIL::SigBit> seen_bits = { sig[i] };
191 while (i+j < GetSize(sig) && sig[i+j].wire && !fcache.count(sig[i+j]) && !seen_bits.count(sig[i+j]))
192 seen_bits.insert(sig[i+j]), j++;
193
194 if (verbose) log("%*s-> external bv: %s\n", 2+2*GetSize(recursive_cells), "",
195 log_signal(sig.extract(i, j)));
196 for (auto bit : sig.extract(i, j))
197 log_assert(bit_driver.count(bit) == 0);
198 decls.push_back(stringf("(declare-fun |%s#%d| (|%s_s|) (_ BitVec %d)) ; %s\n",
199 log_id(module), idcounter, log_id(module), j, log_signal(sig.extract(i, j))));
200 subexpr.push_back(stringf("(|%s#%d| %s)", log_id(module), idcounter, state_name));
201 register_bv(sig.extract(i, j), idcounter++);
202 }
203
204 if (GetSize(subexpr) > 1) {
205 std::string expr = "", end_str = "";
206 for (int i = GetSize(subexpr)-1; i >= 0; i--) {
207 if (i > 0) expr += " (concat", end_str += ")";
208 expr += " " + subexpr[i];
209 }
210 return expr.substr(1) + end_str;
211 } else {
212 log_assert(GetSize(subexpr) == 1);
213 return subexpr[0];
214 }
215 }
216
217 void export_gate(RTLIL::Cell *cell, std::string expr)
218 {
219 RTLIL::SigBit bit = sigmap(cell->getPort("\\Y").as_bit());
220 std::string processed_expr;
221
222 for (char ch : expr) {
223 if (ch == 'A') processed_expr += get_bool(cell->getPort("\\A"));
224 else if (ch == 'B') processed_expr += get_bool(cell->getPort("\\B"));
225 else if (ch == 'C') processed_expr += get_bool(cell->getPort("\\C"));
226 else if (ch == 'D') processed_expr += get_bool(cell->getPort("\\D"));
227 else if (ch == 'S') processed_expr += get_bool(cell->getPort("\\S"));
228 else processed_expr += ch;
229 }
230
231 if (verbose) log("%*s-> import cell: %s\n", 2+2*GetSize(recursive_cells), "",
232 log_id(cell));
233 decls.push_back(stringf("(define-fun |%s#%d| ((state |%s_s|)) Bool %s) ; %s\n",
234 log_id(module), idcounter, log_id(module), processed_expr.c_str(), log_signal(bit)));
235 register_bool(bit, idcounter++);
236 recursive_cells.erase(cell);
237 }
238
239 void export_bvop(RTLIL::Cell *cell, std::string expr, char type = 0)
240 {
241 RTLIL::SigSpec sig_a, sig_b;
242 RTLIL::SigSpec sig_y = sigmap(cell->getPort("\\Y"));
243 bool is_signed = cell->getParam("\\A_SIGNED").as_bool();
244 int width = GetSize(sig_y);
245
246 if (type == 's' || type == 'd' || type == 'b') {
247 width = max(width, GetSize(cell->getPort("\\A")));
248 width = max(width, GetSize(cell->getPort("\\B")));
249 }
250
251 if (cell->hasPort("\\A")) {
252 sig_a = cell->getPort("\\A");
253 sig_a.extend_u0(width, is_signed);
254 }
255
256 if (cell->hasPort("\\B")) {
257 sig_b = cell->getPort("\\B");
258 sig_b.extend_u0(width, is_signed && !(type == 's'));
259 }
260
261 std::string processed_expr;
262
263 for (char ch : expr) {
264 if (ch == 'A') processed_expr += get_bv(sig_a);
265 else if (ch == 'B') processed_expr += get_bv(sig_b);
266 else if (ch == 'L') processed_expr += is_signed ? "a" : "l";
267 else if (ch == 'U') processed_expr += is_signed ? "s" : "u";
268 else processed_expr += ch;
269 }
270
271 if (width != GetSize(sig_y) && type != 'b')
272 processed_expr = stringf("((_ extract %d 0) %s)", GetSize(sig_y)-1, processed_expr.c_str());
273
274 if (verbose) log("%*s-> import cell: %s\n", 2+2*GetSize(recursive_cells), "",
275 log_id(cell));
276
277 if (type == 'b') {
278 decls.push_back(stringf("(define-fun |%s#%d| ((state |%s_s|)) Bool %s) ; %s\n",
279 log_id(module), idcounter, log_id(module), processed_expr.c_str(), log_signal(sig_y)));
280 register_boolvec(sig_y, idcounter++);
281 } else {
282 decls.push_back(stringf("(define-fun |%s#%d| ((state |%s_s|)) (_ BitVec %d) %s) ; %s\n",
283 log_id(module), idcounter, log_id(module), GetSize(sig_y), processed_expr.c_str(), log_signal(sig_y)));
284 register_bv(sig_y, idcounter++);
285 }
286
287 recursive_cells.erase(cell);
288 }
289
290 void export_reduce(RTLIL::Cell *cell, std::string expr, bool identity_val)
291 {
292 RTLIL::SigSpec sig_y = sigmap(cell->getPort("\\Y"));
293 std::string processed_expr;
294
295 for (char ch : expr)
296 if (ch == 'A' || ch == 'B') {
297 RTLIL::SigSpec sig = sigmap(cell->getPort(stringf("\\%c", ch)));
298 for (auto bit : sig)
299 processed_expr += " " + get_bool(bit);
300 if (GetSize(sig) == 1)
301 processed_expr += identity_val ? " true" : " false";
302 } else
303 processed_expr += ch;
304
305 if (verbose) log("%*s-> import cell: %s\n", 2+2*GetSize(recursive_cells), "",
306 log_id(cell));
307 decls.push_back(stringf("(define-fun |%s#%d| ((state |%s_s|)) Bool %s) ; %s\n",
308 log_id(module), idcounter, log_id(module), processed_expr.c_str(), log_signal(sig_y)));
309 register_boolvec(sig_y, idcounter++);
310 recursive_cells.erase(cell);
311 }
312
313 void export_cell(RTLIL::Cell *cell)
314 {
315 if (verbose) log("%*s=> export_cell %s (%s) [%s]\n", 2+2*GetSize(recursive_cells), "",
316 log_id(cell), log_id(cell->type), exported_cells.count(cell) ? "old" : "new");
317
318 if (recursive_cells.count(cell))
319 log_error("Found logic loop in module %s! See cell %s.\n", log_id(module), log_id(cell));
320
321 if (exported_cells.count(cell))
322 return;
323
324 exported_cells.insert(cell);
325 recursive_cells.insert(cell);
326
327 if (cell->type == "$_DFF_P_" || cell->type == "$_DFF_N_")
328 {
329 registers.insert(cell);
330 decls.push_back(stringf("(declare-fun |%s#%d| (|%s_s|) Bool) ; %s\n",
331 log_id(module), idcounter, log_id(module), log_signal(cell->getPort("\\Q"))));
332 register_bool(cell->getPort("\\Q"), idcounter++);
333 recursive_cells.erase(cell);
334 return;
335 }
336
337 if (cell->type == "$_BUF_") return export_gate(cell, "A");
338 if (cell->type == "$_NOT_") return export_gate(cell, "(not A)");
339 if (cell->type == "$_AND_") return export_gate(cell, "(and A B)");
340 if (cell->type == "$_NAND_") return export_gate(cell, "(not (and A B))");
341 if (cell->type == "$_OR_") return export_gate(cell, "(or A B)");
342 if (cell->type == "$_NOR_") return export_gate(cell, "(not (or A B))");
343 if (cell->type == "$_XOR_") return export_gate(cell, "(xor A B)");
344 if (cell->type == "$_XNOR_") return export_gate(cell, "(not (xor A B))");
345 if (cell->type == "$_MUX_") return export_gate(cell, "(ite S B A)");
346 if (cell->type == "$_AOI3_") return export_gate(cell, "(not (or (and A B) C))");
347 if (cell->type == "$_OAI3_") return export_gate(cell, "(not (and (or A B) C))");
348 if (cell->type == "$_AOI4_") return export_gate(cell, "(not (or (and A B) (and C D)))");
349 if (cell->type == "$_OAI4_") return export_gate(cell, "(not (and (or A B) (or C D)))");
350
351 // FIXME: $lut
352
353 if (bvmode)
354 {
355 if (cell->type == "$dff")
356 {
357 registers.insert(cell);
358 decls.push_back(stringf("(declare-fun |%s#%d| (|%s_s|) (_ BitVec %d)) ; %s\n",
359 log_id(module), idcounter, log_id(module), GetSize(cell->getPort("\\Q")), log_signal(cell->getPort("\\Q"))));
360 register_bv(cell->getPort("\\Q"), idcounter++);
361 recursive_cells.erase(cell);
362 return;
363 }
364
365 if (cell->type == "$and") return export_bvop(cell, "(bvand A B)");
366 if (cell->type == "$or") return export_bvop(cell, "(bvor A B)");
367 if (cell->type == "$xor") return export_bvop(cell, "(bvxor A B)");
368 if (cell->type == "$xnor") return export_bvop(cell, "(bvxnor A B)");
369
370 if (cell->type == "$shl") return export_bvop(cell, "(bvshl A B)", 's');
371 if (cell->type == "$shr") return export_bvop(cell, "(bvlshr A B)", 's');
372 if (cell->type == "$sshl") return export_bvop(cell, "(bvshl A B)", 's');
373 if (cell->type == "$sshr") return export_bvop(cell, "(bvLshr A B)", 's');
374
375 // FIXME: $shift $shiftx
376
377 if (cell->type == "$lt") return export_bvop(cell, "(bvUlt A B)", 'b');
378 if (cell->type == "$le") return export_bvop(cell, "(bvUle A B)", 'b');
379 if (cell->type == "$ge") return export_bvop(cell, "(bvUge A B)", 'b');
380 if (cell->type == "$gt") return export_bvop(cell, "(bvUgt A B)", 'b');
381
382 if (cell->type == "$ne") return export_bvop(cell, "(distinct A B)", 'b');
383 if (cell->type == "$nex") return export_bvop(cell, "(distinct A B)", 'b');
384 if (cell->type == "$eq") return export_bvop(cell, "(= A B)", 'b');
385 if (cell->type == "$eqx") return export_bvop(cell, "(= A B)", 'b');
386
387 if (cell->type == "$not") return export_bvop(cell, "(bvnot A)");
388 if (cell->type == "$pos") return export_bvop(cell, "A");
389 if (cell->type == "$neg") return export_bvop(cell, "(bvneg A)");
390
391 if (cell->type == "$add") return export_bvop(cell, "(bvadd A B)");
392 if (cell->type == "$sub") return export_bvop(cell, "(bvsub A B)");
393 if (cell->type == "$mul") return export_bvop(cell, "(bvmul A B)");
394 if (cell->type == "$div") return export_bvop(cell, "(bvUdiv A B)", 'd');
395 if (cell->type == "$mod") return export_bvop(cell, "(bvUrem A B)", 'd');
396
397 if (cell->type == "$reduce_and") return export_reduce(cell, "(and A)", true);
398 if (cell->type == "$reduce_or") return export_reduce(cell, "(or A)", false);
399 if (cell->type == "$reduce_xor") return export_reduce(cell, "(xor A)", false);
400 if (cell->type == "$reduce_xnor") return export_reduce(cell, "(not (xor A))", false);
401 if (cell->type == "$reduce_bool") return export_reduce(cell, "(or A)", false);
402
403 if (cell->type == "$logic_not") return export_reduce(cell, "(not (or A))", false);
404 if (cell->type == "$logic_and") return export_reduce(cell, "(and (or A) (or B))", false);
405 if (cell->type == "$logic_or") return export_reduce(cell, "(or A B)", false);
406
407 if (cell->type == "$mux" || cell->type == "$pmux")
408 {
409 int width = GetSize(cell->getPort("\\Y"));
410 std::string processed_expr = get_bv(cell->getPort("\\A"));
411
412 RTLIL::SigSpec sig_b = cell->getPort("\\B");
413 RTLIL::SigSpec sig_s = cell->getPort("\\S");
414 get_bv(sig_b);
415 get_bv(sig_s);
416
417 for (int i = 0; i < GetSize(sig_s); i++)
418 processed_expr = stringf("(ite %s %s %s)", get_bool(sig_s[i]).c_str(),
419 get_bv(sig_b.extract(i*width, width)).c_str(), processed_expr.c_str());
420
421 if (verbose) log("%*s-> import cell: %s\n", 2+2*GetSize(recursive_cells), "",
422 log_id(cell));
423 RTLIL::SigSpec sig = sigmap(cell->getPort("\\Y"));
424 decls.push_back(stringf("(define-fun |%s#%d| ((state |%s_s|)) (_ BitVec %d) %s) ; %s\n",
425 log_id(module), idcounter, log_id(module), width, processed_expr.c_str(), log_signal(sig)));
426 register_bv(sig, idcounter++);
427 recursive_cells.erase(cell);
428 return;
429 }
430
431 // FIXME: $slice $concat
432 }
433
434 if (memmode && cell->type == "$mem")
435 {
436 int arrayid = idcounter++;
437 memarrays[cell] = arrayid;
438
439 int abits = cell->getParam("\\ABITS").as_int();
440 int width = cell->getParam("\\WIDTH").as_int();
441 int rd_ports = cell->getParam("\\RD_PORTS").as_int();
442
443 decls.push_back(stringf("(declare-fun |%s#%d#0| (|%s_s|) (Array (_ BitVec %d) (_ BitVec %d))) ; %s\n",
444 log_id(module), arrayid, log_id(module), abits, width, log_id(cell)));
445
446 decls.push_back(stringf("(define-fun |%s_m %s| ((state |%s_s|)) (Array (_ BitVec %d) (_ BitVec %d)) (|%s#%d#0| state))\n",
447 log_id(module), log_id(cell), log_id(module), abits, width, log_id(module), arrayid));
448
449 for (int i = 0; i < rd_ports; i++)
450 {
451 std::string addr = get_bv(cell->getPort("\\RD_ADDR").extract(abits*i, abits));
452 SigSpec data_sig = cell->getPort("\\RD_DATA").extract(width*i, width);
453
454 if (cell->getParam("\\RD_CLK_ENABLE").extract(i).as_bool())
455 log_error("Read port %d (%s) of memory %s.%s is clocked. This is not supported by \"write_smt2\"! "
456 "Call \"memory\" with -nordff to avoid this error.\n", i, log_signal(data_sig), log_id(cell), log_id(module));
457
458 decls.push_back(stringf("(define-fun |%s#%d| ((state |%s_s|)) (_ BitVec %d) (select (|%s#%d#0| state) %s)) ; %s\n",
459 log_id(module), idcounter, log_id(module), width, log_id(module), arrayid, addr.c_str(), log_signal(data_sig)));
460 register_bv(data_sig, idcounter++);
461 }
462
463 registers.insert(cell);
464 recursive_cells.erase(cell);
465 return;
466 }
467
468 Module *m = module->design->module(cell->type);
469
470 if (m != nullptr)
471 {
472 decls.push_back(stringf("; yosys-smt2-cell %s %s\n", log_id(cell->type), log_id(cell->name)));
473 string cell_state = stringf("(|%s_h %s| state)", log_id(module), log_id(cell->name));
474
475 for (auto &conn : cell->connections())
476 {
477 Wire *w = m->wire(conn.first);
478 SigSpec sig = sigmap(conn.second);
479
480 if (w->port_output && !w->port_input) {
481 if (GetSize(w) > 1) {
482 if (bvmode) {
483 decls.push_back(stringf("(declare-fun |%s#%d| (|%s_s|) (_ BitVec %d)) ; %s\n",
484 log_id(module), idcounter, log_id(module), GetSize(w), log_signal(sig)));
485 register_bv(sig, idcounter++);
486 } else {
487 for (int i = 0; i < GetSize(w); i++) {
488 decls.push_back(stringf("(declare-fun |%s#%d| (|%s_s|) Bool) ; %s\n",
489 log_id(module), idcounter, log_id(module), log_signal(sig[i])));
490 register_bool(sig[i], idcounter++);
491 }
492 }
493 } else {
494 decls.push_back(stringf("(declare-fun |%s#%d| (|%s_s|) Bool) ; %s\n",
495 log_id(module), idcounter, log_id(module), log_signal(sig)));
496 register_bool(sig, idcounter++);
497 }
498 }
499 }
500
501 decls.push_back(stringf("(declare-fun |%s_h %s| (|%s_s|) |%s_s|)\n",
502 log_id(module), log_id(cell->name), log_id(module), log_id(cell->type)));
503
504 hiercells.insert(cell);
505 recursive_cells.erase(cell);
506
507 for (auto &conn : cell->connections())
508 {
509 Wire *w = m->wire(conn.first);
510 SigSpec sig = sigmap(conn.second);
511
512 if (bvmode || GetSize(w) == 1) {
513 hier.push_back(stringf(" (= %s (|%s_n %s| %s)) ; %s.%s\n", (GetSize(w) > 1 ? get_bv(sig) : get_bool(sig)).c_str(),
514 log_id(cell->type), log_id(w), cell_state.c_str(), log_id(cell->type), log_id(w)));
515 } else {
516 for (int i = 0; i < GetSize(w); i++)
517 hier.push_back(stringf(" (= %s (|%s_n %s %d| %s)) ; %s.%s[%d]\n", get_bool(sig[i]).c_str(),
518 log_id(cell->type), log_id(w), i, cell_state.c_str(), log_id(cell->type), log_id(w), i));
519 }
520 }
521
522 return;
523 }
524
525 log_error("Unsupported cell type %s for cell %s.%s. (Maybe this cell type would be supported in -bv or -mem mode?)\n",
526 log_id(cell->type), log_id(module), log_id(cell));
527 }
528
529 void run()
530 {
531 if (verbose) log("=> export logic driving outputs\n");
532
533 pool<SigBit> reg_bits;
534 if (regsmode) {
535 for (auto cell : module->cells())
536 if (cell->type.in("$_DFF_P_", "$_DFF_N_", "$dff")) {
537 // not using sigmap -- we want the net directly at the dff output
538 for (auto bit : cell->getPort("\\Q"))
539 reg_bits.insert(bit);
540 }
541 }
542
543 for (auto wire : module->wires()) {
544 bool is_register = false;
545 if (regsmode)
546 for (auto bit : SigSpec(wire))
547 if (reg_bits.count(bit))
548 is_register = true;
549 if (wire->port_id || is_register || wire->get_bool_attribute("\\keep") || (wiresmode && wire->name[0] == '\\')) {
550 RTLIL::SigSpec sig = sigmap(wire);
551 if (wire->port_input)
552 decls.push_back(stringf("; yosys-smt2-input %s %d\n", log_id(wire), wire->width));
553 if (wire->port_output)
554 decls.push_back(stringf("; yosys-smt2-output %s %d\n", log_id(wire), wire->width));
555 if (is_register)
556 decls.push_back(stringf("; yosys-smt2-register %s %d\n", log_id(wire), wire->width));
557 if (wire->get_bool_attribute("\\keep") || (wiresmode && wire->name[0] == '\\'))
558 decls.push_back(stringf("; yosys-smt2-wire %s %d\n", log_id(wire), wire->width));
559 if (bvmode && GetSize(sig) > 1) {
560 decls.push_back(stringf("(define-fun |%s_n %s| ((state |%s_s|)) (_ BitVec %d) %s)\n",
561 log_id(module), log_id(wire), log_id(module), GetSize(sig), get_bv(sig).c_str()));
562 } else {
563 for (int i = 0; i < GetSize(sig); i++)
564 if (GetSize(sig) > 1)
565 decls.push_back(stringf("(define-fun |%s_n %s %d| ((state |%s_s|)) Bool %s)\n",
566 log_id(module), log_id(wire), i, log_id(module), get_bool(sig[i]).c_str()));
567 else
568 decls.push_back(stringf("(define-fun |%s_n %s| ((state |%s_s|)) Bool %s)\n",
569 log_id(module), log_id(wire), log_id(module), get_bool(sig[i]).c_str()));
570 }
571 }
572 }
573
574 if (verbose) log("=> export logic associated with the initial state\n");
575
576 vector<string> init_list;
577 for (auto wire : module->wires())
578 if (wire->attributes.count("\\init")) {
579 RTLIL::SigSpec sig = sigmap(wire);
580 Const val = wire->attributes.at("\\init");
581 val.bits.resize(GetSize(sig));
582 if (bvmode && GetSize(sig) > 1) {
583 init_list.push_back(stringf("(= %s #b%s) ; %s", get_bv(sig).c_str(), val.as_string().c_str(), log_id(wire)));
584 } else {
585 for (int i = 0; i < GetSize(sig); i++)
586 init_list.push_back(stringf("(= %s %s) ; %s", get_bool(sig[i]).c_str(), val.bits[i] == State::S1 ? "true" : "false", log_id(wire)));
587 }
588 }
589
590 if (verbose) log("=> export logic driving asserts\n");
591
592 vector<string> assert_list, assume_list;
593 for (auto cell : module->cells())
594 if (cell->type.in("$assert", "$assume")) {
595 string name_a = get_bool(cell->getPort("\\A"));
596 string name_en = get_bool(cell->getPort("\\EN"));
597 decls.push_back(stringf("(define-fun |%s#%d| ((state |%s_s|)) Bool (or %s (not %s))) ; %s\n",
598 log_id(module), idcounter, log_id(module), name_a.c_str(), name_en.c_str(), log_id(cell)));
599 if (cell->type == "$assert")
600 assert_list.push_back(stringf("(|%s#%d| state)", log_id(module), idcounter++));
601 else
602 assume_list.push_back(stringf("(|%s#%d| state)", log_id(module), idcounter++));
603 }
604
605 for (int iter = 1; !registers.empty(); iter++)
606 {
607 pool<Cell*> this_regs;
608 this_regs.swap(registers);
609
610 if (verbose) log("=> export logic driving registers [iteration %d]\n", iter);
611
612 for (auto cell : this_regs)
613 {
614 if (cell->type == "$_DFF_P_" || cell->type == "$_DFF_N_")
615 {
616 std::string expr_d = get_bool(cell->getPort("\\D"));
617 std::string expr_q = get_bool(cell->getPort("\\Q"), "next_state");
618 trans.push_back(stringf(" (= %s %s) ; %s %s\n", expr_d.c_str(), expr_q.c_str(), log_id(cell), log_signal(cell->getPort("\\Q"))));
619 }
620
621 if (cell->type == "$dff")
622 {
623 std::string expr_d = get_bv(cell->getPort("\\D"));
624 std::string expr_q = get_bv(cell->getPort("\\Q"), "next_state");
625 trans.push_back(stringf(" (= %s %s) ; %s %s\n", expr_d.c_str(), expr_q.c_str(), log_id(cell), log_signal(cell->getPort("\\Q"))));
626 }
627
628 if (cell->type == "$mem")
629 {
630 int arrayid = memarrays.at(cell);
631
632 int abits = cell->getParam("\\ABITS").as_int();
633 int width = cell->getParam("\\WIDTH").as_int();
634 int wr_ports = cell->getParam("\\WR_PORTS").as_int();
635
636 for (int i = 0; i < wr_ports; i++)
637 {
638 std::string addr = get_bv(cell->getPort("\\WR_ADDR").extract(abits*i, abits));
639 std::string data = get_bv(cell->getPort("\\WR_DATA").extract(width*i, width));
640 std::string mask = get_bv(cell->getPort("\\WR_EN").extract(width*i, width));
641
642 data = stringf("(bvor (bvand %s %s) (bvand (select (|%s#%d#%d| state) %s) (bvnot %s)))",
643 data.c_str(), mask.c_str(), log_id(module), arrayid, i, addr.c_str(), mask.c_str());
644
645 decls.push_back(stringf("(define-fun |%s#%d#%d| ((state |%s_s|)) (Array (_ BitVec %d) (_ BitVec %d)) "
646 "(store (|%s#%d#%d| state) %s %s)) ; %s\n",
647 log_id(module), arrayid, i+1, log_id(module), abits, width,
648 log_id(module), arrayid, i, addr.c_str(), data.c_str(), log_id(cell)));
649 }
650
651 std::string expr_d = stringf("(|%s#%d#%d| state)", log_id(module), arrayid, wr_ports);
652 std::string expr_q = stringf("(|%s#%d#0| next_state)", log_id(module), arrayid);
653 trans.push_back(stringf(" (= %s %s) ; %s\n", expr_d.c_str(), expr_q.c_str(), log_id(cell)));
654 }
655 }
656 }
657
658 for (auto c : hiercells)
659 assert_list.push_back(stringf("(|%s_a| (|%s_h %s| state))", log_id(c->type), log_id(module), log_id(c->name)));
660
661 for (auto c : hiercells)
662 assume_list.push_back(stringf("(|%s_u| (|%s_h %s| state))", log_id(c->type), log_id(module), log_id(c->name)));
663
664 for (auto c : hiercells)
665 init_list.push_back(stringf("(|%s_i| (|%s_h %s| state))", log_id(c->type), log_id(module), log_id(c->name)));
666
667 string assert_expr = assert_list.empty() ? "true" : "(and";
668 if (!assert_list.empty()) {
669 for (auto &str : assert_list)
670 assert_expr += stringf("\n %s", str.c_str());
671 assert_expr += "\n)";
672 }
673 decls.push_back(stringf("(define-fun |%s_a| ((state |%s_s|)) Bool %s)\n",
674 log_id(module), log_id(module), assert_expr.c_str()));
675
676 string assume_expr = assume_list.empty() ? "true" : "(and";
677 if (!assume_list.empty()) {
678 for (auto &str : assume_list)
679 assume_expr += stringf("\n %s", str.c_str());
680 assume_expr += "\n)";
681 }
682 decls.push_back(stringf("(define-fun |%s_u| ((state |%s_s|)) Bool %s)\n",
683 log_id(module), log_id(module), assume_expr.c_str()));
684
685 string init_expr = init_list.empty() ? "true" : "(and";
686 if (!init_list.empty()) {
687 for (auto &str : init_list)
688 init_expr += stringf("\n %s", str.c_str());
689 init_expr += "\n)";
690 }
691 decls.push_back(stringf("(define-fun |%s_i| ((state |%s_s|)) Bool %s)\n",
692 log_id(module), log_id(module), init_expr.c_str()));
693 }
694
695 void write(std::ostream &f)
696 {
697 f << stringf("; yosys-smt2-module %s\n", log_id(module));
698
699 for (auto it : decls)
700 f << it;
701
702 f << stringf("(define-fun |%s_h| ((state |%s_s|)) Bool ", log_id(module), log_id(module));
703 if (GetSize(hier) > 1) {
704 f << "(and\n";
705 for (auto it : hier)
706 f << it;
707 f << "))\n";
708 } else
709 if (GetSize(hier) == 1)
710 f << "\n" + hier.front() + ")\n";
711 else
712 f << "true)\n";
713
714 f << stringf("(define-fun |%s_t| ((state |%s_s|) (next_state |%s_s|)) Bool ", log_id(module), log_id(module), log_id(module));
715 if (GetSize(trans) > 1) {
716 f << "(and\n";
717 for (auto it : trans)
718 f << it;
719 f << "))";
720 } else
721 if (GetSize(trans) == 1)
722 f << "\n" + trans.front() + ")";
723 else
724 f << "true)";
725 f << stringf(" ; end of module %s\n", log_id(module));
726 }
727 };
728
729 struct Smt2Backend : public Backend {
730 Smt2Backend() : Backend("smt2", "write design to SMT-LIBv2 file") { }
731 virtual void help()
732 {
733 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
734 log("\n");
735 log(" write_smt2 [options] [filename]\n");
736 log("\n");
737 log("Write a SMT-LIBv2 [1] description of the current design. For a module with name\n");
738 log("'<mod>' this will declare the sort '<mod>_s' (state of the module) and the\n");
739 log("functions operating on that state.\n");
740 log("\n");
741 log("The '<mod>_s' sort represents a module state. Additional '<mod>_n' functions\n");
742 log("are provided that can be used to access the values of the signals in the module.\n");
743 log("By default only ports, and signals with the 'keep' attribute set are made\n");
744 log("available via such functions. Without the -bv option, multi-bit wires are\n");
745 log("exported as separate functions of type Bool for the individual bits. With the\n");
746 log("-bv option multi-bit wires are exported as single functions of type BitVec.\n");
747 log("\n");
748 log("The '<mod>_t' function evaluates to 'true' when the given pair of states\n");
749 log("describes a valid state transition.\n");
750 log("\n");
751 log("The '<mod>_a' function evaluates to 'true' when the given state satisfies\n");
752 log("the asserts in the module.\n");
753 log("\n");
754 log("The '<mod>_u' function evaluates to 'true' when the given state satisfies\n");
755 log("the assumptions in the module.\n");
756 log("\n");
757 log("The '<mod>_i' function evaluates to 'true' when the given state conforms\n");
758 log("to the initial state.\n");
759 log("\n");
760 log("For hierarchical designs, the '<mod>_h' function must be asserted for each\n");
761 log("state to establish the design hierarchy. The '<mod>_h <cellname>' function\n");
762 log("evaluates to the state corresponding to the given cell within <mod>.\n");
763 log("\n");
764 log(" -verbose\n");
765 log(" this will print the recursive walk used to export the modules.\n");
766 log("\n");
767 log(" -bv\n");
768 log(" enable support for BitVec (FixedSizeBitVectors theory). with this\n");
769 log(" option set multi-bit wires are represented using the BitVec sort and\n");
770 log(" support for coarse grain cells (incl. arithmetic) is enabled.\n");
771 log("\n");
772 log(" -mem\n");
773 log(" enable support for memories (via ArraysEx theory). this option\n");
774 log(" also implies -bv. only $mem cells without merged registers in\n");
775 log(" read ports are supported. call \"memory\" with -nordff to make sure\n");
776 log(" that no registers are merged into $mem read ports. '<mod>_m' functions\n");
777 log(" will be generated for accessing the arrays that are used to represent\n");
778 log(" memories.\n");
779 log("\n");
780 log(" -regs\n");
781 log(" also create '<mod>_n' functions for all registers.\n");
782 log("\n");
783 log(" -wires\n");
784 log(" also create '<mod>_n' functions for all public wires.\n");
785 log("\n");
786 log(" -tpl <template_file>\n");
787 log(" use the given template file. the line containing only the token '%%%%'\n");
788 log(" is replaced with the regular output of this command.\n");
789 log("\n");
790 log("[1] For more information on SMT-LIBv2 visit http://smt-lib.org/ or read David\n");
791 log("R. Cok's tutorial: http://www.grammatech.com/resources/smt/SMTLIBTutorial.pdf\n");
792 log("\n");
793 log("---------------------------------------------------------------------------\n");
794 log("\n");
795 log("Example:\n");
796 log("\n");
797 log("Consider the following module (test.v). We want to prove that the output can\n");
798 log("never transition from a non-zero value to a zero value.\n");
799 log("\n");
800 log(" module test(input clk, output reg [3:0] y);\n");
801 log(" always @(posedge clk)\n");
802 log(" y <= (y << 1) | ^y;\n");
803 log(" endmodule\n");
804 log("\n");
805 log("For this proof we create the following template (test.tpl).\n");
806 log("\n");
807 log(" ; we need QF_UFBV for this poof\n");
808 log(" (set-logic QF_UFBV)\n");
809 log("\n");
810 log(" ; insert the auto-generated code here\n");
811 log(" %%%%\n");
812 log("\n");
813 log(" ; declare two state variables s1 and s2\n");
814 log(" (declare-fun s1 () test_s)\n");
815 log(" (declare-fun s2 () test_s)\n");
816 log("\n");
817 log(" ; state s2 is the successor of state s1\n");
818 log(" (assert (test_t s1 s2))\n");
819 log("\n");
820 log(" ; we are looking for a model with y non-zero in s1\n");
821 log(" (assert (distinct (|test_n y| s1) #b0000))\n");
822 log("\n");
823 log(" ; we are looking for a model with y zero in s2\n");
824 log(" (assert (= (|test_n y| s2) #b0000))\n");
825 log("\n");
826 log(" ; is there such a model?\n");
827 log(" (check-sat)\n");
828 log("\n");
829 log("The following yosys script will create a 'test.smt2' file for our proof:\n");
830 log("\n");
831 log(" read_verilog test.v\n");
832 log(" hierarchy -check; proc; opt; check -assert\n");
833 log(" write_smt2 -bv -tpl test.tpl test.smt2\n");
834 log("\n");
835 log("Running 'cvc4 test.smt2' will print 'unsat' because y can never transition\n");
836 log("from non-zero to zero in the test design.\n");
837 log("\n");
838 }
839 virtual void execute(std::ostream *&f, std::string filename, std::vector<std::string> args, RTLIL::Design *design)
840 {
841 std::ifstream template_f;
842 bool bvmode = false, memmode = false, regsmode = false, wiresmode = false, verbose = false;
843
844 log_header(design, "Executing SMT2 backend.\n");
845
846 size_t argidx;
847 for (argidx = 1; argidx < args.size(); argidx++)
848 {
849 if (args[argidx] == "-tpl" && argidx+1 < args.size()) {
850 template_f.open(args[++argidx]);
851 if (template_f.fail())
852 log_error("Can't open template file `%s'.\n", args[argidx].c_str());
853 continue;
854 }
855 if (args[argidx] == "-bv") {
856 bvmode = true;
857 continue;
858 }
859 if (args[argidx] == "-mem") {
860 bvmode = true;
861 memmode = true;
862 continue;
863 }
864 if (args[argidx] == "-regs") {
865 regsmode = true;
866 continue;
867 }
868 if (args[argidx] == "-wires") {
869 wiresmode = true;
870 continue;
871 }
872 if (args[argidx] == "-verbose") {
873 verbose = true;
874 continue;
875 }
876 break;
877 }
878 extra_args(f, filename, args, argidx);
879
880 if (template_f.is_open()) {
881 std::string line;
882 while (std::getline(template_f, line)) {
883 int indent = 0;
884 while (indent < GetSize(line) && (line[indent] == ' ' || line[indent] == '\t'))
885 indent++;
886 if (line.substr(indent, 2) == "%%")
887 break;
888 *f << line << std::endl;
889 }
890 }
891
892 *f << stringf("; SMT-LIBv2 description generated by %s\n", yosys_version_str);
893
894 std::vector<RTLIL::Module*> sorted_modules;
895
896 // extract module dependencies
897 std::map<RTLIL::Module*, std::set<RTLIL::Module*>> module_deps;
898 for (auto &mod_it : design->modules_) {
899 module_deps[mod_it.second] = std::set<RTLIL::Module*>();
900 for (auto &cell_it : mod_it.second->cells_)
901 if (design->modules_.count(cell_it.second->type) > 0)
902 module_deps[mod_it.second].insert(design->modules_.at(cell_it.second->type));
903 }
904
905 // simple good-enough topological sort
906 // (O(n*m) on n elements and depth m)
907 while (module_deps.size() > 0) {
908 size_t sorted_modules_idx = sorted_modules.size();
909 for (auto &it : module_deps) {
910 for (auto &dep : it.second)
911 if (module_deps.count(dep) > 0)
912 goto not_ready_yet;
913 // log("Next in topological sort: %s\n", RTLIL::id2cstr(it.first->name));
914 sorted_modules.push_back(it.first);
915 not_ready_yet:;
916 }
917 if (sorted_modules_idx == sorted_modules.size())
918 log_error("Cyclic dependency between modules found! Cycle includes module %s.\n", RTLIL::id2cstr(module_deps.begin()->first->name));
919 while (sorted_modules_idx < sorted_modules.size())
920 module_deps.erase(sorted_modules.at(sorted_modules_idx++));
921 }
922
923 for (auto module : sorted_modules)
924 {
925 if (module->get_bool_attribute("\\blackbox") || module->has_memories_warn() || module->has_processes_warn())
926 continue;
927
928 log("Creating SMT-LIBv2 representation of module %s.\n", log_id(module));
929
930 Smt2Worker worker(module, bvmode, memmode, regsmode, wiresmode, verbose);
931 worker.run();
932 worker.write(*f);
933 }
934
935 Module *topmod = design->top_module();
936 if (topmod)
937 *f << stringf("; yosys-smt2-topmod %s\n", log_id(topmod));
938
939 *f << stringf("; end of yosys output\n");
940
941 if (template_f.is_open()) {
942 std::string line;
943 while (std::getline(template_f, line))
944 *f << line << std::endl;
945 }
946 }
947 } Smt2Backend;
948
949 PRIVATE_NAMESPACE_END