4a53ce6d5d416c3b1a7d90f89086a77c33baff71
[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, statedt, forallmode;
36 dict<IdString, int> &mod_stbv_width;
37 int idcounter = 0, statebv_width = 0;
38
39 std::vector<std::string> decls, trans, hier, dtmembers;
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 pool<SigBit> clock_posedge, clock_negedge;
45 vector<string> ex_state_eq, ex_input_eq;
46
47 std::map<RTLIL::SigBit, std::pair<int, int>> fcache;
48 std::map<Cell*, int> memarrays;
49 std::map<int, int> bvsizes;
50 dict<IdString, char*> ids;
51
52 const char *get_id(IdString n)
53 {
54 if (ids.count(n) == 0) {
55 std::string str = log_id(n);
56 for (int i = 0; i < GetSize(str); i++) {
57 if (str[i] == '\\')
58 str[i] = '/';
59 }
60 ids[n] = strdup(str.c_str());
61 }
62 return ids[n];
63 }
64
65 template<typename T>
66 const char *get_id(T *obj) {
67 return get_id(obj->name);
68 }
69
70 void makebits(std::string name, int width = 0, std::string comment = std::string())
71 {
72 std::string decl_str;
73
74 if (statebv)
75 {
76 if (width == 0) {
77 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);
78 statebv_width += 1;
79 } else {
80 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);
81 statebv_width += width;
82 }
83 }
84 else if (statedt)
85 {
86 if (width == 0) {
87 decl_str = stringf(" (|%s| Bool)", name.c_str());
88 } else {
89 decl_str = stringf(" (|%s| (_ BitVec %d))", name.c_str(), width);
90 }
91 }
92 else
93 {
94 if (width == 0) {
95 decl_str = stringf("(declare-fun |%s| (|%s_s|) Bool)", name.c_str(), get_id(module));
96 } else {
97 decl_str = stringf("(declare-fun |%s| (|%s_s|) (_ BitVec %d))", name.c_str(), get_id(module), width);
98 }
99 }
100
101 if (!comment.empty())
102 decl_str += " ; " + comment;
103
104 if (statedt)
105 dtmembers.push_back(decl_str + "\n");
106 else
107 decls.push_back(decl_str + "\n");
108 }
109
110 Smt2Worker(RTLIL::Module *module, bool bvmode, bool memmode, bool wiresmode, bool verbose, bool statebv, bool statedt, bool forallmode,
111 dict<IdString, int> &mod_stbv_width, dict<IdString, dict<IdString, pair<bool, bool>>> &mod_clk_cache) :
112 ct(module->design), sigmap(module), module(module), bvmode(bvmode), memmode(memmode), wiresmode(wiresmode),
113 verbose(verbose), statebv(statebv), statedt(statedt), forallmode(forallmode), mod_stbv_width(mod_stbv_width)
114 {
115 pool<SigBit> noclock;
116
117 makebits(stringf("%s_is", get_id(module)));
118
119 for (auto cell : module->cells())
120 for (auto &conn : cell->connections())
121 {
122 if (GetSize(conn.second) == 0)
123 continue;
124
125 bool is_input = ct.cell_input(cell->type, conn.first);
126 bool is_output = ct.cell_output(cell->type, conn.first);
127
128 if (is_output && !is_input)
129 for (auto bit : sigmap(conn.second)) {
130 if (bit_driver.count(bit))
131 log_error("Found multiple drivers for %s.\n", log_signal(bit));
132 bit_driver[bit] = cell;
133 }
134 else if (is_output || !is_input)
135 log_error("Unsupported or unknown directionality on port %s of cell %s.%s (%s).\n",
136 log_id(conn.first), log_id(module), log_id(cell), log_id(cell->type));
137
138 if (cell->type.in(ID($mem)) && conn.first.in(ID::RD_CLK, ID::WR_CLK))
139 {
140 SigSpec clk = sigmap(conn.second);
141 for (int i = 0; i < GetSize(clk); i++)
142 {
143 if (clk[i].wire == nullptr)
144 continue;
145
146 if (cell->getParam(conn.first == ID::RD_CLK ? ID::RD_CLK_ENABLE : ID::WR_CLK_ENABLE)[i] != State::S1)
147 continue;
148
149 if (cell->getParam(conn.first == ID::RD_CLK ? ID::RD_CLK_POLARITY : ID::WR_CLK_POLARITY)[i] == State::S1)
150 clock_posedge.insert(clk[i]);
151 else
152 clock_negedge.insert(clk[i]);
153 }
154 }
155 else
156 if (cell->type.in(ID($dff), ID($_DFF_P_), ID($_DFF_N_)) && conn.first.in(ID::CLK, ID::C))
157 {
158 bool posedge = (cell->type == ID($_DFF_N_)) || (cell->type == ID($dff) && cell->getParam(ID::CLK_POLARITY).as_bool());
159 for (auto bit : sigmap(conn.second)) {
160 if (posedge)
161 clock_posedge.insert(bit);
162 else
163 clock_negedge.insert(bit);
164 }
165 }
166 else
167 if (mod_clk_cache.count(cell->type) && mod_clk_cache.at(cell->type).count(conn.first))
168 {
169 for (auto bit : sigmap(conn.second)) {
170 if (mod_clk_cache.at(cell->type).at(conn.first).first)
171 clock_posedge.insert(bit);
172 if (mod_clk_cache.at(cell->type).at(conn.first).second)
173 clock_negedge.insert(bit);
174 }
175 }
176 else
177 {
178 for (auto bit : sigmap(conn.second))
179 noclock.insert(bit);
180 }
181 }
182
183 for (auto bit : noclock) {
184 clock_posedge.erase(bit);
185 clock_negedge.erase(bit);
186 }
187
188 for (auto wire : module->wires())
189 {
190 if (!wire->port_input || GetSize(wire) != 1)
191 continue;
192 SigBit bit = sigmap(wire);
193 if (clock_posedge.count(bit))
194 mod_clk_cache[module->name][wire->name].first = true;
195 if (clock_negedge.count(bit))
196 mod_clk_cache[module->name][wire->name].second = true;
197 }
198 }
199
200 ~Smt2Worker()
201 {
202 for (auto &it : ids)
203 free(it.second);
204 ids.clear();
205 }
206
207 const char *get_id(Module *m)
208 {
209 return get_id(m->name);
210 }
211
212 const char *get_id(Cell *c)
213 {
214 return get_id(c->name);
215 }
216
217 const char *get_id(Wire *w)
218 {
219 return get_id(w->name);
220 }
221
222 void register_bool(RTLIL::SigBit bit, int id)
223 {
224 if (verbose) log("%*s-> register_bool: %s %d\n", 2+2*GetSize(recursive_cells), "",
225 log_signal(bit), id);
226
227 sigmap.apply(bit);
228 log_assert(fcache.count(bit) == 0);
229 fcache[bit] = std::pair<int, int>(id, -1);
230 }
231
232 void register_bv(RTLIL::SigSpec sig, int id)
233 {
234 if (verbose) log("%*s-> register_bv: %s %d\n", 2+2*GetSize(recursive_cells), "",
235 log_signal(sig), id);
236
237 log_assert(bvmode);
238 sigmap.apply(sig);
239
240 log_assert(bvsizes.count(id) == 0);
241 bvsizes[id] = GetSize(sig);
242
243 for (int i = 0; i < GetSize(sig); i++) {
244 log_assert(fcache.count(sig[i]) == 0);
245 fcache[sig[i]] = std::pair<int, int>(id, i);
246 }
247 }
248
249 void register_boolvec(RTLIL::SigSpec sig, int id)
250 {
251 if (verbose) log("%*s-> register_boolvec: %s %d\n", 2+2*GetSize(recursive_cells), "",
252 log_signal(sig), id);
253
254 log_assert(bvmode);
255 sigmap.apply(sig);
256 register_bool(sig[0], id);
257
258 for (int i = 1; i < GetSize(sig); i++)
259 sigmap.add(sig[i], RTLIL::State::S0);
260 }
261
262 std::string get_bool(RTLIL::SigBit bit, const char *state_name = "state")
263 {
264 sigmap.apply(bit);
265
266 if (bit.wire == nullptr)
267 return bit == RTLIL::State::S1 ? "true" : "false";
268
269 if (bit_driver.count(bit))
270 export_cell(bit_driver.at(bit));
271 sigmap.apply(bit);
272
273 if (fcache.count(bit) == 0) {
274 if (verbose) log("%*s-> external bool: %s\n", 2+2*GetSize(recursive_cells), "",
275 log_signal(bit));
276 makebits(stringf("%s#%d", get_id(module), idcounter), 0, log_signal(bit));
277 register_bool(bit, idcounter++);
278 }
279
280 auto f = fcache.at(bit);
281 if (f.second >= 0)
282 return stringf("(= ((_ extract %d %d) (|%s#%d| %s)) #b1)", f.second, f.second, get_id(module), f.first, state_name);
283 return stringf("(|%s#%d| %s)", get_id(module), f.first, state_name);
284 }
285
286 std::string get_bool(RTLIL::SigSpec sig, const char *state_name = "state")
287 {
288 return get_bool(sig.as_bit(), state_name);
289 }
290
291 std::string get_bv(RTLIL::SigSpec sig, const char *state_name = "state")
292 {
293 log_assert(bvmode);
294 sigmap.apply(sig);
295
296 std::vector<std::string> subexpr;
297
298 SigSpec orig_sig;
299 while (orig_sig != sig) {
300 for (auto bit : sig)
301 if (bit_driver.count(bit))
302 export_cell(bit_driver.at(bit));
303 orig_sig = sig;
304 sigmap.apply(sig);
305 }
306
307 for (int i = 0, j = 1; i < GetSize(sig); i += j, j = 1)
308 {
309 if (sig[i].wire == nullptr) {
310 while (i+j < GetSize(sig) && sig[i+j].wire == nullptr) j++;
311 subexpr.push_back("#b");
312 for (int k = i+j-1; k >= i; k--)
313 subexpr.back() += sig[k] == RTLIL::State::S1 ? "1" : "0";
314 continue;
315 }
316
317 if (fcache.count(sig[i]) && fcache.at(sig[i]).second == -1) {
318 subexpr.push_back(stringf("(ite %s #b1 #b0)", get_bool(sig[i], state_name).c_str()));
319 continue;
320 }
321
322 if (fcache.count(sig[i])) {
323 auto t1 = fcache.at(sig[i]);
324 while (i+j < GetSize(sig)) {
325 if (fcache.count(sig[i+j]) == 0)
326 break;
327 auto t2 = fcache.at(sig[i+j]);
328 if (t1.first != t2.first)
329 break;
330 if (t1.second+j != t2.second)
331 break;
332 j++;
333 }
334 if (t1.second == 0 && j == bvsizes.at(t1.first))
335 subexpr.push_back(stringf("(|%s#%d| %s)", get_id(module), t1.first, state_name));
336 else
337 subexpr.push_back(stringf("((_ extract %d %d) (|%s#%d| %s))",
338 t1.second + j - 1, t1.second, get_id(module), t1.first, state_name));
339 continue;
340 }
341
342 std::set<RTLIL::SigBit> seen_bits = { sig[i] };
343 while (i+j < GetSize(sig) && sig[i+j].wire && !fcache.count(sig[i+j]) && !seen_bits.count(sig[i+j]))
344 seen_bits.insert(sig[i+j]), j++;
345
346 if (verbose) log("%*s-> external bv: %s\n", 2+2*GetSize(recursive_cells), "",
347 log_signal(sig.extract(i, j)));
348 for (auto bit : sig.extract(i, j))
349 log_assert(bit_driver.count(bit) == 0);
350 makebits(stringf("%s#%d", get_id(module), idcounter), j, log_signal(sig.extract(i, j)));
351 subexpr.push_back(stringf("(|%s#%d| %s)", get_id(module), idcounter, state_name));
352 register_bv(sig.extract(i, j), idcounter++);
353 }
354
355 if (GetSize(subexpr) > 1) {
356 std::string expr = "", end_str = "";
357 for (int i = GetSize(subexpr)-1; i >= 0; i--) {
358 if (i > 0) expr += " (concat", end_str += ")";
359 expr += " " + subexpr[i];
360 }
361 return expr.substr(1) + end_str;
362 } else {
363 log_assert(GetSize(subexpr) == 1);
364 return subexpr[0];
365 }
366 }
367
368 void export_gate(RTLIL::Cell *cell, std::string expr)
369 {
370 RTLIL::SigBit bit = sigmap(cell->getPort(ID::Y).as_bit());
371 std::string processed_expr;
372
373 for (char ch : expr) {
374 if (ch == 'A') processed_expr += get_bool(cell->getPort(ID::A));
375 else if (ch == 'B') processed_expr += get_bool(cell->getPort(ID::B));
376 else if (ch == 'C') processed_expr += get_bool(cell->getPort(ID::C));
377 else if (ch == 'D') processed_expr += get_bool(cell->getPort(ID::D));
378 else if (ch == 'S') processed_expr += get_bool(cell->getPort(ID::S));
379 else processed_expr += ch;
380 }
381
382 if (verbose)
383 log("%*s-> import cell: %s\n", 2+2*GetSize(recursive_cells), "", log_id(cell));
384
385 decls.push_back(stringf("(define-fun |%s#%d| ((state |%s_s|)) Bool %s) ; %s\n",
386 get_id(module), idcounter, get_id(module), processed_expr.c_str(), log_signal(bit)));
387 register_bool(bit, idcounter++);
388 recursive_cells.erase(cell);
389 }
390
391 void export_bvop(RTLIL::Cell *cell, std::string expr, char type = 0)
392 {
393 RTLIL::SigSpec sig_a, sig_b;
394 RTLIL::SigSpec sig_y = sigmap(cell->getPort(ID::Y));
395 bool is_signed = cell->getParam(ID::A_SIGNED).as_bool();
396 int width = GetSize(sig_y);
397
398 if (type == 's' || type == 'd' || type == 'b') {
399 width = max(width, GetSize(cell->getPort(ID::A)));
400 if (cell->hasPort(ID::B))
401 width = max(width, GetSize(cell->getPort(ID::B)));
402 }
403
404 if (cell->hasPort(ID::A)) {
405 sig_a = cell->getPort(ID::A);
406 sig_a.extend_u0(width, is_signed);
407 }
408
409 if (cell->hasPort(ID::B)) {
410 sig_b = cell->getPort(ID::B);
411 sig_b.extend_u0(width, is_signed && !(type == 's'));
412 }
413
414 std::string processed_expr;
415
416 for (char ch : expr) {
417 if (ch == 'A') processed_expr += get_bv(sig_a);
418 else if (ch == 'B') processed_expr += get_bv(sig_b);
419 else if (ch == 'P') processed_expr += get_bv(cell->getPort(ID::B));
420 else if (ch == 'L') processed_expr += is_signed ? "a" : "l";
421 else if (ch == 'U') processed_expr += is_signed ? "s" : "u";
422 else processed_expr += ch;
423 }
424
425 if (width != GetSize(sig_y) && type != 'b')
426 processed_expr = stringf("((_ extract %d 0) %s)", GetSize(sig_y)-1, processed_expr.c_str());
427
428 if (verbose)
429 log("%*s-> import cell: %s\n", 2+2*GetSize(recursive_cells), "", log_id(cell));
430
431 if (type == 'b') {
432 decls.push_back(stringf("(define-fun |%s#%d| ((state |%s_s|)) Bool %s) ; %s\n",
433 get_id(module), idcounter, get_id(module), processed_expr.c_str(), log_signal(sig_y)));
434 register_boolvec(sig_y, idcounter++);
435 } else {
436 decls.push_back(stringf("(define-fun |%s#%d| ((state |%s_s|)) (_ BitVec %d) %s) ; %s\n",
437 get_id(module), idcounter, get_id(module), GetSize(sig_y), processed_expr.c_str(), log_signal(sig_y)));
438 register_bv(sig_y, idcounter++);
439 }
440
441 recursive_cells.erase(cell);
442 }
443
444 void export_reduce(RTLIL::Cell *cell, std::string expr, bool identity_val)
445 {
446 RTLIL::SigSpec sig_y = sigmap(cell->getPort(ID::Y));
447 std::string processed_expr;
448
449 for (char ch : expr)
450 if (ch == 'A' || ch == 'B') {
451 RTLIL::SigSpec sig = sigmap(cell->getPort(stringf("\\%c", ch)));
452 for (auto bit : sig)
453 processed_expr += " " + get_bool(bit);
454 if (GetSize(sig) == 1)
455 processed_expr += identity_val ? " true" : " false";
456 } else
457 processed_expr += ch;
458
459 if (verbose)
460 log("%*s-> import cell: %s\n", 2+2*GetSize(recursive_cells), "", log_id(cell));
461
462 decls.push_back(stringf("(define-fun |%s#%d| ((state |%s_s|)) Bool %s) ; %s\n",
463 get_id(module), idcounter, get_id(module), processed_expr.c_str(), log_signal(sig_y)));
464 register_boolvec(sig_y, idcounter++);
465 recursive_cells.erase(cell);
466 }
467
468 void export_cell(RTLIL::Cell *cell)
469 {
470 if (verbose)
471 log("%*s=> export_cell %s (%s) [%s]\n", 2+2*GetSize(recursive_cells), "",
472 log_id(cell), log_id(cell->type), exported_cells.count(cell) ? "old" : "new");
473
474 if (recursive_cells.count(cell))
475 log_error("Found logic loop in module %s! See cell %s.\n", get_id(module), get_id(cell));
476
477 if (exported_cells.count(cell))
478 return;
479
480 exported_cells.insert(cell);
481 recursive_cells.insert(cell);
482
483 if (cell->type == ID($initstate))
484 {
485 SigBit bit = sigmap(cell->getPort(ID::Y).as_bit());
486 decls.push_back(stringf("(define-fun |%s#%d| ((state |%s_s|)) Bool (|%s_is| state)) ; %s\n",
487 get_id(module), idcounter, get_id(module), get_id(module), log_signal(bit)));
488 register_bool(bit, idcounter++);
489 recursive_cells.erase(cell);
490 return;
491 }
492
493 if (cell->type.in(ID($_FF_), ID($_DFF_P_), ID($_DFF_N_)))
494 {
495 registers.insert(cell);
496 makebits(stringf("%s#%d", get_id(module), idcounter), 0, log_signal(cell->getPort(ID::Q)));
497 register_bool(cell->getPort(ID::Q), idcounter++);
498 recursive_cells.erase(cell);
499 return;
500 }
501
502 if (cell->type == ID($_BUF_)) return export_gate(cell, "A");
503 if (cell->type == ID($_NOT_)) return export_gate(cell, "(not A)");
504 if (cell->type == ID($_AND_)) return export_gate(cell, "(and A B)");
505 if (cell->type == ID($_NAND_)) return export_gate(cell, "(not (and A B))");
506 if (cell->type == ID($_OR_)) return export_gate(cell, "(or A B)");
507 if (cell->type == ID($_NOR_)) return export_gate(cell, "(not (or A B))");
508 if (cell->type == ID($_XOR_)) return export_gate(cell, "(xor A B)");
509 if (cell->type == ID($_XNOR_)) return export_gate(cell, "(not (xor A B))");
510 if (cell->type == ID($_ANDNOT_)) return export_gate(cell, "(and A (not B))");
511 if (cell->type == ID($_ORNOT_)) return export_gate(cell, "(or A (not B))");
512 if (cell->type == ID($_MUX_)) return export_gate(cell, "(ite S B A)");
513 if (cell->type == ID($_NMUX_)) return export_gate(cell, "(not (ite S B A))");
514 if (cell->type == ID($_AOI3_)) return export_gate(cell, "(not (or (and A B) C))");
515 if (cell->type == ID($_OAI3_)) return export_gate(cell, "(not (and (or A B) C))");
516 if (cell->type == ID($_AOI4_)) return export_gate(cell, "(not (or (and A B) (and C D)))");
517 if (cell->type == ID($_OAI4_)) return export_gate(cell, "(not (and (or A B) (or C D)))");
518
519 // FIXME: $lut
520
521 if (bvmode)
522 {
523 if (cell->type.in(ID($ff), ID($dff)))
524 {
525 registers.insert(cell);
526 makebits(stringf("%s#%d", get_id(module), idcounter), GetSize(cell->getPort(ID::Q)), log_signal(cell->getPort(ID::Q)));
527 register_bv(cell->getPort(ID::Q), idcounter++);
528 recursive_cells.erase(cell);
529 return;
530 }
531
532 if (cell->type.in(ID($anyconst), ID($anyseq), ID($allconst), ID($allseq)))
533 {
534 registers.insert(cell);
535 string infostr = cell->attributes.count(ID::src) ? cell->attributes.at(ID::src).decode_string().c_str() : get_id(cell);
536 if (cell->attributes.count(ID::reg))
537 infostr += " " + cell->attributes.at(ID::reg).decode_string();
538 decls.push_back(stringf("; yosys-smt2-%s %s#%d %d %s\n", cell->type.c_str() + 1, get_id(module), idcounter, GetSize(cell->getPort(ID::Y)), infostr.c_str()));
539 if (cell->getPort(ID::Y).is_wire() && cell->getPort(ID::Y).as_wire()->get_bool_attribute(ID::maximize)){
540 decls.push_back(stringf("; yosys-smt2-maximize %s#%d\n", get_id(module), idcounter));
541 log("Wire %s is maximized\n", cell->getPort(ID::Y).as_wire()->name.str().c_str());
542 }
543 else if (cell->getPort(ID::Y).is_wire() && cell->getPort(ID::Y).as_wire()->get_bool_attribute(ID::minimize)){
544 decls.push_back(stringf("; yosys-smt2-minimize %s#%d\n", get_id(module), idcounter));
545 log("Wire %s is minimized\n", cell->getPort(ID::Y).as_wire()->name.str().c_str());
546 }
547 makebits(stringf("%s#%d", get_id(module), idcounter), GetSize(cell->getPort(ID::Y)), log_signal(cell->getPort(ID::Y)));
548 if (cell->type == ID($anyseq))
549 ex_input_eq.push_back(stringf(" (= (|%s#%d| state) (|%s#%d| other_state))", get_id(module), idcounter, get_id(module), idcounter));
550 register_bv(cell->getPort(ID::Y), idcounter++);
551 recursive_cells.erase(cell);
552 return;
553 }
554
555 if (cell->type == ID($and)) return export_bvop(cell, "(bvand A B)");
556 if (cell->type == ID($or)) return export_bvop(cell, "(bvor A B)");
557 if (cell->type == ID($xor)) return export_bvop(cell, "(bvxor A B)");
558 if (cell->type == ID($xnor)) return export_bvop(cell, "(bvxnor A B)");
559
560 if (cell->type == ID($shl)) return export_bvop(cell, "(bvshl A B)", 's');
561 if (cell->type == ID($shr)) return export_bvop(cell, "(bvlshr A B)", 's');
562 if (cell->type == ID($sshl)) return export_bvop(cell, "(bvshl A B)", 's');
563 if (cell->type == ID($sshr)) return export_bvop(cell, "(bvLshr A B)", 's');
564
565 if (cell->type.in(ID($shift), ID($shiftx))) {
566 if (cell->getParam(ID::B_SIGNED).as_bool()) {
567 return export_bvop(cell, stringf("(ite (bvsge P #b%0*d) "
568 "(bvlshr A B) (bvlshr A (bvneg B)))",
569 GetSize(cell->getPort(ID::B)), 0), 's');
570 } else {
571 return export_bvop(cell, "(bvlshr A B)", 's');
572 }
573 }
574
575 if (cell->type == ID($lt)) return export_bvop(cell, "(bvUlt A B)", 'b');
576 if (cell->type == ID($le)) return export_bvop(cell, "(bvUle A B)", 'b');
577 if (cell->type == ID($ge)) return export_bvop(cell, "(bvUge A B)", 'b');
578 if (cell->type == ID($gt)) return export_bvop(cell, "(bvUgt A B)", 'b');
579
580 if (cell->type == ID($ne)) return export_bvop(cell, "(distinct A B)", 'b');
581 if (cell->type == ID($nex)) return export_bvop(cell, "(distinct A B)", 'b');
582 if (cell->type == ID($eq)) return export_bvop(cell, "(= A B)", 'b');
583 if (cell->type == ID($eqx)) return export_bvop(cell, "(= A B)", 'b');
584
585 if (cell->type == ID($not)) return export_bvop(cell, "(bvnot A)");
586 if (cell->type == ID($pos)) return export_bvop(cell, "A");
587 if (cell->type == ID($neg)) return export_bvop(cell, "(bvneg A)");
588
589 if (cell->type == ID($add)) return export_bvop(cell, "(bvadd A B)");
590 if (cell->type == ID($sub)) return export_bvop(cell, "(bvsub A B)");
591 if (cell->type == ID($mul)) return export_bvop(cell, "(bvmul A B)");
592 if (cell->type == ID($div)) return export_bvop(cell, "(bvUdiv A B)", 'd');
593 // "rem" = truncating modulo
594 if (cell->type == ID($mod)) return export_bvop(cell, "(bvUrem A B)", 'd');
595 // "mod" = flooring modulo
596 if (cell->type == ID($modfloor)) {
597 // bvumod doesn't exist because it's the same as bvurem
598 if (cell->getParam(ID::A_SIGNED).as_bool()) {
599 return export_bvop(cell, "(bvsmod A B)", 'd');
600 } else {
601 return export_bvop(cell, "(bvurem A B)", 'd');
602 }
603 }
604
605 if (cell->type.in(ID($reduce_and), ID($reduce_or), ID($reduce_bool)) &&
606 2*GetSize(cell->getPort(ID::A).chunks()) < GetSize(cell->getPort(ID::A))) {
607 bool is_and = cell->type == ID($reduce_and);
608 string bits(GetSize(cell->getPort(ID::A)), is_and ? '1' : '0');
609 return export_bvop(cell, stringf("(%s A #b%s)", is_and ? "=" : "distinct", bits.c_str()), 'b');
610 }
611
612 if (cell->type == ID($reduce_and)) return export_reduce(cell, "(and A)", true);
613 if (cell->type == ID($reduce_or)) return export_reduce(cell, "(or A)", false);
614 if (cell->type == ID($reduce_xor)) return export_reduce(cell, "(xor A)", false);
615 if (cell->type == ID($reduce_xnor)) return export_reduce(cell, "(not (xor A))", false);
616 if (cell->type == ID($reduce_bool)) return export_reduce(cell, "(or A)", false);
617
618 if (cell->type == ID($logic_not)) return export_reduce(cell, "(not (or A))", false);
619 if (cell->type == ID($logic_and)) return export_reduce(cell, "(and (or A) (or B))", false);
620 if (cell->type == ID($logic_or)) return export_reduce(cell, "(or A B)", false);
621
622 if (cell->type.in(ID($mux), ID($pmux)))
623 {
624 int width = GetSize(cell->getPort(ID::Y));
625 std::string processed_expr = get_bv(cell->getPort(ID::A));
626
627 RTLIL::SigSpec sig_b = cell->getPort(ID::B);
628 RTLIL::SigSpec sig_s = cell->getPort(ID::S);
629 get_bv(sig_b);
630 get_bv(sig_s);
631
632 for (int i = 0; i < GetSize(sig_s); i++)
633 processed_expr = stringf("(ite %s %s %s)", get_bool(sig_s[i]).c_str(),
634 get_bv(sig_b.extract(i*width, width)).c_str(), processed_expr.c_str());
635
636 if (verbose)
637 log("%*s-> import cell: %s\n", 2+2*GetSize(recursive_cells), "", log_id(cell));
638
639 RTLIL::SigSpec sig = sigmap(cell->getPort(ID::Y));
640 decls.push_back(stringf("(define-fun |%s#%d| ((state |%s_s|)) (_ BitVec %d) %s) ; %s\n",
641 get_id(module), idcounter, get_id(module), width, processed_expr.c_str(), log_signal(sig)));
642 register_bv(sig, idcounter++);
643 recursive_cells.erase(cell);
644 return;
645 }
646
647 // FIXME: $slice $concat
648 }
649
650 if (memmode && cell->type == ID($mem))
651 {
652 int arrayid = idcounter++;
653 memarrays[cell] = arrayid;
654
655 int abits = cell->getParam(ID::ABITS).as_int();
656 int width = cell->getParam(ID::WIDTH).as_int();
657 int rd_ports = cell->getParam(ID::RD_PORTS).as_int();
658 int wr_ports = cell->getParam(ID::WR_PORTS).as_int();
659
660 bool async_read = false;
661 if (!cell->getParam(ID::WR_CLK_ENABLE).is_fully_ones()) {
662 if (!cell->getParam(ID::WR_CLK_ENABLE).is_fully_zero())
663 log_error("Memory %s.%s has mixed clocked/nonclocked write ports. This is not supported by \"write_smt2\".\n", log_id(cell), log_id(module));
664 async_read = true;
665 }
666
667 decls.push_back(stringf("; yosys-smt2-memory %s %d %d %d %d %s\n", get_id(cell), abits, width, rd_ports, wr_ports, async_read ? "async" : "sync"));
668
669 string memstate;
670 if (async_read) {
671 memstate = stringf("%s#%d#final", get_id(module), arrayid);
672 } else {
673 memstate = stringf("%s#%d#0", get_id(module), arrayid);
674 }
675
676 if (statebv)
677 {
678 int mem_size = cell->getParam(ID::SIZE).as_int();
679 int mem_offset = cell->getParam(ID::OFFSET).as_int();
680
681 makebits(memstate, width*mem_size, get_id(cell));
682 decls.push_back(stringf("(define-fun |%s_m %s| ((state |%s_s|)) (_ BitVec %d) (|%s| state))\n",
683 get_id(module), get_id(cell), get_id(module), width*mem_size, memstate.c_str()));
684
685 for (int i = 0; i < rd_ports; i++)
686 {
687 SigSpec addr_sig = cell->getPort(ID::RD_ADDR).extract(abits*i, abits);
688 SigSpec data_sig = cell->getPort(ID::RD_DATA).extract(width*i, width);
689 std::string addr = get_bv(addr_sig);
690
691 if (cell->getParam(ID::RD_CLK_ENABLE).extract(i).as_bool())
692 log_error("Read port %d (%s) of memory %s.%s is clocked. This is not supported by \"write_smt2\"! "
693 "Call \"memory\" with -nordff to avoid this error.\n", i, log_signal(data_sig), log_id(cell), log_id(module));
694
695 decls.push_back(stringf("(define-fun |%s_m:R%dA %s| ((state |%s_s|)) (_ BitVec %d) %s) ; %s\n",
696 get_id(module), i, get_id(cell), get_id(module), abits, addr.c_str(), log_signal(addr_sig)));
697
698 std::string read_expr = "#b";
699 for (int k = 0; k < width; k++)
700 read_expr += "0";
701
702 for (int k = 0; k < mem_size; k++)
703 read_expr = stringf("(ite (= (|%s_m:R%dA %s| state) #b%s) ((_ extract %d %d) (|%s| state))\n %s)",
704 get_id(module), i, get_id(cell), Const(k+mem_offset, abits).as_string().c_str(),
705 width*(k+1)-1, width*k, memstate.c_str(), read_expr.c_str());
706
707 decls.push_back(stringf("(define-fun |%s#%d| ((state |%s_s|)) (_ BitVec %d)\n %s) ; %s\n",
708 get_id(module), idcounter, get_id(module), width, read_expr.c_str(), log_signal(data_sig)));
709
710 decls.push_back(stringf("(define-fun |%s_m:R%dD %s| ((state |%s_s|)) (_ BitVec %d) (|%s#%d| state))\n",
711 get_id(module), i, get_id(cell), get_id(module), width, get_id(module), idcounter));
712
713 register_bv(data_sig, idcounter++);
714 }
715 }
716 else
717 {
718 if (statedt)
719 dtmembers.push_back(stringf(" (|%s| (Array (_ BitVec %d) (_ BitVec %d))) ; %s\n",
720 memstate.c_str(), abits, width, get_id(cell)));
721 else
722 decls.push_back(stringf("(declare-fun |%s| (|%s_s|) (Array (_ BitVec %d) (_ BitVec %d))) ; %s\n",
723 memstate.c_str(), get_id(module), abits, width, get_id(cell)));
724
725 decls.push_back(stringf("(define-fun |%s_m %s| ((state |%s_s|)) (Array (_ BitVec %d) (_ BitVec %d)) (|%s| state))\n",
726 get_id(module), get_id(cell), get_id(module), abits, width, memstate.c_str()));
727
728 for (int i = 0; i < rd_ports; i++)
729 {
730 SigSpec addr_sig = cell->getPort(ID::RD_ADDR).extract(abits*i, abits);
731 SigSpec data_sig = cell->getPort(ID::RD_DATA).extract(width*i, width);
732 std::string addr = get_bv(addr_sig);
733
734 if (cell->getParam(ID::RD_CLK_ENABLE).extract(i).as_bool())
735 log_error("Read port %d (%s) of memory %s.%s is clocked. This is not supported by \"write_smt2\"! "
736 "Call \"memory\" with -nordff to avoid this error.\n", i, log_signal(data_sig), log_id(cell), log_id(module));
737
738 decls.push_back(stringf("(define-fun |%s_m:R%dA %s| ((state |%s_s|)) (_ BitVec %d) %s) ; %s\n",
739 get_id(module), i, get_id(cell), get_id(module), abits, addr.c_str(), log_signal(addr_sig)));
740
741 decls.push_back(stringf("(define-fun |%s#%d| ((state |%s_s|)) (_ BitVec %d) (select (|%s| state) (|%s_m:R%dA %s| state))) ; %s\n",
742 get_id(module), idcounter, get_id(module), width, memstate.c_str(), get_id(module), i, get_id(cell), log_signal(data_sig)));
743
744 decls.push_back(stringf("(define-fun |%s_m:R%dD %s| ((state |%s_s|)) (_ BitVec %d) (|%s#%d| state))\n",
745 get_id(module), i, get_id(cell), get_id(module), width, get_id(module), idcounter));
746
747 register_bv(data_sig, idcounter++);
748 }
749 }
750
751 registers.insert(cell);
752 recursive_cells.erase(cell);
753 return;
754 }
755
756 Module *m = module->design->module(cell->type);
757
758 if (m != nullptr)
759 {
760 decls.push_back(stringf("; yosys-smt2-cell %s %s\n", get_id(cell->type), get_id(cell->name)));
761 string cell_state = stringf("(|%s_h %s| state)", get_id(module), get_id(cell->name));
762
763 for (auto &conn : cell->connections())
764 {
765 if (GetSize(conn.second) == 0)
766 continue;
767
768 Wire *w = m->wire(conn.first);
769 SigSpec sig = sigmap(conn.second);
770
771 if (w->port_output && !w->port_input) {
772 if (GetSize(w) > 1) {
773 if (bvmode) {
774 makebits(stringf("%s#%d", get_id(module), idcounter), GetSize(w), log_signal(sig));
775 register_bv(sig, idcounter++);
776 } else {
777 for (int i = 0; i < GetSize(w); i++) {
778 makebits(stringf("%s#%d", get_id(module), idcounter), 0, log_signal(sig[i]));
779 register_bool(sig[i], idcounter++);
780 }
781 }
782 } else {
783 makebits(stringf("%s#%d", get_id(module), idcounter), 0, log_signal(sig));
784 register_bool(sig, idcounter++);
785 }
786 }
787 }
788
789 if (statebv)
790 makebits(stringf("%s_h %s", get_id(module), get_id(cell->name)), mod_stbv_width.at(cell->type));
791 else if (statedt)
792 dtmembers.push_back(stringf(" (|%s_h %s| |%s_s|)\n",
793 get_id(module), get_id(cell->name), get_id(cell->type)));
794 else
795 decls.push_back(stringf("(declare-fun |%s_h %s| (|%s_s|) |%s_s|)\n",
796 get_id(module), get_id(cell->name), get_id(module), get_id(cell->type)));
797
798 hiercells.insert(cell);
799 hiercells_queue.insert(cell);
800 recursive_cells.erase(cell);
801 return;
802 }
803
804 log_error("Unsupported cell type %s for cell %s.%s.\n",
805 log_id(cell->type), log_id(module), log_id(cell));
806 }
807
808 void run()
809 {
810 if (verbose) log("=> export logic driving outputs\n");
811
812 pool<SigBit> reg_bits;
813 for (auto cell : module->cells())
814 if (cell->type.in(ID($ff), ID($dff), ID($_FF_), ID($_DFF_P_), ID($_DFF_N_))) {
815 // not using sigmap -- we want the net directly at the dff output
816 for (auto bit : cell->getPort(ID::Q))
817 reg_bits.insert(bit);
818 }
819
820 for (auto wire : module->wires()) {
821 bool is_register = false;
822 for (auto bit : SigSpec(wire))
823 if (reg_bits.count(bit))
824 is_register = true;
825 if (wire->port_id || is_register || wire->get_bool_attribute(ID::keep) || (wiresmode && wire->name[0] == '\\')) {
826 RTLIL::SigSpec sig = sigmap(wire);
827 std::vector<std::string> comments;
828 if (wire->port_input)
829 comments.push_back(stringf("; yosys-smt2-input %s %d\n", get_id(wire), wire->width));
830 if (wire->port_output)
831 comments.push_back(stringf("; yosys-smt2-output %s %d\n", get_id(wire), wire->width));
832 if (is_register)
833 comments.push_back(stringf("; yosys-smt2-register %s %d\n", get_id(wire), wire->width));
834 if (wire->get_bool_attribute(ID::keep) || (wiresmode && wire->name[0] == '\\'))
835 comments.push_back(stringf("; yosys-smt2-wire %s %d\n", get_id(wire), wire->width));
836 if (GetSize(wire) == 1 && (clock_posedge.count(sig) || clock_negedge.count(sig)))
837 comments.push_back(stringf("; yosys-smt2-clock %s%s%s\n", get_id(wire),
838 clock_posedge.count(sig) ? " posedge" : "", clock_negedge.count(sig) ? " negedge" : ""));
839 if (bvmode && GetSize(sig) > 1) {
840 std::string sig_bv = get_bv(sig);
841 if (!comments.empty())
842 decls.insert(decls.end(), comments.begin(), comments.end());
843 decls.push_back(stringf("(define-fun |%s_n %s| ((state |%s_s|)) (_ BitVec %d) %s)\n",
844 get_id(module), get_id(wire), get_id(module), GetSize(sig), sig_bv.c_str()));
845 if (wire->port_input)
846 ex_input_eq.push_back(stringf(" (= (|%s_n %s| state) (|%s_n %s| other_state))",
847 get_id(module), get_id(wire), get_id(module), get_id(wire)));
848 } else {
849 std::vector<std::string> sig_bool;
850 for (int i = 0; i < GetSize(sig); i++) {
851 sig_bool.push_back(get_bool(sig[i]));
852 }
853 if (!comments.empty())
854 decls.insert(decls.end(), comments.begin(), comments.end());
855 for (int i = 0; i < GetSize(sig); i++) {
856 if (GetSize(sig) > 1) {
857 decls.push_back(stringf("(define-fun |%s_n %s %d| ((state |%s_s|)) Bool %s)\n",
858 get_id(module), get_id(wire), i, get_id(module), sig_bool[i].c_str()));
859 if (wire->port_input)
860 ex_input_eq.push_back(stringf(" (= (|%s_n %s %d| state) (|%s_n %s %d| other_state))",
861 get_id(module), get_id(wire), i, get_id(module), get_id(wire), i));
862 } else {
863 decls.push_back(stringf("(define-fun |%s_n %s| ((state |%s_s|)) Bool %s)\n",
864 get_id(module), get_id(wire), get_id(module), sig_bool[i].c_str()));
865 if (wire->port_input)
866 ex_input_eq.push_back(stringf(" (= (|%s_n %s| state) (|%s_n %s| other_state))",
867 get_id(module), get_id(wire), get_id(module), get_id(wire)));
868 }
869 }
870 }
871 }
872 }
873
874 if (verbose) log("=> export logic associated with the initial state\n");
875
876 vector<string> init_list;
877 for (auto wire : module->wires())
878 if (wire->attributes.count(ID::init)) {
879 RTLIL::SigSpec sig = sigmap(wire);
880 Const val = wire->attributes.at(ID::init);
881 val.bits.resize(GetSize(sig), State::Sx);
882 if (bvmode && GetSize(sig) > 1) {
883 Const mask(State::S1, GetSize(sig));
884 bool use_mask = false;
885 for (int i = 0; i < GetSize(sig); i++)
886 if (val[i] != State::S0 && val[i] != State::S1) {
887 val[i] = State::S0;
888 mask[i] = State::S0;
889 use_mask = true;
890 }
891 if (use_mask)
892 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)));
893 else
894 init_list.push_back(stringf("(= %s #b%s) ; %s", get_bv(sig).c_str(), val.as_string().c_str(), get_id(wire)));
895 } else {
896 for (int i = 0; i < GetSize(sig); i++)
897 if (val[i] == State::S0 || val[i] == State::S1)
898 init_list.push_back(stringf("(= %s %s) ; %s", get_bool(sig[i]).c_str(), val[i] == State::S1 ? "true" : "false", get_id(wire)));
899 }
900 }
901
902 if (verbose) log("=> export logic driving asserts\n");
903
904 int assert_id = 0, assume_id = 0, cover_id = 0;
905 vector<string> assert_list, assume_list, cover_list;
906
907 for (auto cell : module->cells())
908 {
909 if (cell->type.in(ID($assert), ID($assume), ID($cover)))
910 {
911 int &id = cell->type == ID($assert) ? assert_id :
912 cell->type == ID($assume) ? assume_id :
913 cell->type == ID($cover) ? cover_id : *(int*)nullptr;
914
915 char postfix = cell->type == ID($assert) ? 'a' :
916 cell->type == ID($assume) ? 'u' :
917 cell->type == ID($cover) ? 'c' : 0;
918
919 string name_a = get_bool(cell->getPort(ID::A));
920 string name_en = get_bool(cell->getPort(ID::EN));
921 string infostr = (cell->name[0] == '$' && cell->attributes.count(ID::src)) ? cell->attributes.at(ID::src).decode_string() : get_id(cell);
922 decls.push_back(stringf("; yosys-smt2-%s %d %s\n", cell->type.c_str() + 1, id, infostr.c_str()));
923
924 if (cell->type == ID($cover))
925 decls.push_back(stringf("(define-fun |%s_%c %d| ((state |%s_s|)) Bool (and %s %s)) ; %s\n",
926 get_id(module), postfix, id, get_id(module), name_a.c_str(), name_en.c_str(), get_id(cell)));
927 else
928 decls.push_back(stringf("(define-fun |%s_%c %d| ((state |%s_s|)) Bool (or %s (not %s))) ; %s\n",
929 get_id(module), postfix, id, get_id(module), name_a.c_str(), name_en.c_str(), get_id(cell)));
930
931 if (cell->type == ID($assert))
932 assert_list.push_back(stringf("(|%s_a %d| state)", get_id(module), id));
933 else if (cell->type == ID($assume))
934 assume_list.push_back(stringf("(|%s_u %d| state)", get_id(module), id));
935
936 id++;
937 }
938 }
939
940 if (verbose) log("=> export logic driving hierarchical cells\n");
941
942 for (auto cell : module->cells())
943 if (module->design->module(cell->type) != nullptr)
944 export_cell(cell);
945
946 while (!hiercells_queue.empty())
947 {
948 std::set<RTLIL::Cell*> queue;
949 queue.swap(hiercells_queue);
950
951 for (auto cell : queue)
952 {
953 string cell_state = stringf("(|%s_h %s| state)", get_id(module), get_id(cell->name));
954 Module *m = module->design->module(cell->type);
955 log_assert(m != nullptr);
956
957 hier.push_back(stringf(" (= (|%s_is| state) (|%s_is| %s))\n",
958 get_id(module), get_id(cell->type), cell_state.c_str()));
959
960 for (auto &conn : cell->connections())
961 {
962 if (GetSize(conn.second) == 0)
963 continue;
964
965 Wire *w = m->wire(conn.first);
966 SigSpec sig = sigmap(conn.second);
967
968 if (bvmode || GetSize(w) == 1) {
969 hier.push_back(stringf(" (= %s (|%s_n %s| %s)) ; %s.%s\n", (GetSize(w) > 1 ? get_bv(sig) : get_bool(sig)).c_str(),
970 get_id(cell->type), get_id(w), cell_state.c_str(), get_id(cell->type), get_id(w)));
971 } else {
972 for (int i = 0; i < GetSize(w); i++)
973 hier.push_back(stringf(" (= %s (|%s_n %s %d| %s)) ; %s.%s[%d]\n", get_bool(sig[i]).c_str(),
974 get_id(cell->type), get_id(w), i, cell_state.c_str(), get_id(cell->type), get_id(w), i));
975 }
976 }
977 }
978 }
979
980 for (int iter = 1; !registers.empty(); iter++)
981 {
982 pool<Cell*> this_regs;
983 this_regs.swap(registers);
984
985 if (verbose) log("=> export logic driving registers [iteration %d]\n", iter);
986
987 for (auto cell : this_regs)
988 {
989 if (cell->type.in(ID($_FF_), ID($_DFF_P_), ID($_DFF_N_)))
990 {
991 std::string expr_d = get_bool(cell->getPort(ID::D));
992 std::string expr_q = get_bool(cell->getPort(ID::Q), "next_state");
993 trans.push_back(stringf(" (= %s %s) ; %s %s\n", expr_d.c_str(), expr_q.c_str(), get_id(cell), log_signal(cell->getPort(ID::Q))));
994 ex_state_eq.push_back(stringf("(= %s %s)", get_bool(cell->getPort(ID::Q)).c_str(), get_bool(cell->getPort(ID::Q), "other_state").c_str()));
995 }
996
997 if (cell->type.in(ID($ff), ID($dff)))
998 {
999 std::string expr_d = get_bv(cell->getPort(ID::D));
1000 std::string expr_q = get_bv(cell->getPort(ID::Q), "next_state");
1001 trans.push_back(stringf(" (= %s %s) ; %s %s\n", expr_d.c_str(), expr_q.c_str(), get_id(cell), log_signal(cell->getPort(ID::Q))));
1002 ex_state_eq.push_back(stringf("(= %s %s)", get_bv(cell->getPort(ID::Q)).c_str(), get_bv(cell->getPort(ID::Q), "other_state").c_str()));
1003 }
1004
1005 if (cell->type.in(ID($anyconst), ID($allconst)))
1006 {
1007 std::string expr_d = get_bv(cell->getPort(ID::Y));
1008 std::string expr_q = get_bv(cell->getPort(ID::Y), "next_state");
1009 trans.push_back(stringf(" (= %s %s) ; %s %s\n", expr_d.c_str(), expr_q.c_str(), get_id(cell), log_signal(cell->getPort(ID::Y))));
1010 if (cell->type == ID($anyconst))
1011 ex_state_eq.push_back(stringf("(= %s %s)", get_bv(cell->getPort(ID::Y)).c_str(), get_bv(cell->getPort(ID::Y), "other_state").c_str()));
1012 }
1013
1014 if (cell->type == ID($mem))
1015 {
1016 int arrayid = memarrays.at(cell);
1017
1018 int abits = cell->getParam(ID::ABITS).as_int();
1019 int width = cell->getParam(ID::WIDTH).as_int();
1020 int wr_ports = cell->getParam(ID::WR_PORTS).as_int();
1021
1022 bool async_read = false;
1023 string initial_memstate, final_memstate;
1024
1025 if (!cell->getParam(ID::WR_CLK_ENABLE).is_fully_ones()) {
1026 log_assert(cell->getParam(ID::WR_CLK_ENABLE).is_fully_zero());
1027 async_read = true;
1028 initial_memstate = stringf("%s#%d#0", get_id(module), arrayid);
1029 final_memstate = stringf("%s#%d#final", get_id(module), arrayid);
1030 }
1031
1032 if (statebv)
1033 {
1034 int mem_size = cell->getParam(ID::SIZE).as_int();
1035 int mem_offset = cell->getParam(ID::OFFSET).as_int();
1036
1037 if (async_read) {
1038 makebits(final_memstate, width*mem_size, get_id(cell));
1039 }
1040
1041 for (int i = 0; i < wr_ports; i++)
1042 {
1043 SigSpec addr_sig = cell->getPort(ID::WR_ADDR).extract(abits*i, abits);
1044 SigSpec data_sig = cell->getPort(ID::WR_DATA).extract(width*i, width);
1045 SigSpec mask_sig = cell->getPort(ID::WR_EN).extract(width*i, width);
1046
1047 std::string addr = get_bv(addr_sig);
1048 std::string data = get_bv(data_sig);
1049 std::string mask = get_bv(mask_sig);
1050
1051 decls.push_back(stringf("(define-fun |%s_m:W%dA %s| ((state |%s_s|)) (_ BitVec %d) %s) ; %s\n",
1052 get_id(module), i, get_id(cell), get_id(module), abits, addr.c_str(), log_signal(addr_sig)));
1053 addr = stringf("(|%s_m:W%dA %s| state)", get_id(module), i, get_id(cell));
1054
1055 decls.push_back(stringf("(define-fun |%s_m:W%dD %s| ((state |%s_s|)) (_ BitVec %d) %s) ; %s\n",
1056 get_id(module), i, get_id(cell), get_id(module), width, data.c_str(), log_signal(data_sig)));
1057 data = stringf("(|%s_m:W%dD %s| state)", get_id(module), i, get_id(cell));
1058
1059 decls.push_back(stringf("(define-fun |%s_m:W%dM %s| ((state |%s_s|)) (_ BitVec %d) %s) ; %s\n",
1060 get_id(module), i, get_id(cell), get_id(module), width, mask.c_str(), log_signal(mask_sig)));
1061 mask = stringf("(|%s_m:W%dM %s| state)", get_id(module), i, get_id(cell));
1062
1063 std::string data_expr;
1064
1065 for (int k = mem_size-1; k >= 0; k--) {
1066 std::string new_data = stringf("(bvor (bvand %s %s) (bvand ((_ extract %d %d) (|%s#%d#%d| state)) (bvnot %s)))",
1067 data.c_str(), mask.c_str(), width*(k+1)-1, width*k, get_id(module), arrayid, i, mask.c_str());
1068 data_expr += stringf("\n (ite (= %s #b%s) %s ((_ extract %d %d) (|%s#%d#%d| state)))",
1069 addr.c_str(), Const(k+mem_offset, abits).as_string().c_str(), new_data.c_str(),
1070 width*(k+1)-1, width*k, get_id(module), arrayid, i);
1071 }
1072
1073 decls.push_back(stringf("(define-fun |%s#%d#%d| ((state |%s_s|)) (_ BitVec %d) (concat%s)) ; %s\n",
1074 get_id(module), arrayid, i+1, get_id(module), width*mem_size, data_expr.c_str(), get_id(cell)));
1075 }
1076 }
1077 else
1078 {
1079 if (async_read) {
1080 if (statedt)
1081 dtmembers.push_back(stringf(" (|%s| (Array (_ BitVec %d) (_ BitVec %d))) ; %s\n",
1082 initial_memstate.c_str(), abits, width, get_id(cell)));
1083 else
1084 decls.push_back(stringf("(declare-fun |%s| (|%s_s|) (Array (_ BitVec %d) (_ BitVec %d))) ; %s\n",
1085 initial_memstate.c_str(), get_id(module), abits, width, get_id(cell)));
1086 }
1087
1088 for (int i = 0; i < wr_ports; i++)
1089 {
1090 SigSpec addr_sig = cell->getPort(ID::WR_ADDR).extract(abits*i, abits);
1091 SigSpec data_sig = cell->getPort(ID::WR_DATA).extract(width*i, width);
1092 SigSpec mask_sig = cell->getPort(ID::WR_EN).extract(width*i, width);
1093
1094 std::string addr = get_bv(addr_sig);
1095 std::string data = get_bv(data_sig);
1096 std::string mask = get_bv(mask_sig);
1097
1098 decls.push_back(stringf("(define-fun |%s_m:W%dA %s| ((state |%s_s|)) (_ BitVec %d) %s) ; %s\n",
1099 get_id(module), i, get_id(cell), get_id(module), abits, addr.c_str(), log_signal(addr_sig)));
1100 addr = stringf("(|%s_m:W%dA %s| state)", get_id(module), i, get_id(cell));
1101
1102 decls.push_back(stringf("(define-fun |%s_m:W%dD %s| ((state |%s_s|)) (_ BitVec %d) %s) ; %s\n",
1103 get_id(module), i, get_id(cell), get_id(module), width, data.c_str(), log_signal(data_sig)));
1104 data = stringf("(|%s_m:W%dD %s| state)", get_id(module), i, get_id(cell));
1105
1106 decls.push_back(stringf("(define-fun |%s_m:W%dM %s| ((state |%s_s|)) (_ BitVec %d) %s) ; %s\n",
1107 get_id(module), i, get_id(cell), get_id(module), width, mask.c_str(), log_signal(mask_sig)));
1108 mask = stringf("(|%s_m:W%dM %s| state)", get_id(module), i, get_id(cell));
1109
1110 data = stringf("(bvor (bvand %s %s) (bvand (select (|%s#%d#%d| state) %s) (bvnot %s)))",
1111 data.c_str(), mask.c_str(), get_id(module), arrayid, i, addr.c_str(), mask.c_str());
1112
1113 decls.push_back(stringf("(define-fun |%s#%d#%d| ((state |%s_s|)) (Array (_ BitVec %d) (_ BitVec %d)) "
1114 "(store (|%s#%d#%d| state) %s %s)) ; %s\n",
1115 get_id(module), arrayid, i+1, get_id(module), abits, width,
1116 get_id(module), arrayid, i, addr.c_str(), data.c_str(), get_id(cell)));
1117 }
1118 }
1119
1120 std::string expr_d = stringf("(|%s#%d#%d| state)", get_id(module), arrayid, wr_ports);
1121 std::string expr_q = stringf("(|%s#%d#0| next_state)", get_id(module), arrayid);
1122 trans.push_back(stringf(" (= %s %s) ; %s\n", expr_d.c_str(), expr_q.c_str(), get_id(cell)));
1123 ex_state_eq.push_back(stringf("(= (|%s#%d#0| state) (|%s#%d#0| other_state))", get_id(module), arrayid, get_id(module), arrayid));
1124
1125 if (async_read)
1126 hier.push_back(stringf(" (= %s (|%s| state)) ; %s\n", expr_d.c_str(), final_memstate.c_str(), get_id(cell)));
1127
1128 Const init_data = cell->getParam(ID::INIT);
1129 int memsize = cell->getParam(ID::SIZE).as_int();
1130
1131 for (int i = 0; i < memsize; i++)
1132 {
1133 if (i*width >= GetSize(init_data))
1134 break;
1135
1136 Const initword = init_data.extract(i*width, width, State::Sx);
1137 Const initmask = initword;
1138 bool gen_init_constr = false;
1139
1140 for (int k = 0; k < GetSize(initword); k++) {
1141 if (initword[k] == State::S0 || initword[k] == State::S1) {
1142 gen_init_constr = true;
1143 initmask[k] = State::S1;
1144 } else {
1145 initmask[k] = State::S0;
1146 initword[k] = State::S0;
1147 }
1148 }
1149
1150 if (gen_init_constr)
1151 {
1152 if (statebv)
1153 /* FIXME */;
1154 else
1155 init_list.push_back(stringf("(= (bvand (select (|%s#%d#0| state) #b%s) #b%s) #b%s) ; %s[%d]",
1156 get_id(module), arrayid, Const(i, abits).as_string().c_str(),
1157 initmask.as_string().c_str(), initword.as_string().c_str(), get_id(cell), i));
1158 }
1159 }
1160 }
1161 }
1162 }
1163
1164 if (verbose) log("=> finalizing SMT2 representation of %s.\n", log_id(module));
1165
1166 for (auto c : hiercells) {
1167 assert_list.push_back(stringf("(|%s_a| (|%s_h %s| state))", get_id(c->type), get_id(module), get_id(c->name)));
1168 assume_list.push_back(stringf("(|%s_u| (|%s_h %s| state))", get_id(c->type), get_id(module), get_id(c->name)));
1169 init_list.push_back(stringf("(|%s_i| (|%s_h %s| state))", get_id(c->type), get_id(module), get_id(c->name)));
1170 hier.push_back(stringf(" (|%s_h| (|%s_h %s| state))\n", get_id(c->type), get_id(module), get_id(c->name)));
1171 trans.push_back(stringf(" (|%s_t| (|%s_h %s| state) (|%s_h %s| next_state))\n",
1172 get_id(c->type), get_id(module), get_id(c->name), get_id(module), get_id(c->name)));
1173 ex_state_eq.push_back(stringf("(|%s_ex_state_eq| (|%s_h %s| state) (|%s_h %s| other_state))\n",
1174 get_id(c->type), get_id(module), get_id(c->name), get_id(module), get_id(c->name)));
1175 }
1176
1177 if (forallmode)
1178 {
1179 string expr = ex_state_eq.empty() ? "true" : "(and";
1180 if (!ex_state_eq.empty()) {
1181 if (GetSize(ex_state_eq) == 1) {
1182 expr = "\n " + ex_state_eq.front() + "\n";
1183 } else {
1184 for (auto &str : ex_state_eq)
1185 expr += stringf("\n %s", str.c_str());
1186 expr += "\n)";
1187 }
1188 }
1189 decls.push_back(stringf("(define-fun |%s_ex_state_eq| ((state |%s_s|) (other_state |%s_s|)) Bool %s)\n",
1190 get_id(module), get_id(module), get_id(module), expr.c_str()));
1191
1192 expr = ex_input_eq.empty() ? "true" : "(and";
1193 if (!ex_input_eq.empty()) {
1194 if (GetSize(ex_input_eq) == 1) {
1195 expr = "\n " + ex_input_eq.front() + "\n";
1196 } else {
1197 for (auto &str : ex_input_eq)
1198 expr += stringf("\n %s", str.c_str());
1199 expr += "\n)";
1200 }
1201 }
1202 decls.push_back(stringf("(define-fun |%s_ex_input_eq| ((state |%s_s|) (other_state |%s_s|)) Bool %s)\n",
1203 get_id(module), get_id(module), get_id(module), expr.c_str()));
1204 }
1205
1206 string assert_expr = assert_list.empty() ? "true" : "(and";
1207 if (!assert_list.empty()) {
1208 if (GetSize(assert_list) == 1) {
1209 assert_expr = "\n " + assert_list.front() + "\n";
1210 } else {
1211 for (auto &str : assert_list)
1212 assert_expr += stringf("\n %s", str.c_str());
1213 assert_expr += "\n)";
1214 }
1215 }
1216 decls.push_back(stringf("(define-fun |%s_a| ((state |%s_s|)) Bool %s)\n",
1217 get_id(module), get_id(module), assert_expr.c_str()));
1218
1219 string assume_expr = assume_list.empty() ? "true" : "(and";
1220 if (!assume_list.empty()) {
1221 if (GetSize(assume_list) == 1) {
1222 assume_expr = "\n " + assume_list.front() + "\n";
1223 } else {
1224 for (auto &str : assume_list)
1225 assume_expr += stringf("\n %s", str.c_str());
1226 assume_expr += "\n)";
1227 }
1228 }
1229 decls.push_back(stringf("(define-fun |%s_u| ((state |%s_s|)) Bool %s)\n",
1230 get_id(module), get_id(module), assume_expr.c_str()));
1231
1232 string init_expr = init_list.empty() ? "true" : "(and";
1233 if (!init_list.empty()) {
1234 if (GetSize(init_list) == 1) {
1235 init_expr = "\n " + init_list.front() + "\n";
1236 } else {
1237 for (auto &str : init_list)
1238 init_expr += stringf("\n %s", str.c_str());
1239 init_expr += "\n)";
1240 }
1241 }
1242 decls.push_back(stringf("(define-fun |%s_i| ((state |%s_s|)) Bool %s)\n",
1243 get_id(module), get_id(module), init_expr.c_str()));
1244 }
1245
1246 void write(std::ostream &f)
1247 {
1248 f << stringf("; yosys-smt2-module %s\n", get_id(module));
1249
1250 if (statebv) {
1251 f << stringf("(define-sort |%s_s| () (_ BitVec %d))\n", get_id(module), statebv_width);
1252 mod_stbv_width[module->name] = statebv_width;
1253 } else
1254 if (statedt) {
1255 f << stringf("(declare-datatype |%s_s| ((|%s_mk|\n", get_id(module), get_id(module));
1256 for (auto it : dtmembers)
1257 f << it;
1258 f << stringf(")))\n");
1259 } else
1260 f << stringf("(declare-sort |%s_s| 0)\n", get_id(module));
1261
1262 for (auto it : decls)
1263 f << it;
1264
1265 f << stringf("(define-fun |%s_h| ((state |%s_s|)) Bool ", get_id(module), get_id(module));
1266 if (GetSize(hier) > 1) {
1267 f << "(and\n";
1268 for (auto it : hier)
1269 f << it;
1270 f << "))\n";
1271 } else
1272 if (GetSize(hier) == 1)
1273 f << "\n" + hier.front() + ")\n";
1274 else
1275 f << "true)\n";
1276
1277 f << stringf("(define-fun |%s_t| ((state |%s_s|) (next_state |%s_s|)) Bool ", get_id(module), get_id(module), get_id(module));
1278 if (GetSize(trans) > 1) {
1279 f << "(and\n";
1280 for (auto it : trans)
1281 f << it;
1282 f << "))";
1283 } else
1284 if (GetSize(trans) == 1)
1285 f << "\n" + trans.front() + ")";
1286 else
1287 f << "true)";
1288 f << stringf(" ; end of module %s\n", get_id(module));
1289 }
1290 };
1291
1292 struct Smt2Backend : public Backend {
1293 Smt2Backend() : Backend("smt2", "write design to SMT-LIBv2 file") { }
1294 void help() override
1295 {
1296 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
1297 log("\n");
1298 log(" write_smt2 [options] [filename]\n");
1299 log("\n");
1300 log("Write a SMT-LIBv2 [1] description of the current design. For a module with name\n");
1301 log("'<mod>' this will declare the sort '<mod>_s' (state of the module) and will\n");
1302 log("define and declare functions operating on that state.\n");
1303 log("\n");
1304 log("The following SMT2 functions are generated for a module with name '<mod>'.\n");
1305 log("Some declarations/definitions are printed with a special comment. A prover\n");
1306 log("using the SMT2 files can use those comments to collect all relevant metadata\n");
1307 log("about the design.\n");
1308 log("\n");
1309 log(" ; yosys-smt2-module <mod>\n");
1310 log(" (declare-sort |<mod>_s| 0)\n");
1311 log(" The sort representing a state of module <mod>.\n");
1312 log("\n");
1313 log(" (define-fun |<mod>_h| ((state |<mod>_s|)) Bool (...))\n");
1314 log(" This function must be asserted for each state to establish the\n");
1315 log(" design hierarchy.\n");
1316 log("\n");
1317 log(" ; yosys-smt2-input <wirename> <width>\n");
1318 log(" ; yosys-smt2-output <wirename> <width>\n");
1319 log(" ; yosys-smt2-register <wirename> <width>\n");
1320 log(" ; yosys-smt2-wire <wirename> <width>\n");
1321 log(" (define-fun |<mod>_n <wirename>| (|<mod>_s|) (_ BitVec <width>))\n");
1322 log(" (define-fun |<mod>_n <wirename>| (|<mod>_s|) Bool)\n");
1323 log(" For each port, register, and wire with the 'keep' attribute set an\n");
1324 log(" accessor function is generated. Single-bit wires are returned as Bool,\n");
1325 log(" multi-bit wires as BitVec.\n");
1326 log("\n");
1327 log(" ; yosys-smt2-cell <submod> <instancename>\n");
1328 log(" (declare-fun |<mod>_h <instancename>| (|<mod>_s|) |<submod>_s|)\n");
1329 log(" There is a function like that for each hierarchical instance. It\n");
1330 log(" returns the sort that represents the state of the sub-module that\n");
1331 log(" implements the instance.\n");
1332 log("\n");
1333 log(" (declare-fun |<mod>_is| (|<mod>_s|) Bool)\n");
1334 log(" This function must be asserted 'true' for initial states, and 'false'\n");
1335 log(" otherwise.\n");
1336 log("\n");
1337 log(" (define-fun |<mod>_i| ((state |<mod>_s|)) Bool (...))\n");
1338 log(" This function must be asserted 'true' for initial states. For\n");
1339 log(" non-initial states it must be left unconstrained.\n");
1340 log("\n");
1341 log(" (define-fun |<mod>_t| ((state |<mod>_s|) (next_state |<mod>_s|)) Bool (...))\n");
1342 log(" This function evaluates to 'true' if the states 'state' and\n");
1343 log(" 'next_state' form a valid state transition.\n");
1344 log("\n");
1345 log(" (define-fun |<mod>_a| ((state |<mod>_s|)) Bool (...))\n");
1346 log(" This function evaluates to 'true' if all assertions hold in the state.\n");
1347 log("\n");
1348 log(" (define-fun |<mod>_u| ((state |<mod>_s|)) Bool (...))\n");
1349 log(" This function evaluates to 'true' if all assumptions hold in the state.\n");
1350 log("\n");
1351 log(" ; yosys-smt2-assert <id> <filename:linenum>\n");
1352 log(" (define-fun |<mod>_a <id>| ((state |<mod>_s|)) Bool (...))\n");
1353 log(" Each $assert cell is converted into one of this functions. The function\n");
1354 log(" evaluates to 'true' if the assert statement holds in the state.\n");
1355 log("\n");
1356 log(" ; yosys-smt2-assume <id> <filename:linenum>\n");
1357 log(" (define-fun |<mod>_u <id>| ((state |<mod>_s|)) Bool (...))\n");
1358 log(" Each $assume cell is converted into one of this functions. The function\n");
1359 log(" evaluates to 'true' if the assume statement holds in the state.\n");
1360 log("\n");
1361 log(" ; yosys-smt2-cover <id> <filename:linenum>\n");
1362 log(" (define-fun |<mod>_c <id>| ((state |<mod>_s|)) Bool (...))\n");
1363 log(" Each $cover cell is converted into one of this functions. The function\n");
1364 log(" evaluates to 'true' if the cover statement is activated in the state.\n");
1365 log("\n");
1366 log("Options:\n");
1367 log("\n");
1368 log(" -verbose\n");
1369 log(" this will print the recursive walk used to export the modules.\n");
1370 log("\n");
1371 log(" -stbv\n");
1372 log(" Use a BitVec sort to represent a state instead of an uninterpreted\n");
1373 log(" sort. As a side-effect this will prevent use of arrays to model\n");
1374 log(" memories.\n");
1375 log("\n");
1376 log(" -stdt\n");
1377 log(" Use SMT-LIB 2.6 style datatypes to represent a state instead of an\n");
1378 log(" uninterpreted sort.\n");
1379 log("\n");
1380 log(" -nobv\n");
1381 log(" disable support for BitVec (FixedSizeBitVectors theory). without this\n");
1382 log(" option multi-bit wires are represented using the BitVec sort and\n");
1383 log(" support for coarse grain cells (incl. arithmetic) is enabled.\n");
1384 log("\n");
1385 log(" -nomem\n");
1386 log(" disable support for memories (via ArraysEx theory). this option is\n");
1387 log(" implied by -nobv. only $mem cells without merged registers in\n");
1388 log(" read ports are supported. call \"memory\" with -nordff to make sure\n");
1389 log(" that no registers are merged into $mem read ports. '<mod>_m' functions\n");
1390 log(" will be generated for accessing the arrays that are used to represent\n");
1391 log(" memories.\n");
1392 log("\n");
1393 log(" -wires\n");
1394 log(" create '<mod>_n' functions for all public wires. by default only ports,\n");
1395 log(" registers, and wires with the 'keep' attribute are exported.\n");
1396 log("\n");
1397 log(" -tpl <template_file>\n");
1398 log(" use the given template file. the line containing only the token '%%%%'\n");
1399 log(" is replaced with the regular output of this command.\n");
1400 log("\n");
1401 log(" -solver-option <option> <value>\n");
1402 log(" emit a `; yosys-smt2-solver-option` directive for yosys-smtbmc to write\n");
1403 log(" the given option as a `(set-option ...)` command in the SMT-LIBv2.\n");
1404 log("\n");
1405 log("[1] For more information on SMT-LIBv2 visit http://smt-lib.org/ or read David\n");
1406 log("R. Cok's tutorial: https://smtlib.github.io/jSMTLIB/SMTLIBTutorial.pdf\n");
1407 log("\n");
1408 log("---------------------------------------------------------------------------\n");
1409 log("\n");
1410 log("Example:\n");
1411 log("\n");
1412 log("Consider the following module (test.v). We want to prove that the output can\n");
1413 log("never transition from a non-zero value to a zero value.\n");
1414 log("\n");
1415 log(" module test(input clk, output reg [3:0] y);\n");
1416 log(" always @(posedge clk)\n");
1417 log(" y <= (y << 1) | ^y;\n");
1418 log(" endmodule\n");
1419 log("\n");
1420 log("For this proof we create the following template (test.tpl).\n");
1421 log("\n");
1422 log(" ; we need QF_UFBV for this proof\n");
1423 log(" (set-logic QF_UFBV)\n");
1424 log("\n");
1425 log(" ; insert the auto-generated code here\n");
1426 log(" %%%%\n");
1427 log("\n");
1428 log(" ; declare two state variables s1 and s2\n");
1429 log(" (declare-fun s1 () test_s)\n");
1430 log(" (declare-fun s2 () test_s)\n");
1431 log("\n");
1432 log(" ; state s2 is the successor of state s1\n");
1433 log(" (assert (test_t s1 s2))\n");
1434 log("\n");
1435 log(" ; we are looking for a model with y non-zero in s1\n");
1436 log(" (assert (distinct (|test_n y| s1) #b0000))\n");
1437 log("\n");
1438 log(" ; we are looking for a model with y zero in s2\n");
1439 log(" (assert (= (|test_n y| s2) #b0000))\n");
1440 log("\n");
1441 log(" ; is there such a model?\n");
1442 log(" (check-sat)\n");
1443 log("\n");
1444 log("The following yosys script will create a 'test.smt2' file for our proof:\n");
1445 log("\n");
1446 log(" read_verilog test.v\n");
1447 log(" hierarchy -check; proc; opt; check -assert\n");
1448 log(" write_smt2 -bv -tpl test.tpl test.smt2\n");
1449 log("\n");
1450 log("Running 'cvc4 test.smt2' will print 'unsat' because y can never transition\n");
1451 log("from non-zero to zero in the test design.\n");
1452 log("\n");
1453 }
1454 void execute(std::ostream *&f, std::string filename, std::vector<std::string> args, RTLIL::Design *design) override
1455 {
1456 std::ifstream template_f;
1457 bool bvmode = true, memmode = true, wiresmode = false, verbose = false, statebv = false, statedt = false;
1458 bool forallmode = false;
1459 dict<std::string, std::string> solver_options;
1460
1461 log_header(design, "Executing SMT2 backend.\n");
1462
1463 size_t argidx;
1464 for (argidx = 1; argidx < args.size(); argidx++)
1465 {
1466 if (args[argidx] == "-tpl" && argidx+1 < args.size()) {
1467 template_f.open(args[++argidx]);
1468 if (template_f.fail())
1469 log_error("Can't open template file `%s'.\n", args[argidx].c_str());
1470 continue;
1471 }
1472 if (args[argidx] == "-bv" || args[argidx] == "-mem") {
1473 log_warning("Options -bv and -mem are now the default. Support for -bv and -mem will be removed in the future.\n");
1474 continue;
1475 }
1476 if (args[argidx] == "-stbv") {
1477 statebv = true;
1478 statedt = false;
1479 continue;
1480 }
1481 if (args[argidx] == "-stdt") {
1482 statebv = false;
1483 statedt = true;
1484 continue;
1485 }
1486 if (args[argidx] == "-nobv") {
1487 bvmode = false;
1488 memmode = false;
1489 continue;
1490 }
1491 if (args[argidx] == "-nomem") {
1492 memmode = false;
1493 continue;
1494 }
1495 if (args[argidx] == "-wires") {
1496 wiresmode = true;
1497 continue;
1498 }
1499 if (args[argidx] == "-verbose") {
1500 verbose = true;
1501 continue;
1502 }
1503 if (args[argidx] == "-solver-option" && argidx+2 < args.size()) {
1504 solver_options.emplace(args[argidx+1], args[argidx+2]);
1505 argidx += 2;
1506 continue;
1507 }
1508 break;
1509 }
1510 extra_args(f, filename, args, argidx);
1511
1512 if (template_f.is_open()) {
1513 std::string line;
1514 while (std::getline(template_f, line)) {
1515 int indent = 0;
1516 while (indent < GetSize(line) && (line[indent] == ' ' || line[indent] == '\t'))
1517 indent++;
1518 if (line.compare(indent, 2, "%%") == 0)
1519 break;
1520 *f << line << std::endl;
1521 }
1522 }
1523
1524 *f << stringf("; SMT-LIBv2 description generated by %s\n", yosys_version_str);
1525
1526 if (!bvmode)
1527 *f << stringf("; yosys-smt2-nobv\n");
1528
1529 if (!memmode)
1530 *f << stringf("; yosys-smt2-nomem\n");
1531
1532 if (statebv)
1533 *f << stringf("; yosys-smt2-stbv\n");
1534
1535 if (statedt)
1536 *f << stringf("; yosys-smt2-stdt\n");
1537
1538 for (auto &it : solver_options)
1539 *f << stringf("; yosys-smt2-solver-option %s %s\n", it.first.c_str(), it.second.c_str());
1540
1541 std::vector<RTLIL::Module*> sorted_modules;
1542
1543 // extract module dependencies
1544 std::map<RTLIL::Module*, std::set<RTLIL::Module*>> module_deps;
1545 for (auto mod : design->modules()) {
1546 module_deps[mod] = std::set<RTLIL::Module*>();
1547 for (auto cell : mod->cells())
1548 if (design->has(cell->type))
1549 module_deps[mod].insert(design->module(cell->type));
1550 }
1551
1552 // simple good-enough topological sort
1553 // (O(n*m) on n elements and depth m)
1554 while (module_deps.size() > 0) {
1555 size_t sorted_modules_idx = sorted_modules.size();
1556 for (auto &it : module_deps) {
1557 for (auto &dep : it.second)
1558 if (module_deps.count(dep) > 0)
1559 goto not_ready_yet;
1560 // log("Next in topological sort: %s\n", log_id(it.first->name));
1561 sorted_modules.push_back(it.first);
1562 not_ready_yet:;
1563 }
1564 if (sorted_modules_idx == sorted_modules.size())
1565 log_error("Cyclic dependency between modules found! Cycle includes module %s.\n", log_id(module_deps.begin()->first->name));
1566 while (sorted_modules_idx < sorted_modules.size())
1567 module_deps.erase(sorted_modules.at(sorted_modules_idx++));
1568 }
1569
1570 dict<IdString, int> mod_stbv_width;
1571 dict<IdString, dict<IdString, pair<bool, bool>>> mod_clk_cache;
1572 Module *topmod = design->top_module();
1573 std::string topmod_id;
1574
1575 for (auto module : sorted_modules)
1576 for (auto cell : module->cells())
1577 if (cell->type.in(ID($allconst), ID($allseq)))
1578 goto found_forall;
1579 if (0) {
1580 found_forall:
1581 forallmode = true;
1582 *f << stringf("; yosys-smt2-forall\n");
1583 if (!statebv && !statedt)
1584 log_error("Forall-exists problems are only supported in -stbv or -stdt mode.\n");
1585 }
1586
1587 for (auto module : sorted_modules)
1588 {
1589 if (module->get_blackbox_attribute() || module->has_memories_warn() || module->has_processes_warn())
1590 continue;
1591
1592 log("Creating SMT-LIBv2 representation of module %s.\n", log_id(module));
1593
1594 Smt2Worker worker(module, bvmode, memmode, wiresmode, verbose, statebv, statedt, forallmode, mod_stbv_width, mod_clk_cache);
1595 worker.run();
1596 worker.write(*f);
1597
1598 if (module == topmod)
1599 topmod_id = worker.get_id(module);
1600 }
1601
1602 if (topmod)
1603 *f << stringf("; yosys-smt2-topmod %s\n", topmod_id.c_str());
1604
1605 *f << stringf("; end of yosys output\n");
1606
1607 if (template_f.is_open()) {
1608 std::string line;
1609 while (std::getline(template_f, line))
1610 *f << line << std::endl;
1611 }
1612 }
1613 } Smt2Backend;
1614
1615 PRIVATE_NAMESPACE_END