dd56d8c71197d0e4f80952e92b6d352b37f2e2d2
[yosys.git] / passes / sat / sat.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 // [[CITE]] Temporal Induction by Incremental SAT Solving
21 // Niklas Een and Niklas Sörensson (2003)
22 // http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.8161
23
24 #include "kernel/register.h"
25 #include "kernel/celltypes.h"
26 #include "kernel/consteval.h"
27 #include "kernel/sigtools.h"
28 #include "kernel/log.h"
29 #include "kernel/satgen.h"
30 #include <stdlib.h>
31 #include <stdio.h>
32 #include <algorithm>
33 #include <errno.h>
34 #include <string.h>
35
36 USING_YOSYS_NAMESPACE
37 PRIVATE_NAMESPACE_BEGIN
38
39 struct SatHelper
40 {
41 RTLIL::Design *design;
42 RTLIL::Module *module;
43
44 SigMap sigmap;
45 CellTypes ct;
46
47 ezSatPtr ez;
48 SatGen satgen;
49
50 // additional constraints
51 std::vector<std::pair<std::string, std::string>> sets, prove, prove_x, sets_init;
52 std::map<int, std::vector<std::pair<std::string, std::string>>> sets_at;
53 std::map<int, std::vector<std::string>> unsets_at;
54 bool prove_asserts, set_assumes;
55
56 // undef constraints
57 bool enable_undef, set_init_def, set_init_undef, set_init_zero, ignore_unknown_cells;
58 std::vector<std::string> sets_def, sets_any_undef, sets_all_undef;
59 std::map<int, std::vector<std::string>> sets_def_at, sets_any_undef_at, sets_all_undef_at;
60
61 // model variables
62 std::vector<std::string> shows;
63 SigPool show_signal_pool;
64 SigSet<RTLIL::Cell*> show_drivers;
65 int max_timestep, timeout;
66 bool gotTimeout;
67
68 SatHelper(RTLIL::Design *design, RTLIL::Module *module, bool enable_undef) :
69 design(design), module(module), sigmap(module), ct(design), satgen(ez.get(), &sigmap)
70 {
71 this->enable_undef = enable_undef;
72 satgen.model_undef = enable_undef;
73 set_init_def = false;
74 set_init_undef = false;
75 set_init_zero = false;
76 ignore_unknown_cells = false;
77 max_timestep = -1;
78 timeout = 0;
79 gotTimeout = false;
80 }
81
82 void check_undef_enabled(const RTLIL::SigSpec &sig)
83 {
84 if (enable_undef)
85 return;
86
87 std::vector<RTLIL::SigBit> sigbits = sig.to_sigbit_vector();
88 for (size_t i = 0; i < sigbits.size(); i++)
89 if (sigbits[i].wire == NULL && sigbits[i].data == RTLIL::State::Sx)
90 log_cmd_error("Bit %d of %s is undef but option -enable_undef is missing!\n", int(i), log_signal(sig));
91 }
92
93 void setup(int timestep = -1, bool initstate = false)
94 {
95 if (timestep > 0)
96 log ("\nSetting up time step %d:\n", timestep);
97 else
98 log ("\nSetting up SAT problem:\n");
99
100 if (initstate)
101 satgen.setInitState(timestep);
102
103 if (timestep > max_timestep)
104 max_timestep = timestep;
105
106 RTLIL::SigSpec big_lhs, big_rhs;
107
108 for (auto &s : sets)
109 {
110 RTLIL::SigSpec lhs, rhs;
111
112 if (!RTLIL::SigSpec::parse_sel(lhs, design, module, s.first))
113 log_cmd_error("Failed to parse lhs set expression `%s'.\n", s.first.c_str());
114 if (!RTLIL::SigSpec::parse_rhs(lhs, rhs, module, s.second))
115 log_cmd_error("Failed to parse rhs set expression `%s'.\n", s.second.c_str());
116 show_signal_pool.add(sigmap(lhs));
117 show_signal_pool.add(sigmap(rhs));
118
119 if (lhs.size() != rhs.size())
120 log_cmd_error("Set expression with different lhs and rhs sizes: %s (%s, %d bits) vs. %s (%s, %d bits)\n",
121 s.first.c_str(), log_signal(lhs), lhs.size(), s.second.c_str(), log_signal(rhs), rhs.size());
122
123 log("Import set-constraint: %s = %s\n", log_signal(lhs), log_signal(rhs));
124 big_lhs.remove2(lhs, &big_rhs);
125 big_lhs.append(lhs);
126 big_rhs.append(rhs);
127 }
128
129 for (auto &s : sets_at[timestep])
130 {
131 RTLIL::SigSpec lhs, rhs;
132
133 if (!RTLIL::SigSpec::parse_sel(lhs, design, module, s.first))
134 log_cmd_error("Failed to parse lhs set expression `%s'.\n", s.first.c_str());
135 if (!RTLIL::SigSpec::parse_rhs(lhs, rhs, module, s.second))
136 log_cmd_error("Failed to parse rhs set expression `%s'.\n", s.second.c_str());
137 show_signal_pool.add(sigmap(lhs));
138 show_signal_pool.add(sigmap(rhs));
139
140 if (lhs.size() != rhs.size())
141 log_cmd_error("Set expression with different lhs and rhs sizes: %s (%s, %d bits) vs. %s (%s, %d bits)\n",
142 s.first.c_str(), log_signal(lhs), lhs.size(), s.second.c_str(), log_signal(rhs), rhs.size());
143
144 log("Import set-constraint for this timestep: %s = %s\n", log_signal(lhs), log_signal(rhs));
145 big_lhs.remove2(lhs, &big_rhs);
146 big_lhs.append(lhs);
147 big_rhs.append(rhs);
148 }
149
150 for (auto &s : unsets_at[timestep])
151 {
152 RTLIL::SigSpec lhs;
153
154 if (!RTLIL::SigSpec::parse_sel(lhs, design, module, s))
155 log_cmd_error("Failed to parse lhs set expression `%s'.\n", s.c_str());
156 show_signal_pool.add(sigmap(lhs));
157
158 log("Import unset-constraint for this timestep: %s\n", log_signal(lhs));
159 big_lhs.remove2(lhs, &big_rhs);
160 }
161
162 log("Final constraint equation: %s = %s\n", log_signal(big_lhs), log_signal(big_rhs));
163 check_undef_enabled(big_lhs), check_undef_enabled(big_rhs);
164 ez->assume(satgen.signals_eq(big_lhs, big_rhs, timestep));
165
166 // 0 = sets_def
167 // 1 = sets_any_undef
168 // 2 = sets_all_undef
169 std::set<RTLIL::SigSpec> sets_def_undef[3];
170
171 for (auto &s : sets_def) {
172 RTLIL::SigSpec sig;
173 if (!RTLIL::SigSpec::parse_sel(sig, design, module, s))
174 log_cmd_error("Failed to parse set-def expression `%s'.\n", s.c_str());
175 sets_def_undef[0].insert(sig);
176 }
177
178 for (auto &s : sets_any_undef) {
179 RTLIL::SigSpec sig;
180 if (!RTLIL::SigSpec::parse_sel(sig, design, module, s))
181 log_cmd_error("Failed to parse set-def expression `%s'.\n", s.c_str());
182 sets_def_undef[1].insert(sig);
183 }
184
185 for (auto &s : sets_all_undef) {
186 RTLIL::SigSpec sig;
187 if (!RTLIL::SigSpec::parse_sel(sig, design, module, s))
188 log_cmd_error("Failed to parse set-def expression `%s'.\n", s.c_str());
189 sets_def_undef[2].insert(sig);
190 }
191
192 for (auto &s : sets_def_at[timestep]) {
193 RTLIL::SigSpec sig;
194 if (!RTLIL::SigSpec::parse_sel(sig, design, module, s))
195 log_cmd_error("Failed to parse set-def expression `%s'.\n", s.c_str());
196 sets_def_undef[0].insert(sig);
197 sets_def_undef[1].erase(sig);
198 sets_def_undef[2].erase(sig);
199 }
200
201 for (auto &s : sets_any_undef_at[timestep]) {
202 RTLIL::SigSpec sig;
203 if (!RTLIL::SigSpec::parse_sel(sig, design, module, s))
204 log_cmd_error("Failed to parse set-def expression `%s'.\n", s.c_str());
205 sets_def_undef[0].erase(sig);
206 sets_def_undef[1].insert(sig);
207 sets_def_undef[2].erase(sig);
208 }
209
210 for (auto &s : sets_all_undef_at[timestep]) {
211 RTLIL::SigSpec sig;
212 if (!RTLIL::SigSpec::parse_sel(sig, design, module, s))
213 log_cmd_error("Failed to parse set-def expression `%s'.\n", s.c_str());
214 sets_def_undef[0].erase(sig);
215 sets_def_undef[1].erase(sig);
216 sets_def_undef[2].insert(sig);
217 }
218
219 for (int t = 0; t < 3; t++)
220 for (auto &sig : sets_def_undef[t]) {
221 log("Import %s constraint for this timestep: %s\n", t == 0 ? "def" : t == 1 ? "any_undef" : "all_undef", log_signal(sig));
222 std::vector<int> undef_sig = satgen.importUndefSigSpec(sig, timestep);
223 if (t == 0)
224 ez->assume(ez->NOT(ez->expression(ezSAT::OpOr, undef_sig)));
225 if (t == 1)
226 ez->assume(ez->expression(ezSAT::OpOr, undef_sig));
227 if (t == 2)
228 ez->assume(ez->expression(ezSAT::OpAnd, undef_sig));
229 }
230
231 int import_cell_counter = 0;
232 for (auto cell : module->cells())
233 if (design->selected(module, cell)) {
234 // log("Import cell: %s\n", RTLIL::id2cstr(cell->name));
235 if (satgen.importCell(cell, timestep)) {
236 for (auto &p : cell->connections())
237 if (ct.cell_output(cell->type, p.first))
238 show_drivers.insert(sigmap(p.second), cell);
239 import_cell_counter++;
240 } else if (ignore_unknown_cells)
241 log_warning("Failed to import cell %s (type %s) to SAT database.\n", RTLIL::id2cstr(cell->name), RTLIL::id2cstr(cell->type));
242 else
243 log_error("Failed to import cell %s (type %s) to SAT database.\n", RTLIL::id2cstr(cell->name), RTLIL::id2cstr(cell->type));
244 }
245 log("Imported %d cells to SAT database.\n", import_cell_counter);
246
247 if (set_assumes) {
248 RTLIL::SigSpec assumes_a, assumes_en;
249 satgen.getAssumes(assumes_a, assumes_en, timestep);
250 for (int i = 0; i < GetSize(assumes_a); i++)
251 log("Import constraint from assume cell: %s when %s.\n", log_signal(assumes_a[i]), log_signal(assumes_en[i]));
252 ez->assume(satgen.importAssumes(timestep));
253 }
254
255 if (initstate)
256 {
257 RTLIL::SigSpec big_lhs, big_rhs;
258
259 for (auto &it : module->wires_)
260 {
261 if (it.second->attributes.count("\\init") == 0)
262 continue;
263
264 RTLIL::SigSpec lhs = sigmap(it.second);
265 RTLIL::SigSpec rhs = it.second->attributes.at("\\init");
266 log_assert(lhs.size() == rhs.size());
267
268 RTLIL::SigSpec removed_bits;
269 for (int i = 0; i < lhs.size(); i++) {
270 RTLIL::SigSpec bit = lhs.extract(i, 1);
271 if (!satgen.initial_state.check_all(bit)) {
272 removed_bits.append(bit);
273 lhs.remove(i, 1);
274 rhs.remove(i, 1);
275 i--;
276 }
277 }
278
279 if (removed_bits.size())
280 log_warning("ignoring initial value on non-register: %s\n", log_signal(removed_bits));
281
282 if (lhs.size()) {
283 log("Import set-constraint from init attribute: %s = %s\n", log_signal(lhs), log_signal(rhs));
284 big_lhs.remove2(lhs, &big_rhs);
285 big_lhs.append(lhs);
286 big_rhs.append(rhs);
287 }
288 }
289
290 for (auto &s : sets_init)
291 {
292 RTLIL::SigSpec lhs, rhs;
293
294 if (!RTLIL::SigSpec::parse_sel(lhs, design, module, s.first))
295 log_cmd_error("Failed to parse lhs set expression `%s'.\n", s.first.c_str());
296 if (!RTLIL::SigSpec::parse_rhs(lhs, rhs, module, s.second))
297 log_cmd_error("Failed to parse rhs set expression `%s'.\n", s.second.c_str());
298 show_signal_pool.add(sigmap(lhs));
299 show_signal_pool.add(sigmap(rhs));
300
301 if (lhs.size() != rhs.size())
302 log_cmd_error("Set expression with different lhs and rhs sizes: %s (%s, %d bits) vs. %s (%s, %d bits)\n",
303 s.first.c_str(), log_signal(lhs), lhs.size(), s.second.c_str(), log_signal(rhs), rhs.size());
304
305 log("Import init set-constraint: %s = %s\n", log_signal(lhs), log_signal(rhs));
306 big_lhs.remove2(lhs, &big_rhs);
307 big_lhs.append(lhs);
308 big_rhs.append(rhs);
309 }
310
311 if (!satgen.initial_state.check_all(big_lhs)) {
312 RTLIL::SigSpec rem = satgen.initial_state.remove(big_lhs);
313 log_cmd_error("Found -set-init bits that are not part of the initial_state: %s\n", log_signal(rem));
314 }
315
316 if (set_init_def) {
317 RTLIL::SigSpec rem = satgen.initial_state.export_all();
318 std::vector<int> undef_rem = satgen.importUndefSigSpec(rem, 1);
319 ez->assume(ez->NOT(ez->expression(ezSAT::OpOr, undef_rem)));
320 }
321
322 if (set_init_undef) {
323 RTLIL::SigSpec rem = satgen.initial_state.export_all();
324 rem.remove(big_lhs);
325 big_lhs.append(rem);
326 big_rhs.append(RTLIL::SigSpec(RTLIL::State::Sx, rem.size()));
327 }
328
329 if (set_init_zero) {
330 RTLIL::SigSpec rem = satgen.initial_state.export_all();
331 rem.remove(big_lhs);
332 big_lhs.append(rem);
333 big_rhs.append(RTLIL::SigSpec(RTLIL::State::S0, rem.size()));
334 }
335
336 if (big_lhs.size() == 0) {
337 log("No constraints for initial state found.\n\n");
338 return;
339 }
340
341 log("Final init constraint equation: %s = %s\n", log_signal(big_lhs), log_signal(big_rhs));
342 check_undef_enabled(big_lhs), check_undef_enabled(big_rhs);
343 ez->assume(satgen.signals_eq(big_lhs, big_rhs, timestep));
344 }
345 }
346
347 int setup_proof(int timestep = -1)
348 {
349 log_assert(prove.size() || prove_x.size() || prove_asserts);
350
351 RTLIL::SigSpec big_lhs, big_rhs;
352 std::vector<int> prove_bits;
353
354 if (prove.size() > 0)
355 {
356 for (auto &s : prove)
357 {
358 RTLIL::SigSpec lhs, rhs;
359
360 if (!RTLIL::SigSpec::parse_sel(lhs, design, module, s.first))
361 log_cmd_error("Failed to parse lhs proof expression `%s'.\n", s.first.c_str());
362 if (!RTLIL::SigSpec::parse_rhs(lhs, rhs, module, s.second))
363 log_cmd_error("Failed to parse rhs proof expression `%s'.\n", s.second.c_str());
364 show_signal_pool.add(sigmap(lhs));
365 show_signal_pool.add(sigmap(rhs));
366
367 if (lhs.size() != rhs.size())
368 log_cmd_error("Proof expression with different lhs and rhs sizes: %s (%s, %d bits) vs. %s (%s, %d bits)\n",
369 s.first.c_str(), log_signal(lhs), lhs.size(), s.second.c_str(), log_signal(rhs), rhs.size());
370
371 log("Import proof-constraint: %s = %s\n", log_signal(lhs), log_signal(rhs));
372 big_lhs.remove2(lhs, &big_rhs);
373 big_lhs.append(lhs);
374 big_rhs.append(rhs);
375 }
376
377 log("Final proof equation: %s = %s\n", log_signal(big_lhs), log_signal(big_rhs));
378 check_undef_enabled(big_lhs), check_undef_enabled(big_rhs);
379 prove_bits.push_back(satgen.signals_eq(big_lhs, big_rhs, timestep));
380 }
381
382 if (prove_x.size() > 0)
383 {
384 for (auto &s : prove_x)
385 {
386 RTLIL::SigSpec lhs, rhs;
387
388 if (!RTLIL::SigSpec::parse_sel(lhs, design, module, s.first))
389 log_cmd_error("Failed to parse lhs proof-x expression `%s'.\n", s.first.c_str());
390 if (!RTLIL::SigSpec::parse_rhs(lhs, rhs, module, s.second))
391 log_cmd_error("Failed to parse rhs proof-x expression `%s'.\n", s.second.c_str());
392 show_signal_pool.add(sigmap(lhs));
393 show_signal_pool.add(sigmap(rhs));
394
395 if (lhs.size() != rhs.size())
396 log_cmd_error("Proof-x expression with different lhs and rhs sizes: %s (%s, %d bits) vs. %s (%s, %d bits)\n",
397 s.first.c_str(), log_signal(lhs), lhs.size(), s.second.c_str(), log_signal(rhs), rhs.size());
398
399 log("Import proof-x-constraint: %s = %s\n", log_signal(lhs), log_signal(rhs));
400 big_lhs.remove2(lhs, &big_rhs);
401 big_lhs.append(lhs);
402 big_rhs.append(rhs);
403 }
404
405 log("Final proof-x equation: %s = %s\n", log_signal(big_lhs), log_signal(big_rhs));
406
407 std::vector<int> value_lhs = satgen.importDefSigSpec(big_lhs, timestep);
408 std::vector<int> value_rhs = satgen.importDefSigSpec(big_rhs, timestep);
409
410 std::vector<int> undef_lhs = satgen.importUndefSigSpec(big_lhs, timestep);
411 std::vector<int> undef_rhs = satgen.importUndefSigSpec(big_rhs, timestep);
412
413 for (size_t i = 0; i < value_lhs.size(); i++)
414 prove_bits.push_back(ez->OR(undef_lhs.at(i), ez->AND(ez->NOT(undef_rhs.at(i)), ez->NOT(ez->XOR(value_lhs.at(i), value_rhs.at(i))))));
415 }
416
417 if (prove_asserts) {
418 RTLIL::SigSpec asserts_a, asserts_en;
419 satgen.getAsserts(asserts_a, asserts_en, timestep);
420 for (int i = 0; i < GetSize(asserts_a); i++)
421 log("Import proof for assert: %s when %s.\n", log_signal(asserts_a[i]), log_signal(asserts_en[i]));
422 prove_bits.push_back(satgen.importAsserts(timestep));
423 }
424
425 return ez->expression(ezSAT::OpAnd, prove_bits);
426 }
427
428 void force_unique_state(int timestep_from, int timestep_to)
429 {
430 RTLIL::SigSpec state_signals = satgen.initial_state.export_all();
431 for (int i = timestep_from; i < timestep_to; i++)
432 ez->assume(ez->NOT(satgen.signals_eq(state_signals, state_signals, i, timestep_to)));
433 }
434
435 bool solve(const std::vector<int> &assumptions)
436 {
437 log_assert(gotTimeout == false);
438 ez->setSolverTimeout(timeout);
439 bool success = ez->solve(modelExpressions, modelValues, assumptions);
440 if (ez->getSolverTimoutStatus())
441 gotTimeout = true;
442 return success;
443 }
444
445 bool solve(int a = 0, int b = 0, int c = 0, int d = 0, int e = 0, int f = 0)
446 {
447 log_assert(gotTimeout == false);
448 ez->setSolverTimeout(timeout);
449 bool success = ez->solve(modelExpressions, modelValues, a, b, c, d, e, f);
450 if (ez->getSolverTimoutStatus())
451 gotTimeout = true;
452 return success;
453 }
454
455 struct ModelBlockInfo {
456 int timestep, offset, width;
457 std::string description;
458 bool operator < (const ModelBlockInfo &other) const {
459 if (timestep != other.timestep)
460 return timestep < other.timestep;
461 if (description != other.description)
462 return description < other.description;
463 if (offset != other.offset)
464 return offset < other.offset;
465 if (width != other.width)
466 return width < other.width;
467 return false;
468 }
469 };
470
471 std::vector<int> modelExpressions;
472 std::vector<bool> modelValues;
473 std::set<ModelBlockInfo> modelInfo;
474
475 void maximize_undefs()
476 {
477 log_assert(enable_undef);
478 std::vector<bool> backupValues;
479
480 while (1)
481 {
482 std::vector<int> must_undef, maybe_undef;
483
484 for (size_t i = 0; i < modelExpressions.size()/2; i++)
485 if (modelValues.at(modelExpressions.size()/2 + i))
486 must_undef.push_back(modelExpressions.at(modelExpressions.size()/2 + i));
487 else
488 maybe_undef.push_back(modelExpressions.at(modelExpressions.size()/2 + i));
489
490 backupValues.swap(modelValues);
491 if (!solve(ez->expression(ezSAT::OpAnd, must_undef), ez->expression(ezSAT::OpOr, maybe_undef)))
492 break;
493 }
494
495 backupValues.swap(modelValues);
496 }
497
498 void generate_model()
499 {
500 RTLIL::SigSpec modelSig;
501 modelExpressions.clear();
502 modelInfo.clear();
503
504 // Add "show" signals or alternatively the leaves on the input cone on all set and prove signals
505
506 if (shows.size() == 0)
507 {
508 SigPool queued_signals, handled_signals, final_signals;
509 queued_signals = show_signal_pool;
510 while (queued_signals.size() > 0) {
511 RTLIL::SigSpec sig = queued_signals.export_one();
512 queued_signals.del(sig);
513 handled_signals.add(sig);
514 std::set<RTLIL::Cell*> drivers = show_drivers.find(sig);
515 if (drivers.size() == 0) {
516 final_signals.add(sig);
517 } else {
518 for (auto &d : drivers)
519 for (auto &p : d->connections()) {
520 if (d->type == "$dff" && p.first == "\\CLK")
521 continue;
522 if (d->type.begins_with("$_DFF_") && p.first == "\\C")
523 continue;
524 queued_signals.add(handled_signals.remove(sigmap(p.second)));
525 }
526 }
527 }
528 modelSig = final_signals.export_all();
529
530 // additionally add all set and prove signals directly
531 // (it improves user confidence if we write the constraints back ;-)
532 modelSig.append(show_signal_pool.export_all());
533 }
534 else
535 {
536 for (auto &s : shows) {
537 RTLIL::SigSpec sig;
538 if (!RTLIL::SigSpec::parse_sel(sig, design, module, s))
539 log_cmd_error("Failed to parse show expression `%s'.\n", s.c_str());
540 log("Import show expression: %s\n", log_signal(sig));
541 modelSig.append(sig);
542 }
543 }
544
545 modelSig.sort_and_unify();
546 // log("Model signals: %s\n", log_signal(modelSig));
547
548 std::vector<int> modelUndefExpressions;
549
550 for (auto &c : modelSig.chunks())
551 if (c.wire != NULL)
552 {
553 ModelBlockInfo info;
554 RTLIL::SigSpec chunksig = c;
555 info.width = chunksig.size();
556 info.description = log_signal(chunksig);
557
558 for (int timestep = -1; timestep <= max_timestep; timestep++)
559 {
560 if ((timestep == -1 && max_timestep > 0) || timestep == 0)
561 continue;
562
563 info.timestep = timestep;
564 info.offset = modelExpressions.size();
565 modelInfo.insert(info);
566
567 std::vector<int> vec = satgen.importSigSpec(chunksig, timestep);
568 modelExpressions.insert(modelExpressions.end(), vec.begin(), vec.end());
569
570 if (enable_undef) {
571 std::vector<int> undef_vec = satgen.importUndefSigSpec(chunksig, timestep);
572 modelUndefExpressions.insert(modelUndefExpressions.end(), undef_vec.begin(), undef_vec.end());
573 }
574 }
575 }
576
577 // Add initial state signals as collected by satgen
578 //
579 modelSig = satgen.initial_state.export_all();
580 for (auto &c : modelSig.chunks())
581 if (c.wire != NULL)
582 {
583 ModelBlockInfo info;
584 RTLIL::SigSpec chunksig = c;
585
586 info.timestep = 0;
587 info.offset = modelExpressions.size();
588 info.width = chunksig.size();
589 info.description = log_signal(chunksig);
590 modelInfo.insert(info);
591
592 std::vector<int> vec = satgen.importSigSpec(chunksig, 1);
593 modelExpressions.insert(modelExpressions.end(), vec.begin(), vec.end());
594
595 if (enable_undef) {
596 std::vector<int> undef_vec = satgen.importUndefSigSpec(chunksig, 1);
597 modelUndefExpressions.insert(modelUndefExpressions.end(), undef_vec.begin(), undef_vec.end());
598 }
599 }
600
601 modelExpressions.insert(modelExpressions.end(), modelUndefExpressions.begin(), modelUndefExpressions.end());
602 }
603
604 void print_model()
605 {
606 int maxModelName = 10;
607 int maxModelWidth = 10;
608
609 for (auto &info : modelInfo) {
610 maxModelName = max(maxModelName, int(info.description.size()));
611 maxModelWidth = max(maxModelWidth, info.width);
612 }
613
614 log("\n");
615
616 int last_timestep = -2;
617 for (auto &info : modelInfo)
618 {
619 RTLIL::Const value;
620 bool found_undef = false;
621
622 for (int i = 0; i < info.width; i++) {
623 value.bits.push_back(modelValues.at(info.offset+i) ? RTLIL::State::S1 : RTLIL::State::S0);
624 if (enable_undef && modelValues.at(modelExpressions.size()/2 + info.offset + i))
625 value.bits.back() = RTLIL::State::Sx, found_undef = true;
626 }
627
628 if (info.timestep != last_timestep) {
629 const char *hline = "---------------------------------------------------------------------------------------------------"
630 "---------------------------------------------------------------------------------------------------"
631 "---------------------------------------------------------------------------------------------------";
632 if (last_timestep == -2) {
633 log(max_timestep > 0 ? " Time " : " ");
634 log("%-*s %11s %9s %*s\n", maxModelName+5, "Signal Name", "Dec", "Hex", maxModelWidth+3, "Bin");
635 }
636 log(max_timestep > 0 ? " ---- " : " ");
637 log("%*.*s %11.11s %9.9s %*.*s\n", maxModelName+5, maxModelName+5,
638 hline, hline, hline, maxModelWidth+3, maxModelWidth+3, hline);
639 last_timestep = info.timestep;
640 }
641
642 if (max_timestep > 0) {
643 if (info.timestep > 0)
644 log(" %4d ", info.timestep);
645 else
646 log(" init ");
647 } else
648 log(" ");
649
650 if (info.width <= 32 && !found_undef)
651 log("%-*s %11d %9x %*s\n", maxModelName+5, info.description.c_str(), value.as_int(), value.as_int(), maxModelWidth+3, value.as_string().c_str());
652 else
653 log("%-*s %11s %9s %*s\n", maxModelName+5, info.description.c_str(), "--", "--", maxModelWidth+3, value.as_string().c_str());
654 }
655
656 if (last_timestep == -2)
657 log(" no model variables selected for display.\n");
658 }
659
660 void dump_model_to_vcd(std::string vcd_file_name)
661 {
662 rewrite_filename(vcd_file_name);
663 FILE *f = fopen(vcd_file_name.c_str(), "w");
664 if (!f)
665 log_cmd_error("Can't open output file `%s' for writing: %s\n", vcd_file_name.c_str(), strerror(errno));
666
667 log("Dumping SAT model to VCD file %s\n", vcd_file_name.c_str());
668
669 time_t timestamp;
670 struct tm* now;
671 char stime[128] = {};
672 time(&timestamp);
673 now = localtime(&timestamp);
674 strftime(stime, sizeof(stime), "%c", now);
675
676 std::string module_fname = "unknown";
677 auto apos = module->attributes.find("\\src");
678 if(apos != module->attributes.end())
679 module_fname = module->attributes["\\src"].decode_string();
680
681 fprintf(f, "$date\n");
682 fprintf(f, " %s\n", stime);
683 fprintf(f, "$end\n");
684 fprintf(f, "$version\n");
685 fprintf(f, " Generated by %s\n", yosys_version_str);
686 fprintf(f, "$end\n");
687 fprintf(f, "$comment\n");
688 fprintf(f, " Generated from SAT problem in module %s (declared at %s)\n",
689 module->name.c_str(), module_fname.c_str());
690 fprintf(f, "$end\n");
691
692 // VCD has some limits on internal (non-display) identifier names, so make legal ones
693 std::map<std::string, std::string> vcdnames;
694
695 fprintf(f, "$scope module %s $end\n", module->name.c_str());
696 for (auto &info : modelInfo)
697 {
698 if (vcdnames.find(info.description) != vcdnames.end())
699 continue;
700
701 char namebuf[16];
702 snprintf(namebuf, sizeof(namebuf), "v%d", static_cast<int>(vcdnames.size()));
703 vcdnames[info.description] = namebuf;
704
705 // Even display identifiers can't use some special characters
706 std::string legal_desc = info.description.c_str();
707 for (auto &c : legal_desc) {
708 if(c == '$')
709 c = '_';
710 if(c == ':')
711 c = '_';
712 }
713
714 fprintf(f, "$var wire %d %s %s $end\n", info.width, namebuf, legal_desc.c_str());
715
716 // Need to look at first *two* cycles!
717 // We need to put a name on all variables but those without an initialization clause
718 // have no value at timestep 0
719 if(info.timestep > 1)
720 break;
721 }
722 fprintf(f, "$upscope $end\n");
723 fprintf(f, "$enddefinitions $end\n");
724 fprintf(f, "$dumpvars\n");
725
726 static const char bitvals[] = "01xzxx";
727
728 int last_timestep = -2;
729 for (auto &info : modelInfo)
730 {
731 RTLIL::Const value;
732
733 for (int i = 0; i < info.width; i++) {
734 value.bits.push_back(modelValues.at(info.offset+i) ? RTLIL::State::S1 : RTLIL::State::S0);
735 if (enable_undef && modelValues.at(modelExpressions.size()/2 + info.offset + i))
736 value.bits.back() = RTLIL::State::Sx;
737 }
738
739 if (info.timestep != last_timestep) {
740 if(last_timestep == 0)
741 fprintf(f, "$end\n");
742 else
743 fprintf(f, "#%d\n", info.timestep);
744 last_timestep = info.timestep;
745 }
746
747 if(info.width == 1) {
748 fprintf(f, "%c%s\n", bitvals[value.bits[0]], vcdnames[info.description].c_str());
749 } else {
750 fprintf(f, "b");
751 for(int k=info.width-1; k >= 0; k --) //need to flip bit ordering for VCD
752 fprintf(f, "%c", bitvals[value.bits[k]]);
753 fprintf(f, " %s\n", vcdnames[info.description].c_str());
754 }
755 }
756
757 if (last_timestep == -2)
758 log(" no model variables selected for display.\n");
759
760 fclose(f);
761 }
762
763 void dump_model_to_json(std::string json_file_name)
764 {
765 rewrite_filename(json_file_name);
766 FILE *f = fopen(json_file_name.c_str(), "w");
767 if (!f)
768 log_cmd_error("Can't open output file `%s' for writing: %s\n", json_file_name.c_str(), strerror(errno));
769
770 log("Dumping SAT model to WaveJSON file '%s'.\n", json_file_name.c_str());
771
772 int mintime = 1, maxtime = 0, maxwidth = 0;;
773 dict<string, pair<int, dict<int, Const>>> wavedata;
774
775 for (auto &info : modelInfo)
776 {
777 Const value;
778 for (int i = 0; i < info.width; i++) {
779 value.bits.push_back(modelValues.at(info.offset+i) ? RTLIL::State::S1 : RTLIL::State::S0);
780 if (enable_undef && modelValues.at(modelExpressions.size()/2 + info.offset + i))
781 value.bits.back() = RTLIL::State::Sx;
782 }
783
784 wavedata[info.description].first = info.width;
785 wavedata[info.description].second[info.timestep] = value;
786 mintime = min(mintime, info.timestep);
787 maxtime = max(maxtime, info.timestep);
788 maxwidth = max(maxwidth, info.width);
789 }
790
791 fprintf(f, "{ \"signal\": [");
792 bool fist_wavedata = true;
793 for (auto &wd : wavedata)
794 {
795 fprintf(f, "%s", fist_wavedata ? "\n" : ",\n");
796 fist_wavedata = false;
797
798 vector<string> data;
799 string name = wd.first.c_str();
800 while (name.compare(0, 1, "\\") == 0)
801 name = name.substr(1);
802
803 fprintf(f, " { \"name\": \"%s\", \"wave\": \"", name.c_str());
804 for (int i = mintime; i <= maxtime; i++) {
805 if (wd.second.second.count(i)) {
806 string this_data = wd.second.second[i].as_string();
807 char ch = '=';
808 if (wd.second.first == 1)
809 ch = this_data[0];
810 if (!data.empty() && data.back() == this_data) {
811 fprintf(f, ".");
812 } else {
813 data.push_back(this_data);
814 fprintf(f, "%c", ch);
815 }
816 } else {
817 data.push_back("");
818 fprintf(f, "4");
819 }
820 }
821 if (wd.second.first != 1) {
822 fprintf(f, "\", \"data\": [");
823 for (int i = 0; i < GetSize(data); i++)
824 fprintf(f, "%s\"%s\"", i ? ", " : "", data[i].c_str());
825 fprintf(f, "] }");
826 } else {
827 fprintf(f, "\" }");
828 }
829 }
830 fprintf(f, "\n ],\n");
831 fprintf(f, " \"config\": {\n");
832 fprintf(f, " \"hscale\": %.2f\n", maxwidth / 4.0);
833 fprintf(f, " }\n");
834 fprintf(f, "}\n");
835 fclose(f);
836 }
837
838 void invalidate_model(bool max_undef)
839 {
840 std::vector<int> clause;
841 if (enable_undef) {
842 for (size_t i = 0; i < modelExpressions.size()/2; i++) {
843 int bit = modelExpressions.at(i), bit_undef = modelExpressions.at(modelExpressions.size()/2 + i);
844 bool val = modelValues.at(i), val_undef = modelValues.at(modelExpressions.size()/2 + i);
845 if (!max_undef || !val_undef)
846 clause.push_back(val_undef ? ez->NOT(bit_undef) : val ? ez->NOT(bit) : bit);
847 }
848 } else
849 for (size_t i = 0; i < modelExpressions.size(); i++)
850 clause.push_back(modelValues.at(i) ? ez->NOT(modelExpressions.at(i)) : modelExpressions.at(i));
851 ez->assume(ez->expression(ezSAT::OpOr, clause));
852 }
853 };
854
855 void print_proof_failed()
856 {
857 log("\n");
858 log(" ______ ___ ___ _ _ _ _ \n");
859 log(" (_____ \\ / __) / __) (_) | | | |\n");
860 log(" _____) )___ ___ ___ _| |__ _| |__ _____ _| | _____ __| | |\n");
861 log(" | ____/ ___) _ \\ / _ (_ __) (_ __|____ | | || ___ |/ _ |_|\n");
862 log(" | | | | | |_| | |_| || | | | / ___ | | || ____( (_| |_ \n");
863 log(" |_| |_| \\___/ \\___/ |_| |_| \\_____|_|\\_)_____)\\____|_|\n");
864 log("\n");
865 }
866
867 void print_timeout()
868 {
869 log("\n");
870 log(" _____ _ _ _____ ____ _ _____\n");
871 log(" /__ __\\/ \\/ \\__/|/ __// _ \\/ \\ /\\/__ __\\\n");
872 log(" / \\ | || |\\/||| \\ | / \\|| | || / \\\n");
873 log(" | | | || | ||| /_ | \\_/|| \\_/| | |\n");
874 log(" \\_/ \\_/\\_/ \\|\\____\\\\____/\\____/ \\_/\n");
875 log("\n");
876 }
877
878 void print_qed()
879 {
880 log("\n");
881 log(" /$$$$$$ /$$$$$$$$ /$$$$$$$ \n");
882 log(" /$$__ $$ | $$_____/ | $$__ $$ \n");
883 log(" | $$ \\ $$ | $$ | $$ \\ $$ \n");
884 log(" | $$ | $$ | $$$$$ | $$ | $$ \n");
885 log(" | $$ | $$ | $$__/ | $$ | $$ \n");
886 log(" | $$/$$ $$ | $$ | $$ | $$ \n");
887 log(" | $$$$$$/ /$$| $$$$$$$$ /$$| $$$$$$$//$$\n");
888 log(" \\____ $$$|__/|________/|__/|_______/|__/\n");
889 log(" \\__/ \n");
890 log("\n");
891 }
892
893 struct SatPass : public Pass {
894 SatPass() : Pass("sat", "solve a SAT problem in the circuit") { }
895 void help() YS_OVERRIDE
896 {
897 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
898 log("\n");
899 log(" sat [options] [selection]\n");
900 log("\n");
901 log("This command solves a SAT problem defined over the currently selected circuit\n");
902 log("and additional constraints passed as parameters.\n");
903 log("\n");
904 log(" -all\n");
905 log(" show all solutions to the problem (this can grow exponentially, use\n");
906 log(" -max <N> instead to get <N> solutions)\n");
907 log("\n");
908 log(" -max <N>\n");
909 log(" like -all, but limit number of solutions to <N>\n");
910 log("\n");
911 log(" -enable_undef\n");
912 log(" enable modeling of undef value (aka 'x-bits')\n");
913 log(" this option is implied by -set-def, -set-undef et. cetera\n");
914 log("\n");
915 log(" -max_undef\n");
916 log(" maximize the number of undef bits in solutions, giving a better\n");
917 log(" picture of which input bits are actually vital to the solution.\n");
918 log("\n");
919 log(" -set <signal> <value>\n");
920 log(" set the specified signal to the specified value.\n");
921 log("\n");
922 log(" -set-def <signal>\n");
923 log(" add a constraint that all bits of the given signal must be defined\n");
924 log("\n");
925 log(" -set-any-undef <signal>\n");
926 log(" add a constraint that at least one bit of the given signal is undefined\n");
927 log("\n");
928 log(" -set-all-undef <signal>\n");
929 log(" add a constraint that all bits of the given signal are undefined\n");
930 log("\n");
931 log(" -set-def-inputs\n");
932 log(" add -set-def constraints for all module inputs\n");
933 log("\n");
934 log(" -show <signal>\n");
935 log(" show the model for the specified signal. if no -show option is\n");
936 log(" passed then a set of signals to be shown is automatically selected.\n");
937 log("\n");
938 log(" -show-inputs, -show-outputs, -show-ports\n");
939 log(" add all module (input/output) ports to the list of shown signals\n");
940 log("\n");
941 log(" -show-regs, -show-public, -show-all\n");
942 log(" show all registers, show signals with 'public' names, show all signals\n");
943 log("\n");
944 log(" -ignore_div_by_zero\n");
945 log(" ignore all solutions that involve a division by zero\n");
946 log("\n");
947 log(" -ignore_unknown_cells\n");
948 log(" ignore all cells that can not be matched to a SAT model\n");
949 log("\n");
950 log("The following options can be used to set up a sequential problem:\n");
951 log("\n");
952 log(" -seq <N>\n");
953 log(" set up a sequential problem with <N> time steps. The steps will\n");
954 log(" be numbered from 1 to N.\n");
955 log("\n");
956 log(" note: for large <N> it can be significantly faster to use\n");
957 log(" -tempinduct-baseonly -maxsteps <N> instead of -seq <N>.\n");
958 log("\n");
959 log(" -set-at <N> <signal> <value>\n");
960 log(" -unset-at <N> <signal>\n");
961 log(" set or unset the specified signal to the specified value in the\n");
962 log(" given timestep. this has priority over a -set for the same signal.\n");
963 log("\n");
964 log(" -set-assumes\n");
965 log(" set all assumptions provided via $assume cells\n");
966 log("\n");
967 log(" -set-def-at <N> <signal>\n");
968 log(" -set-any-undef-at <N> <signal>\n");
969 log(" -set-all-undef-at <N> <signal>\n");
970 log(" add undef constraints in the given timestep.\n");
971 log("\n");
972 log(" -set-init <signal> <value>\n");
973 log(" set the initial value for the register driving the signal to the value\n");
974 log("\n");
975 log(" -set-init-undef\n");
976 log(" set all initial states (not set using -set-init) to undef\n");
977 log("\n");
978 log(" -set-init-def\n");
979 log(" do not force a value for the initial state but do not allow undef\n");
980 log("\n");
981 log(" -set-init-zero\n");
982 log(" set all initial states (not set using -set-init) to zero\n");
983 log("\n");
984 log(" -dump_vcd <vcd-file-name>\n");
985 log(" dump SAT model (counter example in proof) to VCD file\n");
986 log("\n");
987 log(" -dump_json <json-file-name>\n");
988 log(" dump SAT model (counter example in proof) to a WaveJSON file.\n");
989 log("\n");
990 log(" -dump_cnf <cnf-file-name>\n");
991 log(" dump CNF of SAT problem (in DIMACS format). in temporal induction\n");
992 log(" proofs this is the CNF of the first induction step.\n");
993 log("\n");
994 log("The following additional options can be used to set up a proof. If also -seq\n");
995 log("is passed, a temporal induction proof is performed.\n");
996 log("\n");
997 log(" -tempinduct\n");
998 log(" Perform a temporal induction proof. In a temporal induction proof it is\n");
999 log(" proven that the condition holds forever after the number of time steps\n");
1000 log(" specified using -seq.\n");
1001 log("\n");
1002 log(" -tempinduct-def\n");
1003 log(" Perform a temporal induction proof. Assume an initial state with all\n");
1004 log(" registers set to defined values for the induction step.\n");
1005 log("\n");
1006 log(" -tempinduct-baseonly\n");
1007 log(" Run only the basecase half of temporal induction (requires -maxsteps)\n");
1008 log("\n");
1009 log(" -tempinduct-inductonly\n");
1010 log(" Run only the induction half of temporal induction\n");
1011 log("\n");
1012 log(" -tempinduct-skip <N>\n");
1013 log(" Skip the first <N> steps of the induction proof.\n");
1014 log("\n");
1015 log(" note: this will assume that the base case holds for <N> steps.\n");
1016 log(" this must be proven independently with \"-tempinduct-baseonly\n");
1017 log(" -maxsteps <N>\". Use -initsteps if you just want to set a\n");
1018 log(" minimal induction length.\n");
1019 log("\n");
1020 log(" -prove <signal> <value>\n");
1021 log(" Attempt to proof that <signal> is always <value>.\n");
1022 log("\n");
1023 log(" -prove-x <signal> <value>\n");
1024 log(" Like -prove, but an undef (x) bit in the lhs matches any value on\n");
1025 log(" the right hand side. Useful for equivalence checking.\n");
1026 log("\n");
1027 log(" -prove-asserts\n");
1028 log(" Prove that all asserts in the design hold.\n");
1029 log("\n");
1030 log(" -prove-skip <N>\n");
1031 log(" Do not enforce the prove-condition for the first <N> time steps.\n");
1032 log("\n");
1033 log(" -maxsteps <N>\n");
1034 log(" Set a maximum length for the induction.\n");
1035 log("\n");
1036 log(" -initsteps <N>\n");
1037 log(" Set initial length for the induction.\n");
1038 log(" This will speed up the search of the right induction length\n");
1039 log(" for deep induction proofs.\n");
1040 log("\n");
1041 log(" -stepsize <N>\n");
1042 log(" Increase the size of the induction proof in steps of <N>.\n");
1043 log(" This will speed up the search of the right induction length\n");
1044 log(" for deep induction proofs.\n");
1045 log("\n");
1046 log(" -timeout <N>\n");
1047 log(" Maximum number of seconds a single SAT instance may take.\n");
1048 log("\n");
1049 log(" -verify\n");
1050 log(" Return an error and stop the synthesis script if the proof fails.\n");
1051 log("\n");
1052 log(" -verify-no-timeout\n");
1053 log(" Like -verify but do not return an error for timeouts.\n");
1054 log("\n");
1055 log(" -falsify\n");
1056 log(" Return an error and stop the synthesis script if the proof succeeds.\n");
1057 log("\n");
1058 log(" -falsify-no-timeout\n");
1059 log(" Like -falsify but do not return an error for timeouts.\n");
1060 log("\n");
1061 }
1062 void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
1063 {
1064 std::vector<std::pair<std::string, std::string>> sets, sets_init, prove, prove_x;
1065 std::map<int, std::vector<std::pair<std::string, std::string>>> sets_at;
1066 std::map<int, std::vector<std::string>> unsets_at, sets_def_at, sets_any_undef_at, sets_all_undef_at;
1067 std::vector<std::string> shows, sets_def, sets_any_undef, sets_all_undef;
1068 int loopcount = 0, seq_len = 0, maxsteps = 0, initsteps = 0, timeout = 0, prove_skip = 0;
1069 bool verify = false, fail_on_timeout = false, enable_undef = false, set_def_inputs = false;
1070 bool ignore_div_by_zero = false, set_init_undef = false, set_init_zero = false, max_undef = false;
1071 bool tempinduct = false, prove_asserts = false, show_inputs = false, show_outputs = false;
1072 bool show_regs = false, show_public = false, show_all = false;
1073 bool ignore_unknown_cells = false, falsify = false, tempinduct_def = false, set_init_def = false;
1074 bool tempinduct_baseonly = false, tempinduct_inductonly = false, set_assumes = false;
1075 int tempinduct_skip = 0, stepsize = 1;
1076 std::string vcd_file_name, json_file_name, cnf_file_name;
1077
1078 log_header(design, "Executing SAT pass (solving SAT problems in the circuit).\n");
1079
1080 size_t argidx;
1081 for (argidx = 1; argidx < args.size(); argidx++) {
1082 if (args[argidx] == "-all") {
1083 loopcount = -1;
1084 continue;
1085 }
1086 if (args[argidx] == "-verify") {
1087 fail_on_timeout = true;
1088 verify = true;
1089 continue;
1090 }
1091 if (args[argidx] == "-verify-no-timeout") {
1092 verify = true;
1093 continue;
1094 }
1095 if (args[argidx] == "-falsify") {
1096 fail_on_timeout = true;
1097 falsify = true;
1098 continue;
1099 }
1100 if (args[argidx] == "-falsify-no-timeout") {
1101 falsify = true;
1102 continue;
1103 }
1104 if (args[argidx] == "-timeout" && argidx+1 < args.size()) {
1105 timeout = atoi(args[++argidx].c_str());
1106 continue;
1107 }
1108 if (args[argidx] == "-max" && argidx+1 < args.size()) {
1109 loopcount = atoi(args[++argidx].c_str());
1110 continue;
1111 }
1112 if (args[argidx] == "-maxsteps" && argidx+1 < args.size()) {
1113 maxsteps = atoi(args[++argidx].c_str());
1114 continue;
1115 }
1116 if (args[argidx] == "-initsteps" && argidx+1 < args.size()) {
1117 initsteps = atoi(args[++argidx].c_str());
1118 continue;
1119 }
1120 if (args[argidx] == "-stepsize" && argidx+1 < args.size()) {
1121 stepsize = max(1, atoi(args[++argidx].c_str()));
1122 continue;
1123 }
1124 if (args[argidx] == "-ignore_div_by_zero") {
1125 ignore_div_by_zero = true;
1126 continue;
1127 }
1128 if (args[argidx] == "-enable_undef") {
1129 enable_undef = true;
1130 continue;
1131 }
1132 if (args[argidx] == "-max_undef") {
1133 enable_undef = true;
1134 max_undef = true;
1135 continue;
1136 }
1137 if (args[argidx] == "-set-def-inputs") {
1138 enable_undef = true;
1139 set_def_inputs = true;
1140 continue;
1141 }
1142 if (args[argidx] == "-set" && argidx+2 < args.size()) {
1143 std::string lhs = args[++argidx];
1144 std::string rhs = args[++argidx];
1145 sets.push_back(std::pair<std::string, std::string>(lhs, rhs));
1146 continue;
1147 }
1148 if (args[argidx] == "-set-def" && argidx+1 < args.size()) {
1149 sets_def.push_back(args[++argidx]);
1150 enable_undef = true;
1151 continue;
1152 }
1153 if (args[argidx] == "-set-any-undef" && argidx+1 < args.size()) {
1154 sets_any_undef.push_back(args[++argidx]);
1155 enable_undef = true;
1156 continue;
1157 }
1158 if (args[argidx] == "-set-all-undef" && argidx+1 < args.size()) {
1159 sets_all_undef.push_back(args[++argidx]);
1160 enable_undef = true;
1161 continue;
1162 }
1163 if (args[argidx] == "-set-assumes") {
1164 set_assumes = true;
1165 continue;
1166 }
1167 if (args[argidx] == "-tempinduct") {
1168 tempinduct = true;
1169 continue;
1170 }
1171 if (args[argidx] == "-tempinduct-def") {
1172 tempinduct = true;
1173 tempinduct_def = true;
1174 enable_undef = true;
1175 continue;
1176 }
1177 if (args[argidx] == "-tempinduct-baseonly") {
1178 tempinduct = true;
1179 tempinduct_baseonly = true;
1180 continue;
1181 }
1182 if (args[argidx] == "-tempinduct-inductonly") {
1183 tempinduct = true;
1184 tempinduct_inductonly = true;
1185 continue;
1186 }
1187 if (args[argidx] == "-tempinduct-skip" && argidx+1 < args.size()) {
1188 tempinduct_skip = atoi(args[++argidx].c_str());
1189 continue;
1190 }
1191 if (args[argidx] == "-prove" && argidx+2 < args.size()) {
1192 std::string lhs = args[++argidx];
1193 std::string rhs = args[++argidx];
1194 prove.push_back(std::pair<std::string, std::string>(lhs, rhs));
1195 continue;
1196 }
1197 if (args[argidx] == "-prove-x" && argidx+2 < args.size()) {
1198 std::string lhs = args[++argidx];
1199 std::string rhs = args[++argidx];
1200 prove_x.push_back(std::pair<std::string, std::string>(lhs, rhs));
1201 enable_undef = true;
1202 continue;
1203 }
1204 if (args[argidx] == "-prove-asserts") {
1205 prove_asserts = true;
1206 continue;
1207 }
1208 if (args[argidx] == "-prove-skip" && argidx+1 < args.size()) {
1209 prove_skip = atoi(args[++argidx].c_str());
1210 continue;
1211 }
1212 if (args[argidx] == "-seq" && argidx+1 < args.size()) {
1213 seq_len = atoi(args[++argidx].c_str());
1214 continue;
1215 }
1216 if (args[argidx] == "-set-at" && argidx+3 < args.size()) {
1217 int timestep = atoi(args[++argidx].c_str());
1218 std::string lhs = args[++argidx];
1219 std::string rhs = args[++argidx];
1220 sets_at[timestep].push_back(std::pair<std::string, std::string>(lhs, rhs));
1221 continue;
1222 }
1223 if (args[argidx] == "-unset-at" && argidx+2 < args.size()) {
1224 int timestep = atoi(args[++argidx].c_str());
1225 unsets_at[timestep].push_back(args[++argidx]);
1226 continue;
1227 }
1228 if (args[argidx] == "-set-def-at" && argidx+2 < args.size()) {
1229 int timestep = atoi(args[++argidx].c_str());
1230 sets_def_at[timestep].push_back(args[++argidx]);
1231 enable_undef = true;
1232 continue;
1233 }
1234 if (args[argidx] == "-set-any-undef-at" && argidx+2 < args.size()) {
1235 int timestep = atoi(args[++argidx].c_str());
1236 sets_any_undef_at[timestep].push_back(args[++argidx]);
1237 enable_undef = true;
1238 continue;
1239 }
1240 if (args[argidx] == "-set-all-undef-at" && argidx+2 < args.size()) {
1241 int timestep = atoi(args[++argidx].c_str());
1242 sets_all_undef_at[timestep].push_back(args[++argidx]);
1243 enable_undef = true;
1244 continue;
1245 }
1246 if (args[argidx] == "-set-init" && argidx+2 < args.size()) {
1247 std::string lhs = args[++argidx];
1248 std::string rhs = args[++argidx];
1249 sets_init.push_back(std::pair<std::string, std::string>(lhs, rhs));
1250 continue;
1251 }
1252 if (args[argidx] == "-set-init-undef") {
1253 set_init_undef = true;
1254 enable_undef = true;
1255 continue;
1256 }
1257 if (args[argidx] == "-set-init-def") {
1258 set_init_def = true;
1259 continue;
1260 }
1261 if (args[argidx] == "-set-init-zero") {
1262 set_init_zero = true;
1263 continue;
1264 }
1265 if (args[argidx] == "-show" && argidx+1 < args.size()) {
1266 shows.push_back(args[++argidx]);
1267 continue;
1268 }
1269 if (args[argidx] == "-show-inputs") {
1270 show_inputs = true;
1271 continue;
1272 }
1273 if (args[argidx] == "-show-outputs") {
1274 show_outputs = true;
1275 continue;
1276 }
1277 if (args[argidx] == "-show-ports") {
1278 show_inputs = true;
1279 show_outputs = true;
1280 continue;
1281 }
1282 if (args[argidx] == "-show-regs") {
1283 show_regs = true;
1284 continue;
1285 }
1286 if (args[argidx] == "-show-public") {
1287 show_public = true;
1288 continue;
1289 }
1290 if (args[argidx] == "-show-all") {
1291 show_all = true;
1292 continue;
1293 }
1294 if (args[argidx] == "-ignore_unknown_cells") {
1295 ignore_unknown_cells = true;
1296 continue;
1297 }
1298 if (args[argidx] == "-dump_vcd" && argidx+1 < args.size()) {
1299 vcd_file_name = args[++argidx];
1300 continue;
1301 }
1302 if (args[argidx] == "-dump_json" && argidx+1 < args.size()) {
1303 json_file_name = args[++argidx];
1304 continue;
1305 }
1306 if (args[argidx] == "-dump_cnf" && argidx+1 < args.size()) {
1307 cnf_file_name = args[++argidx];
1308 continue;
1309 }
1310 break;
1311 }
1312 extra_args(args, argidx, design);
1313
1314 RTLIL::Module *module = NULL;
1315 for (auto mod : design->selected_modules()) {
1316 if (module)
1317 log_cmd_error("Only one module must be selected for the SAT pass! (selected: %s and %s)\n", log_id(module), log_id(mod));
1318 module = mod;
1319 }
1320 if (module == NULL)
1321 log_cmd_error("Can't perform SAT on an empty selection!\n");
1322
1323 if (!prove.size() && !prove_x.size() && !prove_asserts && tempinduct)
1324 log_cmd_error("Got -tempinduct but nothing to prove!\n");
1325
1326 if (prove_skip && tempinduct)
1327 log_cmd_error("Options -prove-skip and -tempinduct don't work with each other. Use -seq instead of -prove-skip.\n");
1328
1329 if (prove_skip >= seq_len && prove_skip > 0)
1330 log_cmd_error("The value of -prove-skip must be smaller than the one of -seq.\n");
1331
1332 if (set_init_undef + set_init_zero + set_init_def > 1)
1333 log_cmd_error("The options -set-init-undef, -set-init-def, and -set-init-zero are exclusive!\n");
1334
1335 if (set_def_inputs) {
1336 for (auto &it : module->wires_)
1337 if (it.second->port_input)
1338 sets_def.push_back(it.second->name.str());
1339 }
1340
1341 if (show_inputs) {
1342 for (auto &it : module->wires_)
1343 if (it.second->port_input)
1344 shows.push_back(it.second->name.str());
1345 }
1346
1347 if (show_outputs) {
1348 for (auto &it : module->wires_)
1349 if (it.second->port_output)
1350 shows.push_back(it.second->name.str());
1351 }
1352
1353 if (show_regs) {
1354 pool<Wire*> reg_wires;
1355 for (auto cell : module->cells()) {
1356 if (cell->type == "$dff" || cell->type.begins_with("$_DFF_"))
1357 for (auto bit : cell->getPort("\\Q"))
1358 if (bit.wire)
1359 reg_wires.insert(bit.wire);
1360 }
1361 for (auto wire : reg_wires)
1362 shows.push_back(wire->name.str());
1363 }
1364
1365 if (show_public) {
1366 for (auto wire : module->wires())
1367 if (wire->name[0] == '\\')
1368 shows.push_back(wire->name.str());
1369 }
1370
1371 if (show_all) {
1372 for (auto wire : module->wires())
1373 shows.push_back(wire->name.str());
1374 }
1375
1376 if (tempinduct)
1377 {
1378 if (loopcount > 0 || max_undef)
1379 log_cmd_error("The options -max, -all, and -max_undef are not supported for temporal induction proofs!\n");
1380
1381 SatHelper basecase(design, module, enable_undef);
1382 SatHelper inductstep(design, module, enable_undef);
1383
1384 basecase.sets = sets;
1385 basecase.set_assumes = set_assumes;
1386 basecase.prove = prove;
1387 basecase.prove_x = prove_x;
1388 basecase.prove_asserts = prove_asserts;
1389 basecase.sets_at = sets_at;
1390 basecase.unsets_at = unsets_at;
1391 basecase.shows = shows;
1392 basecase.timeout = timeout;
1393 basecase.sets_def = sets_def;
1394 basecase.sets_any_undef = sets_any_undef;
1395 basecase.sets_all_undef = sets_all_undef;
1396 basecase.sets_def_at = sets_def_at;
1397 basecase.sets_any_undef_at = sets_any_undef_at;
1398 basecase.sets_all_undef_at = sets_all_undef_at;
1399 basecase.sets_init = sets_init;
1400 basecase.set_init_def = set_init_def;
1401 basecase.set_init_undef = set_init_undef;
1402 basecase.set_init_zero = set_init_zero;
1403 basecase.satgen.ignore_div_by_zero = ignore_div_by_zero;
1404 basecase.ignore_unknown_cells = ignore_unknown_cells;
1405
1406 for (int timestep = 1; timestep <= seq_len; timestep++)
1407 if (!tempinduct_inductonly)
1408 basecase.setup(timestep, timestep == 1);
1409
1410 inductstep.sets = sets;
1411 inductstep.set_assumes = set_assumes;
1412 inductstep.prove = prove;
1413 inductstep.prove_x = prove_x;
1414 inductstep.prove_asserts = prove_asserts;
1415 inductstep.shows = shows;
1416 inductstep.timeout = timeout;
1417 inductstep.sets_def = sets_def;
1418 inductstep.sets_any_undef = sets_any_undef;
1419 inductstep.sets_all_undef = sets_all_undef;
1420 inductstep.satgen.ignore_div_by_zero = ignore_div_by_zero;
1421 inductstep.ignore_unknown_cells = ignore_unknown_cells;
1422
1423 if (!tempinduct_baseonly) {
1424 inductstep.setup(1);
1425 inductstep.ez->assume(inductstep.setup_proof(1));
1426 }
1427
1428 if (tempinduct_def) {
1429 std::vector<int> undef_state = inductstep.satgen.importUndefSigSpec(inductstep.satgen.initial_state.export_all(), 1);
1430 inductstep.ez->assume(inductstep.ez->NOT(inductstep.ez->expression(ezSAT::OpOr, undef_state)));
1431 }
1432
1433 for (int inductlen = 1; inductlen <= maxsteps || maxsteps == 0; inductlen++)
1434 {
1435 log("\n** Trying induction with length %d **\n", inductlen);
1436
1437 // phase 1: proving base case
1438
1439 if (!tempinduct_inductonly)
1440 {
1441 basecase.setup(seq_len + inductlen, seq_len + inductlen == 1);
1442 int property = basecase.setup_proof(seq_len + inductlen);
1443 basecase.generate_model();
1444
1445 if (inductlen > 1)
1446 basecase.force_unique_state(seq_len + 1, seq_len + inductlen);
1447
1448 if (tempinduct_skip < inductlen)
1449 {
1450 log("\n[base case %d] Solving problem with %d variables and %d clauses..\n",
1451 inductlen, basecase.ez->numCnfVariables(), basecase.ez->numCnfClauses());
1452 log_flush();
1453
1454 if (basecase.solve(basecase.ez->NOT(property))) {
1455 log("SAT temporal induction proof finished - model found for base case: FAIL!\n");
1456 print_proof_failed();
1457 basecase.print_model();
1458 if(!vcd_file_name.empty())
1459 basecase.dump_model_to_vcd(vcd_file_name);
1460 if(!json_file_name.empty())
1461 basecase.dump_model_to_json(json_file_name);
1462 goto tip_failed;
1463 }
1464
1465 if (basecase.gotTimeout)
1466 goto timeout;
1467
1468 log("Base case for induction length %d proven.\n", inductlen);
1469 }
1470 else
1471 {
1472 log("\n[base case %d] Skipping prove for this step (-tempinduct-skip %d).",
1473 inductlen, tempinduct_skip);
1474 log("\n[base case %d] Problem size so far: %d variables and %d clauses.\n",
1475 inductlen, basecase.ez->numCnfVariables(), basecase.ez->numCnfClauses());
1476 }
1477 basecase.ez->assume(property);
1478 }
1479
1480 // phase 2: proving induction step
1481
1482 if (!tempinduct_baseonly)
1483 {
1484 inductstep.setup(inductlen + 1);
1485 int property = inductstep.setup_proof(inductlen + 1);
1486 inductstep.generate_model();
1487
1488 if (inductlen > 1)
1489 inductstep.force_unique_state(1, inductlen + 1);
1490
1491 if (inductlen <= tempinduct_skip || inductlen <= initsteps || inductlen % stepsize != 0)
1492 {
1493 if (inductlen < tempinduct_skip)
1494 log("\n[induction step %d] Skipping prove for this step (-tempinduct-skip %d).",
1495 inductlen, tempinduct_skip);
1496 if (inductlen < initsteps)
1497 log("\n[induction step %d] Skipping prove for this step (-initsteps %d).",
1498 inductlen, tempinduct_skip);
1499 if (inductlen % stepsize != 0)
1500 log("\n[induction step %d] Skipping prove for this step (-stepsize %d).",
1501 inductlen, stepsize);
1502 log("\n[induction step %d] Problem size so far: %d variables and %d clauses.\n",
1503 inductlen, inductstep.ez->numCnfVariables(), inductstep.ez->numCnfClauses());
1504 inductstep.ez->assume(property);
1505 }
1506 else
1507 {
1508 if (!cnf_file_name.empty())
1509 {
1510 rewrite_filename(cnf_file_name);
1511 FILE *f = fopen(cnf_file_name.c_str(), "w");
1512 if (!f)
1513 log_cmd_error("Can't open output file `%s' for writing: %s\n", cnf_file_name.c_str(), strerror(errno));
1514
1515 log("Dumping CNF to file `%s'.\n", cnf_file_name.c_str());
1516 cnf_file_name.clear();
1517
1518 inductstep.ez->printDIMACS(f, false);
1519 fclose(f);
1520 }
1521
1522 log("\n[induction step %d] Solving problem with %d variables and %d clauses..\n",
1523 inductlen, inductstep.ez->numCnfVariables(), inductstep.ez->numCnfClauses());
1524 log_flush();
1525
1526 if (!inductstep.solve(inductstep.ez->NOT(property))) {
1527 if (inductstep.gotTimeout)
1528 goto timeout;
1529 log("Induction step proven: SUCCESS!\n");
1530 print_qed();
1531 goto tip_success;
1532 }
1533
1534 log("Induction step failed. Incrementing induction length.\n");
1535 inductstep.ez->assume(property);
1536 inductstep.print_model();
1537 }
1538 }
1539 }
1540
1541 if (tempinduct_baseonly) {
1542 log("\nReached maximum number of time steps -> proved base case for %d steps: SUCCESS!\n", maxsteps);
1543 goto tip_success;
1544 }
1545
1546 log("\nReached maximum number of time steps -> proof failed.\n");
1547 if(!vcd_file_name.empty())
1548 inductstep.dump_model_to_vcd(vcd_file_name);
1549 if(!json_file_name.empty())
1550 inductstep.dump_model_to_json(json_file_name);
1551 print_proof_failed();
1552
1553 tip_failed:
1554 if (verify) {
1555 log("\n");
1556 log_error("Called with -verify and proof did fail!\n");
1557 }
1558
1559 if (0)
1560 tip_success:
1561 if (falsify) {
1562 log("\n");
1563 log_error("Called with -falsify and proof did succeed!\n");
1564 }
1565 }
1566 else
1567 {
1568 if (maxsteps > 0)
1569 log_cmd_error("The options -maxsteps is only supported for temporal induction proofs!\n");
1570
1571 SatHelper sathelper(design, module, enable_undef);
1572
1573 sathelper.sets = sets;
1574 sathelper.set_assumes = set_assumes;
1575 sathelper.prove = prove;
1576 sathelper.prove_x = prove_x;
1577 sathelper.prove_asserts = prove_asserts;
1578 sathelper.sets_at = sets_at;
1579 sathelper.unsets_at = unsets_at;
1580 sathelper.shows = shows;
1581 sathelper.timeout = timeout;
1582 sathelper.sets_def = sets_def;
1583 sathelper.sets_any_undef = sets_any_undef;
1584 sathelper.sets_all_undef = sets_all_undef;
1585 sathelper.sets_def_at = sets_def_at;
1586 sathelper.sets_any_undef_at = sets_any_undef_at;
1587 sathelper.sets_all_undef_at = sets_all_undef_at;
1588 sathelper.sets_init = sets_init;
1589 sathelper.set_init_def = set_init_def;
1590 sathelper.set_init_undef = set_init_undef;
1591 sathelper.set_init_zero = set_init_zero;
1592 sathelper.satgen.ignore_div_by_zero = ignore_div_by_zero;
1593 sathelper.ignore_unknown_cells = ignore_unknown_cells;
1594
1595 if (seq_len == 0) {
1596 sathelper.setup();
1597 if (sathelper.prove.size() || sathelper.prove_x.size() || sathelper.prove_asserts)
1598 sathelper.ez->assume(sathelper.ez->NOT(sathelper.setup_proof()));
1599 } else {
1600 std::vector<int> prove_bits;
1601 for (int timestep = 1; timestep <= seq_len; timestep++) {
1602 sathelper.setup(timestep, timestep == 1);
1603 if (sathelper.prove.size() || sathelper.prove_x.size() || sathelper.prove_asserts)
1604 if (timestep > prove_skip)
1605 prove_bits.push_back(sathelper.setup_proof(timestep));
1606 }
1607 if (sathelper.prove.size() || sathelper.prove_x.size() || sathelper.prove_asserts)
1608 sathelper.ez->assume(sathelper.ez->NOT(sathelper.ez->expression(ezSAT::OpAnd, prove_bits)));
1609 }
1610 sathelper.generate_model();
1611
1612 if (!cnf_file_name.empty())
1613 {
1614 rewrite_filename(cnf_file_name);
1615 FILE *f = fopen(cnf_file_name.c_str(), "w");
1616 if (!f)
1617 log_cmd_error("Can't open output file `%s' for writing: %s\n", cnf_file_name.c_str(), strerror(errno));
1618
1619 log("Dumping CNF to file `%s'.\n", cnf_file_name.c_str());
1620 cnf_file_name.clear();
1621
1622 sathelper.ez->printDIMACS(f, false);
1623 fclose(f);
1624 }
1625
1626 int rerun_counter = 0;
1627
1628 rerun_solver:
1629 log("\nSolving problem with %d variables and %d clauses..\n",
1630 sathelper.ez->numCnfVariables(), sathelper.ez->numCnfClauses());
1631 log_flush();
1632
1633 if (sathelper.solve())
1634 {
1635 if (max_undef) {
1636 log("SAT model found. maximizing number of undefs.\n");
1637 sathelper.maximize_undefs();
1638 }
1639
1640 if (!prove.size() && !prove_x.size() && !prove_asserts) {
1641 log("SAT solving finished - model found:\n");
1642 } else {
1643 log("SAT proof finished - model found: FAIL!\n");
1644 print_proof_failed();
1645 }
1646
1647 sathelper.print_model();
1648
1649 if(!vcd_file_name.empty())
1650 sathelper.dump_model_to_vcd(vcd_file_name);
1651 if(!json_file_name.empty())
1652 sathelper.dump_model_to_json(json_file_name);
1653
1654 if (loopcount != 0) {
1655 loopcount--, rerun_counter++;
1656 sathelper.invalidate_model(max_undef);
1657 goto rerun_solver;
1658 }
1659
1660 if (!prove.size() && !prove_x.size() && !prove_asserts) {
1661 if (falsify) {
1662 log("\n");
1663 log_error("Called with -falsify and found a model!\n");
1664 }
1665 } else {
1666 if (verify) {
1667 log("\n");
1668 log_error("Called with -verify and proof did fail!\n");
1669 }
1670 }
1671 }
1672 else
1673 {
1674 if (sathelper.gotTimeout)
1675 goto timeout;
1676 if (rerun_counter)
1677 log("SAT solving finished - no more models found (after %d distinct solutions).\n", rerun_counter);
1678 else if (!prove.size() && !prove_x.size() && !prove_asserts) {
1679 log("SAT solving finished - no model found.\n");
1680 if (verify) {
1681 log("\n");
1682 log_error("Called with -verify and found no model!\n");
1683 }
1684 } else {
1685 log("SAT proof finished - no model found: SUCCESS!\n");
1686 print_qed();
1687 if (falsify) {
1688 log("\n");
1689 log_error("Called with -falsify and proof did succeed!\n");
1690 }
1691 }
1692 }
1693
1694 if (!prove.size() && !prove_x.size() && !prove_asserts) {
1695 if (falsify && rerun_counter) {
1696 log("\n");
1697 log_error("Called with -falsify and found a model!\n");
1698 }
1699 } else {
1700 if (verify && rerun_counter) {
1701 log("\n");
1702 log_error("Called with -verify and proof did fail!\n");
1703 }
1704 }
1705 }
1706
1707 if (0) {
1708 timeout:
1709 log("Interrupted SAT solver: TIMEOUT!\n");
1710 print_timeout();
1711 if (fail_on_timeout)
1712 log_error("Called with -verify and proof did time out!\n");
1713 }
1714 }
1715 } SatPass;
1716
1717 PRIVATE_NAMESPACE_END