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