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