Merge branch 'master' of github.com:cliffordwolf/yosys
[yosys.git] / backends / smt2 / smt2.cc
1 /*
2 * yosys -- Yosys Open SYnthesis Suite
3 *
4 * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
5 *
6 * Permission to use, copy, modify, and/or distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 *
18 */
19
20 #include "kernel/rtlil.h"
21 #include "kernel/register.h"
22 #include "kernel/sigtools.h"
23 #include "kernel/celltypes.h"
24 #include "kernel/log.h"
25 #include <string>
26
27 USING_YOSYS_NAMESPACE
28 PRIVATE_NAMESPACE_BEGIN
29
30 struct Smt2Worker
31 {
32 CellTypes ct;
33 SigMap sigmap;
34 RTLIL::Module *module;
35 bool bvmode, memmode, regsmode, wiresmode, verbose;
36 int idcounter;
37
38 std::vector<std::string> decls, trans, hier;
39 std::map<RTLIL::SigBit, RTLIL::Cell*> bit_driver;
40 std::set<RTLIL::Cell*> exported_cells, hiercells;
41 pool<Cell*> recursive_cells, registers;
42
43 std::map<RTLIL::SigBit, std::pair<int, int>> fcache;
44 std::map<Cell*, int> memarrays;
45 std::map<int, int> bvsizes;
46
47 Smt2Worker(RTLIL::Module *module, bool bvmode, bool memmode, bool regsmode, bool wiresmode, bool verbose) :
48 ct(module->design), sigmap(module), module(module), bvmode(bvmode), memmode(memmode),
49 regsmode(regsmode), wiresmode(wiresmode), verbose(verbose), idcounter(0)
50 {
51 decls.push_back(stringf("(declare-sort |%s_s| 0)\n", log_id(module)));
52 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 // FIXME: $shift $shiftx
387
388 if (cell->type == "$lt") return export_bvop(cell, "(bvUlt A B)", 'b');
389 if (cell->type == "$le") return export_bvop(cell, "(bvUle A B)", 'b');
390 if (cell->type == "$ge") return export_bvop(cell, "(bvUge A B)", 'b');
391 if (cell->type == "$gt") return export_bvop(cell, "(bvUgt A B)", 'b');
392
393 if (cell->type == "$ne") return export_bvop(cell, "(distinct A B)", 'b');
394 if (cell->type == "$nex") return export_bvop(cell, "(distinct A B)", 'b');
395 if (cell->type == "$eq") return export_bvop(cell, "(= A B)", 'b');
396 if (cell->type == "$eqx") return export_bvop(cell, "(= A B)", 'b');
397
398 if (cell->type == "$not") return export_bvop(cell, "(bvnot A)");
399 if (cell->type == "$pos") return export_bvop(cell, "A");
400 if (cell->type == "$neg") return export_bvop(cell, "(bvneg A)");
401
402 if (cell->type == "$add") return export_bvop(cell, "(bvadd A B)");
403 if (cell->type == "$sub") return export_bvop(cell, "(bvsub A B)");
404 if (cell->type == "$mul") return export_bvop(cell, "(bvmul A B)");
405 if (cell->type == "$div") return export_bvop(cell, "(bvUdiv A B)", 'd');
406 if (cell->type == "$mod") return export_bvop(cell, "(bvUrem A B)", 'd');
407
408 if (cell->type == "$reduce_and") return export_reduce(cell, "(and A)", true);
409 if (cell->type == "$reduce_or") return export_reduce(cell, "(or A)", false);
410 if (cell->type == "$reduce_xor") return export_reduce(cell, "(xor A)", false);
411 if (cell->type == "$reduce_xnor") return export_reduce(cell, "(not (xor A))", false);
412 if (cell->type == "$reduce_bool") return export_reduce(cell, "(or A)", false);
413
414 if (cell->type == "$logic_not") return export_reduce(cell, "(not (or A))", false);
415 if (cell->type == "$logic_and") return export_reduce(cell, "(and (or A) (or B))", false);
416 if (cell->type == "$logic_or") return export_reduce(cell, "(or A B)", false);
417
418 if (cell->type == "$mux" || cell->type == "$pmux")
419 {
420 int width = GetSize(cell->getPort("\\Y"));
421 std::string processed_expr = get_bv(cell->getPort("\\A"));
422
423 RTLIL::SigSpec sig_b = cell->getPort("\\B");
424 RTLIL::SigSpec sig_s = cell->getPort("\\S");
425 get_bv(sig_b);
426 get_bv(sig_s);
427
428 for (int i = 0; i < GetSize(sig_s); i++)
429 processed_expr = stringf("(ite %s %s %s)", get_bool(sig_s[i]).c_str(),
430 get_bv(sig_b.extract(i*width, width)).c_str(), processed_expr.c_str());
431
432 if (verbose) log("%*s-> import cell: %s\n", 2+2*GetSize(recursive_cells), "",
433 log_id(cell));
434 RTLIL::SigSpec sig = sigmap(cell->getPort("\\Y"));
435 decls.push_back(stringf("(define-fun |%s#%d| ((state |%s_s|)) (_ BitVec %d) %s) ; %s\n",
436 log_id(module), idcounter, log_id(module), width, processed_expr.c_str(), log_signal(sig)));
437 register_bv(sig, idcounter++);
438 recursive_cells.erase(cell);
439 return;
440 }
441
442 // FIXME: $slice $concat
443 }
444
445 if (memmode && cell->type == "$mem")
446 {
447 int arrayid = idcounter++;
448 memarrays[cell] = arrayid;
449
450 int abits = cell->getParam("\\ABITS").as_int();
451 int width = cell->getParam("\\WIDTH").as_int();
452 int rd_ports = cell->getParam("\\RD_PORTS").as_int();
453
454 decls.push_back(stringf("(declare-fun |%s#%d#0| (|%s_s|) (Array (_ BitVec %d) (_ BitVec %d))) ; %s\n",
455 log_id(module), arrayid, log_id(module), abits, width, log_id(cell)));
456
457 decls.push_back(stringf("(define-fun |%s_m %s| ((state |%s_s|)) (Array (_ BitVec %d) (_ BitVec %d)) (|%s#%d#0| state))\n",
458 log_id(module), log_id(cell), log_id(module), abits, width, log_id(module), arrayid));
459
460 for (int i = 0; i < rd_ports; i++)
461 {
462 std::string addr = get_bv(cell->getPort("\\RD_ADDR").extract(abits*i, abits));
463 SigSpec data_sig = cell->getPort("\\RD_DATA").extract(width*i, width);
464
465 if (cell->getParam("\\RD_CLK_ENABLE").extract(i).as_bool())
466 log_error("Read port %d (%s) of memory %s.%s is clocked. This is not supported by \"write_smt2\"! "
467 "Call \"memory\" with -nordff to avoid this error.\n", i, log_signal(data_sig), log_id(cell), log_id(module));
468
469 decls.push_back(stringf("(define-fun |%s#%d| ((state |%s_s|)) (_ BitVec %d) (select (|%s#%d#0| state) %s)) ; %s\n",
470 log_id(module), idcounter, log_id(module), width, log_id(module), arrayid, addr.c_str(), log_signal(data_sig)));
471 register_bv(data_sig, idcounter++);
472 }
473
474 registers.insert(cell);
475 recursive_cells.erase(cell);
476 return;
477 }
478
479 Module *m = module->design->module(cell->type);
480
481 if (m != nullptr)
482 {
483 decls.push_back(stringf("; yosys-smt2-cell %s %s\n", log_id(cell->type), log_id(cell->name)));
484 string cell_state = stringf("(|%s_h %s| state)", log_id(module), log_id(cell->name));
485
486 for (auto &conn : cell->connections())
487 {
488 Wire *w = m->wire(conn.first);
489 SigSpec sig = sigmap(conn.second);
490
491 if (w->port_output && !w->port_input) {
492 if (GetSize(w) > 1) {
493 if (bvmode) {
494 decls.push_back(stringf("(declare-fun |%s#%d| (|%s_s|) (_ BitVec %d)) ; %s\n",
495 log_id(module), idcounter, log_id(module), GetSize(w), log_signal(sig)));
496 register_bv(sig, idcounter++);
497 } else {
498 for (int i = 0; i < GetSize(w); i++) {
499 decls.push_back(stringf("(declare-fun |%s#%d| (|%s_s|) Bool) ; %s\n",
500 log_id(module), idcounter, log_id(module), log_signal(sig[i])));
501 register_bool(sig[i], idcounter++);
502 }
503 }
504 } else {
505 decls.push_back(stringf("(declare-fun |%s#%d| (|%s_s|) Bool) ; %s\n",
506 log_id(module), idcounter, log_id(module), log_signal(sig)));
507 register_bool(sig, idcounter++);
508 }
509 }
510 }
511
512 decls.push_back(stringf("(declare-fun |%s_h %s| (|%s_s|) |%s_s|)\n",
513 log_id(module), log_id(cell->name), log_id(module), log_id(cell->type)));
514
515 hiercells.insert(cell);
516 recursive_cells.erase(cell);
517
518 for (auto &conn : cell->connections())
519 {
520 Wire *w = m->wire(conn.first);
521 SigSpec sig = sigmap(conn.second);
522
523 if (bvmode || GetSize(w) == 1) {
524 hier.push_back(stringf(" (= %s (|%s_n %s| %s)) ; %s.%s\n", (GetSize(w) > 1 ? get_bv(sig) : get_bool(sig)).c_str(),
525 log_id(cell->type), log_id(w), cell_state.c_str(), log_id(cell->type), log_id(w)));
526 } else {
527 for (int i = 0; i < GetSize(w); i++)
528 hier.push_back(stringf(" (= %s (|%s_n %s %d| %s)) ; %s.%s[%d]\n", get_bool(sig[i]).c_str(),
529 log_id(cell->type), log_id(w), i, cell_state.c_str(), log_id(cell->type), log_id(w), i));
530 }
531 }
532
533 return;
534 }
535
536 log_error("Unsupported cell type %s for cell %s.%s. (Maybe this cell type would be supported in -bv or -mem mode?)\n",
537 log_id(cell->type), log_id(module), log_id(cell));
538 }
539
540 void run()
541 {
542 if (verbose) log("=> export logic driving outputs\n");
543
544 pool<SigBit> reg_bits;
545 if (regsmode) {
546 for (auto cell : module->cells())
547 if (cell->type.in("$_DFF_P_", "$_DFF_N_", "$dff")) {
548 // not using sigmap -- we want the net directly at the dff output
549 for (auto bit : cell->getPort("\\Q"))
550 reg_bits.insert(bit);
551 }
552 }
553
554 for (auto wire : module->wires()) {
555 bool is_register = false;
556 if (regsmode)
557 for (auto bit : SigSpec(wire))
558 if (reg_bits.count(bit))
559 is_register = true;
560 if (wire->port_id || is_register || wire->get_bool_attribute("\\keep") || (wiresmode && wire->name[0] == '\\')) {
561 RTLIL::SigSpec sig = sigmap(wire);
562 if (wire->port_input)
563 decls.push_back(stringf("; yosys-smt2-input %s %d\n", log_id(wire), wire->width));
564 if (wire->port_output)
565 decls.push_back(stringf("; yosys-smt2-output %s %d\n", log_id(wire), wire->width));
566 if (is_register)
567 decls.push_back(stringf("; yosys-smt2-register %s %d\n", log_id(wire), wire->width));
568 if (wire->get_bool_attribute("\\keep") || (wiresmode && wire->name[0] == '\\'))
569 decls.push_back(stringf("; yosys-smt2-wire %s %d\n", log_id(wire), wire->width));
570 if (bvmode && GetSize(sig) > 1) {
571 decls.push_back(stringf("(define-fun |%s_n %s| ((state |%s_s|)) (_ BitVec %d) %s)\n",
572 log_id(module), log_id(wire), log_id(module), GetSize(sig), get_bv(sig).c_str()));
573 } else {
574 for (int i = 0; i < GetSize(sig); i++)
575 if (GetSize(sig) > 1)
576 decls.push_back(stringf("(define-fun |%s_n %s %d| ((state |%s_s|)) Bool %s)\n",
577 log_id(module), log_id(wire), i, log_id(module), get_bool(sig[i]).c_str()));
578 else
579 decls.push_back(stringf("(define-fun |%s_n %s| ((state |%s_s|)) Bool %s)\n",
580 log_id(module), log_id(wire), log_id(module), get_bool(sig[i]).c_str()));
581 }
582 }
583 }
584
585 if (verbose) log("=> export logic associated with the initial state\n");
586
587 vector<string> init_list;
588 for (auto wire : module->wires())
589 if (wire->attributes.count("\\init")) {
590 RTLIL::SigSpec sig = sigmap(wire);
591 Const val = wire->attributes.at("\\init");
592 val.bits.resize(GetSize(sig));
593 if (bvmode && GetSize(sig) > 1) {
594 init_list.push_back(stringf("(= %s #b%s) ; %s", get_bv(sig).c_str(), val.as_string().c_str(), log_id(wire)));
595 } else {
596 for (int i = 0; i < GetSize(sig); i++)
597 init_list.push_back(stringf("(= %s %s) ; %s", get_bool(sig[i]).c_str(), val.bits[i] == State::S1 ? "true" : "false", log_id(wire)));
598 }
599 }
600
601 if (verbose) log("=> export logic driving asserts\n");
602
603 vector<string> assert_list, assume_list;
604 for (auto cell : module->cells())
605 if (cell->type.in("$assert", "$assume")) {
606 string name_a = get_bool(cell->getPort("\\A"));
607 string name_en = get_bool(cell->getPort("\\EN"));
608 decls.push_back(stringf("(define-fun |%s#%d| ((state |%s_s|)) Bool (or %s (not %s))) ; %s\n",
609 log_id(module), idcounter, log_id(module), name_a.c_str(), name_en.c_str(), log_id(cell)));
610 if (cell->type == "$assert")
611 assert_list.push_back(stringf("(|%s#%d| state)", log_id(module), idcounter++));
612 else
613 assume_list.push_back(stringf("(|%s#%d| state)", log_id(module), idcounter++));
614 }
615
616 for (int iter = 1; !registers.empty(); iter++)
617 {
618 pool<Cell*> this_regs;
619 this_regs.swap(registers);
620
621 if (verbose) log("=> export logic driving registers [iteration %d]\n", iter);
622
623 for (auto cell : this_regs)
624 {
625 if (cell->type == "$_DFF_P_" || cell->type == "$_DFF_N_")
626 {
627 std::string expr_d = get_bool(cell->getPort("\\D"));
628 std::string expr_q = get_bool(cell->getPort("\\Q"), "next_state");
629 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"))));
630 }
631
632 if (cell->type == "$dff")
633 {
634 std::string expr_d = get_bv(cell->getPort("\\D"));
635 std::string expr_q = get_bv(cell->getPort("\\Q"), "next_state");
636 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"))));
637 }
638
639 if (cell->type == "$mem")
640 {
641 int arrayid = memarrays.at(cell);
642
643 int abits = cell->getParam("\\ABITS").as_int();
644 int width = cell->getParam("\\WIDTH").as_int();
645 int wr_ports = cell->getParam("\\WR_PORTS").as_int();
646
647 for (int i = 0; i < wr_ports; i++)
648 {
649 std::string addr = get_bv(cell->getPort("\\WR_ADDR").extract(abits*i, abits));
650 std::string data = get_bv(cell->getPort("\\WR_DATA").extract(width*i, width));
651 std::string mask = get_bv(cell->getPort("\\WR_EN").extract(width*i, width));
652
653 data = stringf("(bvor (bvand %s %s) (bvand (select (|%s#%d#%d| state) %s) (bvnot %s)))",
654 data.c_str(), mask.c_str(), log_id(module), arrayid, i, addr.c_str(), mask.c_str());
655
656 decls.push_back(stringf("(define-fun |%s#%d#%d| ((state |%s_s|)) (Array (_ BitVec %d) (_ BitVec %d)) "
657 "(store (|%s#%d#%d| state) %s %s)) ; %s\n",
658 log_id(module), arrayid, i+1, log_id(module), abits, width,
659 log_id(module), arrayid, i, addr.c_str(), data.c_str(), log_id(cell)));
660 }
661
662 std::string expr_d = stringf("(|%s#%d#%d| state)", log_id(module), arrayid, wr_ports);
663 std::string expr_q = stringf("(|%s#%d#0| next_state)", log_id(module), arrayid);
664 trans.push_back(stringf(" (= %s %s) ; %s\n", expr_d.c_str(), expr_q.c_str(), log_id(cell)));
665 }
666 }
667 }
668
669 for (auto c : hiercells)
670 assert_list.push_back(stringf("(|%s_a| (|%s_h %s| state))", log_id(c->type), log_id(module), log_id(c->name)));
671
672 for (auto c : hiercells)
673 assume_list.push_back(stringf("(|%s_u| (|%s_h %s| state))", log_id(c->type), log_id(module), log_id(c->name)));
674
675 for (auto c : hiercells)
676 init_list.push_back(stringf("(|%s_i| (|%s_h %s| state))", log_id(c->type), log_id(module), log_id(c->name)));
677
678 string assert_expr = assert_list.empty() ? "true" : "(and";
679 if (!assert_list.empty()) {
680 for (auto &str : assert_list)
681 assert_expr += stringf("\n %s", str.c_str());
682 assert_expr += "\n)";
683 }
684 decls.push_back(stringf("(define-fun |%s_a| ((state |%s_s|)) Bool %s)\n",
685 log_id(module), log_id(module), assert_expr.c_str()));
686
687 string assume_expr = assume_list.empty() ? "true" : "(and";
688 if (!assume_list.empty()) {
689 for (auto &str : assume_list)
690 assume_expr += stringf("\n %s", str.c_str());
691 assume_expr += "\n)";
692 }
693 decls.push_back(stringf("(define-fun |%s_u| ((state |%s_s|)) Bool %s)\n",
694 log_id(module), log_id(module), assume_expr.c_str()));
695
696 string init_expr = init_list.empty() ? "true" : "(and";
697 if (!init_list.empty()) {
698 for (auto &str : init_list)
699 init_expr += stringf("\n %s", str.c_str());
700 init_expr += "\n)";
701 }
702 decls.push_back(stringf("(define-fun |%s_i| ((state |%s_s|)) Bool %s)\n",
703 log_id(module), log_id(module), init_expr.c_str()));
704 }
705
706 void write(std::ostream &f)
707 {
708 f << stringf("; yosys-smt2-module %s\n", log_id(module));
709
710 for (auto it : decls)
711 f << it;
712
713 f << stringf("(define-fun |%s_h| ((state |%s_s|)) Bool ", log_id(module), log_id(module));
714 if (GetSize(hier) > 1) {
715 f << "(and\n";
716 for (auto it : hier)
717 f << it;
718 f << "))\n";
719 } else
720 if (GetSize(hier) == 1)
721 f << "\n" + hier.front() + ")\n";
722 else
723 f << "true)\n";
724
725 f << stringf("(define-fun |%s_t| ((state |%s_s|) (next_state |%s_s|)) Bool ", log_id(module), log_id(module), log_id(module));
726 if (GetSize(trans) > 1) {
727 f << "(and\n";
728 for (auto it : trans)
729 f << it;
730 f << "))";
731 } else
732 if (GetSize(trans) == 1)
733 f << "\n" + trans.front() + ")";
734 else
735 f << "true)";
736 f << stringf(" ; end of module %s\n", log_id(module));
737 }
738 };
739
740 struct Smt2Backend : public Backend {
741 Smt2Backend() : Backend("smt2", "write design to SMT-LIBv2 file") { }
742 virtual void help()
743 {
744 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
745 log("\n");
746 log(" write_smt2 [options] [filename]\n");
747 log("\n");
748 log("Write a SMT-LIBv2 [1] description of the current design. For a module with name\n");
749 log("'<mod>' this will declare the sort '<mod>_s' (state of the module) and the\n");
750 log("functions operating on that state.\n");
751 log("\n");
752 log("The '<mod>_s' sort represents a module state. Additional '<mod>_n' functions\n");
753 log("are provided that can be used to access the values of the signals in the module.\n");
754 log("By default only ports, and signals with the 'keep' attribute set are made\n");
755 log("available via such functions. Without the -bv option, multi-bit wires are\n");
756 log("exported as separate functions of type Bool for the individual bits. With the\n");
757 log("-bv option multi-bit wires are exported as single functions of type BitVec.\n");
758 log("\n");
759 log("The '<mod>_t' function evaluates to 'true' when the given pair of states\n");
760 log("describes a valid state transition.\n");
761 log("\n");
762 log("The '<mod>_a' function evaluates to 'true' when the given state satisfies\n");
763 log("the asserts in the module.\n");
764 log("\n");
765 log("The '<mod>_u' function evaluates to 'true' when the given state satisfies\n");
766 log("the assumptions in the module.\n");
767 log("\n");
768 log("The '<mod>_i' function evaluates to 'true' when the given state conforms\n");
769 log("to the initial state. Furthermore the '<mod>_is' function should be asserted\n");
770 log("to be true for initial states in addition to '<mod>_i', and should be\n");
771 log("asserted to be false for non-initial states.\n");
772 log("\n");
773 log("For hierarchical designs, the '<mod>_h' function must be asserted for each\n");
774 log("state to establish the design hierarchy. The '<mod>_h <cellname>' function\n");
775 log("evaluates to the state corresponding to the given cell within <mod>.\n");
776 log("\n");
777 log(" -verbose\n");
778 log(" this will print the recursive walk used to export the modules.\n");
779 log("\n");
780 log(" -bv\n");
781 log(" enable support for BitVec (FixedSizeBitVectors theory). with this\n");
782 log(" option set multi-bit wires are represented using the BitVec sort and\n");
783 log(" support for coarse grain cells (incl. arithmetic) is enabled.\n");
784 log("\n");
785 log(" -mem\n");
786 log(" enable support for memories (via ArraysEx theory). this option\n");
787 log(" also implies -bv. only $mem cells without merged registers in\n");
788 log(" read ports are supported. call \"memory\" with -nordff to make sure\n");
789 log(" that no registers are merged into $mem read ports. '<mod>_m' functions\n");
790 log(" will be generated for accessing the arrays that are used to represent\n");
791 log(" memories.\n");
792 log("\n");
793 log(" -regs\n");
794 log(" also create '<mod>_n' functions for all registers.\n");
795 log("\n");
796 log(" -wires\n");
797 log(" also create '<mod>_n' functions for all public wires.\n");
798 log("\n");
799 log(" -tpl <template_file>\n");
800 log(" use the given template file. the line containing only the token '%%%%'\n");
801 log(" is replaced with the regular output of this command.\n");
802 log("\n");
803 log("[1] For more information on SMT-LIBv2 visit http://smt-lib.org/ or read David\n");
804 log("R. Cok's tutorial: http://www.grammatech.com/resources/smt/SMTLIBTutorial.pdf\n");
805 log("\n");
806 log("---------------------------------------------------------------------------\n");
807 log("\n");
808 log("Example:\n");
809 log("\n");
810 log("Consider the following module (test.v). We want to prove that the output can\n");
811 log("never transition from a non-zero value to a zero value.\n");
812 log("\n");
813 log(" module test(input clk, output reg [3:0] y);\n");
814 log(" always @(posedge clk)\n");
815 log(" y <= (y << 1) | ^y;\n");
816 log(" endmodule\n");
817 log("\n");
818 log("For this proof we create the following template (test.tpl).\n");
819 log("\n");
820 log(" ; we need QF_UFBV for this poof\n");
821 log(" (set-logic QF_UFBV)\n");
822 log("\n");
823 log(" ; insert the auto-generated code here\n");
824 log(" %%%%\n");
825 log("\n");
826 log(" ; declare two state variables s1 and s2\n");
827 log(" (declare-fun s1 () test_s)\n");
828 log(" (declare-fun s2 () test_s)\n");
829 log("\n");
830 log(" ; state s2 is the successor of state s1\n");
831 log(" (assert (test_t s1 s2))\n");
832 log("\n");
833 log(" ; we are looking for a model with y non-zero in s1\n");
834 log(" (assert (distinct (|test_n y| s1) #b0000))\n");
835 log("\n");
836 log(" ; we are looking for a model with y zero in s2\n");
837 log(" (assert (= (|test_n y| s2) #b0000))\n");
838 log("\n");
839 log(" ; is there such a model?\n");
840 log(" (check-sat)\n");
841 log("\n");
842 log("The following yosys script will create a 'test.smt2' file for our proof:\n");
843 log("\n");
844 log(" read_verilog test.v\n");
845 log(" hierarchy -check; proc; opt; check -assert\n");
846 log(" write_smt2 -bv -tpl test.tpl test.smt2\n");
847 log("\n");
848 log("Running 'cvc4 test.smt2' will print 'unsat' because y can never transition\n");
849 log("from non-zero to zero in the test design.\n");
850 log("\n");
851 }
852 virtual void execute(std::ostream *&f, std::string filename, std::vector<std::string> args, RTLIL::Design *design)
853 {
854 std::ifstream template_f;
855 bool bvmode = false, memmode = false, regsmode = false, wiresmode = false, verbose = false;
856
857 log_header(design, "Executing SMT2 backend.\n");
858
859 size_t argidx;
860 for (argidx = 1; argidx < args.size(); argidx++)
861 {
862 if (args[argidx] == "-tpl" && argidx+1 < args.size()) {
863 template_f.open(args[++argidx]);
864 if (template_f.fail())
865 log_error("Can't open template file `%s'.\n", args[argidx].c_str());
866 continue;
867 }
868 if (args[argidx] == "-bv") {
869 bvmode = true;
870 continue;
871 }
872 if (args[argidx] == "-mem") {
873 bvmode = true;
874 memmode = true;
875 continue;
876 }
877 if (args[argidx] == "-regs") {
878 regsmode = 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, regsmode, 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