Added $assume support to write_smt2
[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, verbose;
36 int idcounter;
37
38 std::vector<std::string> decls, trans;
39 std::map<RTLIL::SigBit, RTLIL::Cell*> bit_driver;
40 std::set<RTLIL::Cell*> exported_cells;
41 pool<Cell*> recursive_cells, registers;
42
43 std::map<RTLIL::SigBit, std::pair<int, int>> fcache;
44 std::map<int, int> bvsizes;
45
46 Smt2Worker(RTLIL::Module *module, bool bvmode, bool verbose) :
47 ct(module->design), sigmap(module), module(module), bvmode(bvmode), verbose(verbose), idcounter(0)
48 {
49 decls.push_back(stringf("(declare-sort |%s_s| 0)\n", log_id(module)));
50
51 for (auto cell : module->cells())
52 for (auto &conn : cell->connections()) {
53 bool is_input = ct.cell_input(cell->type, conn.first);
54 bool is_output = ct.cell_output(cell->type, conn.first);
55 if (is_output && !is_input)
56 for (auto bit : sigmap(conn.second)) {
57 if (bit_driver.count(bit))
58 log_error("Found multiple drivers for %s.\n", log_signal(bit));
59 bit_driver[bit] = cell;
60 }
61 else if (is_output || !is_input)
62 log_error("Unsupported or unknown directionality on port %s of cell %s.%s (%s).\n",
63 log_id(conn.first), log_id(module), log_id(cell), log_id(cell->type));
64 }
65 }
66
67 void register_bool(RTLIL::SigBit bit, int id)
68 {
69 if (verbose) log("%*s-> register_bool: %s %d\n", 2+2*GetSize(recursive_cells), "",
70 log_signal(bit), id);
71
72 sigmap.apply(bit);
73 log_assert(fcache.count(bit) == 0);
74 fcache[bit] = std::pair<int, int>(id, -1);
75 }
76
77 void register_bv(RTLIL::SigSpec sig, int id)
78 {
79 if (verbose) log("%*s-> register_bv: %s %d\n", 2+2*GetSize(recursive_cells), "",
80 log_signal(sig), id);
81
82 log_assert(bvmode);
83 sigmap.apply(sig);
84
85 log_assert(bvsizes.count(id) == 0);
86 bvsizes[id] = GetSize(sig);
87
88 for (int i = 0; i < GetSize(sig); i++) {
89 log_assert(fcache.count(sig[i]) == 0);
90 fcache[sig[i]] = std::pair<int, int>(id, i);
91 }
92 }
93
94 void register_boolvec(RTLIL::SigSpec sig, int id)
95 {
96 if (verbose) log("%*s-> register_boolvec: %s %d\n", 2+2*GetSize(recursive_cells), "",
97 log_signal(sig), id);
98
99 log_assert(bvmode);
100 sigmap.apply(sig);
101 register_bool(sig[0], id);
102
103 for (int i = 1; i < GetSize(sig); i++)
104 sigmap.add(sig[i], RTLIL::State::S0);
105 }
106
107 std::string get_bool(RTLIL::SigBit bit, const char *state_name = "state")
108 {
109 sigmap.apply(bit);
110
111 if (bit.wire == nullptr)
112 return bit == RTLIL::State::S1 ? "true" : "false";
113
114 if (bit_driver.count(bit))
115 export_cell(bit_driver.at(bit));
116 sigmap.apply(bit);
117
118 if (fcache.count(bit) == 0) {
119 if (verbose) log("%*s-> external bool: %s\n", 2+2*GetSize(recursive_cells), "",
120 log_signal(bit));
121 decls.push_back(stringf("(declare-fun |%s#%d| (|%s_s|) Bool) ; %s\n",
122 log_id(module), idcounter, log_id(module), log_signal(bit)));
123 register_bool(bit, idcounter++);
124 }
125
126 auto f = fcache.at(bit);
127 if (f.second >= 0)
128 return stringf("(= ((_ extract %d %d) (|%s#%d| %s)) #b1)", f.second, f.second, log_id(module), f.first, state_name);
129 return stringf("(|%s#%d| %s)", log_id(module), f.first, state_name);
130 }
131
132 std::string get_bool(RTLIL::SigSpec sig, const char *state_name = "state")
133 {
134 return get_bool(sig.to_single_sigbit(), state_name);
135 }
136
137 std::string get_bv(RTLIL::SigSpec sig, const char *state_name = "state")
138 {
139 log_assert(bvmode);
140 sigmap.apply(sig);
141
142 std::vector<std::string> subexpr;
143
144 SigSpec orig_sig;
145 while (orig_sig != sig) {
146 for (auto bit : sig)
147 if (bit_driver.count(bit))
148 export_cell(bit_driver.at(bit));
149 orig_sig = sig;
150 sigmap.apply(sig);
151 }
152
153 for (int i = 0, j = 1; i < GetSize(sig); i += j, j = 1)
154 {
155 if (sig[i].wire == nullptr) {
156 while (i+j < GetSize(sig) && sig[i+j].wire == nullptr) j++;
157 subexpr.push_back("#b");
158 for (int k = i+j-1; k >= i; k--)
159 subexpr.back() += sig[k] == RTLIL::State::S1 ? "1" : "0";
160 continue;
161 }
162
163 if (fcache.count(sig[i]) && fcache.at(sig[i]).second == -1) {
164 subexpr.push_back(stringf("(ite %s #b1 #b0)", get_bool(sig[i], state_name).c_str()));
165 continue;
166 }
167
168 if (fcache.count(sig[i])) {
169 auto t1 = fcache.at(sig[i]);
170 while (i+j < GetSize(sig)) {
171 if (fcache.count(sig[i+j]) == 0)
172 break;
173 auto t2 = fcache.at(sig[i+j]);
174 if (t1.first != t2.first)
175 break;
176 if (t1.second+j != t2.second)
177 break;
178 j++;
179 }
180 if (t1.second == 0 && j == bvsizes.at(t1.first))
181 subexpr.push_back(stringf("(|%s#%d| %s)", log_id(module), t1.first, state_name));
182 else
183 subexpr.push_back(stringf("((_ extract %d %d) (|%s#%d| %s))",
184 t1.second + j - 1, t1.second, log_id(module), t1.first, state_name));
185 continue;
186 }
187
188 std::set<RTLIL::SigBit> seen_bits = { sig[i] };
189 while (i+j < GetSize(sig) && sig[i+j].wire && !fcache.count(sig[i+j]) && !seen_bits.count(sig[i+j]))
190 seen_bits.insert(sig[i+j]), j++;
191
192 if (verbose) log("%*s-> external bv: %s\n", 2+2*GetSize(recursive_cells), "",
193 log_signal(sig.extract(i, j)));
194 for (auto bit : sig.extract(i, j))
195 log_assert(bit_driver.count(bit) == 0);
196 decls.push_back(stringf("(declare-fun |%s#%d| (|%s_s|) (_ BitVec %d)) ; %s\n",
197 log_id(module), idcounter, log_id(module), j, log_signal(sig.extract(i, j))));
198 subexpr.push_back(stringf("(|%s#%d| %s)", log_id(module), idcounter, state_name));
199 register_bv(sig.extract(i, j), idcounter++);
200 }
201
202 if (GetSize(subexpr) > 1) {
203 std::string expr = "(concat";
204 for (int i = GetSize(subexpr)-1; i >= 0; i--)
205 expr += " " + subexpr[i];
206 return expr + ")";
207 } else {
208 log_assert(GetSize(subexpr) == 1);
209 return subexpr[0];
210 }
211 }
212
213 void export_gate(RTLIL::Cell *cell, std::string expr)
214 {
215 RTLIL::SigBit bit = sigmap(cell->getPort("\\Y").to_single_sigbit());
216 std::string processed_expr;
217
218 for (char ch : expr) {
219 if (ch == 'A') processed_expr += get_bool(cell->getPort("\\A"));
220 else if (ch == 'B') processed_expr += get_bool(cell->getPort("\\B"));
221 else if (ch == 'C') processed_expr += get_bool(cell->getPort("\\C"));
222 else if (ch == 'D') processed_expr += get_bool(cell->getPort("\\D"));
223 else if (ch == 'S') processed_expr += get_bool(cell->getPort("\\S"));
224 else processed_expr += ch;
225 }
226
227 if (verbose) log("%*s-> import cell: %s\n", 2+2*GetSize(recursive_cells), "",
228 log_id(cell));
229 decls.push_back(stringf("(define-fun |%s#%d| ((state |%s_s|)) Bool %s) ; %s\n",
230 log_id(module), idcounter, log_id(module), processed_expr.c_str(), log_signal(bit)));
231 register_bool(bit, idcounter++);
232 recursive_cells.erase(cell);
233 }
234
235 void export_bvop(RTLIL::Cell *cell, std::string expr, char type = 0)
236 {
237 RTLIL::SigSpec sig_a, sig_b;
238 RTLIL::SigSpec sig_y = sigmap(cell->getPort("\\Y"));
239 bool is_signed = cell->getParam("\\A_SIGNED").as_bool();
240 int width = GetSize(sig_y);
241
242 if (type == 's' || type == 'd' || type == 'b') {
243 width = std::max(width, GetSize(cell->getPort("\\A")));
244 width = std::max(width, GetSize(cell->getPort("\\B")));
245 }
246
247 if (cell->hasPort("\\A")) {
248 sig_a = cell->getPort("\\A");
249 sig_a.extend_u0(width, is_signed);
250 }
251
252 if (cell->hasPort("\\B")) {
253 sig_b = cell->getPort("\\B");
254 sig_b.extend_u0(width, is_signed && !(type == 's'));
255 }
256
257 std::string processed_expr;
258
259 for (char ch : expr) {
260 if (ch == 'A') processed_expr += get_bv(sig_a);
261 else if (ch == 'B') processed_expr += get_bv(sig_b);
262 else if (ch == 'L') processed_expr += is_signed ? "a" : "l";
263 else if (ch == 'U') processed_expr += is_signed ? "s" : "u";
264 else processed_expr += ch;
265 }
266
267 if (width != GetSize(sig_y) && type != 'b')
268 processed_expr = stringf("((_ extract %d 0) %s)", GetSize(sig_y)-1, processed_expr.c_str());
269
270 if (verbose) log("%*s-> import cell: %s\n", 2+2*GetSize(recursive_cells), "",
271 log_id(cell));
272
273 if (type == 'b') {
274 decls.push_back(stringf("(define-fun |%s#%d| ((state |%s_s|)) Bool %s) ; %s\n",
275 log_id(module), idcounter, log_id(module), processed_expr.c_str(), log_signal(sig_y)));
276 register_boolvec(sig_y, idcounter++);
277 } else {
278 decls.push_back(stringf("(define-fun |%s#%d| ((state |%s_s|)) (_ BitVec %d) %s) ; %s\n",
279 log_id(module), idcounter, log_id(module), GetSize(sig_y), processed_expr.c_str(), log_signal(sig_y)));
280 register_bv(sig_y, idcounter++);
281 }
282
283 recursive_cells.erase(cell);
284 }
285
286 void export_reduce(RTLIL::Cell *cell, std::string expr, bool identity_val)
287 {
288 RTLIL::SigSpec sig_y = sigmap(cell->getPort("\\Y"));
289 std::string processed_expr;
290
291 for (char ch : expr)
292 if (ch == 'A' || ch == 'B') {
293 RTLIL::SigSpec sig = sigmap(cell->getPort(stringf("\\%c", ch)));
294 for (auto bit : sig)
295 processed_expr += " " + get_bool(bit);
296 if (GetSize(sig) == 1)
297 processed_expr += identity_val ? " true" : " false";
298 } else
299 processed_expr += ch;
300
301 if (verbose) log("%*s-> import cell: %s\n", 2+2*GetSize(recursive_cells), "",
302 log_id(cell));
303 decls.push_back(stringf("(define-fun |%s#%d| ((state |%s_s|)) Bool %s) ; %s\n",
304 log_id(module), idcounter, log_id(module), processed_expr.c_str(), log_signal(sig_y)));
305 register_boolvec(sig_y, idcounter++);
306 recursive_cells.erase(cell);
307 }
308
309 void export_cell(RTLIL::Cell *cell)
310 {
311 if (verbose) log("%*s=> export_cell %s (%s) [%s]\n", 2+2*GetSize(recursive_cells), "",
312 log_id(cell), log_id(cell->type), exported_cells.count(cell) ? "old" : "new");
313
314 if (recursive_cells.count(cell))
315 log_error("Found logic loop in module %s! See cell %s.\n", log_id(module), log_id(cell));
316
317 if (exported_cells.count(cell))
318 return;
319 exported_cells.insert(cell);
320 recursive_cells.insert(cell);
321
322 if (cell->type == "$_DFF_P_" || cell->type == "$_DFF_N_")
323 {
324 registers.insert(cell);
325 decls.push_back(stringf("(declare-fun |%s#%d| (|%s_s|) Bool) ; %s\n",
326 log_id(module), idcounter, log_id(module), log_signal(cell->getPort("\\Q"))));
327 register_bool(cell->getPort("\\Q"), idcounter++);
328 recursive_cells.erase(cell);
329 return;
330 }
331
332 if (cell->type == "$_BUF_") return export_gate(cell, "A");
333 if (cell->type == "$_NOT_") return export_gate(cell, "(not A)");
334 if (cell->type == "$_AND_") return export_gate(cell, "(and A B)");
335 if (cell->type == "$_NAND_") return export_gate(cell, "(not (and A B))");
336 if (cell->type == "$_OR_") return export_gate(cell, "(or A B)");
337 if (cell->type == "$_NOR_") return export_gate(cell, "(not (or A B))");
338 if (cell->type == "$_XOR_") return export_gate(cell, "(xor A B)");
339 if (cell->type == "$_XNOR_") return export_gate(cell, "(not (xor A B))");
340 if (cell->type == "$_MUX_") return export_gate(cell, "(ite S B A)");
341 if (cell->type == "$_AOI3_") return export_gate(cell, "(not (or (and A B) C))");
342 if (cell->type == "$_OAI3_") return export_gate(cell, "(not (and (or A B) C))");
343 if (cell->type == "$_AOI4_") return export_gate(cell, "(not (or (and A B) (and C D)))");
344 if (cell->type == "$_OAI4_") return export_gate(cell, "(not (and (or A B) (or C D)))");
345
346 // FIXME: $lut
347
348 if (!bvmode)
349 log_error("Unsupported cell type %s for cell %s.%s. (Maybe this cell type would be supported in -bv mode?)\n",
350 log_id(cell->type), log_id(module), log_id(cell));
351
352 if (cell->type == "$dff")
353 {
354 registers.insert(cell);
355 decls.push_back(stringf("(declare-fun |%s#%d| (|%s_s|) (_ BitVec %d)) ; %s\n",
356 log_id(module), idcounter, log_id(module), GetSize(cell->getPort("\\Q")), log_signal(cell->getPort("\\Q"))));
357 register_bv(cell->getPort("\\Q"), idcounter++);
358 recursive_cells.erase(cell);
359 return;
360 }
361
362 if (cell->type == "$and") return export_bvop(cell, "(bvand A B)");
363 if (cell->type == "$or") return export_bvop(cell, "(bvor A B)");
364 if (cell->type == "$xor") return export_bvop(cell, "(bvxor A B)");
365 if (cell->type == "$xnor") return export_bvop(cell, "(bvxnor A B)");
366
367 if (cell->type == "$shl") return export_bvop(cell, "(bvshl A B)", 's');
368 if (cell->type == "$shr") return export_bvop(cell, "(bvlshr A B)", 's');
369 if (cell->type == "$sshl") return export_bvop(cell, "(bvshl A B)", 's');
370 if (cell->type == "$sshr") return export_bvop(cell, "(bvLshr A B)", 's');
371
372 // FIXME: $shift $shiftx
373
374 if (cell->type == "$lt") return export_bvop(cell, "(bvUlt A B)", 'b');
375 if (cell->type == "$le") return export_bvop(cell, "(bvUle A B)", 'b');
376 if (cell->type == "$ge") return export_bvop(cell, "(bvUge A B)", 'b');
377 if (cell->type == "$gt") return export_bvop(cell, "(bvUgt A B)", 'b');
378
379 if (cell->type == "$ne") return export_bvop(cell, "(distinct A B)", 'b');
380 if (cell->type == "$nex") return export_bvop(cell, "(distinct A B)", 'b');
381 if (cell->type == "$eq") return export_bvop(cell, "(= A B)", 'b');
382 if (cell->type == "$eqx") return export_bvop(cell, "(= A B)", 'b');
383
384 if (cell->type == "$not") return export_bvop(cell, "(bvnot A)");
385 if (cell->type == "$pos") return export_bvop(cell, "A");
386 if (cell->type == "$neg") return export_bvop(cell, "(bvneg A)");
387
388 if (cell->type == "$add") return export_bvop(cell, "(bvadd A B)");
389 if (cell->type == "$sub") return export_bvop(cell, "(bvsub A B)");
390 if (cell->type == "$mul") return export_bvop(cell, "(bvmul A B)");
391 if (cell->type == "$div") return export_bvop(cell, "(bvUdiv A B)", 'd');
392 if (cell->type == "$mod") return export_bvop(cell, "(bvUrem A B)", 'd');
393
394 if (cell->type == "$reduce_and") return export_reduce(cell, "(and A)", true);
395 if (cell->type == "$reduce_or") return export_reduce(cell, "(or A)", false);
396 if (cell->type == "$reduce_xor") return export_reduce(cell, "(xor A)", false);
397 if (cell->type == "$reduce_xnor") return export_reduce(cell, "(not (xor A))", false);
398 if (cell->type == "$reduce_bool") return export_reduce(cell, "(or A)", false);
399
400 if (cell->type == "$logic_not") return export_reduce(cell, "(not (or A))", false);
401 if (cell->type == "$logic_and") return export_reduce(cell, "(and (or A) (or B))", false);
402 if (cell->type == "$logic_or") return export_reduce(cell, "(or A B)", false);
403
404 if (cell->type == "$mux" || cell->type == "$pmux")
405 {
406 int width = GetSize(cell->getPort("\\Y"));
407 std::string processed_expr = get_bv(cell->getPort("\\A"));
408
409 RTLIL::SigSpec sig_b = cell->getPort("\\B");
410 RTLIL::SigSpec sig_s = cell->getPort("\\S");
411 get_bv(sig_b);
412 get_bv(sig_s);
413
414 for (int i = 0; i < GetSize(sig_s); i++)
415 processed_expr = stringf("(ite %s %s %s)", get_bool(sig_s[i]).c_str(),
416 get_bv(sig_b.extract(i*width, width)).c_str(), processed_expr.c_str());
417
418 if (verbose) log("%*s-> import cell: %s\n", 2+2*GetSize(recursive_cells), "",
419 log_id(cell));
420 RTLIL::SigSpec sig = sigmap(cell->getPort("\\Y"));
421 decls.push_back(stringf("(define-fun |%s#%d| ((state |%s_s|)) (_ BitVec %d) %s) ; %s\n",
422 log_id(module), idcounter, log_id(module), width, processed_expr.c_str(), log_signal(sig)));
423 register_bv(sig, idcounter++);
424 recursive_cells.erase(cell);
425 return;
426 }
427
428 // FIXME: $slice $concat
429
430 log_error("Unsupported cell type %s for cell %s.%s.\n",
431 log_id(cell->type), log_id(module), log_id(cell));
432 }
433
434 void run()
435 {
436 if (verbose) log("=> export logic driving outputs\n");
437
438 for (auto wire : module->wires())
439 if (wire->port_id || wire->get_bool_attribute("\\keep")) {
440 RTLIL::SigSpec sig = sigmap(wire);
441 if (bvmode && GetSize(sig) > 1) {
442 decls.push_back(stringf("(define-fun |%s_n %s| ((state |%s_s|)) (_ BitVec %d) %s)\n",
443 log_id(module), log_id(wire), log_id(module), GetSize(sig), get_bv(sig).c_str()));
444 } else {
445 for (int i = 0; i < GetSize(sig); i++)
446 if (GetSize(sig) > 1)
447 decls.push_back(stringf("(define-fun |%s_n %s %d| ((state |%s_s|)) Bool %s)\n",
448 log_id(module), log_id(wire), i, log_id(module), get_bool(sig[i]).c_str()));
449 else
450 decls.push_back(stringf("(define-fun |%s_n %s| ((state |%s_s|)) Bool %s)\n",
451 log_id(module), log_id(wire), log_id(module), get_bool(sig[i]).c_str()));
452 }
453 }
454
455 if (verbose) log("=> export logic associated with the initial state\n");
456
457 vector<string> init_list;
458 for (auto wire : module->wires())
459 if (wire->attributes.count("\\init")) {
460 RTLIL::SigSpec sig = sigmap(wire);
461 Const val = wire->attributes.at("\\init");
462 val.bits.resize(GetSize(sig));
463 if (bvmode && GetSize(sig) > 1) {
464 init_list.push_back(stringf("(= %s #b%s) ; %s", get_bv(sig).c_str(), val.as_string().c_str(), log_id(wire)));
465 } else {
466 for (int i = 0; i < GetSize(sig); i++)
467 init_list.push_back(stringf("(= %s %s) ; %s", get_bool(sig[i]).c_str(), val.bits[i] == State::S1 ? "true" : "false", log_id(wire)));
468 }
469 }
470
471 if (verbose) log("=> export logic driving asserts\n");
472
473 vector<int> assert_list, assume_list;
474 for (auto cell : module->cells())
475 if (cell->type.in("$assert", "$assume")) {
476 string name_a = get_bool(cell->getPort("\\A"));
477 string name_en = get_bool(cell->getPort("\\EN"));
478 decls.push_back(stringf("(define-fun |%s#%d| ((state |%s_s|)) Bool (or %s (not %s))) ; %s\n",
479 log_id(module), idcounter, log_id(module), name_a.c_str(), name_en.c_str(), log_id(cell)));
480 if (cell->type == "$assert")
481 assert_list.push_back(idcounter++);
482 else
483 assume_list.push_back(idcounter++);
484 }
485
486 for (int iter = 1; !registers.empty(); iter++)
487 {
488 pool<Cell*> this_regs;
489 this_regs.swap(registers);
490
491 if (verbose) log("=> export logic driving registers [iteration %d]\n", iter);
492
493 for (auto cell : this_regs) {
494 if (cell->type == "$_DFF_P_" || cell->type == "$_DFF_N_") {
495 std::string expr_d = get_bool(cell->getPort("\\D"));
496 std::string expr_q = get_bool(cell->getPort("\\Q"), "next_state");
497 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"))));
498 }
499 if (cell->type == "$dff") {
500 std::string expr_d = get_bv(cell->getPort("\\D"));
501 std::string expr_q = get_bv(cell->getPort("\\Q"), "next_state");
502 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"))));
503 }
504 }
505 }
506
507 string assert_expr = assert_list.empty() ? "true" : "(and";
508 if (!assert_list.empty()) {
509 for (int i : assert_list)
510 assert_expr += stringf(" (|%s#%d| state)", log_id(module), i);
511 assert_expr += ")";
512 }
513 decls.push_back(stringf("(define-fun |%s_a| ((state |%s_s|)) Bool %s)\n",
514 log_id(module), log_id(module), assert_expr.c_str()));
515
516 string assume_expr = assume_list.empty() ? "true" : "(and";
517 if (!assume_list.empty()) {
518 for (int i : assume_list)
519 assume_expr += stringf(" (|%s#%d| state)", log_id(module), i);
520 assume_expr += ")";
521 }
522 decls.push_back(stringf("(define-fun |%s_u| ((state |%s_s|)) Bool %s)\n",
523 log_id(module), log_id(module), assume_expr.c_str()));
524
525 string init_expr = init_list.empty() ? "true" : "(and";
526 if (!init_list.empty()) {
527 for (auto &str : init_list)
528 init_expr += stringf("\n\t%s", str.c_str());
529 init_expr += "\n)";
530 }
531 decls.push_back(stringf("(define-fun |%s_i| ((state |%s_s|)) Bool %s)\n",
532 log_id(module), log_id(module), init_expr.c_str()));
533 }
534
535 void write(std::ostream &f)
536 {
537 for (auto it : decls)
538 f << it;
539
540 f << stringf("(define-fun |%s_t| ((state |%s_s|) (next_state |%s_s|)) Bool ", log_id(module), log_id(module), log_id(module));
541 if (GetSize(trans) > 1) {
542 f << "(and\n";
543 for (auto it : trans)
544 f << it;
545 f << "))";
546 } else
547 if (GetSize(trans) == 1)
548 f << "\n" + trans.front() + ")";
549 else
550 f << "true)";
551 f << stringf(" ; end of module %s\n", log_id(module));
552 }
553 };
554
555 struct Smt2Backend : public Backend {
556 Smt2Backend() : Backend("smt2", "write design to SMT-LIBv2 file") { }
557 virtual void help()
558 {
559 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
560 log("\n");
561 log(" write_smt2 [options] [filename]\n");
562 log("\n");
563 log("Write a SMT-LIBv2 [1] description of the current design. For a module with name\n");
564 log("'<mod>' this will declare the sort '<mod>_s' (state of the module) and the\n");
565 log("functions operating on that state.\n");
566 log("\n");
567 log("The '<mod>_s' sort represents a module state. Additional '<mod>_n' functions\n");
568 log("are provided that can be used to access the values of the signals in the module.\n");
569 log("Only ports, and signals with the 'keep' attribute set are made available via\n");
570 log("such functions. Without the -bv option, multi-bit wires are exported as\n");
571 log("separate functions of type Bool for the individual bits. With the -bv option\n");
572 log("multi-bit wires are exported as single functions of type BitVec.\n");
573 log("\n");
574 log("The '<mod>_t' function evaluates to 'true' when the given pair of states\n");
575 log("describes a valid state transition.\n");
576 log("\n");
577 log("The '<mod>_a' function evaluates to 'true' when the given state satisfies\n");
578 log("the asserts in the module.\n");
579 log("\n");
580 log("The '<mod>_u' function evaluates to 'true' when the given state satisfies\n");
581 log("the assumptions in the module.\n");
582 log("\n");
583 log("The '<mod>_i' function evaluates to 'true' when the given state conforms\n");
584 log("to the initial state.\n");
585 log("\n");
586 log(" -verbose\n");
587 log(" this will print the recursive walk used to export the modules.\n");
588 log("\n");
589 log(" -bv\n");
590 log(" enable support for BitVec (FixedSizeBitVectors theory). with this\n");
591 log(" option set multi-bit wires are represented using the BitVec sort and\n");
592 log(" support for coarse grain cells (incl. arithmetic) is enabled.\n");
593 log("\n");
594 log(" -tpl <template_file>\n");
595 log(" use the given template file. the line containing only the token '%%%%'\n");
596 log(" is replaced with the regular output of this command.\n");
597 log("\n");
598 log("[1] For more information on SMT-LIBv2 visit http://smt-lib.org/ or read David\n");
599 log("R. Cok's tutorial: http://www.grammatech.com/resources/smt/SMTLIBTutorial.pdf\n");
600 log("\n");
601 log("---------------------------------------------------------------------------\n");
602 log("\n");
603 log("Example:\n");
604 log("\n");
605 log("Consider the following module (test.v). We want to prove that the output can\n");
606 log("never transition from a non-zero value to a zero value.\n");
607 log("\n");
608 log(" module test(input clk, output reg [3:0] y);\n");
609 log(" always @(posedge clk)\n");
610 log(" y <= (y << 1) | ^y;\n");
611 log(" endmodule\n");
612 log("\n");
613 log("For this proof we create the following template (test.tpl).\n");
614 log("\n");
615 log(" ; we need QF_UFBV for this poof\n");
616 log(" (set-logic QF_UFBV)\n");
617 log("\n");
618 log(" ; insert the auto-generated code here\n");
619 log(" %%%%\n");
620 log("\n");
621 log(" ; declare two state variables s1 and s2\n");
622 log(" (declare-fun s1 () test_s)\n");
623 log(" (declare-fun s2 () test_s)\n");
624 log("\n");
625 log(" ; state s2 is the successor of state s1\n");
626 log(" (assert (test_t s1 s2))\n");
627 log("\n");
628 log(" ; we are looking for a model with y non-zero in s1\n");
629 log(" (assert (distinct (|test_n y| s1) #b0000))\n");
630 log("\n");
631 log(" ; we are looking for a model with y zero in s2\n");
632 log(" (assert (= (|test_n y| s2) #b0000))\n");
633 log("\n");
634 log(" ; is there such a model?\n");
635 log(" (check-sat)\n");
636 log("\n");
637 log("The following yosys script will create a 'test.smt2' file for our proof:\n");
638 log("\n");
639 log(" read_verilog test.v\n");
640 log(" hierarchy -check; proc; opt; check -assert\n");
641 log(" write_smt2 -bv -tpl test.tpl test.smt2\n");
642 log("\n");
643 log("Running 'cvc4 test.smt2' will print 'unsat' because y can never transition\n");
644 log("from non-zero to zero in the test design.\n");
645 log("\n");
646 }
647 virtual void execute(std::ostream *&f, std::string filename, std::vector<std::string> args, RTLIL::Design *design)
648 {
649 std::ifstream template_f;
650 bool bvmode = false, verbose = false;
651
652 log_header("Executing SMT2 backend.\n");
653
654 size_t argidx;
655 for (argidx = 1; argidx < args.size(); argidx++)
656 {
657 if (args[argidx] == "-tpl" && argidx+1 < args.size()) {
658 template_f.open(args[++argidx]);
659 if (template_f.fail())
660 log_error("Can't open template file `%s'.\n", args[argidx].c_str());
661 continue;
662 }
663 if (args[argidx] == "-bv") {
664 bvmode = true;
665 continue;
666 }
667 if (args[argidx] == "-verbose") {
668 verbose = true;
669 continue;
670 }
671 break;
672 }
673 extra_args(f, filename, args, argidx);
674
675 if (template_f.is_open()) {
676 std::string line;
677 while (std::getline(template_f, line)) {
678 int indent = 0;
679 while (indent < GetSize(line) && (line[indent] == ' ' || line[indent] == '\t'))
680 indent++;
681 if (line.substr(indent, 2) == "%%")
682 break;
683 *f << line << std::endl;
684 }
685 }
686
687 *f << stringf("; SMT-LIBv2 description generated by %s\n", yosys_version_str);
688
689 for (auto module : design->modules())
690 {
691 if (module->get_bool_attribute("\\blackbox") || module->has_memories_warn() || module->has_processes_warn())
692 continue;
693
694 log("Creating SMT-LIBv2 representation of module %s.\n", log_id(module));
695
696 Smt2Worker worker(module, bvmode, verbose);
697 worker.run();
698 worker.write(*f);
699 }
700
701 *f << stringf("; end of yosys output\n");
702
703 if (template_f.is_open()) {
704 std::string line;
705 while (std::getline(template_f, line))
706 *f << line << std::endl;
707 }
708 }
709 } Smt2Backend;
710
711 PRIVATE_NAMESPACE_END