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