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