Symmetry detection module (#1749)
[cvc5.git] / src / smt / smt_engine.cpp
1 /********************* */
2 /*! \file smt_engine.cpp
3 ** \verbatim
4 ** Top contributors (to current version):
5 ** Morgan Deters, Andrew Reynolds, Tim King
6 ** This file is part of the CVC4 project.
7 ** Copyright (c) 2009-2018 by the authors listed in the file AUTHORS
8 ** in the top-level source directory) and their institutional affiliations.
9 ** All rights reserved. See the file COPYING in the top-level source
10 ** directory for licensing information.\endverbatim
11 **
12 ** \brief The main entry point into the CVC4 library's SMT interface
13 **
14 ** The main entry point into the CVC4 library's SMT interface.
15 **/
16
17 #include "smt/smt_engine.h"
18
19 #include <algorithm>
20 #include <cctype>
21 #include <iterator>
22 #include <memory>
23 #include <sstream>
24 #include <stack>
25 #include <string>
26 #include <unordered_map>
27 #include <unordered_set>
28 #include <utility>
29 #include <vector>
30
31 #include "base/configuration.h"
32 #include "base/configuration_private.h"
33 #include "base/exception.h"
34 #include "base/listener.h"
35 #include "base/modal_exception.h"
36 #include "base/output.h"
37 #include "context/cdhashmap.h"
38 #include "context/cdhashset.h"
39 #include "context/cdlist.h"
40 #include "context/context.h"
41 #include "decision/decision_engine.h"
42 #include "expr/attribute.h"
43 #include "expr/expr.h"
44 #include "expr/kind.h"
45 #include "expr/metakind.h"
46 #include "expr/node.h"
47 #include "expr/node_builder.h"
48 #include "expr/node_self_iterator.h"
49 #include "options/arith_options.h"
50 #include "options/arrays_options.h"
51 #include "options/base_options.h"
52 #include "options/booleans_options.h"
53 #include "options/bv_options.h"
54 #include "options/datatypes_options.h"
55 #include "options/decision_mode.h"
56 #include "options/decision_options.h"
57 #include "options/language.h"
58 #include "options/main_options.h"
59 #include "options/open_ostream.h"
60 #include "options/option_exception.h"
61 #include "options/printer_options.h"
62 #include "options/proof_options.h"
63 #include "options/prop_options.h"
64 #include "options/quantifiers_options.h"
65 #include "options/sep_options.h"
66 #include "options/set_language.h"
67 #include "options/smt_options.h"
68 #include "options/strings_options.h"
69 #include "options/theory_options.h"
70 #include "options/uf_options.h"
71 #include "preprocessing/passes/bv_gauss.h"
72 #include "preprocessing/passes/int_to_bv.h"
73 #include "preprocessing/passes/pseudo_boolean_processor.h"
74 #include "preprocessing/passes/symmetry_detect.h"
75 #include "preprocessing/preprocessing_pass.h"
76 #include "preprocessing/preprocessing_pass_context.h"
77 #include "preprocessing/preprocessing_pass_registry.h"
78 #include "printer/printer.h"
79 #include "proof/proof.h"
80 #include "proof/proof_manager.h"
81 #include "proof/theory_proof.h"
82 #include "proof/unsat_core.h"
83 #include "prop/prop_engine.h"
84 #include "smt/command.h"
85 #include "smt/command_list.h"
86 #include "smt/logic_request.h"
87 #include "smt/managed_ostreams.h"
88 #include "smt/smt_engine_scope.h"
89 #include "smt/term_formula_removal.h"
90 #include "smt/update_ostream.h"
91 #include "smt_util/boolean_simplification.h"
92 #include "smt_util/nary_builder.h"
93 #include "smt_util/node_visitor.h"
94 #include "theory/arith/arith_msum.h"
95 #include "theory/booleans/circuit_propagator.h"
96 #include "theory/bv/bvintropow2.h"
97 #include "theory/bv/theory_bv_rewriter.h"
98 #include "theory/logic_info.h"
99 #include "theory/quantifiers/fun_def_process.h"
100 #include "theory/quantifiers/global_negate.h"
101 #include "theory/quantifiers/macros.h"
102 #include "theory/quantifiers/quantifiers_rewriter.h"
103 #include "theory/quantifiers/single_inv_partition.h"
104 #include "theory/quantifiers/sygus/ce_guided_instantiation.h"
105 #include "theory/quantifiers/sygus_inference.h"
106 #include "theory/quantifiers/term_util.h"
107 #include "theory/sort_inference.h"
108 #include "theory/strings/theory_strings.h"
109 #include "theory/substitutions.h"
110 #include "theory/theory_engine.h"
111 #include "theory/theory_model.h"
112 #include "theory/theory_traits.h"
113 #include "util/hash.h"
114 #include "util/proof.h"
115 #include "util/random.h"
116 #include "util/resource_manager.h"
117
118 using namespace std;
119 using namespace CVC4;
120 using namespace CVC4::smt;
121 using namespace CVC4::preprocessing;
122 using namespace CVC4::preprocessing::passes;
123 using namespace CVC4::prop;
124 using namespace CVC4::context;
125 using namespace CVC4::theory;
126
127 namespace CVC4 {
128 namespace smt {
129
130 struct DeleteCommandFunction : public std::unary_function<const Command*, void>
131 {
132 void operator()(const Command* command) { delete command; }
133 };
134
135 void DeleteAndClearCommandVector(std::vector<Command*>& commands) {
136 std::for_each(commands.begin(), commands.end(), DeleteCommandFunction());
137 commands.clear();
138 }
139
140 /** Useful for counting the number of recursive calls. */
141 class ScopeCounter {
142 private:
143 unsigned& d_depth;
144 public:
145 ScopeCounter(unsigned& d) : d_depth(d) {
146 ++d_depth;
147 }
148 ~ScopeCounter(){
149 --d_depth;
150 }
151 };
152
153 /**
154 * Representation of a defined function. We keep these around in
155 * SmtEngine to permit expanding definitions late (and lazily), to
156 * support getValue() over defined functions, to support user output
157 * in terms of defined functions, etc.
158 */
159 class DefinedFunction {
160 Node d_func;
161 vector<Node> d_formals;
162 Node d_formula;
163 public:
164 DefinedFunction() {}
165 DefinedFunction(Node func, vector<Node> formals, Node formula) :
166 d_func(func),
167 d_formals(formals),
168 d_formula(formula) {
169 }
170 Node getFunction() const { return d_func; }
171 vector<Node> getFormals() const { return d_formals; }
172 Node getFormula() const { return d_formula; }
173 };/* class DefinedFunction */
174
175 struct SmtEngineStatistics {
176 /** time spent in gaussian elimination */
177 TimerStat d_gaussElimTime;
178 /** time spent in definition-expansion */
179 TimerStat d_definitionExpansionTime;
180 /** time spent in non-clausal simplification */
181 TimerStat d_nonclausalSimplificationTime;
182 /** time spent in miplib pass */
183 TimerStat d_miplibPassTime;
184 /** number of assertions removed by miplib pass */
185 IntStat d_numMiplibAssertionsRemoved;
186 /** number of constant propagations found during nonclausal simp */
187 IntStat d_numConstantProps;
188 /** time spent in static learning */
189 TimerStat d_staticLearningTime;
190 /** time spent in simplifying ITEs */
191 TimerStat d_simpITETime;
192 /** time spent in simplifying ITEs */
193 TimerStat d_unconstrainedSimpTime;
194 /** time spent removing ITEs */
195 TimerStat d_iteRemovalTime;
196 /** time spent in theory preprocessing */
197 TimerStat d_theoryPreprocessTime;
198 /** time spent in theory preprocessing */
199 TimerStat d_rewriteApplyToConstTime;
200 /** time spent converting to CNF */
201 TimerStat d_cnfConversionTime;
202 /** Num of assertions before ite removal */
203 IntStat d_numAssertionsPre;
204 /** Num of assertions after ite removal */
205 IntStat d_numAssertionsPost;
206 /** time spent in checkModel() */
207 TimerStat d_checkModelTime;
208 /** time spent in checkProof() */
209 TimerStat d_checkProofTime;
210 /** time spent in checkUnsatCore() */
211 TimerStat d_checkUnsatCoreTime;
212 /** time spent in PropEngine::checkSat() */
213 TimerStat d_solveTime;
214 /** time spent in pushing/popping */
215 TimerStat d_pushPopTime;
216 /** time spent in processAssertions() */
217 TimerStat d_processAssertionsTime;
218
219 /** Has something simplified to false? */
220 IntStat d_simplifiedToFalse;
221 /** Number of resource units spent. */
222 ReferenceStat<uint64_t> d_resourceUnitsUsed;
223
224 SmtEngineStatistics() :
225 d_gaussElimTime("smt::SmtEngine::gaussElimTime"),
226 d_definitionExpansionTime("smt::SmtEngine::definitionExpansionTime"),
227 d_nonclausalSimplificationTime("smt::SmtEngine::nonclausalSimplificationTime"),
228 d_miplibPassTime("smt::SmtEngine::miplibPassTime"),
229 d_numMiplibAssertionsRemoved("smt::SmtEngine::numMiplibAssertionsRemoved", 0),
230 d_numConstantProps("smt::SmtEngine::numConstantProps", 0),
231 d_staticLearningTime("smt::SmtEngine::staticLearningTime"),
232 d_simpITETime("smt::SmtEngine::simpITETime"),
233 d_unconstrainedSimpTime("smt::SmtEngine::unconstrainedSimpTime"),
234 d_iteRemovalTime("smt::SmtEngine::iteRemovalTime"),
235 d_theoryPreprocessTime("smt::SmtEngine::theoryPreprocessTime"),
236 d_rewriteApplyToConstTime("smt::SmtEngine::rewriteApplyToConstTime"),
237 d_cnfConversionTime("smt::SmtEngine::cnfConversionTime"),
238 d_numAssertionsPre("smt::SmtEngine::numAssertionsPreITERemoval", 0),
239 d_numAssertionsPost("smt::SmtEngine::numAssertionsPostITERemoval", 0),
240 d_checkModelTime("smt::SmtEngine::checkModelTime"),
241 d_checkProofTime("smt::SmtEngine::checkProofTime"),
242 d_checkUnsatCoreTime("smt::SmtEngine::checkUnsatCoreTime"),
243 d_solveTime("smt::SmtEngine::solveTime"),
244 d_pushPopTime("smt::SmtEngine::pushPopTime"),
245 d_processAssertionsTime("smt::SmtEngine::processAssertionsTime"),
246 d_simplifiedToFalse("smt::SmtEngine::simplifiedToFalse", 0),
247 d_resourceUnitsUsed("smt::SmtEngine::resourceUnitsUsed")
248 {
249
250 smtStatisticsRegistry()->registerStat(&d_gaussElimTime);
251 smtStatisticsRegistry()->registerStat(&d_definitionExpansionTime);
252 smtStatisticsRegistry()->registerStat(&d_nonclausalSimplificationTime);
253 smtStatisticsRegistry()->registerStat(&d_miplibPassTime);
254 smtStatisticsRegistry()->registerStat(&d_numMiplibAssertionsRemoved);
255 smtStatisticsRegistry()->registerStat(&d_numConstantProps);
256 smtStatisticsRegistry()->registerStat(&d_staticLearningTime);
257 smtStatisticsRegistry()->registerStat(&d_simpITETime);
258 smtStatisticsRegistry()->registerStat(&d_unconstrainedSimpTime);
259 smtStatisticsRegistry()->registerStat(&d_iteRemovalTime);
260 smtStatisticsRegistry()->registerStat(&d_theoryPreprocessTime);
261 smtStatisticsRegistry()->registerStat(&d_rewriteApplyToConstTime);
262 smtStatisticsRegistry()->registerStat(&d_cnfConversionTime);
263 smtStatisticsRegistry()->registerStat(&d_numAssertionsPre);
264 smtStatisticsRegistry()->registerStat(&d_numAssertionsPost);
265 smtStatisticsRegistry()->registerStat(&d_checkModelTime);
266 smtStatisticsRegistry()->registerStat(&d_checkProofTime);
267 smtStatisticsRegistry()->registerStat(&d_checkUnsatCoreTime);
268 smtStatisticsRegistry()->registerStat(&d_solveTime);
269 smtStatisticsRegistry()->registerStat(&d_pushPopTime);
270 smtStatisticsRegistry()->registerStat(&d_processAssertionsTime);
271 smtStatisticsRegistry()->registerStat(&d_simplifiedToFalse);
272 smtStatisticsRegistry()->registerStat(&d_resourceUnitsUsed);
273 }
274
275 ~SmtEngineStatistics() {
276 smtStatisticsRegistry()->unregisterStat(&d_gaussElimTime);
277 smtStatisticsRegistry()->unregisterStat(&d_definitionExpansionTime);
278 smtStatisticsRegistry()->unregisterStat(&d_nonclausalSimplificationTime);
279 smtStatisticsRegistry()->unregisterStat(&d_miplibPassTime);
280 smtStatisticsRegistry()->unregisterStat(&d_numMiplibAssertionsRemoved);
281 smtStatisticsRegistry()->unregisterStat(&d_numConstantProps);
282 smtStatisticsRegistry()->unregisterStat(&d_staticLearningTime);
283 smtStatisticsRegistry()->unregisterStat(&d_simpITETime);
284 smtStatisticsRegistry()->unregisterStat(&d_unconstrainedSimpTime);
285 smtStatisticsRegistry()->unregisterStat(&d_iteRemovalTime);
286 smtStatisticsRegistry()->unregisterStat(&d_theoryPreprocessTime);
287 smtStatisticsRegistry()->unregisterStat(&d_rewriteApplyToConstTime);
288 smtStatisticsRegistry()->unregisterStat(&d_cnfConversionTime);
289 smtStatisticsRegistry()->unregisterStat(&d_numAssertionsPre);
290 smtStatisticsRegistry()->unregisterStat(&d_numAssertionsPost);
291 smtStatisticsRegistry()->unregisterStat(&d_checkModelTime);
292 smtStatisticsRegistry()->unregisterStat(&d_checkProofTime);
293 smtStatisticsRegistry()->unregisterStat(&d_checkUnsatCoreTime);
294 smtStatisticsRegistry()->unregisterStat(&d_solveTime);
295 smtStatisticsRegistry()->unregisterStat(&d_pushPopTime);
296 smtStatisticsRegistry()->unregisterStat(&d_processAssertionsTime);
297 smtStatisticsRegistry()->unregisterStat(&d_simplifiedToFalse);
298 smtStatisticsRegistry()->unregisterStat(&d_resourceUnitsUsed);
299 }
300 };/* struct SmtEngineStatistics */
301
302
303 class SoftResourceOutListener : public Listener {
304 public:
305 SoftResourceOutListener(SmtEngine& smt) : d_smt(&smt) {}
306 void notify() override
307 {
308 SmtScope scope(d_smt);
309 Assert(smt::smtEngineInScope());
310 d_smt->interrupt();
311 }
312 private:
313 SmtEngine* d_smt;
314 }; /* class SoftResourceOutListener */
315
316
317 class HardResourceOutListener : public Listener {
318 public:
319 HardResourceOutListener(SmtEngine& smt) : d_smt(&smt) {}
320 void notify() override
321 {
322 SmtScope scope(d_smt);
323 theory::Rewriter::clearCaches();
324 }
325 private:
326 SmtEngine* d_smt;
327 }; /* class HardResourceOutListener */
328
329 class SetLogicListener : public Listener {
330 public:
331 SetLogicListener(SmtEngine& smt) : d_smt(&smt) {}
332 void notify() override
333 {
334 LogicInfo inOptions(options::forceLogicString());
335 d_smt->setLogic(inOptions);
336 }
337 private:
338 SmtEngine* d_smt;
339 }; /* class SetLogicListener */
340
341 class BeforeSearchListener : public Listener {
342 public:
343 BeforeSearchListener(SmtEngine& smt) : d_smt(&smt) {}
344 void notify() override { d_smt->beforeSearch(); }
345
346 private:
347 SmtEngine* d_smt;
348 }; /* class BeforeSearchListener */
349
350 class UseTheoryListListener : public Listener {
351 public:
352 UseTheoryListListener(TheoryEngine* theoryEngine)
353 : d_theoryEngine(theoryEngine)
354 {}
355
356 void notify() override
357 {
358 std::stringstream commaList(options::useTheoryList());
359 std::string token;
360
361 Debug("UseTheoryListListener") << "UseTheoryListListener::notify() "
362 << options::useTheoryList() << std::endl;
363
364 while(std::getline(commaList, token, ',')){
365 if(token == "help") {
366 puts(theory::useTheoryHelp);
367 exit(1);
368 }
369 if(theory::useTheoryValidate(token)) {
370 d_theoryEngine->enableTheoryAlternative(token);
371 } else {
372 throw OptionException(
373 std::string("unknown option for --use-theory : `") + token +
374 "'. Try --use-theory=help.");
375 }
376 }
377 }
378
379 private:
380 TheoryEngine* d_theoryEngine;
381 }; /* class UseTheoryListListener */
382
383
384 class SetDefaultExprDepthListener : public Listener {
385 public:
386 void notify() override
387 {
388 int depth = options::defaultExprDepth();
389 Debug.getStream() << expr::ExprSetDepth(depth);
390 Trace.getStream() << expr::ExprSetDepth(depth);
391 Notice.getStream() << expr::ExprSetDepth(depth);
392 Chat.getStream() << expr::ExprSetDepth(depth);
393 Message.getStream() << expr::ExprSetDepth(depth);
394 Warning.getStream() << expr::ExprSetDepth(depth);
395 // intentionally exclude Dump stream from this list
396 }
397 };
398
399 class SetDefaultExprDagListener : public Listener {
400 public:
401 void notify() override
402 {
403 int dag = options::defaultDagThresh();
404 Debug.getStream() << expr::ExprDag(dag);
405 Trace.getStream() << expr::ExprDag(dag);
406 Notice.getStream() << expr::ExprDag(dag);
407 Chat.getStream() << expr::ExprDag(dag);
408 Message.getStream() << expr::ExprDag(dag);
409 Warning.getStream() << expr::ExprDag(dag);
410 Dump.getStream() << expr::ExprDag(dag);
411 }
412 };
413
414 class SetPrintExprTypesListener : public Listener {
415 public:
416 void notify() override
417 {
418 bool value = options::printExprTypes();
419 Debug.getStream() << expr::ExprPrintTypes(value);
420 Trace.getStream() << expr::ExprPrintTypes(value);
421 Notice.getStream() << expr::ExprPrintTypes(value);
422 Chat.getStream() << expr::ExprPrintTypes(value);
423 Message.getStream() << expr::ExprPrintTypes(value);
424 Warning.getStream() << expr::ExprPrintTypes(value);
425 // intentionally exclude Dump stream from this list
426 }
427 };
428
429 class DumpModeListener : public Listener {
430 public:
431 void notify() override
432 {
433 const std::string& value = options::dumpModeString();
434 Dump.setDumpFromString(value);
435 }
436 };
437
438 class PrintSuccessListener : public Listener {
439 public:
440 void notify() override
441 {
442 bool value = options::printSuccess();
443 Debug.getStream() << Command::printsuccess(value);
444 Trace.getStream() << Command::printsuccess(value);
445 Notice.getStream() << Command::printsuccess(value);
446 Chat.getStream() << Command::printsuccess(value);
447 Message.getStream() << Command::printsuccess(value);
448 Warning.getStream() << Command::printsuccess(value);
449 *options::out() << Command::printsuccess(value);
450 }
451 };
452
453
454
455 /**
456 * This is an inelegant solution, but for the present, it will work.
457 * The point of this is to separate the public and private portions of
458 * the SmtEngine class, so that smt_engine.h doesn't
459 * include "expr/node.h", which is a private CVC4 header (and can lead
460 * to linking errors due to the improper inlining of non-visible symbols
461 * into user code!).
462 *
463 * The "real" solution (that which is usually implemented) is to move
464 * ALL the implementation to SmtEnginePrivate and maintain a
465 * heap-allocated instance of it in SmtEngine. SmtEngine (the public
466 * one) becomes an "interface shell" which simply acts as a forwarder
467 * of method calls.
468 */
469 class SmtEnginePrivate : public NodeManagerListener {
470 SmtEngine& d_smt;
471
472 typedef unordered_map<Node, Node, NodeHashFunction> NodeToNodeHashMap;
473 typedef unordered_map<Node, bool, NodeHashFunction> NodeToBoolHashMap;
474
475 /**
476 * Manager for limiting time and abstract resource usage.
477 */
478 ResourceManager* d_resourceManager;
479
480 /** Manager for the memory of regular-output-channel. */
481 ManagedRegularOutputChannel d_managedRegularChannel;
482
483 /** Manager for the memory of diagnostic-output-channel. */
484 ManagedDiagnosticOutputChannel d_managedDiagnosticChannel;
485
486 /** Manager for the memory of --dump-to. */
487 ManagedDumpOStream d_managedDumpChannel;
488
489 /** Manager for --replay-log. */
490 ManagedReplayLogOstream d_managedReplayLog;
491
492 /**
493 * This list contains:
494 * softResourceOut
495 * hardResourceOut
496 * setForceLogic
497 * beforeSearchListener
498 * UseTheoryListListener
499 *
500 * This needs to be deleted before both NodeManager's Options,
501 * SmtEngine, d_resourceManager, and TheoryEngine.
502 */
503 ListenerRegistrationList* d_listenerRegistrations;
504
505 /** Learned literals */
506 vector<Node> d_nonClausalLearnedLiterals;
507
508 /** Size of assertions array when preprocessing starts */
509 unsigned d_realAssertionsEnd;
510
511 /** A circuit propagator for non-clausal propositional deduction */
512 booleans::CircuitPropagator d_propagator;
513 bool d_propagatorNeedsFinish;
514 std::vector<Node> d_boolVars;
515
516 /** Assertions in the preprocessing pipeline */
517 AssertionPipeline d_assertions;
518
519 /** Whether any assertions have been processed */
520 CDO<bool> d_assertionsProcessed;
521
522 /** Index for where to store substitutions */
523 CDO<unsigned> d_substitutionsIndex;
524
525 // Cached true value
526 Node d_true;
527
528 /**
529 * A context that never pushes/pops, for use by CD structures (like
530 * SubstitutionMaps) that should be "global".
531 */
532 context::Context d_fakeContext;
533
534 /**
535 * A map of AbsractValues to their actual constants. Only used if
536 * options::abstractValues() is on.
537 */
538 SubstitutionMap d_abstractValueMap;
539
540 /**
541 * A mapping of all abstract values (actual value |-> abstract) that
542 * we've handed out. This is necessary to ensure that we give the
543 * same AbstractValues for the same real constants. Only used if
544 * options::abstractValues() is on.
545 */
546 NodeToNodeHashMap d_abstractValues;
547
548 /** Number of calls of simplify assertions active.
549 */
550 unsigned d_simplifyAssertionsDepth;
551
552 /** TODO: whether certain preprocess steps are necessary */
553 //bool d_needsExpandDefs;
554
555 //------------------------------- expression names
556 /** mapping from expressions to name */
557 context::CDHashMap< Node, std::string, NodeHashFunction > d_exprNames;
558 //------------------------------- end expression names
559 public:
560 /**
561 * Map from skolem variables to index in d_assertions containing
562 * corresponding introduced Boolean ite
563 */
564 IteSkolemMap d_iteSkolemMap;
565
566 /** Instance of the ITE remover */
567 RemoveTermFormulas d_iteRemover;
568
569 /* Finishes the initialization of the private portion of SMTEngine. */
570 void finishInit();
571
572 private:
573 std::unique_ptr<PreprocessingPassContext> d_preprocessingPassContext;
574 PreprocessingPassRegistry d_preprocessingPassRegistry;
575
576 /** The top level substitutions */
577 SubstitutionMap d_topLevelSubstitutions;
578
579 static const bool d_doConstantProp = true;
580
581 /**
582 * Runs the nonclausal solver and tries to solve all the assigned
583 * theory literals.
584 *
585 * Returns false if the formula simplifies to "false"
586 */
587 bool nonClausalSimplify();
588
589 /**
590 * Performs static learning on the assertions.
591 */
592 void staticLearning();
593
594 /**
595 * Remove ITEs from the assertions.
596 */
597 void removeITEs();
598
599 Node realToInt(TNode n, NodeToNodeHashMap& cache, std::vector< Node >& var_eq);
600 Node purifyNlTerms(TNode n, NodeToNodeHashMap& cache, NodeToNodeHashMap& bcache, std::vector< Node >& var_eq, bool beneathMult = false);
601
602 /**
603 * Helper function to fix up assertion list to restore invariants needed after
604 * ite removal.
605 */
606 void collectSkolems(TNode n, set<TNode>& skolemSet, NodeToBoolHashMap& cache);
607
608 /**
609 * Helper function to fix up assertion list to restore invariants needed after
610 * ite removal.
611 */
612 bool checkForBadSkolems(TNode n, TNode skolem, NodeToBoolHashMap& cache);
613
614 // Lift bit-vectors of size 1 to booleans
615 void bvToBool();
616
617 // Convert booleans to bit-vectors of size 1
618 void boolToBv();
619
620 // Abstract common structure over small domains to UF
621 // return true if changes were made.
622 void bvAbstraction();
623
624 // Simplify ITE structure
625 bool simpITE();
626
627 // Simplify based on unconstrained values
628 void unconstrainedSimp();
629
630 /**
631 * Ensures the assertions asserted after before now effectively come before
632 * d_realAssertionsEnd.
633 */
634 void compressBeforeRealAssertions(size_t before);
635
636 /**
637 * Trace nodes back to their assertions using CircuitPropagator's
638 * BackEdgesMap.
639 */
640 void traceBackToAssertions(const std::vector<Node>& nodes,
641 std::vector<TNode>& assertions);
642
643 /**
644 * Remove conjuncts in toRemove from conjunction n. Return # of removed
645 * conjuncts.
646 */
647 size_t removeFromConjunction(Node& n,
648 const std::unordered_set<unsigned long>& toRemove);
649
650 /** Scrub miplib encodings. */
651 void doMiplibTrick();
652
653 /**
654 * Perform non-clausal simplification of a Node. This involves
655 * Theory implementations, but does NOT involve the SAT solver in
656 * any way.
657 *
658 * Returns false if the formula simplifies to "false"
659 */
660 bool simplifyAssertions();
661
662 public:
663
664 SmtEnginePrivate(SmtEngine& smt) :
665 d_smt(smt),
666 d_managedRegularChannel(),
667 d_managedDiagnosticChannel(),
668 d_managedDumpChannel(),
669 d_managedReplayLog(),
670 d_listenerRegistrations(new ListenerRegistrationList()),
671 d_nonClausalLearnedLiterals(),
672 d_realAssertionsEnd(0),
673 d_propagator(d_nonClausalLearnedLiterals, true, true),
674 d_propagatorNeedsFinish(false),
675 d_assertions(),
676 d_assertionsProcessed(smt.d_userContext, false),
677 d_substitutionsIndex(smt.d_userContext, 0),
678 d_fakeContext(),
679 d_abstractValueMap(&d_fakeContext),
680 d_abstractValues(),
681 d_simplifyAssertionsDepth(0),
682 //d_needsExpandDefs(true), //TODO?
683 d_exprNames(smt.d_userContext),
684 d_iteSkolemMap(),
685 d_iteRemover(smt.d_userContext),
686 d_topLevelSubstitutions(smt.d_userContext)
687 {
688 d_smt.d_nodeManager->subscribeEvents(this);
689 d_true = NodeManager::currentNM()->mkConst(true);
690 d_resourceManager = NodeManager::currentResourceManager();
691
692 d_listenerRegistrations->add(d_resourceManager->registerSoftListener(
693 new SoftResourceOutListener(d_smt)));
694
695 d_listenerRegistrations->add(d_resourceManager->registerHardListener(
696 new HardResourceOutListener(d_smt)));
697
698 Options& nodeManagerOptions = NodeManager::currentNM()->getOptions();
699 d_listenerRegistrations->add(
700 nodeManagerOptions.registerForceLogicListener(
701 new SetLogicListener(d_smt), true));
702
703 // Multiple options reuse BeforeSearchListener so registration requires an
704 // extra bit of care.
705 // We can safely not call notify on this before search listener at
706 // registration time. This d_smt cannot be beforeSearch at construction
707 // time. Therefore the BeforeSearchListener is a no-op. Therefore it does
708 // not have to be called.
709 d_listenerRegistrations->add(
710 nodeManagerOptions.registerBeforeSearchListener(
711 new BeforeSearchListener(d_smt)));
712
713 // These do need registration calls.
714 d_listenerRegistrations->add(
715 nodeManagerOptions.registerSetDefaultExprDepthListener(
716 new SetDefaultExprDepthListener(), true));
717 d_listenerRegistrations->add(
718 nodeManagerOptions.registerSetDefaultExprDagListener(
719 new SetDefaultExprDagListener(), true));
720 d_listenerRegistrations->add(
721 nodeManagerOptions.registerSetPrintExprTypesListener(
722 new SetPrintExprTypesListener(), true));
723 d_listenerRegistrations->add(
724 nodeManagerOptions.registerSetDumpModeListener(
725 new DumpModeListener(), true));
726 d_listenerRegistrations->add(
727 nodeManagerOptions.registerSetPrintSuccessListener(
728 new PrintSuccessListener(), true));
729 d_listenerRegistrations->add(
730 nodeManagerOptions.registerSetRegularOutputChannelListener(
731 new SetToDefaultSourceListener(&d_managedRegularChannel), true));
732 d_listenerRegistrations->add(
733 nodeManagerOptions.registerSetDiagnosticOutputChannelListener(
734 new SetToDefaultSourceListener(&d_managedDiagnosticChannel), true));
735 d_listenerRegistrations->add(
736 nodeManagerOptions.registerDumpToFileNameListener(
737 new SetToDefaultSourceListener(&d_managedDumpChannel), true));
738 d_listenerRegistrations->add(
739 nodeManagerOptions.registerSetReplayLogFilename(
740 new SetToDefaultSourceListener(&d_managedReplayLog), true));
741 }
742
743 ~SmtEnginePrivate()
744 {
745 delete d_listenerRegistrations;
746
747 if(d_propagatorNeedsFinish) {
748 d_propagator.finish();
749 d_propagatorNeedsFinish = false;
750 }
751 d_smt.d_nodeManager->unsubscribeEvents(this);
752 }
753
754 ResourceManager* getResourceManager() { return d_resourceManager; }
755 void spendResource(unsigned amount)
756 {
757 d_resourceManager->spendResource(amount);
758 }
759
760 void nmNotifyNewSort(TypeNode tn, uint32_t flags) override
761 {
762 DeclareTypeCommand c(tn.getAttribute(expr::VarNameAttr()),
763 0,
764 tn.toType());
765 if((flags & ExprManager::SORT_FLAG_PLACEHOLDER) == 0) {
766 d_smt.addToModelCommandAndDump(c, flags);
767 }
768 }
769
770 void nmNotifyNewSortConstructor(TypeNode tn) override
771 {
772 DeclareTypeCommand c(tn.getAttribute(expr::VarNameAttr()),
773 tn.getAttribute(expr::SortArityAttr()),
774 tn.toType());
775 d_smt.addToModelCommandAndDump(c);
776 }
777
778 void nmNotifyNewDatatypes(const std::vector<DatatypeType>& dtts) override
779 {
780 DatatypeDeclarationCommand c(dtts);
781 d_smt.addToModelCommandAndDump(c);
782 }
783
784 void nmNotifyNewVar(TNode n, uint32_t flags) override
785 {
786 DeclareFunctionCommand c(n.getAttribute(expr::VarNameAttr()),
787 n.toExpr(),
788 n.getType().toType());
789 if((flags & ExprManager::VAR_FLAG_DEFINED) == 0) {
790 d_smt.addToModelCommandAndDump(c, flags);
791 }
792 if(n.getType().isBoolean() && !options::incrementalSolving()) {
793 d_boolVars.push_back(n);
794 }
795 }
796
797 void nmNotifyNewSkolem(TNode n,
798 const std::string& comment,
799 uint32_t flags) override
800 {
801 string id = n.getAttribute(expr::VarNameAttr());
802 DeclareFunctionCommand c(id, n.toExpr(), n.getType().toType());
803 if(Dump.isOn("skolems") && comment != "") {
804 Dump("skolems") << CommentCommand(id + " is " + comment);
805 }
806 if((flags & ExprManager::VAR_FLAG_DEFINED) == 0) {
807 d_smt.addToModelCommandAndDump(c, flags, false, "skolems");
808 }
809 if(n.getType().isBoolean() && !options::incrementalSolving()) {
810 d_boolVars.push_back(n);
811 }
812 }
813
814 void nmNotifyDeleteNode(TNode n) override {}
815
816 Node applySubstitutions(TNode node) const {
817 return Rewriter::rewrite(d_topLevelSubstitutions.apply(node));
818 }
819
820 /**
821 * Apply the substitutions in d_topLevelAssertions and the rewriter to each of
822 * the assertions in d_assertions, and store the result back in d_assertions.
823 */
824 void applySubstitutionsToAssertions();
825
826 /**
827 * Process the assertions that have been asserted.
828 */
829 void processAssertions();
830
831 /** Process a user push.
832 */
833 void notifyPush() {
834
835 }
836
837 /**
838 * Process a user pop. Clears out the non-context-dependent stuff in this
839 * SmtEnginePrivate. Necessary to clear out our assertion vectors in case
840 * someone does a push-assert-pop without a check-sat. It also pops the
841 * last map of expression names from notifyPush.
842 */
843 void notifyPop() {
844 d_assertions.clear();
845 d_nonClausalLearnedLiterals.clear();
846 d_realAssertionsEnd = 0;
847 d_iteSkolemMap.clear();
848 }
849
850 /**
851 * Adds a formula to the current context. Action here depends on
852 * the SimplificationMode (in the current Options scope); the
853 * formula might be pushed out to the propositional layer
854 * immediately, or it might be simplified and kept, or it might not
855 * even be simplified.
856 * the 2nd and 3rd arguments added for bookkeeping for proofs
857 */
858 void addFormula(TNode n, bool inUnsatCore, bool inInput = true);
859
860 /** Expand definitions in n. */
861 Node expandDefinitions(TNode n,
862 NodeToNodeHashMap& cache,
863 bool expandOnly = false);
864
865 /**
866 * Simplify node "in" by expanding definitions and applying any
867 * substitutions learned from preprocessing.
868 */
869 Node simplify(TNode in) {
870 // Substitute out any abstract values in ex.
871 // Expand definitions.
872 NodeToNodeHashMap cache;
873 Node n = expandDefinitions(in, cache).toExpr();
874 // Make sure we've done all preprocessing, etc.
875 Assert(d_assertions.size() == 0);
876 return applySubstitutions(n).toExpr();
877 }
878
879 /**
880 * Substitute away all AbstractValues in a node.
881 */
882 Node substituteAbstractValues(TNode n) {
883 // We need to do this even if options::abstractValues() is off,
884 // since the setting might have changed after we already gave out
885 // some abstract values.
886 return d_abstractValueMap.apply(n);
887 }
888
889 /**
890 * Make a new (or return an existing) abstract value for a node.
891 * Can only use this if options::abstractValues() is on.
892 */
893 Node mkAbstractValue(TNode n) {
894 Assert(options::abstractValues());
895 Node& val = d_abstractValues[n];
896 if(val.isNull()) {
897 val = d_smt.d_nodeManager->mkAbstractValue(n.getType());
898 d_abstractValueMap.addSubstitution(val, n);
899 }
900 // We are supposed to ascribe types to all abstract values that go out.
901 NodeManager* current = d_smt.d_nodeManager;
902 Node ascription = current->mkConst(AscriptionType(n.getType().toType()));
903 Node retval = current->mkNode(kind::APPLY_TYPE_ASCRIPTION, ascription, val);
904 return retval;
905 }
906
907 NodeToNodeHashMap d_rewriteApplyToConstCache;
908 Node rewriteApplyToConst(TNode n) {
909 Trace("rewriteApplyToConst") << "rewriteApplyToConst :: " << n << std::endl;
910
911 if(n.getMetaKind() == kind::metakind::CONSTANT ||
912 n.getMetaKind() == kind::metakind::VARIABLE ||
913 n.getMetaKind() == kind::metakind::NULLARY_OPERATOR)
914 {
915 return n;
916 }
917
918 if(d_rewriteApplyToConstCache.find(n) != d_rewriteApplyToConstCache.end()) {
919 Trace("rewriteApplyToConst") << "in cache :: "
920 << d_rewriteApplyToConstCache[n]
921 << std::endl;
922 return d_rewriteApplyToConstCache[n];
923 }
924
925 if(n.getKind() == kind::APPLY_UF) {
926 if(n.getNumChildren() == 1 && n[0].isConst() &&
927 n[0].getType().isInteger())
928 {
929 stringstream ss;
930 ss << n.getOperator() << "_";
931 if(n[0].getConst<Rational>() < 0) {
932 ss << "m" << -n[0].getConst<Rational>();
933 } else {
934 ss << n[0];
935 }
936 Node newvar = NodeManager::currentNM()->mkSkolem(
937 ss.str(), n.getType(), "rewriteApplyToConst skolem",
938 NodeManager::SKOLEM_EXACT_NAME);
939 d_rewriteApplyToConstCache[n] = newvar;
940 Trace("rewriteApplyToConst") << "made :: " << newvar << std::endl;
941 return newvar;
942 } else {
943 stringstream ss;
944 ss << "The rewrite-apply-to-const preprocessor is currently limited;"
945 << std::endl
946 << "it only works if all function symbols are unary and with Integer"
947 << std::endl
948 << "domain, and all applications are to integer values." << std::endl
949 << "Found application: " << n;
950 Unhandled(ss.str());
951 }
952 }
953
954 NodeBuilder<> builder(n.getKind());
955 if(n.getMetaKind() == kind::metakind::PARAMETERIZED) {
956 builder << n.getOperator();
957 }
958 for(unsigned i = 0; i < n.getNumChildren(); ++i) {
959 builder << rewriteApplyToConst(n[i]);
960 }
961 Node rewr = builder;
962 d_rewriteApplyToConstCache[n] = rewr;
963 Trace("rewriteApplyToConst") << "built :: " << rewr << std::endl;
964 return rewr;
965 }
966
967 void addUseTheoryListListener(TheoryEngine* theoryEngine){
968 Options& nodeManagerOptions = NodeManager::currentNM()->getOptions();
969 d_listenerRegistrations->add(
970 nodeManagerOptions.registerUseTheoryListListener(
971 new UseTheoryListListener(theoryEngine), true));
972 }
973
974 std::ostream* getReplayLog() const {
975 return d_managedReplayLog.getReplayLog();
976 }
977
978 //------------------------------- expression names
979 // implements setExpressionName, as described in smt_engine.h
980 void setExpressionName(Expr e, std::string name) {
981 d_exprNames[Node::fromExpr(e)] = name;
982 }
983
984 // implements getExpressionName, as described in smt_engine.h
985 bool getExpressionName(Expr e, std::string& name) const {
986 context::CDHashMap< Node, std::string, NodeHashFunction >::const_iterator it = d_exprNames.find(e);
987 if(it!=d_exprNames.end()) {
988 name = (*it).second;
989 return true;
990 }else{
991 return false;
992 }
993 }
994 //------------------------------- end expression names
995
996 };/* class SmtEnginePrivate */
997
998 }/* namespace CVC4::smt */
999
1000 SmtEngine::SmtEngine(ExprManager* em)
1001 : d_context(new Context()),
1002 d_userLevels(),
1003 d_userContext(new UserContext()),
1004 d_exprManager(em),
1005 d_nodeManager(d_exprManager->getNodeManager()),
1006 d_decisionEngine(NULL),
1007 d_theoryEngine(NULL),
1008 d_propEngine(NULL),
1009 d_proofManager(NULL),
1010 d_definedFunctions(NULL),
1011 d_fmfRecFunctionsDefined(NULL),
1012 d_assertionList(NULL),
1013 d_assignments(NULL),
1014 d_modelGlobalCommands(),
1015 d_modelCommands(NULL),
1016 d_dumpCommands(),
1017 d_defineCommands(),
1018 d_logic(),
1019 d_originalOptions(),
1020 d_pendingPops(0),
1021 d_fullyInited(false),
1022 d_problemExtended(false),
1023 d_queryMade(false),
1024 d_needPostsolve(false),
1025 d_earlyTheoryPP(true),
1026 d_globalNegation(false),
1027 d_status(),
1028 d_replayStream(NULL),
1029 d_private(NULL),
1030 d_statisticsRegistry(NULL),
1031 d_stats(NULL),
1032 d_channels(new LemmaChannels())
1033 {
1034 SmtScope smts(this);
1035 d_originalOptions.copyValues(em->getOptions());
1036 d_private = new smt::SmtEnginePrivate(*this);
1037 d_statisticsRegistry = new StatisticsRegistry();
1038 d_stats = new SmtEngineStatistics();
1039 d_stats->d_resourceUnitsUsed.setData(
1040 d_private->getResourceManager()->getResourceUsage());
1041
1042 // The ProofManager is constructed before any other proof objects such as
1043 // SatProof and TheoryProofs. The TheoryProofEngine and the SatProof are
1044 // initialized in TheoryEngine and PropEngine respectively.
1045 Assert(d_proofManager == NULL);
1046
1047 // d_proofManager must be created before Options has been finished
1048 // being parsed from the input file. Because of this, we cannot trust
1049 // that options::proof() is set correctly yet.
1050 #ifdef CVC4_PROOF
1051 d_proofManager = new ProofManager(d_userContext);
1052 #endif
1053
1054 // We have mutual dependency here, so we add the prop engine to the theory
1055 // engine later (it is non-essential there)
1056 d_theoryEngine = new TheoryEngine(d_context, d_userContext,
1057 d_private->d_iteRemover,
1058 const_cast<const LogicInfo&>(d_logic),
1059 d_channels);
1060
1061 // Add the theories
1062 for(TheoryId id = theory::THEORY_FIRST; id < theory::THEORY_LAST; ++id) {
1063 TheoryConstructor::addTheory(d_theoryEngine, id);
1064 //register with proof engine if applicable
1065 #ifdef CVC4_PROOF
1066 ProofManager::currentPM()->getTheoryProofEngine()->registerTheory(d_theoryEngine->theoryOf(id));
1067 #endif
1068 }
1069
1070 d_private->addUseTheoryListListener(d_theoryEngine);
1071
1072 // global push/pop around everything, to ensure proper destruction
1073 // of context-dependent data structures
1074 d_userContext->push();
1075 d_context->push();
1076
1077 d_definedFunctions = new(true) DefinedFunctionMap(d_userContext);
1078 d_fmfRecFunctionsDefined = new(true) NodeList(d_userContext);
1079 d_modelCommands = new(true) smt::CommandList(d_userContext);
1080 }
1081
1082 void SmtEngine::finishInit() {
1083 Trace("smt-debug") << "SmtEngine::finishInit" << std::endl;
1084 // ensure that our heuristics are properly set up
1085 setDefaults();
1086
1087 Trace("smt-debug") << "Making decision engine..." << std::endl;
1088
1089 d_decisionEngine = new DecisionEngine(d_context, d_userContext);
1090 d_decisionEngine->init(); // enable appropriate strategies
1091
1092 Trace("smt-debug") << "Making prop engine..." << std::endl;
1093 d_propEngine = new PropEngine(d_theoryEngine, d_decisionEngine, d_context,
1094 d_userContext, d_private->getReplayLog(),
1095 d_replayStream, d_channels);
1096
1097 Trace("smt-debug") << "Setting up theory engine..." << std::endl;
1098 d_theoryEngine->setPropEngine(d_propEngine);
1099 d_theoryEngine->setDecisionEngine(d_decisionEngine);
1100 Trace("smt-debug") << "Finishing init for theory engine..." << std::endl;
1101 d_theoryEngine->finishInit();
1102
1103 Trace("smt-debug") << "Set up assertion list..." << std::endl;
1104 // [MGD 10/20/2011] keep around in incremental mode, due to a
1105 // cleanup ordering issue and Nodes/TNodes. If SAT is popped
1106 // first, some user-context-dependent TNodes might still exist
1107 // with rc == 0.
1108 if(options::produceAssertions() ||
1109 options::incrementalSolving()) {
1110 // In the case of incremental solving, we appear to need these to
1111 // ensure the relevant Nodes remain live.
1112 d_assertionList = new(true) AssertionList(d_userContext);
1113 }
1114
1115 // dump out a set-logic command
1116 if(Dump.isOn("benchmark")) {
1117 if (Dump.isOn("raw-benchmark")) {
1118 Dump("raw-benchmark") << SetBenchmarkLogicCommand(d_logic.getLogicString());
1119 } else {
1120 LogicInfo everything;
1121 everything.lock();
1122 Dump("benchmark") << CommentCommand("CVC4 always dumps the most general, all-supported logic (below), as some internals might require the use of a logic more general than the input.")
1123 << SetBenchmarkLogicCommand(everything.getLogicString());
1124 }
1125 }
1126
1127 Trace("smt-debug") << "Dump declaration commands..." << std::endl;
1128 // dump out any pending declaration commands
1129 for(unsigned i = 0; i < d_dumpCommands.size(); ++i) {
1130 Dump("declarations") << *d_dumpCommands[i];
1131 delete d_dumpCommands[i];
1132 }
1133 d_dumpCommands.clear();
1134
1135 PROOF( ProofManager::currentPM()->setLogic(d_logic); );
1136 PROOF({
1137 for(TheoryId id = theory::THEORY_FIRST; id < theory::THEORY_LAST; ++id) {
1138 ProofManager::currentPM()->getTheoryProofEngine()->
1139 finishRegisterTheory(d_theoryEngine->theoryOf(id));
1140 }
1141 });
1142 d_private->finishInit();
1143 Trace("smt-debug") << "SmtEngine::finishInit done" << std::endl;
1144 }
1145
1146 void SmtEngine::finalOptionsAreSet() {
1147 if(d_fullyInited) {
1148 return;
1149 }
1150
1151 if(! d_logic.isLocked()) {
1152 setLogicInternal();
1153 }
1154
1155 // finish initialization, create the prop engine, etc.
1156 finishInit();
1157
1158 AlwaysAssert( d_propEngine->getAssertionLevel() == 0,
1159 "The PropEngine has pushed but the SmtEngine "
1160 "hasn't finished initializing!" );
1161
1162 d_fullyInited = true;
1163 Assert(d_logic.isLocked());
1164
1165 d_propEngine->assertFormula(NodeManager::currentNM()->mkConst<bool>(true));
1166 d_propEngine->assertFormula(NodeManager::currentNM()->mkConst<bool>(false).notNode());
1167 }
1168
1169 void SmtEngine::shutdown() {
1170 doPendingPops();
1171
1172 while(options::incrementalSolving() && d_userContext->getLevel() > 1) {
1173 internalPop(true);
1174 }
1175
1176 // check to see if a postsolve() is pending
1177 if(d_needPostsolve) {
1178 d_theoryEngine->postsolve();
1179 d_needPostsolve = false;
1180 }
1181
1182 if(d_propEngine != NULL) {
1183 d_propEngine->shutdown();
1184 }
1185 if(d_theoryEngine != NULL) {
1186 d_theoryEngine->shutdown();
1187 }
1188 if(d_decisionEngine != NULL) {
1189 d_decisionEngine->shutdown();
1190 }
1191 }
1192
1193 SmtEngine::~SmtEngine()
1194 {
1195 SmtScope smts(this);
1196
1197 try {
1198 shutdown();
1199
1200 // global push/pop around everything, to ensure proper destruction
1201 // of context-dependent data structures
1202 d_context->popto(0);
1203 d_userContext->popto(0);
1204
1205 if(d_assignments != NULL) {
1206 d_assignments->deleteSelf();
1207 }
1208
1209 if(d_assertionList != NULL) {
1210 d_assertionList->deleteSelf();
1211 }
1212
1213 for(unsigned i = 0; i < d_dumpCommands.size(); ++i) {
1214 delete d_dumpCommands[i];
1215 d_dumpCommands[i] = NULL;
1216 }
1217 d_dumpCommands.clear();
1218
1219 DeleteAndClearCommandVector(d_modelGlobalCommands);
1220
1221 if(d_modelCommands != NULL) {
1222 d_modelCommands->deleteSelf();
1223 }
1224
1225 d_definedFunctions->deleteSelf();
1226 d_fmfRecFunctionsDefined->deleteSelf();
1227
1228 delete d_theoryEngine;
1229 d_theoryEngine = NULL;
1230 delete d_propEngine;
1231 d_propEngine = NULL;
1232 delete d_decisionEngine;
1233 d_decisionEngine = NULL;
1234
1235
1236 // d_proofManager is always created when proofs are enabled at configure time.
1237 // Becuase of this, this code should not be wrapped in PROOF() which
1238 // additionally checks flags such as options::proof().
1239 #ifdef CVC4_PROOF
1240 delete d_proofManager;
1241 d_proofManager = NULL;
1242 #endif
1243
1244 delete d_stats;
1245 d_stats = NULL;
1246 delete d_statisticsRegistry;
1247 d_statisticsRegistry = NULL;
1248
1249 delete d_private;
1250 d_private = NULL;
1251
1252 delete d_userContext;
1253 d_userContext = NULL;
1254 delete d_context;
1255 d_context = NULL;
1256
1257 delete d_channels;
1258 d_channels = NULL;
1259
1260 } catch(Exception& e) {
1261 Warning() << "CVC4 threw an exception during cleanup." << endl
1262 << e << endl;
1263 }
1264 }
1265
1266 void SmtEngine::setLogic(const LogicInfo& logic)
1267 {
1268 SmtScope smts(this);
1269 if(d_fullyInited) {
1270 throw ModalException("Cannot set logic in SmtEngine after the engine has "
1271 "finished initializing.");
1272 }
1273 d_logic = logic;
1274 setLogicInternal();
1275 }
1276
1277 void SmtEngine::setLogic(const std::string& s)
1278 {
1279 SmtScope smts(this);
1280 try {
1281 setLogic(LogicInfo(s));
1282 } catch(IllegalArgumentException& e) {
1283 throw LogicException(e.what());
1284 }
1285 }
1286
1287 void SmtEngine::setLogic(const char* logic) { setLogic(string(logic)); }
1288 LogicInfo SmtEngine::getLogicInfo() const {
1289 return d_logic;
1290 }
1291 void SmtEngine::setLogicInternal()
1292 {
1293 Assert(!d_fullyInited, "setting logic in SmtEngine but the engine has already"
1294 " finished initializing for this run");
1295 d_logic.lock();
1296 }
1297
1298 void SmtEngine::setDefaults() {
1299 Random::getRandom().setSeed(options::seed());
1300 // Language-based defaults
1301 if (!options::bitvectorDivByZeroConst.wasSetByUser())
1302 {
1303 options::bitvectorDivByZeroConst.set(options::inputLanguage()
1304 == language::input::LANG_SMTLIB_V2_6);
1305 }
1306 if (options::inputLanguage() == language::input::LANG_SYGUS)
1307 {
1308 if (!options::ceGuidedInst.wasSetByUser())
1309 {
1310 options::ceGuidedInst.set(true);
1311 }
1312 // must use Ferrante/Rackoff for real arithmetic
1313 if (!options::cbqiMidpoint.wasSetByUser())
1314 {
1315 options::cbqiMidpoint.set(true);
1316 }
1317 }
1318
1319 if(options::forceLogicString.wasSetByUser()) {
1320 d_logic = LogicInfo(options::forceLogicString());
1321 }else if (options::solveIntAsBV() > 0) {
1322 d_logic = LogicInfo("QF_BV");
1323 }else if (d_logic.getLogicString() == "QF_NRA" && options::solveRealAsInt()) {
1324 d_logic = LogicInfo("QF_NIA");
1325 } else if ((d_logic.getLogicString() == "QF_UFBV" ||
1326 d_logic.getLogicString() == "QF_ABV") &&
1327 options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER) {
1328 d_logic = LogicInfo("QF_BV");
1329 }
1330
1331 // set strings-exp
1332 /* - disabled for 1.4 release [MGD 2014.06.25]
1333 if(!d_logic.hasEverything() && d_logic.isTheoryEnabled(THEORY_STRINGS) ) {
1334 if(! options::stringExp.wasSetByUser()) {
1335 options::stringExp.set( true );
1336 Trace("smt") << "turning on strings-exp, for the theory of strings" << std::endl;
1337 }
1338 }
1339 */
1340 // for strings
1341 if(options::stringExp()) {
1342 if( !d_logic.isQuantified() ) {
1343 d_logic = d_logic.getUnlockedCopy();
1344 d_logic.enableQuantifiers();
1345 d_logic.lock();
1346 Trace("smt") << "turning on quantifier logic, for strings-exp"
1347 << std::endl;
1348 }
1349 if(! options::fmfBound.wasSetByUser()) {
1350 options::fmfBound.set( true );
1351 Trace("smt") << "turning on fmf-bound-int, for strings-exp" << std::endl;
1352 }
1353 if(! options::fmfInstEngine.wasSetByUser()) {
1354 options::fmfInstEngine.set( true );
1355 Trace("smt") << "turning on fmf-inst-engine, for strings-exp" << std::endl;
1356 }
1357 /*
1358 if(! options::rewriteDivk.wasSetByUser()) {
1359 options::rewriteDivk.set( true );
1360 Trace("smt") << "turning on rewrite-divk, for strings-exp" << std::endl;
1361 }*/
1362 /*
1363 if(! options::stringFMF.wasSetByUser()) {
1364 options::stringFMF.set( true );
1365 Trace("smt") << "turning on strings-fmf, for strings-exp" << std::endl;
1366 }
1367 */
1368 }
1369
1370 // sygus inference may require datatypes
1371 if (options::sygusInference())
1372 {
1373 d_logic = d_logic.getUnlockedCopy();
1374 d_logic.enableTheory(THEORY_DATATYPES);
1375 d_logic.lock();
1376 }
1377
1378 if ((options::checkModels() || options::checkSynthSol())
1379 && !options::produceAssertions())
1380 {
1381 Notice() << "SmtEngine: turning on produce-assertions to support "
1382 << "check-models or check-synth-sol." << endl;
1383 setOption("produce-assertions", SExpr("true"));
1384 }
1385
1386 if(options::unsatCores()) {
1387 if(options::simplificationMode() != SIMPLIFICATION_MODE_NONE) {
1388 if(options::simplificationMode.wasSetByUser()) {
1389 throw OptionException("simplification not supported with unsat cores");
1390 }
1391 Notice() << "SmtEngine: turning off simplification to support unsat-cores"
1392 << endl;
1393 options::simplificationMode.set(SIMPLIFICATION_MODE_NONE);
1394 }
1395
1396 if(options::unconstrainedSimp()) {
1397 if(options::unconstrainedSimp.wasSetByUser()) {
1398 throw OptionException("unconstrained simplification not supported with unsat cores");
1399 }
1400 Notice() << "SmtEngine: turning off unconstrained simplification to support unsat-cores" << endl;
1401 options::unconstrainedSimp.set(false);
1402 }
1403
1404 if(options::pbRewrites()) {
1405 if(options::pbRewrites.wasSetByUser()) {
1406 throw OptionException("pseudoboolean rewrites not supported with unsat cores");
1407 }
1408 Notice() << "SmtEngine: turning off pseudoboolean rewrites to support unsat-cores" << endl;
1409 setOption("pb-rewrites", false);
1410 }
1411
1412 if(options::sortInference()) {
1413 if(options::sortInference.wasSetByUser()) {
1414 throw OptionException("sort inference not supported with unsat cores");
1415 }
1416 Notice() << "SmtEngine: turning off sort inference to support unsat-cores" << endl;
1417 options::sortInference.set(false);
1418 }
1419
1420 if(options::preSkolemQuant()) {
1421 if(options::preSkolemQuant.wasSetByUser()) {
1422 throw OptionException("pre-skolemization not supported with unsat cores");
1423 }
1424 Notice() << "SmtEngine: turning off pre-skolemization to support unsat-cores" << endl;
1425 options::preSkolemQuant.set(false);
1426 }
1427
1428 if(options::bitvectorToBool()) {
1429 if(options::bitvectorToBool.wasSetByUser()) {
1430 throw OptionException("bv-to-bool not supported with unsat cores");
1431 }
1432 Notice() << "SmtEngine: turning off bitvector-to-bool to support unsat-cores" << endl;
1433 options::bitvectorToBool.set(false);
1434 }
1435
1436 if(options::boolToBitvector()) {
1437 if(options::boolToBitvector.wasSetByUser()) {
1438 throw OptionException("bool-to-bv not supported with unsat cores");
1439 }
1440 Notice() << "SmtEngine: turning off bool-to-bitvector to support unsat-cores" << endl;
1441 options::boolToBitvector.set(false);
1442 }
1443
1444 if(options::bvIntroducePow2()) {
1445 if(options::bvIntroducePow2.wasSetByUser()) {
1446 throw OptionException("bv-intro-pow2 not supported with unsat cores");
1447 }
1448 Notice() << "SmtEngine: turning off bv-intro-pow2 to support unsat-cores" << endl;
1449 setOption("bv-intro-pow2", false);
1450 }
1451
1452 if(options::repeatSimp()) {
1453 if(options::repeatSimp.wasSetByUser()) {
1454 throw OptionException("repeat-simp not supported with unsat cores");
1455 }
1456 Notice() << "SmtEngine: turning off repeat-simp to support unsat-cores" << endl;
1457 setOption("repeat-simp", false);
1458 }
1459
1460 if (options::globalNegate())
1461 {
1462 if (options::globalNegate.wasSetByUser())
1463 {
1464 throw OptionException("global-negate not supported with unsat cores");
1465 }
1466 Notice() << "SmtEngine: turning off global-negate to support unsat-cores"
1467 << endl;
1468 setOption("global-negate", false);
1469 }
1470 }
1471
1472 if (options::cbqiBv() && d_logic.isQuantified())
1473 {
1474 if(options::boolToBitvector.wasSetByUser()) {
1475 throw OptionException(
1476 "bool-to-bv not supported with CBQI BV for quantified logics");
1477 }
1478 Notice() << "SmtEngine: turning off bool-to-bitvector to support CBQI BV"
1479 << endl;
1480 options::boolToBitvector.set(false);
1481 }
1482
1483 // cases where we need produce models
1484 if (!options::produceModels()
1485 && (options::produceAssignments() || options::sygusRewSynthCheck()))
1486 {
1487 Notice() << "SmtEngine: turning on produce-models" << endl;
1488 setOption("produce-models", SExpr("true"));
1489 }
1490
1491 // Set the options for the theoryOf
1492 if(!options::theoryOfMode.wasSetByUser()) {
1493 if(d_logic.isSharingEnabled() &&
1494 !d_logic.isTheoryEnabled(THEORY_BV) &&
1495 !d_logic.isTheoryEnabled(THEORY_STRINGS) &&
1496 !d_logic.isTheoryEnabled(THEORY_SETS) ) {
1497 Trace("smt") << "setting theoryof-mode to term-based" << endl;
1498 options::theoryOfMode.set(THEORY_OF_TERM_BASED);
1499 }
1500 }
1501
1502 // strings require LIA, UF; widen the logic
1503 if(d_logic.isTheoryEnabled(THEORY_STRINGS)) {
1504 LogicInfo log(d_logic.getUnlockedCopy());
1505 // Strings requires arith for length constraints, and also UF
1506 if(!d_logic.isTheoryEnabled(THEORY_UF)) {
1507 Trace("smt") << "because strings are enabled, also enabling UF" << endl;
1508 log.enableTheory(THEORY_UF);
1509 }
1510 if(!d_logic.isTheoryEnabled(THEORY_ARITH) || d_logic.isDifferenceLogic() || !d_logic.areIntegersUsed()) {
1511 Trace("smt") << "because strings are enabled, also enabling linear integer arithmetic" << endl;
1512 log.enableTheory(THEORY_ARITH);
1513 log.enableIntegers();
1514 log.arithOnlyLinear();
1515 }
1516 d_logic = log;
1517 d_logic.lock();
1518 }
1519 if(d_logic.isTheoryEnabled(THEORY_ARRAYS) || d_logic.isTheoryEnabled(THEORY_DATATYPES) || d_logic.isTheoryEnabled(THEORY_SETS)) {
1520 if(!d_logic.isTheoryEnabled(THEORY_UF)) {
1521 LogicInfo log(d_logic.getUnlockedCopy());
1522 Trace("smt") << "because a theory that permits Boolean terms is enabled, also enabling UF" << endl;
1523 log.enableTheory(THEORY_UF);
1524 d_logic = log;
1525 d_logic.lock();
1526 }
1527 }
1528
1529 // by default, symmetry breaker is on only for QF_UF
1530 if(! options::ufSymmetryBreaker.wasSetByUser()) {
1531 bool qf_uf = d_logic.isPure(THEORY_UF) && !d_logic.isQuantified() && !options::proof();
1532 Trace("smt") << "setting uf symmetry breaker to " << qf_uf << endl;
1533 options::ufSymmetryBreaker.set(qf_uf);
1534 }
1535 // by default, nonclausal simplification is off for QF_SAT
1536 if(! options::simplificationMode.wasSetByUser()) {
1537 bool qf_sat = d_logic.isPure(THEORY_BOOL) && !d_logic.isQuantified();
1538 Trace("smt") << "setting simplification mode to <" << d_logic.getLogicString() << "> " << (!qf_sat) << endl;
1539 //simplification=none works better for SMT LIB benchmarks with quantifiers, not others
1540 //options::simplificationMode.set(qf_sat || quantifiers ? SIMPLIFICATION_MODE_NONE : SIMPLIFICATION_MODE_BATCH);
1541 options::simplificationMode.set(qf_sat ? SIMPLIFICATION_MODE_NONE : SIMPLIFICATION_MODE_BATCH);
1542 }
1543
1544 // If in arrays, set the UF handler to arrays
1545 if(d_logic.isTheoryEnabled(THEORY_ARRAYS) && ( !d_logic.isQuantified() ||
1546 (d_logic.isQuantified() && !d_logic.isTheoryEnabled(THEORY_UF)))) {
1547 Theory::setUninterpretedSortOwner(THEORY_ARRAYS);
1548 } else {
1549 Theory::setUninterpretedSortOwner(THEORY_UF);
1550 }
1551
1552 // Turn on ite simplification for QF_LIA and QF_AUFBV
1553 // WARNING: These checks match much more than just QF_AUFBV and
1554 // QF_LIA logics. --K [2014/10/15]
1555 if(! options::doITESimp.wasSetByUser()) {
1556 bool qf_aufbv = !d_logic.isQuantified() &&
1557 d_logic.isTheoryEnabled(THEORY_ARRAYS) &&
1558 d_logic.isTheoryEnabled(THEORY_UF) &&
1559 d_logic.isTheoryEnabled(THEORY_BV);
1560 bool qf_lia = !d_logic.isQuantified() &&
1561 d_logic.isPure(THEORY_ARITH) &&
1562 d_logic.isLinear() &&
1563 !d_logic.isDifferenceLogic() &&
1564 !d_logic.areRealsUsed();
1565
1566 bool iteSimp = (qf_aufbv || qf_lia);
1567 Trace("smt") << "setting ite simplification to " << iteSimp << endl;
1568 options::doITESimp.set(iteSimp);
1569 }
1570 if(! options::compressItes.wasSetByUser() ){
1571 bool qf_lia = !d_logic.isQuantified() &&
1572 d_logic.isPure(THEORY_ARITH) &&
1573 d_logic.isLinear() &&
1574 !d_logic.isDifferenceLogic() &&
1575 !d_logic.areRealsUsed();
1576
1577 bool compressIte = qf_lia;
1578 Trace("smt") << "setting ite compression to " << compressIte << endl;
1579 options::compressItes.set(compressIte);
1580 }
1581 if(! options::simplifyWithCareEnabled.wasSetByUser() ){
1582 bool qf_aufbv = !d_logic.isQuantified() &&
1583 d_logic.isTheoryEnabled(THEORY_ARRAYS) &&
1584 d_logic.isTheoryEnabled(THEORY_UF) &&
1585 d_logic.isTheoryEnabled(THEORY_BV);
1586
1587 bool withCare = qf_aufbv;
1588 Trace("smt") << "setting ite simplify with care to " << withCare << endl;
1589 options::simplifyWithCareEnabled.set(withCare);
1590 }
1591 // Turn off array eager index splitting for QF_AUFLIA
1592 if(! options::arraysEagerIndexSplitting.wasSetByUser()) {
1593 if (not d_logic.isQuantified() &&
1594 d_logic.isTheoryEnabled(THEORY_ARRAYS) &&
1595 d_logic.isTheoryEnabled(THEORY_UF) &&
1596 d_logic.isTheoryEnabled(THEORY_ARITH)) {
1597 Trace("smt") << "setting array eager index splitting to false" << endl;
1598 options::arraysEagerIndexSplitting.set(false);
1599 }
1600 }
1601 // Turn on model-based arrays for QF_AX (unless models are enabled)
1602 // if(! options::arraysModelBased.wasSetByUser()) {
1603 // if (not d_logic.isQuantified() &&
1604 // d_logic.isTheoryEnabled(THEORY_ARRAYS) &&
1605 // d_logic.isPure(THEORY_ARRAYS) &&
1606 // !options::produceModels() &&
1607 // !options::checkModels()) {
1608 // Trace("smt") << "turning on model-based array solver" << endl;
1609 // options::arraysModelBased.set(true);
1610 // }
1611 // }
1612 // Turn on multiple-pass non-clausal simplification for QF_AUFBV
1613 if(! options::repeatSimp.wasSetByUser()) {
1614 bool repeatSimp = !d_logic.isQuantified() &&
1615 (d_logic.isTheoryEnabled(THEORY_ARRAYS) &&
1616 d_logic.isTheoryEnabled(THEORY_UF) &&
1617 d_logic.isTheoryEnabled(THEORY_BV)) &&
1618 !options::unsatCores();
1619 Trace("smt") << "setting repeat simplification to " << repeatSimp << endl;
1620 options::repeatSimp.set(repeatSimp);
1621 }
1622 // Turn on unconstrained simplification for QF_AUFBV
1623 if(!options::unconstrainedSimp.wasSetByUser() ||
1624 options::incrementalSolving()) {
1625 // bool qf_sat = d_logic.isPure(THEORY_BOOL) && !d_logic.isQuantified();
1626 // bool uncSimp = false && !qf_sat && !options::incrementalSolving();
1627 bool uncSimp = !options::incrementalSolving() &&
1628 !d_logic.isQuantified() &&
1629 !options::produceModels() &&
1630 !options::produceAssignments() &&
1631 !options::checkModels() &&
1632 !options::unsatCores() &&
1633 (d_logic.isTheoryEnabled(THEORY_ARRAYS) && d_logic.isTheoryEnabled(THEORY_BV));
1634 Trace("smt") << "setting unconstrained simplification to " << uncSimp << endl;
1635 options::unconstrainedSimp.set(uncSimp);
1636 }
1637 // Unconstrained simp currently does *not* support model generation
1638 if (options::unconstrainedSimp.wasSetByUser() && options::unconstrainedSimp()) {
1639 if (options::produceModels()) {
1640 if (options::produceModels.wasSetByUser()) {
1641 throw OptionException("Cannot use unconstrained-simp with model generation.");
1642 }
1643 Notice() << "SmtEngine: turning off produce-models to support unconstrainedSimp" << endl;
1644 setOption("produce-models", SExpr("false"));
1645 }
1646 if (options::produceAssignments()) {
1647 if (options::produceAssignments.wasSetByUser()) {
1648 throw OptionException("Cannot use unconstrained-simp with model generation (produce-assignments).");
1649 }
1650 Notice() << "SmtEngine: turning off produce-assignments to support unconstrainedSimp" << endl;
1651 setOption("produce-assignments", SExpr("false"));
1652 }
1653 if (options::checkModels()) {
1654 if (options::checkModels.wasSetByUser()) {
1655 throw OptionException("Cannot use unconstrained-simp with model generation (check-models).");
1656 }
1657 Notice() << "SmtEngine: turning off check-models to support unconstrainedSimp" << endl;
1658 setOption("check-models", SExpr("false"));
1659 }
1660 }
1661
1662
1663 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER &&
1664 options::incrementalSolving()) {
1665 if (options::incrementalSolving.wasSetByUser()) {
1666 throw OptionException(std::string("Eager bit-blasting does not currently support incremental mode. \n\
1667 Try --bitblast=lazy"));
1668 }
1669 Notice() << "SmtEngine: turning off incremental to support eager bit-blasting" << endl;
1670 setOption("incremental", SExpr("false"));
1671 }
1672
1673 if (! options::bvEagerExplanations.wasSetByUser() &&
1674 d_logic.isTheoryEnabled(THEORY_ARRAYS) &&
1675 d_logic.isTheoryEnabled(THEORY_BV)) {
1676 Trace("smt") << "enabling eager bit-vector explanations " << endl;
1677 options::bvEagerExplanations.set(true);
1678 }
1679
1680 if( !options::bitvectorEqualitySolver() ){
1681 Trace("smt") << "disabling bvLazyRewriteExtf since equality solver is disabled" << endl;
1682 options::bvLazyRewriteExtf.set(false);
1683 }
1684
1685 // Turn on arith rewrite equalities only for pure arithmetic
1686 if(! options::arithRewriteEq.wasSetByUser()) {
1687 bool arithRewriteEq = d_logic.isPure(THEORY_ARITH) && d_logic.isLinear() && !d_logic.isQuantified();
1688 Trace("smt") << "setting arith rewrite equalities " << arithRewriteEq << endl;
1689 options::arithRewriteEq.set(arithRewriteEq);
1690 }
1691 if(! options::arithHeuristicPivots.wasSetByUser()) {
1692 int16_t heuristicPivots = 5;
1693 if(d_logic.isPure(THEORY_ARITH) && !d_logic.isQuantified()) {
1694 if(d_logic.isDifferenceLogic()) {
1695 heuristicPivots = -1;
1696 } else if(!d_logic.areIntegersUsed()) {
1697 heuristicPivots = 0;
1698 }
1699 }
1700 Trace("smt") << "setting arithHeuristicPivots " << heuristicPivots << endl;
1701 options::arithHeuristicPivots.set(heuristicPivots);
1702 }
1703 if(! options::arithPivotThreshold.wasSetByUser()){
1704 uint16_t pivotThreshold = 2;
1705 if(d_logic.isPure(THEORY_ARITH) && !d_logic.isQuantified()){
1706 if(d_logic.isDifferenceLogic()){
1707 pivotThreshold = 16;
1708 }
1709 }
1710 Trace("smt") << "setting arith arithPivotThreshold " << pivotThreshold << endl;
1711 options::arithPivotThreshold.set(pivotThreshold);
1712 }
1713 if(! options::arithStandardCheckVarOrderPivots.wasSetByUser()){
1714 int16_t varOrderPivots = -1;
1715 if(d_logic.isPure(THEORY_ARITH) && !d_logic.isQuantified()){
1716 varOrderPivots = 200;
1717 }
1718 Trace("smt") << "setting arithStandardCheckVarOrderPivots " << varOrderPivots << endl;
1719 options::arithStandardCheckVarOrderPivots.set(varOrderPivots);
1720 }
1721 // Turn off early theory preprocessing if arithRewriteEq is on
1722 if (options::arithRewriteEq()) {
1723 d_earlyTheoryPP = false;
1724 }
1725
1726 // Set decision mode based on logic (if not set by user)
1727 if(!options::decisionMode.wasSetByUser()) {
1728 decision::DecisionMode decMode =
1729 // ALL
1730 d_logic.hasEverything() ? decision::DECISION_STRATEGY_JUSTIFICATION :
1731 ( // QF_BV
1732 (not d_logic.isQuantified() &&
1733 d_logic.isPure(THEORY_BV)
1734 ) ||
1735 // QF_AUFBV or QF_ABV or QF_UFBV
1736 (not d_logic.isQuantified() &&
1737 (d_logic.isTheoryEnabled(THEORY_ARRAYS) ||
1738 d_logic.isTheoryEnabled(THEORY_UF)) &&
1739 d_logic.isTheoryEnabled(THEORY_BV)
1740 ) ||
1741 // QF_AUFLIA (and may be ends up enabling QF_AUFLRA?)
1742 (not d_logic.isQuantified() &&
1743 d_logic.isTheoryEnabled(THEORY_ARRAYS) &&
1744 d_logic.isTheoryEnabled(THEORY_UF) &&
1745 d_logic.isTheoryEnabled(THEORY_ARITH)
1746 ) ||
1747 // QF_LRA
1748 (not d_logic.isQuantified() &&
1749 d_logic.isPure(THEORY_ARITH) && d_logic.isLinear() && !d_logic.isDifferenceLogic() && !d_logic.areIntegersUsed()
1750 ) ||
1751 // Quantifiers
1752 d_logic.isQuantified() ||
1753 // Strings
1754 d_logic.isTheoryEnabled(THEORY_STRINGS)
1755 ? decision::DECISION_STRATEGY_JUSTIFICATION
1756 : decision::DECISION_STRATEGY_INTERNAL
1757 );
1758
1759 bool stoponly =
1760 // ALL
1761 d_logic.hasEverything() || d_logic.isTheoryEnabled(THEORY_STRINGS) ? false :
1762 ( // QF_AUFLIA
1763 (not d_logic.isQuantified() &&
1764 d_logic.isTheoryEnabled(THEORY_ARRAYS) &&
1765 d_logic.isTheoryEnabled(THEORY_UF) &&
1766 d_logic.isTheoryEnabled(THEORY_ARITH)
1767 ) ||
1768 // QF_LRA
1769 (not d_logic.isQuantified() &&
1770 d_logic.isPure(THEORY_ARITH) && d_logic.isLinear() && !d_logic.isDifferenceLogic() && !d_logic.areIntegersUsed()
1771 )
1772 ? true : false
1773 );
1774
1775 Trace("smt") << "setting decision mode to " << decMode << endl;
1776 options::decisionMode.set(decMode);
1777 options::decisionStopOnly.set(stoponly);
1778 }
1779 if( options::incrementalSolving() ){
1780 //disable modes not supported by incremental
1781 options::sortInference.set( false );
1782 options::ufssFairnessMonotone.set( false );
1783 options::quantEpr.set( false );
1784 options::globalNegate.set(false);
1785 }
1786 if( d_logic.hasCardinalityConstraints() ){
1787 //must have finite model finding on
1788 options::finiteModelFind.set( true );
1789 }
1790
1791 //if it contains a theory with non-termination, do not strictly enforce that quantifiers and theory combination must be interleaved
1792 if( d_logic.isTheoryEnabled(THEORY_STRINGS) || (d_logic.isTheoryEnabled(THEORY_ARITH) && !d_logic.isLinear()) ){
1793 if( !options::instWhenStrictInterleave.wasSetByUser() ){
1794 options::instWhenStrictInterleave.set( false );
1795 }
1796 }
1797
1798 //local theory extensions
1799 if( options::localTheoryExt() ){
1800 if( !options::instMaxLevel.wasSetByUser() ){
1801 options::instMaxLevel.set( 0 );
1802 }
1803 }
1804 if( options::instMaxLevel()!=-1 ){
1805 Notice() << "SmtEngine: turning off cbqi to support instMaxLevel" << endl;
1806 options::cbqi.set(false);
1807 }
1808 //track instantiations?
1809 if( options::cbqiNestedQE() || ( options::proof() && !options::trackInstLemmas.wasSetByUser() ) ){
1810 options::trackInstLemmas.set( true );
1811 }
1812
1813 if( ( options::fmfBoundLazy.wasSetByUser() && options::fmfBoundLazy() ) ||
1814 ( options::fmfBoundInt.wasSetByUser() && options::fmfBoundInt() ) ) {
1815 options::fmfBound.set( true );
1816 }
1817 //now have determined whether fmfBoundInt is on/off
1818 //apply fmfBoundInt options
1819 if( options::fmfBound() ){
1820 //must have finite model finding on
1821 options::finiteModelFind.set( true );
1822 if( ! options::mbqiMode.wasSetByUser() ||
1823 ( options::mbqiMode()!=quantifiers::MBQI_NONE &&
1824 options::mbqiMode()!=quantifiers::MBQI_FMC &&
1825 options::mbqiMode()!=quantifiers::MBQI_FMC_INTERVAL ) ){
1826 //if bounded integers are set, use no MBQI by default
1827 options::mbqiMode.set( quantifiers::MBQI_NONE );
1828 }
1829 if( ! options::prenexQuant.wasSetByUser() ){
1830 options::prenexQuant.set( quantifiers::PRENEX_QUANT_NONE );
1831 }
1832 }
1833 if( options::ufHo() ){
1834 //if higher-order, then current variants of model-based instantiation cannot be used
1835 if( options::mbqiMode()!=quantifiers::MBQI_NONE ){
1836 options::mbqiMode.set( quantifiers::MBQI_NONE );
1837 }
1838 }
1839 if( options::mbqiMode()==quantifiers::MBQI_ABS ){
1840 if( !d_logic.isPure(THEORY_UF) ){
1841 //MBQI_ABS is only supported in pure quantified UF
1842 options::mbqiMode.set( quantifiers::MBQI_FMC );
1843 }
1844 }
1845 if( options::ufssSymBreak() ){
1846 options::sortInference.set( true );
1847 }
1848 if( options::fmfFunWellDefinedRelevant() ){
1849 if( !options::fmfFunWellDefined.wasSetByUser() ){
1850 options::fmfFunWellDefined.set( true );
1851 }
1852 }
1853 if( options::fmfFunWellDefined() ){
1854 if( !options::finiteModelFind.wasSetByUser() ){
1855 options::finiteModelFind.set( true );
1856 }
1857 }
1858 //EPR
1859 if( options::quantEpr() ){
1860 if( !options::preSkolemQuant.wasSetByUser() ){
1861 options::preSkolemQuant.set( true );
1862 }
1863 }
1864
1865 //now, have determined whether finite model find is on/off
1866 //apply finite model finding options
1867 if( options::finiteModelFind() ){
1868 //apply conservative quantifiers splitting
1869 if( !options::quantDynamicSplit.wasSetByUser() ){
1870 options::quantDynamicSplit.set( quantifiers::QUANT_DSPLIT_MODE_DEFAULT );
1871 }
1872 //do not eliminate extended arithmetic symbols from quantified formulas
1873 if( !options::elimExtArithQuant.wasSetByUser() ){
1874 options::elimExtArithQuant.set( false );
1875 }
1876 if( !options::eMatching.wasSetByUser() ){
1877 options::eMatching.set( options::fmfInstEngine() );
1878 }
1879 if( !options::instWhenMode.wasSetByUser() ){
1880 //instantiate only on last call
1881 if( options::eMatching() ){
1882 options::instWhenMode.set( quantifiers::INST_WHEN_LAST_CALL );
1883 }
1884 }
1885 if( options::mbqiMode()==quantifiers::MBQI_ABS ){
1886 if( !options::preSkolemQuant.wasSetByUser() ){
1887 options::preSkolemQuant.set( true );
1888 }
1889 if( !options::preSkolemQuantNested.wasSetByUser() ){
1890 options::preSkolemQuantNested.set( true );
1891 }
1892 if( !options::fmfOneInstPerRound.wasSetByUser() ){
1893 options::fmfOneInstPerRound.set( true );
1894 }
1895 }
1896 }
1897
1898 //apply counterexample guided instantiation options
1899 // if we are attempting to rewrite everything to SyGuS, use ceGuidedInst
1900 if (options::sygusInference())
1901 {
1902 if (!options::ceGuidedInst.wasSetByUser())
1903 {
1904 options::ceGuidedInst.set(true);
1905 }
1906 // optimization: apply preskolemization, makes it succeed more often
1907 if (!options::preSkolemQuant.wasSetByUser())
1908 {
1909 options::preSkolemQuant.set(true);
1910 }
1911 if (!options::preSkolemQuantNested.wasSetByUser())
1912 {
1913 options::preSkolemQuantNested.set(true);
1914 }
1915 }
1916 if( options::cegqiSingleInvMode()!=quantifiers::CEGQI_SI_MODE_NONE ){
1917 if( !options::ceGuidedInst.wasSetByUser() ){
1918 options::ceGuidedInst.set( true );
1919 }
1920 }
1921 if( options::ceGuidedInst() ){
1922 //counterexample-guided instantiation for sygus
1923 if( !options::cegqiSingleInvMode.wasSetByUser() ){
1924 options::cegqiSingleInvMode.set( quantifiers::CEGQI_SI_MODE_USE );
1925 }
1926 if( !options::quantConflictFind.wasSetByUser() ){
1927 options::quantConflictFind.set( false );
1928 }
1929 if( !options::instNoEntail.wasSetByUser() ){
1930 options::instNoEntail.set( false );
1931 }
1932 if (options::sygusRew())
1933 {
1934 options::sygusRewSynth.set(true);
1935 options::sygusRewVerify.set(true);
1936 }
1937 if (options::sygusRewSynth() || options::sygusRewVerify())
1938 {
1939 // rewrite rule synthesis implies that sygus stream must be true
1940 options::sygusStream.set(true);
1941 }
1942 if (options::sygusStream())
1943 {
1944 // PBE and streaming modes are incompatible
1945 if (!options::sygusPbe.wasSetByUser())
1946 {
1947 options::sygusPbe.set(false);
1948 }
1949 }
1950 //do not allow partial functions
1951 if( !options::bitvectorDivByZeroConst.wasSetByUser() ){
1952 options::bitvectorDivByZeroConst.set( true );
1953 }
1954 if( !options::dtRewriteErrorSel.wasSetByUser() ){
1955 options::dtRewriteErrorSel.set( true );
1956 }
1957 //do not miniscope
1958 if( !options::miniscopeQuant.wasSetByUser() ){
1959 options::miniscopeQuant.set( false );
1960 }
1961 if( !options::miniscopeQuantFreeVar.wasSetByUser() ){
1962 options::miniscopeQuantFreeVar.set( false );
1963 }
1964 //rewrite divk
1965 if( !options::rewriteDivk.wasSetByUser()) {
1966 options::rewriteDivk.set( true );
1967 }
1968 //do not do macros
1969 if( !options::macrosQuant.wasSetByUser()) {
1970 options::macrosQuant.set( false );
1971 }
1972 if( !options::cbqiPreRegInst.wasSetByUser()) {
1973 options::cbqiPreRegInst.set( true );
1974 }
1975 }
1976 //counterexample-guided instantiation for non-sygus
1977 // enable if any possible quantifiers with arithmetic, datatypes or bitvectors
1978 if( d_logic.isQuantified() &&
1979 ( ( options::decisionMode()!=decision::DECISION_STRATEGY_INTERNAL &&
1980 ( d_logic.isTheoryEnabled(THEORY_ARITH) || d_logic.isTheoryEnabled(THEORY_DATATYPES) || d_logic.isTheoryEnabled(THEORY_BV) ) ) ||
1981 d_logic.isPure(THEORY_ARITH) || d_logic.isPure(THEORY_BV) ||
1982 options::cbqiAll() ) ){
1983 if( !options::cbqi.wasSetByUser() ){
1984 options::cbqi.set( true );
1985 }
1986 // check whether we should apply full cbqi
1987 if (d_logic.isPure(THEORY_BV))
1988 {
1989 if (!options::cbqiFullEffort.wasSetByUser())
1990 {
1991 options::cbqiFullEffort.set(true);
1992 }
1993 }
1994 }
1995 if( options::cbqi() ){
1996 //must rewrite divk
1997 if( !options::rewriteDivk.wasSetByUser()) {
1998 options::rewriteDivk.set( true );
1999 }
2000 if (d_logic.isPure(THEORY_ARITH) || d_logic.isPure(THEORY_BV))
2001 {
2002 options::cbqiAll.set( false );
2003 if( !options::quantConflictFind.wasSetByUser() ){
2004 options::quantConflictFind.set( false );
2005 }
2006 if( !options::instNoEntail.wasSetByUser() ){
2007 options::instNoEntail.set( false );
2008 }
2009 if( !options::instWhenMode.wasSetByUser() && options::cbqiModel() ){
2010 //only instantiation should happen at last call when model is avaiable
2011 options::instWhenMode.set( quantifiers::INST_WHEN_LAST_CALL );
2012 }
2013 }else{
2014 // only supported in pure arithmetic or pure BV
2015 options::cbqiNestedQE.set(false);
2016 }
2017 // prenexing
2018 if (options::cbqiNestedQE()
2019 || options::decisionMode() == decision::DECISION_STRATEGY_INTERNAL)
2020 {
2021 // only complete with prenex = disj_normal or normal
2022 if (options::prenexQuant() <= quantifiers::PRENEX_QUANT_DISJ_NORMAL)
2023 {
2024 options::prenexQuant.set(quantifiers::PRENEX_QUANT_DISJ_NORMAL);
2025 }
2026 }
2027 else if (options::globalNegate())
2028 {
2029 if (!options::prenexQuant.wasSetByUser())
2030 {
2031 options::prenexQuant.set(quantifiers::PRENEX_QUANT_NONE);
2032 }
2033 }
2034 }
2035 //implied options...
2036 if( options::strictTriggers() ){
2037 if( !options::userPatternsQuant.wasSetByUser() ){
2038 options::userPatternsQuant.set( quantifiers::USER_PAT_MODE_TRUST );
2039 }
2040 }
2041 if( options::qcfMode.wasSetByUser() || options::qcfTConstraint() ){
2042 options::quantConflictFind.set( true );
2043 }
2044 if( options::cbqiNestedQE() ){
2045 options::prenexQuantUser.set( true );
2046 if( !options::preSkolemQuant.wasSetByUser() ){
2047 options::preSkolemQuant.set( true );
2048 }
2049 }
2050 //for induction techniques
2051 if( options::quantInduction() ){
2052 if( !options::dtStcInduction.wasSetByUser() ){
2053 options::dtStcInduction.set( true );
2054 }
2055 if( !options::intWfInduction.wasSetByUser() ){
2056 options::intWfInduction.set( true );
2057 }
2058 }
2059 if( options::dtStcInduction() ){
2060 //leads to unfairness FIXME
2061 if( !options::dtForceAssignment.wasSetByUser() ){
2062 options::dtForceAssignment.set( true );
2063 }
2064 //try to remove ITEs from quantified formulas
2065 if( !options::iteDtTesterSplitQuant.wasSetByUser() ){
2066 options::iteDtTesterSplitQuant.set( true );
2067 }
2068 if( !options::iteLiftQuant.wasSetByUser() ){
2069 options::iteLiftQuant.set( quantifiers::ITE_LIFT_QUANT_MODE_ALL );
2070 }
2071 }
2072 if( options::intWfInduction() ){
2073 if( !options::purifyTriggers.wasSetByUser() ){
2074 options::purifyTriggers.set( true );
2075 }
2076 }
2077 if( options::conjectureNoFilter() ){
2078 if( !options::conjectureFilterActiveTerms.wasSetByUser() ){
2079 options::conjectureFilterActiveTerms.set( false );
2080 }
2081 if( !options::conjectureFilterCanonical.wasSetByUser() ){
2082 options::conjectureFilterCanonical.set( false );
2083 }
2084 if( !options::conjectureFilterModel.wasSetByUser() ){
2085 options::conjectureFilterModel.set( false );
2086 }
2087 }
2088 if( options::conjectureGenPerRound.wasSetByUser() ){
2089 if( options::conjectureGenPerRound()>0 ){
2090 options::conjectureGen.set( true );
2091 }else{
2092 options::conjectureGen.set( false );
2093 }
2094 }
2095 //can't pre-skolemize nested quantifiers without UF theory
2096 if( !d_logic.isTheoryEnabled(THEORY_UF) && options::preSkolemQuant() ){
2097 if( !options::preSkolemQuantNested.wasSetByUser() ){
2098 options::preSkolemQuantNested.set( false );
2099 }
2100 }
2101 if( !d_logic.isTheoryEnabled(THEORY_DATATYPES) ){
2102 options::quantDynamicSplit.set( quantifiers::QUANT_DSPLIT_MODE_NONE );
2103 }
2104
2105 //until bugs 371,431 are fixed
2106 if( ! options::minisatUseElim.wasSetByUser()){
2107 //AJR: cannot use minisat elim for new implementation of sets TODO: why?
2108 if( d_logic.isTheoryEnabled(THEORY_SETS) || d_logic.isQuantified() || options::produceModels() || options::produceAssignments() || options::checkModels() ){
2109 options::minisatUseElim.set( false );
2110 }
2111 }
2112 else if (options::minisatUseElim()) {
2113 if (options::produceModels()) {
2114 Notice() << "SmtEngine: turning off produce-models to support minisatUseElim" << endl;
2115 setOption("produce-models", SExpr("false"));
2116 }
2117 if (options::produceAssignments()) {
2118 Notice() << "SmtEngine: turning off produce-assignments to support minisatUseElim" << endl;
2119 setOption("produce-assignments", SExpr("false"));
2120 }
2121 if (options::checkModels()) {
2122 Notice() << "SmtEngine: turning off check-models to support minisatUseElim" << endl;
2123 setOption("check-models", SExpr("false"));
2124 }
2125 }
2126
2127 // For now, these array theory optimizations do not support model-building
2128 if (options::produceModels() || options::produceAssignments() || options::checkModels()) {
2129 options::arraysOptimizeLinear.set(false);
2130 options::arraysLazyRIntro1.set(false);
2131 }
2132
2133 // Non-linear arithmetic does not support models unless nlExt is enabled
2134 if ((d_logic.isTheoryEnabled(THEORY_ARITH) && !d_logic.isLinear()
2135 && !options::nlExt())
2136 || options::globalNegate())
2137 {
2138 std::string reason =
2139 options::globalNegate() ? "--global-negate" : "nonlinear arithmetic";
2140 if (options::produceModels()) {
2141 if(options::produceModels.wasSetByUser()) {
2142 throw OptionException(
2143 std::string("produce-model not supported with " + reason));
2144 }
2145 Warning()
2146 << "SmtEngine: turning off produce-models because unsupported for "
2147 << reason << endl;
2148 setOption("produce-models", SExpr("false"));
2149 }
2150 if (options::produceAssignments()) {
2151 if(options::produceAssignments.wasSetByUser()) {
2152 throw OptionException(
2153 std::string("produce-assignments not supported with " + reason));
2154 }
2155 Warning() << "SmtEngine: turning off produce-assignments because "
2156 "unsupported for "
2157 << reason << endl;
2158 setOption("produce-assignments", SExpr("false"));
2159 }
2160 if (options::checkModels()) {
2161 if(options::checkModels.wasSetByUser()) {
2162 throw OptionException(
2163 std::string("check-models not supported with " + reason));
2164 }
2165 Warning()
2166 << "SmtEngine: turning off check-models because unsupported for "
2167 << reason << endl;
2168 setOption("check-models", SExpr("false"));
2169 }
2170 }
2171
2172 if(options::incrementalSolving() && options::proof()) {
2173 Warning() << "SmtEngine: turning off incremental solving mode (not yet supported with --proof, try --tear-down-incremental instead)" << endl;
2174 setOption("incremental", SExpr("false"));
2175 }
2176 }
2177
2178 void SmtEngine::setProblemExtended(bool value)
2179 {
2180 d_problemExtended = value;
2181 if (value) { d_assumptions.clear(); }
2182 }
2183
2184 void SmtEngine::setInfo(const std::string& key, const CVC4::SExpr& value)
2185 {
2186 SmtScope smts(this);
2187
2188 Trace("smt") << "SMT setInfo(" << key << ", " << value << ")" << endl;
2189
2190 if(Dump.isOn("benchmark")) {
2191 if(key == "status") {
2192 string s = value.getValue();
2193 BenchmarkStatus status =
2194 (s == "sat") ? SMT_SATISFIABLE :
2195 ((s == "unsat") ? SMT_UNSATISFIABLE : SMT_UNKNOWN);
2196 Dump("benchmark") << SetBenchmarkStatusCommand(status);
2197 } else {
2198 Dump("benchmark") << SetInfoCommand(key, value);
2199 }
2200 }
2201
2202 // Check for CVC4-specific info keys (prefixed with "cvc4-" or "cvc4_")
2203 if(key.length() > 5) {
2204 string prefix = key.substr(0, 5);
2205 if(prefix == "cvc4-" || prefix == "cvc4_") {
2206 string cvc4key = key.substr(5);
2207 if(cvc4key == "logic") {
2208 if(! value.isAtom()) {
2209 throw OptionException("argument to (set-info :cvc4-logic ..) must be a string");
2210 }
2211 SmtScope smts(this);
2212 d_logic = value.getValue();
2213 setLogicInternal();
2214 return;
2215 } else {
2216 throw UnrecognizedOptionException();
2217 }
2218 }
2219 }
2220
2221 // Check for standard info keys (SMT-LIB v1, SMT-LIB v2, ...)
2222 if(key == "source" ||
2223 key == "category" ||
2224 key == "difficulty" ||
2225 key == "notes") {
2226 // ignore these
2227 return;
2228 } else if(key == "name") {
2229 d_filename = value.getValue();
2230 return;
2231 } else if(key == "smt-lib-version") {
2232 if( (value.isInteger() && value.getIntegerValue() == Integer(2)) ||
2233 (value.isRational() && value.getRationalValue() == Rational(2)) ||
2234 value.getValue() == "2" ||
2235 value.getValue() == "2.0" ) {
2236 options::inputLanguage.set(language::input::LANG_SMTLIB_V2_0);
2237
2238 // supported SMT-LIB version
2239 if(!options::outputLanguage.wasSetByUser() &&
2240 ( options::outputLanguage() == language::output::LANG_SMTLIB_V2_5 || options::outputLanguage() == language::output::LANG_SMTLIB_V2_6 )) {
2241 options::outputLanguage.set(language::output::LANG_SMTLIB_V2_0);
2242 *options::out() << language::SetLanguage(language::output::LANG_SMTLIB_V2_0);
2243 }
2244 return;
2245 } else if( (value.isRational() && value.getRationalValue() == Rational(5, 2)) ||
2246 value.getValue() == "2.5" ) {
2247 options::inputLanguage.set(language::input::LANG_SMTLIB_V2_5);
2248
2249 // supported SMT-LIB version
2250 if(!options::outputLanguage.wasSetByUser() &&
2251 options::outputLanguage() == language::output::LANG_SMTLIB_V2_0) {
2252 options::outputLanguage.set(language::output::LANG_SMTLIB_V2_5);
2253 *options::out() << language::SetLanguage(language::output::LANG_SMTLIB_V2_5);
2254 }
2255 return;
2256 } else if( (value.isRational() && value.getRationalValue() == Rational(13, 5)) ||
2257 value.getValue() == "2.6" ) {
2258 options::inputLanguage.set(language::input::LANG_SMTLIB_V2_6);
2259
2260 // supported SMT-LIB version
2261 if(!options::outputLanguage.wasSetByUser() &&
2262 options::outputLanguage() == language::output::LANG_SMTLIB_V2_0) {
2263 options::outputLanguage.set(language::output::LANG_SMTLIB_V2_6);
2264 *options::out() << language::SetLanguage(language::output::LANG_SMTLIB_V2_6);
2265 }
2266 return;
2267 }
2268 Warning() << "Warning: unsupported smt-lib-version: " << value << endl;
2269 throw UnrecognizedOptionException();
2270 } else if(key == "status") {
2271 string s;
2272 if(value.isAtom()) {
2273 s = value.getValue();
2274 }
2275 if(s != "sat" && s != "unsat" && s != "unknown") {
2276 throw OptionException("argument to (set-info :status ..) must be "
2277 "`sat' or `unsat' or `unknown'");
2278 }
2279 d_status = Result(s, d_filename);
2280 return;
2281 }
2282 throw UnrecognizedOptionException();
2283 }
2284
2285 CVC4::SExpr SmtEngine::getInfo(const std::string& key) const {
2286
2287 SmtScope smts(this);
2288
2289 Trace("smt") << "SMT getInfo(" << key << ")" << endl;
2290 if(key == "all-statistics") {
2291 vector<SExpr> stats;
2292 for(StatisticsRegistry::const_iterator i = NodeManager::fromExprManager(d_exprManager)->getStatisticsRegistry()->begin();
2293 i != NodeManager::fromExprManager(d_exprManager)->getStatisticsRegistry()->end();
2294 ++i) {
2295 vector<SExpr> v;
2296 v.push_back((*i).first);
2297 v.push_back((*i).second);
2298 stats.push_back(v);
2299 }
2300 for(StatisticsRegistry::const_iterator i = d_statisticsRegistry->begin();
2301 i != d_statisticsRegistry->end();
2302 ++i) {
2303 vector<SExpr> v;
2304 v.push_back((*i).first);
2305 v.push_back((*i).second);
2306 stats.push_back(v);
2307 }
2308 return SExpr(stats);
2309 } else if(key == "error-behavior") {
2310 // immediate-exit | continued-execution
2311 if( options::continuedExecution() || options::interactive() ) {
2312 return SExpr(SExpr::Keyword("continued-execution"));
2313 } else {
2314 return SExpr(SExpr::Keyword("immediate-exit"));
2315 }
2316 } else if(key == "name") {
2317 return SExpr(Configuration::getName());
2318 } else if(key == "version") {
2319 return SExpr(Configuration::getVersionString());
2320 } else if(key == "authors") {
2321 return SExpr(Configuration::about());
2322 } else if(key == "status") {
2323 // sat | unsat | unknown
2324 switch(d_status.asSatisfiabilityResult().isSat()) {
2325 case Result::SAT:
2326 return SExpr(SExpr::Keyword("sat"));
2327 case Result::UNSAT:
2328 return SExpr(SExpr::Keyword("unsat"));
2329 default:
2330 return SExpr(SExpr::Keyword("unknown"));
2331 }
2332 } else if(key == "reason-unknown") {
2333 if(!d_status.isNull() && d_status.isUnknown()) {
2334 stringstream ss;
2335 ss << d_status.whyUnknown();
2336 string s = ss.str();
2337 transform(s.begin(), s.end(), s.begin(), ::tolower);
2338 return SExpr(SExpr::Keyword(s));
2339 } else {
2340 throw ModalException("Can't get-info :reason-unknown when the "
2341 "last result wasn't unknown!");
2342 }
2343 } else if(key == "assertion-stack-levels") {
2344 AlwaysAssert(d_userLevels.size() <=
2345 std::numeric_limits<unsigned long int>::max());
2346 return SExpr(static_cast<unsigned long int>(d_userLevels.size()));
2347 } else if(key == "all-options") {
2348 // get the options, like all-statistics
2349 std::vector< std::vector<std::string> > current_options =
2350 Options::current()->getOptions();
2351 return SExpr::parseListOfListOfAtoms(current_options);
2352 } else {
2353 throw UnrecognizedOptionException();
2354 }
2355 }
2356
2357 void SmtEngine::debugCheckFormals(const std::vector<Expr>& formals, Expr func)
2358 {
2359 for(std::vector<Expr>::const_iterator i = formals.begin(); i != formals.end(); ++i) {
2360 if((*i).getKind() != kind::BOUND_VARIABLE) {
2361 stringstream ss;
2362 ss << "All formal arguments to defined functions must be BOUND_VARIABLEs, but in the\n"
2363 << "definition of function " << func << ", formal\n"
2364 << " " << *i << "\n"
2365 << "has kind " << (*i).getKind();
2366 throw TypeCheckingException(func, ss.str());
2367 }
2368 }
2369 }
2370
2371 void SmtEngine::debugCheckFunctionBody(Expr formula,
2372 const std::vector<Expr>& formals,
2373 Expr func)
2374 {
2375 Type formulaType = formula.getType(options::typeChecking());
2376 Type funcType = func.getType();
2377 // We distinguish here between definitions of constants and functions,
2378 // because the type checking for them is subtly different. Perhaps we
2379 // should instead have SmtEngine::defineFunction() and
2380 // SmtEngine::defineConstant() for better clarity, although then that
2381 // doesn't match the SMT-LIBv2 standard...
2382 if(formals.size() > 0) {
2383 Type rangeType = FunctionType(funcType).getRangeType();
2384 if(! formulaType.isComparableTo(rangeType)) {
2385 stringstream ss;
2386 ss << "Type of defined function does not match its declaration\n"
2387 << "The function : " << func << "\n"
2388 << "Declared type : " << rangeType << "\n"
2389 << "The body : " << formula << "\n"
2390 << "Body type : " << formulaType;
2391 throw TypeCheckingException(func, ss.str());
2392 }
2393 } else {
2394 if(! formulaType.isComparableTo(funcType)) {
2395 stringstream ss;
2396 ss << "Declared type of defined constant does not match its definition\n"
2397 << "The constant : " << func << "\n"
2398 << "Declared type : " << funcType << " " << Type::getTypeNode(funcType)->getId() << "\n"
2399 << "The definition : " << formula << "\n"
2400 << "Definition type: " << formulaType << " " << Type::getTypeNode(formulaType)->getId();
2401 throw TypeCheckingException(func, ss.str());
2402 }
2403 }
2404 }
2405
2406 void SmtEngine::defineFunction(Expr func,
2407 const std::vector<Expr>& formals,
2408 Expr formula)
2409 {
2410 SmtScope smts(this);
2411 doPendingPops();
2412 Trace("smt") << "SMT defineFunction(" << func << ")" << endl;
2413 debugCheckFormals(formals, func);
2414
2415 stringstream ss;
2416 ss << language::SetLanguage(
2417 language::SetLanguage::getLanguage(Dump.getStream()))
2418 << func;
2419 DefineFunctionCommand c(ss.str(), func, formals, formula);
2420 addToModelCommandAndDump(
2421 c, ExprManager::VAR_FLAG_DEFINED, true, "declarations");
2422
2423 PROOF(if (options::checkUnsatCores()) {
2424 d_defineCommands.push_back(c.clone());
2425 });
2426
2427 // type check body
2428 debugCheckFunctionBody(formula, formals, func);
2429
2430 // Substitute out any abstract values in formula
2431 Expr form =
2432 d_private->substituteAbstractValues(Node::fromExpr(formula)).toExpr();
2433
2434 TNode funcNode = func.getTNode();
2435 vector<Node> formalsNodes;
2436 for(vector<Expr>::const_iterator i = formals.begin(),
2437 iend = formals.end();
2438 i != iend;
2439 ++i) {
2440 formalsNodes.push_back((*i).getNode());
2441 }
2442 TNode formNode = form.getTNode();
2443 DefinedFunction def(funcNode, formalsNodes, formNode);
2444 // Permit (check-sat) (define-fun ...) (get-value ...) sequences.
2445 // Otherwise, (check-sat) (get-value ((! foo :named bar))) breaks
2446 // d_haveAdditions = true;
2447 Debug("smt") << "definedFunctions insert " << funcNode << " " << formNode << endl;
2448 d_definedFunctions->insert(funcNode, def);
2449 }
2450
2451 void SmtEngine::defineFunctionsRec(
2452 const std::vector<Expr>& funcs,
2453 const std::vector<std::vector<Expr> >& formals,
2454 const std::vector<Expr>& formulas)
2455 {
2456 SmtScope smts(this);
2457 finalOptionsAreSet();
2458 doPendingPops();
2459 Trace("smt") << "SMT defineFunctionsRec(...)" << endl;
2460
2461 if (funcs.size() != formals.size() && funcs.size() != formulas.size())
2462 {
2463 stringstream ss;
2464 ss << "Number of functions, formals, and function bodies passed to "
2465 "defineFunctionsRec do not match:"
2466 << "\n"
2467 << " #functions : " << funcs.size() << "\n"
2468 << " #arg lists : " << formals.size() << "\n"
2469 << " #function bodies : " << formulas.size() << "\n";
2470 throw ModalException(ss.str());
2471 }
2472 for (unsigned i = 0, size = funcs.size(); i < size; i++)
2473 {
2474 // check formal argument list
2475 debugCheckFormals(formals[i], funcs[i]);
2476 // type check body
2477 debugCheckFunctionBody(formulas[i], formals[i], funcs[i]);
2478 }
2479
2480 if (Dump.isOn("raw-benchmark"))
2481 {
2482 Dump("raw-benchmark") << DefineFunctionRecCommand(funcs, formals, formulas);
2483 }
2484
2485 ExprManager* em = getExprManager();
2486 for (unsigned i = 0, size = funcs.size(); i < size; i++)
2487 {
2488 // we assert a quantified formula
2489 Expr func_app;
2490 // make the function application
2491 if (formals[i].empty())
2492 {
2493 // it has no arguments
2494 func_app = funcs[i];
2495 }
2496 else
2497 {
2498 std::vector<Expr> children;
2499 children.push_back(funcs[i]);
2500 children.insert(children.end(), formals[i].begin(), formals[i].end());
2501 func_app = em->mkExpr(kind::APPLY_UF, children);
2502 }
2503 Expr lem = em->mkExpr(kind::EQUAL, func_app, formulas[i]);
2504 if (!formals[i].empty())
2505 {
2506 // set the attribute to denote this is a function definition
2507 std::string attr_name("fun-def");
2508 Expr aexpr = em->mkExpr(kind::INST_ATTRIBUTE, func_app);
2509 aexpr = em->mkExpr(kind::INST_PATTERN_LIST, aexpr);
2510 std::vector<Expr> expr_values;
2511 std::string str_value;
2512 setUserAttribute(attr_name, func_app, expr_values, str_value);
2513 // make the quantified formula
2514 Expr boundVars = em->mkExpr(kind::BOUND_VAR_LIST, formals[i]);
2515 lem = em->mkExpr(kind::FORALL, boundVars, lem, aexpr);
2516 }
2517 // assert the quantified formula
2518 // notice we don't call assertFormula directly, since this would
2519 // duplicate the output on raw-benchmark.
2520 Expr e = d_private->substituteAbstractValues(Node::fromExpr(lem)).toExpr();
2521 if (d_assertionList != NULL)
2522 {
2523 d_assertionList->push_back(e);
2524 }
2525 d_private->addFormula(e.getNode(), false);
2526 }
2527 }
2528
2529 void SmtEngine::defineFunctionRec(Expr func,
2530 const std::vector<Expr>& formals,
2531 Expr formula)
2532 {
2533 std::vector<Expr> funcs;
2534 funcs.push_back(func);
2535 std::vector<std::vector<Expr> > formals_multi;
2536 formals_multi.push_back(formals);
2537 std::vector<Expr> formulas;
2538 formulas.push_back(formula);
2539 defineFunctionsRec(funcs, formals_multi, formulas);
2540 }
2541
2542 bool SmtEngine::isDefinedFunction( Expr func ){
2543 Node nf = Node::fromExpr( func );
2544 Debug("smt") << "isDefined function " << nf << "?" << std::endl;
2545 return d_definedFunctions->find(nf) != d_definedFunctions->end();
2546 }
2547
2548 void SmtEnginePrivate::finishInit() {
2549 d_preprocessingPassContext.reset(new PreprocessingPassContext(&d_smt));
2550 // TODO: register passes here (this will likely change when we add support for
2551 // actually assembling preprocessing pipelines).
2552 std::unique_ptr<BVGauss> bvGauss(new BVGauss(d_preprocessingPassContext.get()));
2553 std::unique_ptr<IntToBV> intToBV(new IntToBV(d_preprocessingPassContext.get()));
2554 std::unique_ptr<PseudoBooleanProcessor> pbProc(
2555 new PseudoBooleanProcessor(d_preprocessingPassContext.get()));
2556
2557 d_preprocessingPassRegistry.registerPass("bv-gauss", std::move(bvGauss));
2558 d_preprocessingPassRegistry.registerPass("int-to-bv", std::move(intToBV));
2559 d_preprocessingPassRegistry.registerPass("pseudo-boolean-processor",
2560 std::move(pbProc));
2561 }
2562
2563 Node SmtEnginePrivate::expandDefinitions(TNode n, unordered_map<Node, Node, NodeHashFunction>& cache, bool expandOnly)
2564 {
2565 stack< triple<Node, Node, bool> > worklist;
2566 stack<Node> result;
2567 worklist.push(make_triple(Node(n), Node(n), false));
2568 // The worklist is made of triples, each is input / original node then the output / rewritten node
2569 // and finally a flag tracking whether the children have been explored (i.e. if this is a downward
2570 // or upward pass).
2571
2572 do {
2573 spendResource(options::preprocessStep());
2574 n = worklist.top().first; // n is the input / original
2575 Node node = worklist.top().second; // node is the output / result
2576 bool childrenPushed = worklist.top().third;
2577 worklist.pop();
2578
2579 // Working downwards
2580 if(!childrenPushed) {
2581 Kind k = n.getKind();
2582
2583 // we can short circuit (variable) leaves
2584 if(n.isVar()) {
2585 SmtEngine::DefinedFunctionMap::const_iterator i = d_smt.d_definedFunctions->find(n);
2586 if(i != d_smt.d_definedFunctions->end()) {
2587 // replacement must be closed
2588 if((*i).second.getFormals().size() > 0) {
2589 result.push(d_smt.d_nodeManager->mkNode(kind::LAMBDA, d_smt.d_nodeManager->mkNode(kind::BOUND_VAR_LIST, (*i).second.getFormals()), (*i).second.getFormula()));
2590 continue;
2591 }
2592 // don't bother putting in the cache
2593 result.push((*i).second.getFormula());
2594 continue;
2595 }
2596 // don't bother putting in the cache
2597 result.push(n);
2598 continue;
2599 }
2600
2601 // maybe it's in the cache
2602 unordered_map<Node, Node, NodeHashFunction>::iterator cacheHit = cache.find(n);
2603 if(cacheHit != cache.end()) {
2604 TNode ret = (*cacheHit).second;
2605 result.push(ret.isNull() ? n : ret);
2606 continue;
2607 }
2608
2609 // otherwise expand it
2610 bool doExpand = k == kind::APPLY;
2611 if( !doExpand ){
2612 if( options::macrosQuant() ){
2613 //expand if we have inferred an operator corresponds to a defined function
2614 doExpand = k==kind::APPLY_UF && d_smt.isDefinedFunction( n.getOperator().toExpr() );
2615 }
2616 }
2617 if (doExpand) {
2618 vector<Node> formals;
2619 TNode fm;
2620 if( n.getOperator().getKind() == kind::LAMBDA ){
2621 TNode op = n.getOperator();
2622 // lambda
2623 for( unsigned i=0; i<op[0].getNumChildren(); i++ ){
2624 formals.push_back( op[0][i] );
2625 }
2626 fm = op[1];
2627 }else{
2628 // application of a user-defined symbol
2629 TNode func = n.getOperator();
2630 SmtEngine::DefinedFunctionMap::const_iterator i = d_smt.d_definedFunctions->find(func);
2631 if(i == d_smt.d_definedFunctions->end()) {
2632 throw TypeCheckingException(n.toExpr(), string("Undefined function: `") + func.toString() + "'");
2633 }
2634 DefinedFunction def = (*i).second;
2635 formals = def.getFormals();
2636
2637 if(Debug.isOn("expand")) {
2638 Debug("expand") << "found: " << n << endl;
2639 Debug("expand") << " func: " << func << endl;
2640 string name = func.getAttribute(expr::VarNameAttr());
2641 Debug("expand") << " : \"" << name << "\"" << endl;
2642 }
2643 if(Debug.isOn("expand")) {
2644 Debug("expand") << " defn: " << def.getFunction() << endl
2645 << " [";
2646 if(formals.size() > 0) {
2647 copy( formals.begin(), formals.end() - 1,
2648 ostream_iterator<Node>(Debug("expand"), ", ") );
2649 Debug("expand") << formals.back();
2650 }
2651 Debug("expand") << "]" << endl
2652 << " " << def.getFunction().getType() << endl
2653 << " " << def.getFormula() << endl;
2654 }
2655
2656 fm = def.getFormula();
2657 }
2658
2659 Node instance = fm.substitute(formals.begin(),
2660 formals.end(),
2661 n.begin(),
2662 n.begin() + formals.size());
2663 Debug("expand") << "made : " << instance << endl;
2664
2665 Node expanded = expandDefinitions(instance, cache, expandOnly);
2666 cache[n] = (n == expanded ? Node::null() : expanded);
2667 result.push(expanded);
2668 continue;
2669
2670 } else if(! expandOnly) {
2671 // do not do any theory stuff if expandOnly is true
2672
2673 theory::Theory* t = d_smt.d_theoryEngine->theoryOf(node);
2674
2675 Assert(t != NULL);
2676 LogicRequest req(d_smt);
2677 node = t->expandDefinition(req, n);
2678 }
2679
2680 // the partial functions can fall through, in which case we still
2681 // consider their children
2682 worklist.push(make_triple(Node(n), node, true)); // Original and rewritten result
2683
2684 for(size_t i = 0; i < node.getNumChildren(); ++i) {
2685 worklist.push(make_triple(node[i], node[i], false)); // Rewrite the children of the result only
2686 }
2687
2688 } else {
2689 // Working upwards
2690 // Reconstruct the node from it's (now rewritten) children on the stack
2691
2692 Debug("expand") << "cons : " << node << endl;
2693 if(node.getNumChildren()>0) {
2694 //cout << "cons : " << node << endl;
2695 NodeBuilder<> nb(node.getKind());
2696 if(node.getMetaKind() == kind::metakind::PARAMETERIZED) {
2697 Debug("expand") << "op : " << node.getOperator() << endl;
2698 //cout << "op : " << node.getOperator() << endl;
2699 nb << node.getOperator();
2700 }
2701 for(size_t i = 0; i < node.getNumChildren(); ++i) {
2702 Assert(!result.empty());
2703 Node expanded = result.top();
2704 result.pop();
2705 //cout << "exchld : " << expanded << endl;
2706 Debug("expand") << "exchld : " << expanded << endl;
2707 nb << expanded;
2708 }
2709 node = nb;
2710 }
2711 cache[n] = n == node ? Node::null() : node; // Only cache once all subterms are expanded
2712 result.push(node);
2713 }
2714 } while(!worklist.empty());
2715
2716 AlwaysAssert(result.size() == 1);
2717
2718 return result.top();
2719 }
2720
2721 typedef std::unordered_map<Node, Node, NodeHashFunction> NodeMap;
2722
2723 Node SmtEnginePrivate::realToInt(TNode n, NodeMap& cache, std::vector< Node >& var_eq) {
2724 Trace("real-as-int-debug") << "Convert : " << n << std::endl;
2725 NodeMap::iterator find = cache.find(n);
2726 if (find != cache.end()) {
2727 return (*find).second;
2728 }else{
2729 Node ret = n;
2730 if( n.getNumChildren()>0 ){
2731 if( n.getKind()==kind::EQUAL || n.getKind()==kind::GEQ || n.getKind()==kind::LT || n.getKind()==kind::GT || n.getKind()==kind::LEQ ){
2732 ret = Rewriter::rewrite( n );
2733 Trace("real-as-int-debug") << "Now looking at : " << ret << std::endl;
2734 if( !ret.isConst() ){
2735 Node ret_lit = ret.getKind()==kind::NOT ? ret[0] : ret;
2736 bool ret_pol = ret.getKind()!=kind::NOT;
2737 std::map< Node, Node > msum;
2738 if (ArithMSum::getMonomialSumLit(ret_lit, msum))
2739 {
2740 //get common coefficient
2741 std::vector< Node > coeffs;
2742 for( std::map< Node, Node >::iterator itm = msum.begin(); itm != msum.end(); ++itm ){
2743 Node v = itm->first;
2744 Node c = itm->second;
2745 if( !c.isNull() ){
2746 Assert( c.isConst() );
2747 coeffs.push_back( NodeManager::currentNM()->mkConst( Rational( c.getConst<Rational>().getDenominator() ) ) );
2748 }
2749 }
2750 Node cc = coeffs.empty() ? Node::null() : ( coeffs.size()==1 ? coeffs[0] : Rewriter::rewrite( NodeManager::currentNM()->mkNode( kind::MULT, coeffs ) ) );
2751 std::vector< Node > sum;
2752 for( std::map< Node, Node >::iterator itm = msum.begin(); itm != msum.end(); ++itm ){
2753 Node v = itm->first;
2754 Node c = itm->second;
2755 Node s;
2756 if( c.isNull() ){
2757 c = cc.isNull() ? NodeManager::currentNM()->mkConst( Rational( 1 ) ) : cc;
2758 }else{
2759 if( !cc.isNull() ){
2760 c = Rewriter::rewrite( NodeManager::currentNM()->mkNode( kind::MULT, c, cc ) );
2761 }
2762 }
2763 Assert( c.getType().isInteger() );
2764 if( v.isNull() ){
2765 sum.push_back( c );
2766 }else{
2767 Node vv = realToInt( v, cache, var_eq );
2768 if( vv.getType().isInteger() ){
2769 sum.push_back( NodeManager::currentNM()->mkNode( kind::MULT, c, vv ) );
2770 }else{
2771 throw TypeCheckingException(v.toExpr(), string("Cannot translate to Int: ") + v.toString());
2772 }
2773 }
2774 }
2775 Node sumt = sum.empty() ? NodeManager::currentNM()->mkConst( Rational( 0 ) ) : ( sum.size()==1 ? sum[0] : NodeManager::currentNM()->mkNode( kind::PLUS, sum ) );
2776 ret = NodeManager::currentNM()->mkNode( ret_lit.getKind(), sumt, NodeManager::currentNM()->mkConst( Rational( 0 ) ) );
2777 if( !ret_pol ){
2778 ret = ret.negate();
2779 }
2780 Trace("real-as-int") << "Convert : " << std::endl;
2781 Trace("real-as-int") << " " << n << std::endl;
2782 Trace("real-as-int") << " " << ret << std::endl;
2783 }else{
2784 throw TypeCheckingException(n.toExpr(), string("Cannot translate to Int: ") + n.toString());
2785 }
2786 }
2787 }else{
2788 bool childChanged = false;
2789 std::vector< Node > children;
2790 for( unsigned i=0; i<n.getNumChildren(); i++ ){
2791 Node nc = realToInt( n[i], cache, var_eq );
2792 childChanged = childChanged || nc!=n[i];
2793 children.push_back( nc );
2794 }
2795 if( childChanged ){
2796 ret = NodeManager::currentNM()->mkNode( n.getKind(), children );
2797 }
2798 }
2799 }else{
2800 if( n.isVar() ){
2801 if( !n.getType().isInteger() ){
2802 ret = NodeManager::currentNM()->mkSkolem("__realToInt_var", NodeManager::currentNM()->integerType(), "Variable introduced in realToInt pass");
2803 var_eq.push_back( n.eqNode( ret ) );
2804 TheoryModel* m = d_smt.d_theoryEngine->getModel();
2805 m->addSubstitution(n,ret);
2806 }
2807 }
2808 }
2809 cache[n] = ret;
2810 return ret;
2811 }
2812 }
2813
2814 Node SmtEnginePrivate::purifyNlTerms(TNode n, NodeMap& cache, NodeMap& bcache, std::vector< Node >& var_eq, bool beneathMult) {
2815 if( beneathMult ){
2816 NodeMap::iterator find = bcache.find(n);
2817 if (find != bcache.end()) {
2818 return (*find).second;
2819 }
2820 }else{
2821 NodeMap::iterator find = cache.find(n);
2822 if (find != cache.end()) {
2823 return (*find).second;
2824 }
2825 }
2826 Node ret = n;
2827 if( n.getNumChildren()>0 ){
2828 if( beneathMult && n.getKind()!=kind::MULT ){
2829 //new variable
2830 ret = NodeManager::currentNM()->mkSkolem("__purifyNl_var", n.getType(), "Variable introduced in purifyNl pass");
2831 Node np = purifyNlTerms( n, cache, bcache, var_eq, false );
2832 var_eq.push_back( np.eqNode( ret ) );
2833 }else{
2834 bool beneathMultNew = beneathMult || n.getKind()==kind::MULT;
2835 bool childChanged = false;
2836 std::vector< Node > children;
2837 for( unsigned i=0; i<n.getNumChildren(); i++ ){
2838 Node nc = purifyNlTerms( n[i], cache, bcache, var_eq, beneathMultNew );
2839 childChanged = childChanged || nc!=n[i];
2840 children.push_back( nc );
2841 }
2842 if( childChanged ){
2843 ret = NodeManager::currentNM()->mkNode( n.getKind(), children );
2844 }
2845 }
2846 }
2847 if( beneathMult ){
2848 bcache[n] = ret;
2849 }else{
2850 cache[n] = ret;
2851 }
2852 return ret;
2853 }
2854
2855 void SmtEnginePrivate::removeITEs() {
2856 d_smt.finalOptionsAreSet();
2857 spendResource(options::preprocessStep());
2858 Trace("simplify") << "SmtEnginePrivate::removeITEs()" << endl;
2859
2860 // Remove all of the ITE occurrences and normalize
2861 d_iteRemover.run(d_assertions.ref(), d_iteSkolemMap, true);
2862 for (unsigned i = 0; i < d_assertions.size(); ++ i) {
2863 d_assertions.replace(i, Rewriter::rewrite(d_assertions[i]));
2864 }
2865 }
2866
2867 void SmtEnginePrivate::staticLearning() {
2868 d_smt.finalOptionsAreSet();
2869 spendResource(options::preprocessStep());
2870
2871 TimerStat::CodeTimer staticLearningTimer(d_smt.d_stats->d_staticLearningTime);
2872
2873 Trace("simplify") << "SmtEnginePrivate::staticLearning()" << endl;
2874
2875 for (unsigned i = 0; i < d_assertions.size(); ++ i) {
2876
2877 NodeBuilder<> learned(kind::AND);
2878 learned << d_assertions[i];
2879 d_smt.d_theoryEngine->ppStaticLearn(d_assertions[i], learned);
2880 if(learned.getNumChildren() == 1) {
2881 learned.clear();
2882 } else {
2883 d_assertions.replace(i, learned);
2884 }
2885 }
2886 }
2887
2888 // do dumping (before/after any preprocessing pass)
2889 static void dumpAssertions(const char* key,
2890 const AssertionPipeline& assertionList) {
2891 if( Dump.isOn("assertions") &&
2892 Dump.isOn(string("assertions:") + key) ) {
2893 // Push the simplified assertions to the dump output stream
2894 for(unsigned i = 0; i < assertionList.size(); ++ i) {
2895 TNode n = assertionList[i];
2896 Dump("assertions") << AssertCommand(Expr(n.toExpr()));
2897 }
2898 }
2899 }
2900
2901 // returns false if it learns a conflict
2902 bool SmtEnginePrivate::nonClausalSimplify() {
2903 spendResource(options::preprocessStep());
2904 d_smt.finalOptionsAreSet();
2905
2906 if(options::unsatCores() || options::fewerPreprocessingHoles()) {
2907 return true;
2908 }
2909
2910 TimerStat::CodeTimer nonclausalTimer(d_smt.d_stats->d_nonclausalSimplificationTime);
2911
2912 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify()" << endl;
2913 for (unsigned i = 0; i < d_assertions.size(); ++ i) {
2914 Trace("simplify") << "Assertion #" << i << " : " << d_assertions[i] << std::endl;
2915 }
2916
2917 if(d_propagatorNeedsFinish) {
2918 d_propagator.finish();
2919 d_propagatorNeedsFinish = false;
2920 }
2921 d_propagator.initialize();
2922
2923 // Assert all the assertions to the propagator
2924 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
2925 << "asserting to propagator" << endl;
2926 for (unsigned i = 0; i < d_assertions.size(); ++ i) {
2927 Assert(Rewriter::rewrite(d_assertions[i]) == d_assertions[i]);
2928 // Don't reprocess substitutions
2929 if (d_substitutionsIndex > 0 && i == d_substitutionsIndex) {
2930 continue;
2931 }
2932 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): asserting " << d_assertions[i] << endl;
2933 Debug("cores") << "d_propagator assertTrue: " << d_assertions[i] << std::endl;
2934 d_propagator.assertTrue(d_assertions[i]);
2935 }
2936
2937 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
2938 << "propagating" << endl;
2939 if (d_propagator.propagate()) {
2940 // If in conflict, just return false
2941 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
2942 << "conflict in non-clausal propagation" << endl;
2943 Node falseNode = NodeManager::currentNM()->mkConst<bool>(false);
2944 Assert(!options::unsatCores() && !options::fewerPreprocessingHoles());
2945 d_assertions.clear();
2946 addFormula(falseNode, false, false);
2947 d_propagatorNeedsFinish = true;
2948 return false;
2949 }
2950
2951
2952 Trace("simplify") << "Iterate through " << d_nonClausalLearnedLiterals.size() << " learned literals." << std::endl;
2953 // No conflict, go through the literals and solve them
2954 SubstitutionMap constantPropagations(d_smt.d_context);
2955 SubstitutionMap newSubstitutions(d_smt.d_context);
2956 SubstitutionMap::iterator pos;
2957 unsigned j = 0;
2958 for(unsigned i = 0, i_end = d_nonClausalLearnedLiterals.size(); i < i_end; ++ i) {
2959 // Simplify the literal we learned wrt previous substitutions
2960 Node learnedLiteral = d_nonClausalLearnedLiterals[i];
2961 Assert(Rewriter::rewrite(learnedLiteral) == learnedLiteral);
2962 Assert(d_topLevelSubstitutions.apply(learnedLiteral) == learnedLiteral);
2963 Trace("simplify") << "Process learnedLiteral : " << learnedLiteral << std::endl;
2964 Node learnedLiteralNew = newSubstitutions.apply(learnedLiteral);
2965 if (learnedLiteral != learnedLiteralNew) {
2966 learnedLiteral = Rewriter::rewrite(learnedLiteralNew);
2967 }
2968 Trace("simplify") << "Process learnedLiteral, after newSubs : " << learnedLiteral << std::endl;
2969 for (;;) {
2970 learnedLiteralNew = constantPropagations.apply(learnedLiteral);
2971 if (learnedLiteralNew == learnedLiteral) {
2972 break;
2973 }
2974 ++d_smt.d_stats->d_numConstantProps;
2975 learnedLiteral = Rewriter::rewrite(learnedLiteralNew);
2976 }
2977 Trace("simplify") << "Process learnedLiteral, after constProp : " << learnedLiteral << std::endl;
2978 // It might just simplify to a constant
2979 if (learnedLiteral.isConst()) {
2980 if (learnedLiteral.getConst<bool>()) {
2981 // If the learned literal simplifies to true, it's redundant
2982 continue;
2983 } else {
2984 // If the learned literal simplifies to false, we're in conflict
2985 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
2986 << "conflict with "
2987 << d_nonClausalLearnedLiterals[i] << endl;
2988 Assert(!options::unsatCores());
2989 d_assertions.clear();
2990 addFormula(NodeManager::currentNM()->mkConst<bool>(false), false, false);
2991 d_propagatorNeedsFinish = true;
2992 return false;
2993 }
2994 }
2995
2996 // Solve it with the corresponding theory, possibly adding new
2997 // substitutions to newSubstitutions
2998 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
2999 << "solving " << learnedLiteral << endl;
3000
3001 Theory::PPAssertStatus solveStatus =
3002 d_smt.d_theoryEngine->solve(learnedLiteral, newSubstitutions);
3003
3004 switch (solveStatus) {
3005 case Theory::PP_ASSERT_STATUS_SOLVED: {
3006 // The literal should rewrite to true
3007 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
3008 << "solved " << learnedLiteral << endl;
3009 Assert(Rewriter::rewrite(newSubstitutions.apply(learnedLiteral)).isConst());
3010 // vector<pair<Node, Node> > equations;
3011 // constantPropagations.simplifyLHS(d_topLevelSubstitutions, equations, true);
3012 // if (equations.empty()) {
3013 // break;
3014 // }
3015 // Assert(equations[0].first.isConst() && equations[0].second.isConst() && equations[0].first != equations[0].second);
3016 // else fall through
3017 break;
3018 }
3019 case Theory::PP_ASSERT_STATUS_CONFLICT:
3020 // If in conflict, we return false
3021 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
3022 << "conflict while solving "
3023 << learnedLiteral << endl;
3024 Assert(!options::unsatCores());
3025 d_assertions.clear();
3026 addFormula(NodeManager::currentNM()->mkConst<bool>(false), false, false);
3027 d_propagatorNeedsFinish = true;
3028 return false;
3029 default:
3030 if (d_doConstantProp && learnedLiteral.getKind() == kind::EQUAL && (learnedLiteral[0].isConst() || learnedLiteral[1].isConst())) {
3031 // constant propagation
3032 TNode t;
3033 TNode c;
3034 if (learnedLiteral[0].isConst()) {
3035 t = learnedLiteral[1];
3036 c = learnedLiteral[0];
3037 }
3038 else {
3039 t = learnedLiteral[0];
3040 c = learnedLiteral[1];
3041 }
3042 Assert(!t.isConst());
3043 Assert(constantPropagations.apply(t) == t);
3044 Assert(d_topLevelSubstitutions.apply(t) == t);
3045 Assert(newSubstitutions.apply(t) == t);
3046 constantPropagations.addSubstitution(t, c);
3047 // vector<pair<Node,Node> > equations;
3048 // constantPropagations.simplifyLHS(t, c, equations, true);
3049 // if (!equations.empty()) {
3050 // Assert(equations[0].first.isConst() && equations[0].second.isConst() && equations[0].first != equations[0].second);
3051 // d_assertions.clear();
3052 // addFormula(NodeManager::currentNM()->mkConst<bool>(false), false, false);
3053 // return;
3054 // }
3055 // d_topLevelSubstitutions.simplifyRHS(constantPropagations);
3056 }
3057 else {
3058 // Keep the literal
3059 d_nonClausalLearnedLiterals[j++] = d_nonClausalLearnedLiterals[i];
3060 }
3061 break;
3062 }
3063 }
3064
3065 #ifdef CVC4_ASSERTIONS
3066 // NOTE: When debugging this code, consider moving this check inside of the
3067 // loop over d_nonClausalLearnedLiterals. This check has been moved outside
3068 // because it is costly for certain inputs (see bug 508).
3069 //
3070 // Check data structure invariants:
3071 // 1. for each lhs of d_topLevelSubstitutions, does not appear anywhere in rhs of d_topLevelSubstitutions or anywhere in constantPropagations
3072 // 2. each lhs of constantPropagations rewrites to itself
3073 // 3. if l -> r is a constant propagation and l is a subterm of l' with l' -> r' another constant propagation, then l'[l/r] -> r' should be a
3074 // constant propagation too
3075 // 4. each lhs of constantPropagations is different from each rhs
3076 for (pos = newSubstitutions.begin(); pos != newSubstitutions.end(); ++pos) {
3077 Assert((*pos).first.isVar());
3078 Assert(d_topLevelSubstitutions.apply((*pos).first) == (*pos).first);
3079 Assert(d_topLevelSubstitutions.apply((*pos).second) == (*pos).second);
3080 Assert(newSubstitutions.apply(newSubstitutions.apply((*pos).second)) == newSubstitutions.apply((*pos).second));
3081 }
3082 for (pos = constantPropagations.begin(); pos != constantPropagations.end(); ++pos) {
3083 Assert((*pos).second.isConst());
3084 Assert(Rewriter::rewrite((*pos).first) == (*pos).first);
3085 // Node newLeft = d_topLevelSubstitutions.apply((*pos).first);
3086 // if (newLeft != (*pos).first) {
3087 // newLeft = Rewriter::rewrite(newLeft);
3088 // Assert(newLeft == (*pos).second ||
3089 // (constantPropagations.hasSubstitution(newLeft) && constantPropagations.apply(newLeft) == (*pos).second));
3090 // }
3091 // newLeft = constantPropagations.apply((*pos).first);
3092 // if (newLeft != (*pos).first) {
3093 // newLeft = Rewriter::rewrite(newLeft);
3094 // Assert(newLeft == (*pos).second ||
3095 // (constantPropagations.hasSubstitution(newLeft) && constantPropagations.apply(newLeft) == (*pos).second));
3096 // }
3097 Assert(constantPropagations.apply((*pos).second) == (*pos).second);
3098 }
3099 #endif /* CVC4_ASSERTIONS */
3100
3101 // Resize the learnt
3102 Trace("simplify") << "Resize non-clausal learned literals to " << j << std::endl;
3103 d_nonClausalLearnedLiterals.resize(j);
3104
3105 unordered_set<TNode, TNodeHashFunction> s;
3106 Trace("debugging") << "NonClausal simplify pre-preprocess\n";
3107 for (unsigned i = 0; i < d_assertions.size(); ++ i) {
3108 Node assertion = d_assertions[i];
3109 Node assertionNew = newSubstitutions.apply(assertion);
3110 Trace("debugging") << "assertion = " << assertion << endl;
3111 Trace("debugging") << "assertionNew = " << assertionNew << endl;
3112 if (assertion != assertionNew) {
3113 assertion = Rewriter::rewrite(assertionNew);
3114 Trace("debugging") << "rewrite(assertion) = " << assertion << endl;
3115 }
3116 Assert(Rewriter::rewrite(assertion) == assertion);
3117 for (;;) {
3118 assertionNew = constantPropagations.apply(assertion);
3119 if (assertionNew == assertion) {
3120 break;
3121 }
3122 ++d_smt.d_stats->d_numConstantProps;
3123 Trace("debugging") << "assertionNew = " << assertionNew << endl;
3124 assertion = Rewriter::rewrite(assertionNew);
3125 Trace("debugging") << "assertionNew = " << assertionNew << endl;
3126 }
3127 Trace("debugging") << "\n";
3128 s.insert(assertion);
3129 d_assertions.replace(i, assertion);
3130 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
3131 << "non-clausal preprocessed: "
3132 << assertion << endl;
3133 }
3134
3135 // If in incremental mode, add substitutions to the list of assertions
3136 if (d_substitutionsIndex > 0) {
3137 NodeBuilder<> substitutionsBuilder(kind::AND);
3138 substitutionsBuilder << d_assertions[d_substitutionsIndex];
3139 pos = newSubstitutions.begin();
3140 for (; pos != newSubstitutions.end(); ++pos) {
3141 // Add back this substitution as an assertion
3142 TNode lhs = (*pos).first, rhs = newSubstitutions.apply((*pos).second);
3143 Node n = NodeManager::currentNM()->mkNode(kind::EQUAL, lhs, rhs);
3144 substitutionsBuilder << n;
3145 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): will notify SAT layer of substitution: " << n << endl;
3146 }
3147 if (substitutionsBuilder.getNumChildren() > 1) {
3148 d_assertions.replace(d_substitutionsIndex,
3149 Rewriter::rewrite(Node(substitutionsBuilder)));
3150 }
3151 } else {
3152 // If not in incremental mode, must add substitutions to model
3153 TheoryModel* m = d_smt.d_theoryEngine->getModel();
3154 if(m != NULL) {
3155 for(pos = newSubstitutions.begin(); pos != newSubstitutions.end(); ++pos) {
3156 Node n = (*pos).first;
3157 Node v = newSubstitutions.apply((*pos).second);
3158 Trace("model") << "Add substitution : " << n << " " << v << endl;
3159 m->addSubstitution( n, v );
3160 }
3161 }
3162 }
3163
3164 NodeBuilder<> learnedBuilder(kind::AND);
3165 Assert(d_realAssertionsEnd <= d_assertions.size());
3166 learnedBuilder << d_assertions[d_realAssertionsEnd - 1];
3167
3168 for (unsigned i = 0; i < d_nonClausalLearnedLiterals.size(); ++ i) {
3169 Node learned = d_nonClausalLearnedLiterals[i];
3170 Assert(d_topLevelSubstitutions.apply(learned) == learned);
3171 Node learnedNew = newSubstitutions.apply(learned);
3172 if (learned != learnedNew) {
3173 learned = Rewriter::rewrite(learnedNew);
3174 }
3175 Assert(Rewriter::rewrite(learned) == learned);
3176 for (;;) {
3177 learnedNew = constantPropagations.apply(learned);
3178 if (learnedNew == learned) {
3179 break;
3180 }
3181 ++d_smt.d_stats->d_numConstantProps;
3182 learned = Rewriter::rewrite(learnedNew);
3183 }
3184 if (s.find(learned) != s.end()) {
3185 continue;
3186 }
3187 s.insert(learned);
3188 learnedBuilder << learned;
3189 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
3190 << "non-clausal learned : "
3191 << learned << endl;
3192 }
3193 d_nonClausalLearnedLiterals.clear();
3194
3195 for (pos = constantPropagations.begin(); pos != constantPropagations.end(); ++pos) {
3196 Node cProp = (*pos).first.eqNode((*pos).second);
3197 Assert(d_topLevelSubstitutions.apply(cProp) == cProp);
3198 Node cPropNew = newSubstitutions.apply(cProp);
3199 if (cProp != cPropNew) {
3200 cProp = Rewriter::rewrite(cPropNew);
3201 Assert(Rewriter::rewrite(cProp) == cProp);
3202 }
3203 if (s.find(cProp) != s.end()) {
3204 continue;
3205 }
3206 s.insert(cProp);
3207 learnedBuilder << cProp;
3208 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
3209 << "non-clausal constant propagation : "
3210 << cProp << endl;
3211 }
3212
3213 // Add new substitutions to topLevelSubstitutions
3214 // Note that we don't have to keep rhs's in full solved form
3215 // because SubstitutionMap::apply does a fixed-point iteration when substituting
3216 d_topLevelSubstitutions.addSubstitutions(newSubstitutions);
3217
3218 if(learnedBuilder.getNumChildren() > 1) {
3219 d_assertions.replace(d_realAssertionsEnd - 1,
3220 Rewriter::rewrite(Node(learnedBuilder)));
3221 }
3222
3223 d_propagatorNeedsFinish = true;
3224 return true;
3225 }
3226
3227 void SmtEnginePrivate::bvAbstraction() {
3228 Trace("bv-abstraction") << "SmtEnginePrivate::bvAbstraction()" << endl;
3229 std::vector<Node> new_assertions;
3230 bool changed = d_smt.d_theoryEngine->ppBvAbstraction(d_assertions.ref(), new_assertions);
3231 for (unsigned i = 0; i < d_assertions.size(); ++ i) {
3232 d_assertions.replace(i, Rewriter::rewrite(new_assertions[i]));
3233 }
3234 // if we are using the lazy solver and the abstraction
3235 // applies, then UF symbols were introduced
3236 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_LAZY &&
3237 changed) {
3238 LogicRequest req(d_smt);
3239 req.widenLogic(THEORY_UF);
3240 }
3241 }
3242
3243
3244 void SmtEnginePrivate::bvToBool() {
3245 Trace("bv-to-bool") << "SmtEnginePrivate::bvToBool()" << endl;
3246 spendResource(options::preprocessStep());
3247 std::vector<Node> new_assertions;
3248 d_smt.d_theoryEngine->ppBvToBool(d_assertions.ref(), new_assertions);
3249 for (unsigned i = 0; i < d_assertions.size(); ++ i) {
3250 d_assertions.replace(i, Rewriter::rewrite(new_assertions[i]));
3251 }
3252 }
3253
3254 void SmtEnginePrivate::boolToBv() {
3255 Trace("bool-to-bv") << "SmtEnginePrivate::boolToBv()" << endl;
3256 spendResource(options::preprocessStep());
3257 std::vector<Node> new_assertions;
3258 d_smt.d_theoryEngine->ppBoolToBv(d_assertions.ref(), new_assertions);
3259 for (unsigned i = 0; i < d_assertions.size(); ++ i) {
3260 d_assertions.replace(i, Rewriter::rewrite(new_assertions[i]));
3261 }
3262 }
3263
3264 bool SmtEnginePrivate::simpITE() {
3265 TimerStat::CodeTimer simpITETimer(d_smt.d_stats->d_simpITETime);
3266
3267 spendResource(options::preprocessStep());
3268
3269 Trace("simplify") << "SmtEnginePrivate::simpITE()" << endl;
3270
3271 unsigned numAssertionOnEntry = d_assertions.size();
3272 for (unsigned i = 0; i < d_assertions.size(); ++i) {
3273 spendResource(options::preprocessStep());
3274 Node result = d_smt.d_theoryEngine->ppSimpITE(d_assertions[i]);
3275 d_assertions.replace(i, result);
3276 if(result.isConst() && !result.getConst<bool>()){
3277 return false;
3278 }
3279 }
3280 bool result = d_smt.d_theoryEngine->donePPSimpITE(d_assertions.ref());
3281 if(numAssertionOnEntry < d_assertions.size()){
3282 compressBeforeRealAssertions(numAssertionOnEntry);
3283 }
3284 return result;
3285 }
3286
3287 void SmtEnginePrivate::compressBeforeRealAssertions(size_t before){
3288 size_t curr = d_assertions.size();
3289 if(before >= curr ||
3290 d_realAssertionsEnd <= 0 ||
3291 d_realAssertionsEnd >= curr){
3292 return;
3293 }
3294
3295 // assertions
3296 // original: [0 ... d_realAssertionsEnd)
3297 // can be modified
3298 // ites skolems [d_realAssertionsEnd, before)
3299 // cannot be moved
3300 // added [before, curr)
3301 // can be modified
3302 Assert(0 < d_realAssertionsEnd);
3303 Assert(d_realAssertionsEnd <= before);
3304 Assert(before < curr);
3305
3306 std::vector<Node> intoConjunction;
3307 for(size_t i = before; i<curr; ++i){
3308 intoConjunction.push_back(d_assertions[i]);
3309 }
3310 d_assertions.resize(before);
3311 size_t lastBeforeItes = d_realAssertionsEnd - 1;
3312 intoConjunction.push_back(d_assertions[lastBeforeItes]);
3313 Node newLast = util::NaryBuilder::mkAssoc(kind::AND, intoConjunction);
3314 d_assertions.replace(lastBeforeItes, newLast);
3315 Assert(d_assertions.size() == before);
3316 }
3317
3318 void SmtEnginePrivate::unconstrainedSimp() {
3319 TimerStat::CodeTimer unconstrainedSimpTimer(d_smt.d_stats->d_unconstrainedSimpTime);
3320 spendResource(options::preprocessStep());
3321 Trace("simplify") << "SmtEnginePrivate::unconstrainedSimp()" << endl;
3322 d_smt.d_theoryEngine->ppUnconstrainedSimp(d_assertions.ref());
3323 }
3324
3325 void SmtEnginePrivate::traceBackToAssertions(const std::vector<Node>& nodes, std::vector<TNode>& assertions) {
3326 const booleans::CircuitPropagator::BackEdgesMap& backEdges = d_propagator.getBackEdges();
3327 for(vector<Node>::const_iterator i = nodes.begin(); i != nodes.end(); ++i) {
3328 booleans::CircuitPropagator::BackEdgesMap::const_iterator j = backEdges.find(*i);
3329 // term must appear in map, otherwise how did we get here?!
3330 Assert(j != backEdges.end());
3331 // if term maps to empty, that means it's a top-level assertion
3332 if(!(*j).second.empty()) {
3333 traceBackToAssertions((*j).second, assertions);
3334 } else {
3335 assertions.push_back(*i);
3336 }
3337 }
3338 }
3339
3340 size_t SmtEnginePrivate::removeFromConjunction(Node& n, const std::unordered_set<unsigned long>& toRemove) {
3341 Assert(n.getKind() == kind::AND);
3342 size_t removals = 0;
3343 for(Node::iterator j = n.begin(); j != n.end(); ++j) {
3344 size_t subremovals = 0;
3345 Node sub = *j;
3346 if(toRemove.find(sub.getId()) != toRemove.end() ||
3347 (sub.getKind() == kind::AND && (subremovals = removeFromConjunction(sub, toRemove)) > 0)) {
3348 NodeBuilder<> b(kind::AND);
3349 b.append(n.begin(), j);
3350 if(subremovals > 0) {
3351 removals += subremovals;
3352 b << sub;
3353 } else {
3354 ++removals;
3355 }
3356 for(++j; j != n.end(); ++j) {
3357 if(toRemove.find((*j).getId()) != toRemove.end()) {
3358 ++removals;
3359 } else if((*j).getKind() == kind::AND) {
3360 sub = *j;
3361 if((subremovals = removeFromConjunction(sub, toRemove)) > 0) {
3362 removals += subremovals;
3363 b << sub;
3364 } else {
3365 b << *j;
3366 }
3367 } else {
3368 b << *j;
3369 }
3370 }
3371 if(b.getNumChildren() == 0) {
3372 n = d_true;
3373 b.clear();
3374 } else if(b.getNumChildren() == 1) {
3375 n = b[0];
3376 b.clear();
3377 } else {
3378 n = b;
3379 }
3380 n = Rewriter::rewrite(n);
3381 return removals;
3382 }
3383 }
3384
3385 Assert(removals == 0);
3386 return 0;
3387 }
3388
3389 void SmtEnginePrivate::doMiplibTrick() {
3390 Assert(d_realAssertionsEnd == d_assertions.size());
3391 Assert(!options::incrementalSolving());
3392
3393 const booleans::CircuitPropagator::BackEdgesMap& backEdges = d_propagator.getBackEdges();
3394 unordered_set<unsigned long> removeAssertions;
3395
3396 NodeManager* nm = NodeManager::currentNM();
3397 Node zero = nm->mkConst(Rational(0)), one = nm->mkConst(Rational(1));
3398
3399 unordered_map<TNode, Node, TNodeHashFunction> intVars;
3400 for(vector<Node>::const_iterator i = d_boolVars.begin(); i != d_boolVars.end(); ++i) {
3401 if(d_propagator.isAssigned(*i)) {
3402 Debug("miplib") << "ineligible: " << *i << " because assigned " << d_propagator.getAssignment(*i) << endl;
3403 continue;
3404 }
3405
3406 vector<TNode> assertions;
3407 booleans::CircuitPropagator::BackEdgesMap::const_iterator j = backEdges.find(*i);
3408 // if not in back edges map, the bool var is unconstrained, showing up in no assertions.
3409 // if maps to an empty vector, that means the bool var was asserted itself.
3410 if(j != backEdges.end()) {
3411 if(!(*j).second.empty()) {
3412 traceBackToAssertions((*j).second, assertions);
3413 } else {
3414 assertions.push_back(*i);
3415 }
3416 }
3417 Debug("miplib") << "for " << *i << endl;
3418 bool eligible = true;
3419 map<pair<Node, Node>, uint64_t> marks;
3420 map<pair<Node, Node>, vector<Rational> > coef;
3421 map<pair<Node, Node>, vector<Rational> > checks;
3422 map<pair<Node, Node>, vector<TNode> > asserts;
3423 for(vector<TNode>::const_iterator j = assertions.begin(); j != assertions.end(); ++j) {
3424 Debug("miplib") << " found: " << *j << endl;
3425 if((*j).getKind() != kind::IMPLIES) {
3426 eligible = false;
3427 Debug("miplib") << " -- INELIGIBLE -- (not =>)" << endl;
3428 break;
3429 }
3430 Node conj = BooleanSimplification::simplify((*j)[0]);
3431 if(conj.getKind() == kind::AND && conj.getNumChildren() > 6) {
3432 eligible = false;
3433 Debug("miplib") << " -- INELIGIBLE -- (N-ary /\\ too big)" << endl;
3434 break;
3435 }
3436 if(conj.getKind() != kind::AND && !conj.isVar() && !(conj.getKind() == kind::NOT && conj[0].isVar())) {
3437 eligible = false;
3438 Debug("miplib") << " -- INELIGIBLE -- (not /\\ or literal)" << endl;
3439 break;
3440 }
3441 if((*j)[1].getKind() != kind::EQUAL ||
3442 !( ( (*j)[1][0].isVar() &&
3443 (*j)[1][1].getKind() == kind::CONST_RATIONAL ) ||
3444 ( (*j)[1][0].getKind() == kind::CONST_RATIONAL &&
3445 (*j)[1][1].isVar() ) )) {
3446 eligible = false;
3447 Debug("miplib") << " -- INELIGIBLE -- (=> (and X X) X)" << endl;
3448 break;
3449 }
3450 if(conj.getKind() == kind::AND) {
3451 vector<Node> posv;
3452 bool found_x = false;
3453 map<TNode, bool> neg;
3454 for(Node::iterator ii = conj.begin(); ii != conj.end(); ++ii) {
3455 if((*ii).isVar()) {
3456 posv.push_back(*ii);
3457 neg[*ii] = false;
3458 found_x = found_x || *i == *ii;
3459 } else if((*ii).getKind() == kind::NOT && (*ii)[0].isVar()) {
3460 posv.push_back((*ii)[0]);
3461 neg[(*ii)[0]] = true;
3462 found_x = found_x || *i == (*ii)[0];
3463 } else {
3464 eligible = false;
3465 Debug("miplib") << " -- INELIGIBLE -- (non-var: " << *ii << ")" << endl;
3466 break;
3467 }
3468 if(d_propagator.isAssigned(posv.back())) {
3469 eligible = false;
3470 Debug("miplib") << " -- INELIGIBLE -- (" << posv.back() << " asserted)" << endl;
3471 break;
3472 }
3473 }
3474 if(!eligible) {
3475 break;
3476 }
3477 if(!found_x) {
3478 eligible = false;
3479 Debug("miplib") << " --INELIGIBLE -- (couldn't find " << *i << " in conjunction)" << endl;
3480 break;
3481 }
3482 sort(posv.begin(), posv.end());
3483 const Node pos = NodeManager::currentNM()->mkNode(kind::AND, posv);
3484 const TNode var = ((*j)[1][0].getKind() == kind::CONST_RATIONAL) ? (*j)[1][1] : (*j)[1][0];
3485 const pair<Node, Node> pos_var(pos, var);
3486 const Rational& constant = ((*j)[1][0].getKind() == kind::CONST_RATIONAL) ? (*j)[1][0].getConst<Rational>() : (*j)[1][1].getConst<Rational>();
3487 uint64_t mark = 0;
3488 unsigned countneg = 0, thepos = 0;
3489 for(unsigned ii = 0; ii < pos.getNumChildren(); ++ii) {
3490 if(neg[pos[ii]]) {
3491 ++countneg;
3492 } else {
3493 thepos = ii;
3494 mark |= (0x1 << ii);
3495 }
3496 }
3497 if((marks[pos_var] & (1lu << mark)) != 0) {
3498 eligible = false;
3499 Debug("miplib") << " -- INELIGIBLE -- (remarked)" << endl;
3500 break;
3501 }
3502 Debug("miplib") << "mark is " << mark << " -- " << (1lu << mark) << endl;
3503 marks[pos_var] |= (1lu << mark);
3504 Debug("miplib") << "marks[" << pos << "," << var << "] now " << marks[pos_var] << endl;
3505 if(countneg == pos.getNumChildren()) {
3506 if(constant != 0) {
3507 eligible = false;
3508 Debug("miplib") << " -- INELIGIBLE -- (nonzero constant)" << endl;
3509 break;
3510 }
3511 } else if(countneg == pos.getNumChildren() - 1) {
3512 Assert(coef[pos_var].size() <= 6 && thepos < 6);
3513 if(coef[pos_var].size() <= thepos) {
3514 coef[pos_var].resize(thepos + 1);
3515 }
3516 coef[pos_var][thepos] = constant;
3517 } else {
3518 if(checks[pos_var].size() <= mark) {
3519 checks[pos_var].resize(mark + 1);
3520 }
3521 checks[pos_var][mark] = constant;
3522 }
3523 asserts[pos_var].push_back(*j);
3524 } else {
3525 TNode x = conj;
3526 if(x != *i && x != (*i).notNode()) {
3527 eligible = false;
3528 Debug("miplib") << " -- INELIGIBLE -- (x not present where I expect it)" << endl;
3529 break;
3530 }
3531 const bool xneg = (x.getKind() == kind::NOT);
3532 x = xneg ? x[0] : x;
3533 Debug("miplib") << " x:" << x << " " << xneg << endl;
3534 const TNode var = ((*j)[1][0].getKind() == kind::CONST_RATIONAL) ? (*j)[1][1] : (*j)[1][0];
3535 const pair<Node, Node> x_var(x, var);
3536 const Rational& constant = ((*j)[1][0].getKind() == kind::CONST_RATIONAL) ? (*j)[1][0].getConst<Rational>() : (*j)[1][1].getConst<Rational>();
3537 unsigned mark = (xneg ? 0 : 1);
3538 if((marks[x_var] & (1u << mark)) != 0) {
3539 eligible = false;
3540 Debug("miplib") << " -- INELIGIBLE -- (remarked)" << endl;
3541 break;
3542 }
3543 marks[x_var] |= (1u << mark);
3544 if(xneg) {
3545 if(constant != 0) {
3546 eligible = false;
3547 Debug("miplib") << " -- INELIGIBLE -- (nonzero constant)" << endl;
3548 break;
3549 }
3550 } else {
3551 Assert(coef[x_var].size() <= 6);
3552 coef[x_var].resize(6);
3553 coef[x_var][0] = constant;
3554 }
3555 asserts[x_var].push_back(*j);
3556 }
3557 }
3558 if(eligible) {
3559 for(map<pair<Node, Node>, uint64_t>::const_iterator j = marks.begin(); j != marks.end(); ++j) {
3560 const TNode pos = (*j).first.first;
3561 const TNode var = (*j).first.second;
3562 const pair<Node, Node>& pos_var = (*j).first;
3563 const uint64_t mark = (*j).second;
3564 const unsigned numVars = pos.getKind() == kind::AND ? pos.getNumChildren() : 1;
3565 uint64_t expected = (uint64_t(1) << (1 << numVars)) - 1;
3566 expected = (expected == 0) ? -1 : expected; // fix for overflow
3567 Debug("miplib") << "[" << pos << "] => " << hex << mark << " expect " << expected << dec << endl;
3568 Assert(pos.getKind() == kind::AND || pos.isVar());
3569 if(mark != expected) {
3570 Debug("miplib") << " -- INELIGIBLE " << pos << " -- (insufficiently marked, got " << mark << " for " << numVars << " vars, expected " << expected << endl;
3571 } else {
3572 if(mark != 3) { // exclude single-var case; nothing to check there
3573 uint64_t sz = (uint64_t(1) << checks[pos_var].size()) - 1;
3574 sz = (sz == 0) ? -1 : sz; // fix for overflow
3575 Assert(sz == mark, "expected size %u == mark %u", sz, mark);
3576 for(size_t k = 0; k < checks[pos_var].size(); ++k) {
3577 if((k & (k - 1)) != 0) {
3578 Rational sum = 0;
3579 Debug("miplib") << k << " => " << checks[pos_var][k] << endl;
3580 for(size_t v = 1, kk = k; kk != 0; ++v, kk >>= 1) {
3581 if((kk & 0x1) == 1) {
3582 Assert(pos.getKind() == kind::AND);
3583 Debug("miplib") << "var " << v << " : " << pos[v - 1] << " coef:" << coef[pos_var][v - 1] << endl;
3584 sum += coef[pos_var][v - 1];
3585 }
3586 }
3587 Debug("miplib") << "checkSum is " << sum << " input says " << checks[pos_var][k] << endl;
3588 if(sum != checks[pos_var][k]) {
3589 eligible = false;
3590 Debug("miplib") << " -- INELIGIBLE " << pos << " -- (nonlinear combination)" << endl;
3591 break;
3592 }
3593 } else {
3594 Assert(checks[pos_var][k] == 0, "checks[(%s,%s)][%u] should be 0, but it's %s", pos.toString().c_str(), var.toString().c_str(), k, checks[pos_var][k].toString().c_str()); // we never set for single-positive-var
3595 }
3596 }
3597 }
3598 if(!eligible) {
3599 eligible = true; // next is still eligible
3600 continue;
3601 }
3602
3603 Debug("miplib") << " -- ELIGIBLE " << *i << " , " << pos << " --" << endl;
3604 vector<Node> newVars;
3605 expr::NodeSelfIterator ii, iiend;
3606 if(pos.getKind() == kind::AND) {
3607 ii = pos.begin();
3608 iiend = pos.end();
3609 } else {
3610 ii = expr::NodeSelfIterator::self(pos);
3611 iiend = expr::NodeSelfIterator::selfEnd(pos);
3612 }
3613 for(; ii != iiend; ++ii) {
3614 Node& varRef = intVars[*ii];
3615 if(varRef.isNull()) {
3616 stringstream ss;
3617 ss << "mipvar_" << *ii;
3618 Node newVar = nm->mkSkolem(ss.str(), nm->integerType(), "a variable introduced due to scrubbing a miplib encoding", NodeManager::SKOLEM_EXACT_NAME);
3619 Node geq = Rewriter::rewrite(nm->mkNode(kind::GEQ, newVar, zero));
3620 Node leq = Rewriter::rewrite(nm->mkNode(kind::LEQ, newVar, one));
3621 addFormula(Rewriter::rewrite(geq.andNode(leq)), false, false);
3622 SubstitutionMap nullMap(&d_fakeContext);
3623 Theory::PPAssertStatus status CVC4_UNUSED; // just for assertions
3624 status = d_smt.d_theoryEngine->solve(geq, nullMap);
3625 Assert(status == Theory::PP_ASSERT_STATUS_UNSOLVED,
3626 "unexpected solution from arith's ppAssert()");
3627 Assert(nullMap.empty(),
3628 "unexpected substitution from arith's ppAssert()");
3629 status = d_smt.d_theoryEngine->solve(leq, nullMap);
3630 Assert(status == Theory::PP_ASSERT_STATUS_UNSOLVED,
3631 "unexpected solution from arith's ppAssert()");
3632 Assert(nullMap.empty(),
3633 "unexpected substitution from arith's ppAssert()");
3634 d_smt.d_theoryEngine->getModel()->addSubstitution(*ii, newVar.eqNode(one));
3635 newVars.push_back(newVar);
3636 varRef = newVar;
3637 } else {
3638 newVars.push_back(varRef);
3639 }
3640 if(!d_smt.d_logic.areIntegersUsed()) {
3641 d_smt.d_logic = d_smt.d_logic.getUnlockedCopy();
3642 d_smt.d_logic.enableIntegers();
3643 d_smt.d_logic.lock();
3644 }
3645 }
3646 Node sum;
3647 if(pos.getKind() == kind::AND) {
3648 NodeBuilder<> sumb(kind::PLUS);
3649 for(size_t ii = 0; ii < pos.getNumChildren(); ++ii) {
3650 sumb << nm->mkNode(kind::MULT, nm->mkConst(coef[pos_var][ii]), newVars[ii]);
3651 }
3652 sum = sumb;
3653 } else {
3654 sum = nm->mkNode(kind::MULT, nm->mkConst(coef[pos_var][0]), newVars[0]);
3655 }
3656 Debug("miplib") << "vars[] " << var << endl
3657 << " eq " << Rewriter::rewrite(sum) << endl;
3658 Node newAssertion = var.eqNode(Rewriter::rewrite(sum));
3659 if(d_topLevelSubstitutions.hasSubstitution(newAssertion[0])) {
3660 //Warning() << "RE-SUBSTITUTION " << newAssertion[0] << endl;
3661 //Warning() << "REPLACE " << newAssertion[1] << endl;
3662 //Warning() << "ORIG " << d_topLevelSubstitutions.getSubstitution(newAssertion[0]) << endl;
3663 Assert(d_topLevelSubstitutions.getSubstitution(newAssertion[0]) == newAssertion[1]);
3664 } else if(pos.getNumChildren() <= options::arithMLTrickSubstitutions()) {
3665 d_topLevelSubstitutions.addSubstitution(newAssertion[0], newAssertion[1]);
3666 Debug("miplib") << "addSubs: " << newAssertion[0] << " to " << newAssertion[1] << endl;
3667 } else {
3668 Debug("miplib") << "skipSubs: " << newAssertion[0] << " to " << newAssertion[1] << " (threshold is " << options::arithMLTrickSubstitutions() << ")" << endl;
3669 }
3670 newAssertion = Rewriter::rewrite(newAssertion);
3671 Debug("miplib") << " " << newAssertion << endl;
3672 addFormula(newAssertion, false, false);
3673 Debug("miplib") << " assertions to remove: " << endl;
3674 for(vector<TNode>::const_iterator k = asserts[pos_var].begin(), k_end = asserts[pos_var].end(); k != k_end; ++k) {
3675 Debug("miplib") << " " << *k << endl;
3676 removeAssertions.insert((*k).getId());
3677 }
3678 }
3679 }
3680 }
3681 }
3682 if(!removeAssertions.empty()) {
3683 Debug("miplib") << "SmtEnginePrivate::simplify(): scrubbing miplib encoding..." << endl;
3684 for(size_t i = 0; i < d_realAssertionsEnd; ++i) {
3685 if(removeAssertions.find(d_assertions[i].getId()) != removeAssertions.end()) {
3686 Debug("miplib") << "SmtEnginePrivate::simplify(): - removing " << d_assertions[i] << endl;
3687 d_assertions[i] = d_true;
3688 ++d_smt.d_stats->d_numMiplibAssertionsRemoved;
3689 } else if(d_assertions[i].getKind() == kind::AND) {
3690 size_t removals = removeFromConjunction(d_assertions[i], removeAssertions);
3691 if(removals > 0) {
3692 Debug("miplib") << "SmtEnginePrivate::simplify(): - reduced " << d_assertions[i] << endl;
3693 Debug("miplib") << "SmtEnginePrivate::simplify(): - by " << removals << " conjuncts" << endl;
3694 d_smt.d_stats->d_numMiplibAssertionsRemoved += removals;
3695 }
3696 }
3697 Debug("miplib") << "had: " << d_assertions[i] << endl;
3698 d_assertions[i] = Rewriter::rewrite(d_topLevelSubstitutions.apply(d_assertions[i]));
3699 Debug("miplib") << "now: " << d_assertions[i] << endl;
3700 }
3701 } else {
3702 Debug("miplib") << "SmtEnginePrivate::simplify(): miplib pass found nothing." << endl;
3703 }
3704 d_realAssertionsEnd = d_assertions.size();
3705 }
3706
3707
3708 // returns false if simplification led to "false"
3709 bool SmtEnginePrivate::simplifyAssertions()
3710 {
3711 spendResource(options::preprocessStep());
3712 Assert(d_smt.d_pendingPops == 0);
3713 try {
3714 ScopeCounter depth(d_simplifyAssertionsDepth);
3715
3716 Trace("simplify") << "SmtEnginePrivate::simplify()" << endl;
3717
3718 dumpAssertions("pre-nonclausal", d_assertions);
3719
3720 if(options::simplificationMode() != SIMPLIFICATION_MODE_NONE) {
3721 // Perform non-clausal simplification
3722 Chat() << "...performing nonclausal simplification..." << endl;
3723 Trace("simplify") << "SmtEnginePrivate::simplify(): "
3724 << "performing non-clausal simplification" << endl;
3725 bool noConflict = nonClausalSimplify();
3726 if(!noConflict) {
3727 return false;
3728 }
3729
3730 // We piggy-back off of the BackEdgesMap in the CircuitPropagator to
3731 // do the miplib trick.
3732 if( // check that option is on
3733 options::arithMLTrick() &&
3734 // miplib rewrites aren't safe in incremental mode
3735 ! options::incrementalSolving() &&
3736 // only useful in arith
3737 d_smt.d_logic.isTheoryEnabled(THEORY_ARITH) &&
3738 // we add new assertions and need this (in practice, this
3739 // restriction only disables miplib processing during
3740 // re-simplification, which we don't expect to be useful anyway)
3741 d_realAssertionsEnd == d_assertions.size() ) {
3742 Chat() << "...fixing miplib encodings..." << endl;
3743 Trace("simplify") << "SmtEnginePrivate::simplify(): "
3744 << "looking for miplib pseudobooleans..." << endl;
3745
3746 TimerStat::CodeTimer miplibTimer(d_smt.d_stats->d_miplibPassTime);
3747
3748 doMiplibTrick();
3749 } else {
3750 Trace("simplify") << "SmtEnginePrivate::simplify(): "
3751 << "skipping miplib pseudobooleans pass (either incrementalSolving is on, or miplib pbs are turned off)..." << endl;
3752 }
3753 }
3754
3755 dumpAssertions("post-nonclausal", d_assertions);
3756 Trace("smt") << "POST nonClausalSimplify" << endl;
3757 Debug("smt") << " d_assertions : " << d_assertions.size() << endl;
3758
3759 // before ppRewrite check if only core theory for BV theory
3760 d_smt.d_theoryEngine->staticInitializeBVOptions(d_assertions.ref());
3761
3762 dumpAssertions("pre-theorypp", d_assertions);
3763
3764 // Theory preprocessing
3765 if (d_smt.d_earlyTheoryPP) {
3766 Chat() << "...doing early theory preprocessing..." << endl;
3767 TimerStat::CodeTimer codeTimer(d_smt.d_stats->d_theoryPreprocessTime);
3768 // Call the theory preprocessors
3769 d_smt.d_theoryEngine->preprocessStart();
3770 for (unsigned i = 0; i < d_assertions.size(); ++ i) {
3771 Assert(Rewriter::rewrite(d_assertions[i]) == d_assertions[i]);
3772 d_assertions.replace(i, d_smt.d_theoryEngine->preprocess(d_assertions[i]));
3773 Assert(Rewriter::rewrite(d_assertions[i]) == d_assertions[i]);
3774 }
3775 }
3776
3777 dumpAssertions("post-theorypp", d_assertions);
3778 Trace("smt") << "POST theoryPP" << endl;
3779 Debug("smt") << " d_assertions : " << d_assertions.size() << endl;
3780
3781 // ITE simplification
3782 if(options::doITESimp() &&
3783 (d_simplifyAssertionsDepth <= 1 || options::doITESimpOnRepeat())) {
3784 Chat() << "...doing ITE simplification..." << endl;
3785 bool noConflict = simpITE();
3786 if(!noConflict){
3787 Chat() << "...ITE simplification found unsat..." << endl;
3788 return false;
3789 }
3790 }
3791
3792 dumpAssertions("post-itesimp", d_assertions);
3793 Trace("smt") << "POST iteSimp" << endl;
3794 Debug("smt") << " d_assertions : " << d_assertions.size() << endl;
3795
3796 // Unconstrained simplification
3797 if(options::unconstrainedSimp()) {
3798 Chat() << "...doing unconstrained simplification..." << endl;
3799 unconstrainedSimp();
3800 }
3801
3802 dumpAssertions("post-unconstrained", d_assertions);
3803 Trace("smt") << "POST unconstrainedSimp" << endl;
3804 Debug("smt") << " d_assertions : " << d_assertions.size() << endl;
3805
3806 if(options::repeatSimp() && options::simplificationMode() != SIMPLIFICATION_MODE_NONE) {
3807 Chat() << "...doing another round of nonclausal simplification..." << endl;
3808 Trace("simplify") << "SmtEnginePrivate::simplify(): "
3809 << " doing repeated simplification" << endl;
3810 bool noConflict = nonClausalSimplify();
3811 if(!noConflict) {
3812 return false;
3813 }
3814 }
3815
3816 dumpAssertions("post-repeatsimp", d_assertions);
3817 Trace("smt") << "POST repeatSimp" << endl;
3818 Debug("smt") << " d_assertions : " << d_assertions.size() << endl;
3819
3820 } catch(TypeCheckingExceptionPrivate& tcep) {
3821 // Calls to this function should have already weeded out any
3822 // typechecking exceptions via (e.g.) ensureBoolean(). But a
3823 // theory could still create a new expression that isn't
3824 // well-typed, and we don't want the C++ runtime to abort our
3825 // process without any error notice.
3826 stringstream ss;
3827 ss << "A bad expression was produced. Original exception follows:\n"
3828 << tcep;
3829 InternalError(ss.str().c_str());
3830 }
3831 return true;
3832 }
3833
3834 Result SmtEngine::check() {
3835 Assert(d_fullyInited);
3836 Assert(d_pendingPops == 0);
3837
3838 Trace("smt") << "SmtEngine::check()" << endl;
3839
3840 ResourceManager* resourceManager = d_private->getResourceManager();
3841
3842 resourceManager->beginCall();
3843
3844 // Only way we can be out of resource is if cumulative budget is on
3845 if (resourceManager->cumulativeLimitOn() &&
3846 resourceManager->out()) {
3847 Result::UnknownExplanation why = resourceManager->outOfResources() ?
3848 Result::RESOURCEOUT : Result::TIMEOUT;
3849 return Result(Result::VALIDITY_UNKNOWN, why, d_filename);
3850 }
3851
3852 // Make sure the prop layer has all of the assertions
3853 Trace("smt") << "SmtEngine::check(): processing assertions" << endl;
3854 d_private->processAssertions();
3855 Trace("smt") << "SmtEngine::check(): done processing assertions" << endl;
3856
3857 // Turn off stop only for QF_LRA
3858 // TODO: Bring up in a meeting where to put this
3859 if(options::decisionStopOnly() && !options::decisionMode.wasSetByUser() ){
3860 if( // QF_LRA
3861 (not d_logic.isQuantified() &&
3862 d_logic.isPure(THEORY_ARITH) && d_logic.isLinear() && !d_logic.isDifferenceLogic() && !d_logic.areIntegersUsed()
3863 )){
3864 if(d_private->d_iteSkolemMap.empty()){
3865 options::decisionStopOnly.set(false);
3866 d_decisionEngine->clearStrategies();
3867 Trace("smt") << "SmtEngine::check(): turning off stop only" << endl;
3868 }
3869 }
3870 }
3871
3872 TimerStat::CodeTimer solveTimer(d_stats->d_solveTime);
3873
3874 Chat() << "solving..." << endl;
3875 Trace("smt") << "SmtEngine::check(): running check" << endl;
3876 Result result = d_propEngine->checkSat();
3877
3878 resourceManager->endCall();
3879 Trace("limit") << "SmtEngine::check(): cumulative millis " << resourceManager->getTimeUsage()
3880 << ", resources " << resourceManager->getResourceUsage() << endl;
3881
3882
3883 return Result(result, d_filename);
3884 }
3885
3886 Result SmtEngine::quickCheck() {
3887 Assert(d_fullyInited);
3888 Trace("smt") << "SMT quickCheck()" << endl;
3889 return Result(Result::VALIDITY_UNKNOWN, Result::REQUIRES_FULL_CHECK, d_filename);
3890 }
3891
3892
3893 void SmtEnginePrivate::collectSkolems(TNode n, set<TNode>& skolemSet, unordered_map<Node, bool, NodeHashFunction>& cache)
3894 {
3895 unordered_map<Node, bool, NodeHashFunction>::iterator it;
3896 it = cache.find(n);
3897 if (it != cache.end()) {
3898 return;
3899 }
3900
3901 size_t sz = n.getNumChildren();
3902 if (sz == 0) {
3903 IteSkolemMap::iterator it = d_iteSkolemMap.find(n);
3904 if (it != d_iteSkolemMap.end()) {
3905 skolemSet.insert(n);
3906 }
3907 cache[n] = true;
3908 return;
3909 }
3910
3911 size_t k = 0;
3912 for (; k < sz; ++k) {
3913 collectSkolems(n[k], skolemSet, cache);
3914 }
3915 cache[n] = true;
3916 }
3917
3918
3919 bool SmtEnginePrivate::checkForBadSkolems(TNode n, TNode skolem, unordered_map<Node, bool, NodeHashFunction>& cache)
3920 {
3921 unordered_map<Node, bool, NodeHashFunction>::iterator it;
3922 it = cache.find(n);
3923 if (it != cache.end()) {
3924 return (*it).second;
3925 }
3926
3927 size_t sz = n.getNumChildren();
3928 if (sz == 0) {
3929 IteSkolemMap::iterator it = d_iteSkolemMap.find(n);
3930 bool bad = false;
3931 if (it != d_iteSkolemMap.end()) {
3932 if (!((*it).first < n)) {
3933 bad = true;
3934 }
3935 }
3936 cache[n] = bad;
3937 return bad;
3938 }
3939
3940 size_t k = 0;
3941 for (; k < sz; ++k) {
3942 if (checkForBadSkolems(n[k], skolem, cache)) {
3943 cache[n] = true;
3944 return true;
3945 }
3946 }
3947
3948 cache[n] = false;
3949 return false;
3950 }
3951
3952 void SmtEnginePrivate::applySubstitutionsToAssertions() {
3953 if(!options::unsatCores()) {
3954 Chat() << "applying substitutions..." << endl;
3955 Trace("simplify") << "SmtEnginePrivate::processAssertions(): "
3956 << "applying substitutions" << endl;
3957 // TODO(b/1255): Substitutions in incremental mode should be managed with a
3958 // proper data structure.
3959
3960 // When solving incrementally, all substitutions are piled into the
3961 // assertion at d_substitutionsIndex: we don't want to apply substitutions
3962 // to this assertion or information will be lost.
3963 unsigned substitutionAssertion = d_substitutionsIndex > 0 ? d_substitutionsIndex : d_assertions.size();
3964 for (unsigned i = 0; i < d_assertions.size(); ++ i) {
3965 if (i == substitutionAssertion) {
3966 continue;
3967 }
3968 Trace("simplify") << "applying to " << d_assertions[i] << endl;
3969 spendResource(options::preprocessStep());
3970 d_assertions.replace(i, Rewriter::rewrite(d_topLevelSubstitutions.apply(d_assertions[i])));
3971 Trace("simplify") << " got " << d_assertions[i] << endl;
3972 }
3973 }
3974 }
3975
3976 void SmtEnginePrivate::processAssertions() {
3977 TimerStat::CodeTimer paTimer(d_smt.d_stats->d_processAssertionsTime);
3978 spendResource(options::preprocessStep());
3979 Assert(d_smt.d_fullyInited);
3980 Assert(d_smt.d_pendingPops == 0);
3981
3982 // Dump the assertions
3983 dumpAssertions("pre-everything", d_assertions);
3984
3985 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() begin" << endl;
3986 Trace("smt") << "SmtEnginePrivate::processAssertions()" << endl;
3987
3988 Debug("smt") << " d_assertions : " << d_assertions.size() << endl;
3989
3990 if (d_assertions.size() == 0) {
3991 // nothing to do
3992 return;
3993 }
3994
3995 if (options::bvGaussElim())
3996 {
3997 TimerStat::CodeTimer gaussElimTimer(d_smt.d_stats->d_gaussElimTime);
3998 d_preprocessingPassRegistry.getPass("bv-gauss")->apply(&d_assertions);
3999 }
4000
4001 if (d_assertionsProcessed && options::incrementalSolving()) {
4002 // TODO(b/1255): Substitutions in incremental mode should be managed with a
4003 // proper data structure.
4004
4005 // Placeholder for storing substitutions
4006 d_substitutionsIndex = d_assertions.size();
4007 d_assertions.push_back(NodeManager::currentNM()->mkConst<bool>(true));
4008 }
4009
4010 // Add dummy assertion in last position - to be used as a
4011 // placeholder for any new assertions to get added
4012 d_assertions.push_back(NodeManager::currentNM()->mkConst<bool>(true));
4013 // any assertions added beyond realAssertionsEnd must NOT affect the
4014 // equisatisfiability
4015 d_realAssertionsEnd = d_assertions.size();
4016
4017 // Assertions are NOT guaranteed to be rewritten by this point
4018
4019 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-definition-expansion" << endl;
4020 dumpAssertions("pre-definition-expansion", d_assertions);
4021 {
4022 Chat() << "expanding definitions..." << endl;
4023 Trace("simplify") << "SmtEnginePrivate::simplify(): expanding definitions" << endl;
4024 TimerStat::CodeTimer codeTimer(d_smt.d_stats->d_definitionExpansionTime);
4025 unordered_map<Node, Node, NodeHashFunction> cache;
4026 for(unsigned i = 0; i < d_assertions.size(); ++ i) {
4027 d_assertions.replace(i, expandDefinitions(d_assertions[i], cache));
4028 }
4029 }
4030 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-definition-expansion" << endl;
4031 dumpAssertions("post-definition-expansion", d_assertions);
4032
4033 // save the assertions now
4034 THEORY_PROOF
4035 (
4036 for (unsigned i = 0; i < d_assertions.size(); ++i) {
4037 ProofManager::currentPM()->addAssertion(d_assertions[i].toExpr());
4038 }
4039 );
4040
4041 Debug("smt") << " d_assertions : " << d_assertions.size() << endl;
4042
4043 if (options::sygusInference())
4044 {
4045 // try recast as sygus
4046 quantifiers::SygusInference si;
4047 if (si.simplify(d_assertions.ref()))
4048 {
4049 Trace("smt-proc") << "...converted to sygus conjecture." << std::endl;
4050 d_smt.d_globalNegation = !d_smt.d_globalNegation;
4051 }
4052 }
4053 else if (options::globalNegate())
4054 {
4055 // global negation of the formula
4056 quantifiers::GlobalNegate gn;
4057 gn.simplify(d_assertions.ref());
4058 d_smt.d_globalNegation = !d_smt.d_globalNegation;
4059 }
4060
4061 if( options::nlExtPurify() ){
4062 unordered_map<Node, Node, NodeHashFunction> cache;
4063 unordered_map<Node, Node, NodeHashFunction> bcache;
4064 std::vector< Node > var_eq;
4065 for (unsigned i = 0; i < d_assertions.size(); ++ i) {
4066 d_assertions.replace(i, purifyNlTerms(d_assertions[i], cache, bcache, var_eq));
4067 }
4068 if( !var_eq.empty() ){
4069 unsigned lastIndex = d_assertions.size()-1;
4070 var_eq.insert( var_eq.begin(), d_assertions[lastIndex] );
4071 d_assertions.replace(lastIndex, NodeManager::currentNM()->mkNode( kind::AND, var_eq ) );
4072 }
4073 }
4074
4075 if( options::ceGuidedInst() ){
4076 //register sygus conjecture pre-rewrite (motivated by solution reconstruction)
4077 for (unsigned i = 0; i < d_assertions.size(); ++ i) {
4078 d_smt.d_theoryEngine->getQuantifiersEngine()->getCegInstantiation()->preregisterAssertion( d_assertions[i] );
4079 }
4080 }
4081
4082 if (options::solveRealAsInt()) {
4083 Chat() << "converting reals to ints..." << endl;
4084 unordered_map<Node, Node, NodeHashFunction> cache;
4085 std::vector< Node > var_eq;
4086 for(unsigned i = 0; i < d_assertions.size(); ++ i) {
4087 d_assertions.replace(i, realToInt(d_assertions[i], cache, var_eq));
4088 }
4089 /*
4090 if( !var_eq.empty() ){
4091 unsigned lastIndex = d_assertions.size()-1;
4092 var_eq.insert( var_eq.begin(), d_assertions[lastIndex] );
4093 d_assertions.replace(last_index, NodeManager::currentNM()->mkNode( kind::AND, var_eq ) );
4094 }
4095 */
4096 }
4097
4098 if (options::solveIntAsBV() > 0)
4099 {
4100 d_preprocessingPassRegistry.getPass("int-to-bv")->apply(&d_assertions);
4101 }
4102
4103 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER &&
4104 !d_smt.d_logic.isPure(THEORY_BV) &&
4105 d_smt.d_logic.getLogicString() != "QF_UFBV" &&
4106 d_smt.d_logic.getLogicString() != "QF_ABV") {
4107 throw ModalException("Eager bit-blasting does not currently support theory combination. "
4108 "Note that in a QF_BV problem UF symbols can be introduced for division. "
4109 "Try --bv-div-zero-const to interpret division by zero as a constant.");
4110 }
4111
4112 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER) {
4113 d_smt.d_theoryEngine->mkAckermanizationAssertions(d_assertions.ref());
4114 }
4115
4116 if ( options::bvAbstraction() &&
4117 !options::incrementalSolving()) {
4118 dumpAssertions("pre-bv-abstraction", d_assertions);
4119 bvAbstraction();
4120 dumpAssertions("post-bv-abstraction", d_assertions);
4121 }
4122
4123 Debug("smt") << " d_assertions : " << d_assertions.size() << endl;
4124
4125 bool noConflict = true;
4126
4127 if (options::extRewPrep())
4128 {
4129 theory::quantifiers::ExtendedRewriter extr(options::extRewPrepAgg());
4130 for (unsigned i = 0; i < d_assertions.size(); ++i)
4131 {
4132 Node a = d_assertions[i];
4133 d_assertions.replace(i, extr.extendedRewrite(a));
4134 }
4135 }
4136
4137 // Unconstrained simplification
4138 if(options::unconstrainedSimp()) {
4139 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-unconstrained-simp" << endl;
4140 dumpAssertions("pre-unconstrained-simp", d_assertions);
4141 Chat() << "...doing unconstrained simplification..." << endl;
4142 for (unsigned i = 0; i < d_assertions.size(); ++ i) {
4143 d_assertions.replace(i, Rewriter::rewrite(d_assertions[i]));
4144 }
4145 unconstrainedSimp();
4146 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-unconstrained-simp" << endl;
4147 dumpAssertions("post-unconstrained-simp", d_assertions);
4148 }
4149
4150 if(options::bvIntroducePow2()){
4151 theory::bv::BVIntroducePow2::pow2Rewrite(d_assertions.ref());
4152 }
4153
4154 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-substitution" << endl;
4155 dumpAssertions("pre-substitution", d_assertions);
4156
4157 if(options::unsatCores()) {
4158 // special rewriting pass for unsat cores, since many of the passes below are skipped
4159 for (unsigned i = 0; i < d_assertions.size(); ++ i) {
4160 d_assertions.replace(i, Rewriter::rewrite(d_assertions[i]));
4161 }
4162 } else {
4163 applySubstitutionsToAssertions();
4164 }
4165 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-substitution" << endl;
4166 dumpAssertions("post-substitution", d_assertions);
4167
4168 // Assertions ARE guaranteed to be rewritten by this point
4169 #ifdef CVC4_ASSERTIONS
4170 for (unsigned i = 0; i < d_assertions.size(); ++i)
4171 {
4172 Assert(Rewriter::rewrite(d_assertions[i]) == d_assertions[i]);
4173 }
4174 #endif
4175
4176 // Lift bit-vectors of size 1 to bool
4177 if(options::bitvectorToBool()) {
4178 dumpAssertions("pre-bv-to-bool", d_assertions);
4179 Chat() << "...doing bvToBool..." << endl;
4180 bvToBool();
4181 dumpAssertions("post-bv-to-bool", d_assertions);
4182 Trace("smt") << "POST bvToBool" << endl;
4183 }
4184 // Convert non-top-level Booleans to bit-vectors of size 1
4185 if(options::boolToBitvector()) {
4186 dumpAssertions("pre-bool-to-bv", d_assertions);
4187 Chat() << "...doing boolToBv..." << endl;
4188 boolToBv();
4189 dumpAssertions("post-bool-to-bv", d_assertions);
4190 Trace("smt") << "POST boolToBv" << endl;
4191 }
4192 if(options::sepPreSkolemEmp()) {
4193 for (unsigned i = 0; i < d_assertions.size(); ++ i) {
4194 Node prev = d_assertions[i];
4195 Node next = sep::TheorySepRewriter::preprocess( prev );
4196 if( next!=prev ){
4197 d_assertions.replace( i, Rewriter::rewrite( next ) );
4198 Trace("sep-preprocess") << "*** Preprocess sep " << prev << endl;
4199 Trace("sep-preprocess") << " ...got " << d_assertions[i] << endl;
4200 }
4201 }
4202 }
4203
4204 if( d_smt.d_logic.isQuantified() ){
4205 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-quant-preprocess" << endl;
4206
4207 dumpAssertions("pre-skolem-quant", d_assertions);
4208 //remove rewrite rules, apply pre-skolemization to existential quantifiers
4209 for (unsigned i = 0; i < d_assertions.size(); ++ i) {
4210 Node prev = d_assertions[i];
4211 Node next = quantifiers::QuantifiersRewriter::preprocess( prev );
4212 if( next!=prev ){
4213 d_assertions.replace( i, Rewriter::rewrite( next ) );
4214 Trace("quantifiers-preprocess") << "*** Pre-skolemize " << prev << endl;
4215 Trace("quantifiers-preprocess") << " ...got " << d_assertions[i] << endl;
4216 }
4217 }
4218 dumpAssertions("post-skolem-quant", d_assertions);
4219 if( options::macrosQuant() ){
4220 //quantifiers macro expansion
4221 quantifiers::QuantifierMacros qm( d_smt.d_theoryEngine->getQuantifiersEngine() );
4222 bool success;
4223 do{
4224 success = qm.simplify( d_assertions.ref(), true );
4225 }while( success );
4226 //finalize the definitions
4227 qm.finalizeDefinitions();
4228 }
4229
4230 //fmf-fun : assume admissible functions, applying preprocessing reduction to FMF
4231 if( options::fmfFunWellDefined() ){
4232 quantifiers::FunDefFmf fdf;
4233 Assert( d_smt.d_fmfRecFunctionsDefined!=NULL );
4234 //must carry over current definitions (for incremental)
4235 for( context::CDList<Node>::const_iterator fit = d_smt.d_fmfRecFunctionsDefined->begin();
4236 fit != d_smt.d_fmfRecFunctionsDefined->end(); ++fit ) {
4237 Node f = (*fit);
4238 Assert( d_smt.d_fmfRecFunctionsAbs.find( f )!=d_smt.d_fmfRecFunctionsAbs.end() );
4239 TypeNode ft = d_smt.d_fmfRecFunctionsAbs[f];
4240 fdf.d_sorts[f] = ft;
4241 std::map< Node, std::vector< Node > >::iterator fcit = d_smt.d_fmfRecFunctionsConcrete.find( f );
4242 Assert( fcit!=d_smt.d_fmfRecFunctionsConcrete.end() );
4243 for( unsigned j=0; j<fcit->second.size(); j++ ){
4244 fdf.d_input_arg_inj[f].push_back( fcit->second[j] );
4245 }
4246 }
4247 fdf.simplify( d_assertions.ref() );
4248 //must store new definitions (for incremental)
4249 for( unsigned i=0; i<fdf.d_funcs.size(); i++ ){
4250 Node f = fdf.d_funcs[i];
4251 d_smt.d_fmfRecFunctionsAbs[f] = fdf.d_sorts[f];
4252 d_smt.d_fmfRecFunctionsConcrete[f].clear();
4253 for( unsigned j=0; j<fdf.d_input_arg_inj[f].size(); j++ ){
4254 d_smt.d_fmfRecFunctionsConcrete[f].push_back( fdf.d_input_arg_inj[f][j] );
4255 }
4256 d_smt.d_fmfRecFunctionsDefined->push_back( f );
4257 }
4258 }
4259 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-quant-preprocess" << endl;
4260 }
4261
4262 if( options::sortInference() || options::ufssFairnessMonotone() ){
4263 //sort inference technique
4264 SortInference * si = d_smt.d_theoryEngine->getSortInference();
4265 si->simplify( d_assertions.ref(), options::sortInference(), options::ufssFairnessMonotone() );
4266 for( std::map< Node, Node >::iterator it = si->d_model_replace_f.begin(); it != si->d_model_replace_f.end(); ++it ){
4267 d_smt.setPrintFuncInModel( it->first.toExpr(), false );
4268 d_smt.setPrintFuncInModel( it->second.toExpr(), true );
4269 }
4270 }
4271
4272 if( options::pbRewrites() ){
4273 d_preprocessingPassRegistry.getPass("pseudo-boolean-processor")
4274 ->apply(&d_assertions);
4275 }
4276
4277 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-simplify" << endl;
4278 dumpAssertions("pre-simplify", d_assertions);
4279 Chat() << "simplifying assertions..." << endl;
4280 noConflict = simplifyAssertions();
4281 if(!noConflict){
4282 ++(d_smt.d_stats->d_simplifiedToFalse);
4283 }
4284 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-simplify" << endl;
4285 dumpAssertions("post-simplify", d_assertions);
4286
4287 if (options::symmetryDetect())
4288 {
4289 SymmetryDetect symd;
4290 vector<vector<Node>> part;
4291 symd.getPartition(part, d_assertions.ref());
4292 }
4293
4294 dumpAssertions("pre-static-learning", d_assertions);
4295 if(options::doStaticLearning()) {
4296 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-static-learning" << endl;
4297 // Perform static learning
4298 Chat() << "doing static learning..." << endl;
4299 Trace("simplify") << "SmtEnginePrivate::simplify(): "
4300 << "performing static learning" << endl;
4301 staticLearning();
4302 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-static-learning" << endl;
4303 }
4304 dumpAssertions("post-static-learning", d_assertions);
4305
4306 Debug("smt") << " d_assertions : " << d_assertions.size() << endl;
4307
4308
4309 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-ite-removal" << endl;
4310 dumpAssertions("pre-ite-removal", d_assertions);
4311 {
4312 Chat() << "removing term ITEs..." << endl;
4313 TimerStat::CodeTimer codeTimer(d_smt.d_stats->d_iteRemovalTime);
4314 // Remove ITEs, updating d_iteSkolemMap
4315 d_smt.d_stats->d_numAssertionsPre += d_assertions.size();
4316 removeITEs();
4317 // This is needed because when solving incrementally, removeITEs may introduce
4318 // skolems that were solved for earlier and thus appear in the substitution
4319 // map.
4320 applySubstitutionsToAssertions();
4321 d_smt.d_stats->d_numAssertionsPost += d_assertions.size();
4322 }
4323 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-ite-removal" << endl;
4324 dumpAssertions("post-ite-removal", d_assertions);
4325
4326 dumpAssertions("pre-repeat-simplify", d_assertions);
4327 if(options::repeatSimp()) {
4328 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-repeat-simplify" << endl;
4329 Chat() << "re-simplifying assertions..." << endl;
4330 ScopeCounter depth(d_simplifyAssertionsDepth);
4331 noConflict &= simplifyAssertions();
4332 if (noConflict) {
4333 // Need to fix up assertion list to maintain invariants:
4334 // Let Sk be the set of Skolem variables introduced by ITE's. Let <_sk be the order in which these variables were introduced
4335 // during ite removal.
4336 // For each skolem variable sk, let iteExpr = iteMap(sk) be the ite expr mapped to by sk.
4337
4338 // cache for expression traversal
4339 unordered_map<Node, bool, NodeHashFunction> cache;
4340
4341 // First, find all skolems that appear in the substitution map - their associated iteExpr will need
4342 // to be moved to the main assertion set
4343 set<TNode> skolemSet;
4344 SubstitutionMap::iterator pos = d_topLevelSubstitutions.begin();
4345 for (; pos != d_topLevelSubstitutions.end(); ++pos) {
4346 collectSkolems((*pos).first, skolemSet, cache);
4347 collectSkolems((*pos).second, skolemSet, cache);
4348 }
4349
4350 // We need to ensure:
4351 // 1. iteExpr has the form (ite cond (sk = t) (sk = e))
4352 // 2. if some sk' in Sk appears in cond, t, or e, then sk' <_sk sk
4353 // If either of these is violated, we must add iteExpr as a proper assertion
4354 IteSkolemMap::iterator it = d_iteSkolemMap.begin();
4355 IteSkolemMap::iterator iend = d_iteSkolemMap.end();
4356 NodeBuilder<> builder(kind::AND);
4357 builder << d_assertions[d_realAssertionsEnd - 1];
4358 vector<TNode> toErase;
4359 for (; it != iend; ++it) {
4360 if (skolemSet.find((*it).first) == skolemSet.end()) {
4361 TNode iteExpr = d_assertions[(*it).second];
4362 if (iteExpr.getKind() == kind::ITE &&
4363 iteExpr[1].getKind() == kind::EQUAL &&
4364 iteExpr[1][0] == (*it).first &&
4365 iteExpr[2].getKind() == kind::EQUAL &&
4366 iteExpr[2][0] == (*it).first) {
4367 cache.clear();
4368 bool bad = checkForBadSkolems(iteExpr[0], (*it).first, cache);
4369 bad = bad || checkForBadSkolems(iteExpr[1][1], (*it).first, cache);
4370 bad = bad || checkForBadSkolems(iteExpr[2][1], (*it).first, cache);
4371 if (!bad) {
4372 continue;
4373 }
4374 }
4375 }
4376 // Move this iteExpr into the main assertions
4377 builder << d_assertions[(*it).second];
4378 d_assertions[(*it).second] = NodeManager::currentNM()->mkConst<bool>(true);
4379 toErase.push_back((*it).first);
4380 }
4381 if(builder.getNumChildren() > 1) {
4382 while (!toErase.empty()) {
4383 d_iteSkolemMap.erase(toErase.back());
4384 toErase.pop_back();
4385 }
4386 d_assertions[d_realAssertionsEnd - 1] = Rewriter::rewrite(Node(builder));
4387 }
4388 // TODO(b/1256): For some reason this is needed for some benchmarks, such as
4389 // QF_AUFBV/dwp_formulas/try5_small_difret_functions_dwp_tac.re_node_set_remove_at.il.dwp.smt2
4390 removeITEs();
4391 applySubstitutionsToAssertions();
4392 // Assert(iteRewriteAssertionsEnd == d_assertions.size());
4393 }
4394 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-repeat-simplify" << endl;
4395 }
4396 dumpAssertions("post-repeat-simplify", d_assertions);
4397
4398 dumpAssertions("pre-rewrite-apply-to-const", d_assertions);
4399 if(options::rewriteApplyToConst()) {
4400 Chat() << "Rewriting applies to constants..." << endl;
4401 TimerStat::CodeTimer codeTimer(d_smt.d_stats->d_rewriteApplyToConstTime);
4402 for (unsigned i = 0; i < d_assertions.size(); ++ i) {
4403 d_assertions[i] = Rewriter::rewrite(rewriteApplyToConst(d_assertions[i]));
4404 }
4405 }
4406 dumpAssertions("post-rewrite-apply-to-const", d_assertions);
4407
4408 // begin: INVARIANT to maintain: no reordering of assertions or
4409 // introducing new ones
4410 #ifdef CVC4_ASSERTIONS
4411 unsigned iteRewriteAssertionsEnd = d_assertions.size();
4412 #endif
4413
4414 Debug("smt") << " d_assertions : " << d_assertions.size() << endl;
4415
4416 Debug("smt") << "SmtEnginePrivate::processAssertions() POST SIMPLIFICATION" << endl;
4417 Debug("smt") << " d_assertions : " << d_assertions.size() << endl;
4418
4419 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-theory-preprocessing" << endl;
4420 dumpAssertions("pre-theory-preprocessing", d_assertions);
4421 {
4422 Chat() << "theory preprocessing..." << endl;
4423 TimerStat::CodeTimer codeTimer(d_smt.d_stats->d_theoryPreprocessTime);
4424 // Call the theory preprocessors
4425 d_smt.d_theoryEngine->preprocessStart();
4426 for (unsigned i = 0; i < d_assertions.size(); ++ i) {
4427 d_assertions.replace(i, d_smt.d_theoryEngine->preprocess(d_assertions[i]));
4428 }
4429 }
4430 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-theory-preprocessing" << endl;
4431 dumpAssertions("post-theory-preprocessing", d_assertions);
4432
4433 // If we are using eager bit-blasting wrap assertions in fake atom so that
4434 // everything gets bit-blasted to internal SAT solver
4435 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER) {
4436 for (unsigned i = 0; i < d_assertions.size(); ++i) {
4437 TNode atom = d_assertions[i];
4438 Node eager_atom = NodeManager::currentNM()->mkNode(kind::BITVECTOR_EAGER_ATOM, atom);
4439 d_assertions.replace(i, eager_atom);
4440 TheoryModel* m = d_smt.d_theoryEngine->getModel();
4441 m->addSubstitution(eager_atom, atom);
4442 }
4443 }
4444
4445 //notify theory engine new preprocessed assertions
4446 d_smt.d_theoryEngine->notifyPreprocessedAssertions( d_assertions.ref() );
4447
4448 // Push the formula to decision engine
4449 if(noConflict) {
4450 Chat() << "pushing to decision engine..." << endl;
4451 Assert(iteRewriteAssertionsEnd == d_assertions.size());
4452 d_smt.d_decisionEngine->addAssertions
4453 (d_assertions.ref(), d_realAssertionsEnd, d_iteSkolemMap);
4454 }
4455
4456 // end: INVARIANT to maintain: no reordering of assertions or
4457 // introducing new ones
4458
4459 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() end" << endl;
4460 dumpAssertions("post-everything", d_assertions);
4461
4462 // Push the formula to SAT
4463 {
4464 Chat() << "converting to CNF..." << endl;
4465 TimerStat::CodeTimer codeTimer(d_smt.d_stats->d_cnfConversionTime);
4466 for (unsigned i = 0; i < d_assertions.size(); ++ i) {
4467 Chat() << "+ " << d_assertions[i] << std::endl;
4468 d_smt.d_propEngine->assertFormula(d_assertions[i]);
4469 }
4470 }
4471
4472 d_assertionsProcessed = true;
4473
4474 d_assertions.clear();
4475 d_iteSkolemMap.clear();
4476 }
4477
4478 void SmtEnginePrivate::addFormula(TNode n, bool inUnsatCore, bool inInput)
4479 {
4480 if (n == d_true) {
4481 // nothing to do
4482 return;
4483 }
4484
4485 Trace("smt") << "SmtEnginePrivate::addFormula(" << n << "), inUnsatCore = " << inUnsatCore << ", inInput = " << inInput << endl;
4486
4487 // Give it to proof manager
4488 PROOF(
4489 if( inInput ){
4490 // n is an input assertion
4491 if (inUnsatCore || options::unsatCores() || options::dumpUnsatCores() || options::checkUnsatCores() || options::fewerPreprocessingHoles()) {
4492
4493 ProofManager::currentPM()->addCoreAssertion(n.toExpr());
4494 }
4495 }else{
4496 // n is the result of an unknown preprocessing step, add it to dependency map to null
4497 ProofManager::currentPM()->addDependence(n, Node::null());
4498 }
4499 // rewrite rules are by default in the unsat core because
4500 // they need to be applied until saturation
4501 if(options::unsatCores() &&
4502 n.getKind() == kind::REWRITE_RULE ){
4503 ProofManager::currentPM()->addUnsatCore(n.toExpr());
4504 }
4505 );
4506
4507 // Add the normalized formula to the queue
4508 d_assertions.push_back(n);
4509 //d_assertions.push_back(Rewriter::rewrite(n));
4510 }
4511
4512 void SmtEngine::ensureBoolean(const Expr& e)
4513 {
4514 Type type = e.getType(options::typeChecking());
4515 Type boolType = d_exprManager->booleanType();
4516 if(type != boolType) {
4517 stringstream ss;
4518 ss << "Expected " << boolType << "\n"
4519 << "The assertion : " << e << "\n"
4520 << "Its type : " << type;
4521 throw TypeCheckingException(e, ss.str());
4522 }
4523 }
4524
4525 Result SmtEngine::checkSat(const Expr& assumption, bool inUnsatCore)
4526 {
4527 return checkSatisfiability(assumption, inUnsatCore, false);
4528 }
4529
4530 Result SmtEngine::checkSat(const vector<Expr>& assumptions, bool inUnsatCore)
4531 {
4532 return checkSatisfiability(assumptions, inUnsatCore, false);
4533 }
4534
4535 Result SmtEngine::query(const Expr& assumption, bool inUnsatCore)
4536 {
4537 Assert(!assumption.isNull());
4538 return checkSatisfiability(assumption, inUnsatCore, true);
4539 }
4540
4541 Result SmtEngine::query(const vector<Expr>& assumptions, bool inUnsatCore)
4542 {
4543 return checkSatisfiability(assumptions, inUnsatCore, true);
4544 }
4545
4546 Result SmtEngine::checkSatisfiability(const Expr& expr,
4547 bool inUnsatCore,
4548 bool isQuery)
4549 {
4550 return checkSatisfiability(
4551 expr.isNull() ? vector<Expr>() : vector<Expr>{expr},
4552 inUnsatCore,
4553 isQuery);
4554 }
4555
4556 Result SmtEngine::checkSatisfiability(const vector<Expr>& assumptions,
4557 bool inUnsatCore,
4558 bool isQuery)
4559 {
4560 try
4561 {
4562 SmtScope smts(this);
4563 finalOptionsAreSet();
4564 doPendingPops();
4565
4566 Trace("smt") << "SmtEngine::" << (isQuery ? "query" : "checkSat") << "("
4567 << assumptions << ")" << endl;
4568
4569 if(d_queryMade && !options::incrementalSolving()) {
4570 throw ModalException("Cannot make multiple queries unless "
4571 "incremental solving is enabled "
4572 "(try --incremental)");
4573 }
4574
4575 // check to see if a postsolve() is pending
4576 if(d_needPostsolve) {
4577 d_theoryEngine->postsolve();
4578 d_needPostsolve = false;
4579 }
4580 // Note that a query has been made
4581 d_queryMade = true;
4582 // reset global negation
4583 d_globalNegation = false;
4584
4585 bool didInternalPush = false;
4586
4587 setProblemExtended(true);
4588
4589 if (isQuery)
4590 {
4591 size_t size = assumptions.size();
4592 if (size > 1)
4593 {
4594 /* Assume: not (BIGAND assumptions) */
4595 d_assumptions.push_back(
4596 d_exprManager->mkExpr(kind::AND, assumptions).notExpr());
4597 }
4598 else if (size == 1)
4599 {
4600 /* Assume: not expr */
4601 d_assumptions.push_back(assumptions[0].notExpr());
4602 }
4603 }
4604 else
4605 {
4606 /* Assume: BIGAND assumptions */
4607 d_assumptions = assumptions;
4608 }
4609
4610 Result r(Result::SAT_UNKNOWN, Result::UNKNOWN_REASON);
4611 for (Expr e : d_assumptions)
4612 {
4613 // Substitute out any abstract values in ex.
4614 e = d_private->substituteAbstractValues(Node::fromExpr(e)).toExpr();
4615 Assert(e.getExprManager() == d_exprManager);
4616 // Ensure expr is type-checked at this point.
4617 ensureBoolean(e);
4618
4619 /* Add assumption */
4620 internalPush();
4621 didInternalPush = true;
4622 if (d_assertionList != NULL)
4623 {
4624 d_assertionList->push_back(e);
4625 }
4626 d_private->addFormula(e.getNode(), inUnsatCore);
4627 }
4628
4629 r = isQuery ? check().asValidityResult() : check().asSatisfiabilityResult();
4630
4631 if ((options::solveRealAsInt() || options::solveIntAsBV() > 0)
4632 && r.asSatisfiabilityResult().isSat() == Result::UNSAT)
4633 {
4634 r = Result(Result::SAT_UNKNOWN, Result::UNKNOWN_REASON);
4635 }
4636 // flipped if we did a global negation
4637 if (d_globalNegation)
4638 {
4639 Trace("smt") << "SmtEngine::process global negate " << r << std::endl;
4640 if (r.asSatisfiabilityResult().isSat() == Result::UNSAT)
4641 {
4642 r = Result(Result::SAT);
4643 }
4644 else if (r.asSatisfiabilityResult().isSat() == Result::SAT)
4645 {
4646 // only if satisfaction complete
4647 if (d_logic.isPure(THEORY_ARITH) || d_logic.isPure(THEORY_BV))
4648 {
4649 r = Result(Result::UNSAT);
4650 }
4651 else
4652 {
4653 r = Result(Result::SAT_UNKNOWN, Result::UNKNOWN_REASON);
4654 }
4655 }
4656 Trace("smt") << "SmtEngine::global negate returned " << r << std::endl;
4657 }
4658
4659 d_needPostsolve = true;
4660
4661 // Dump the query if requested
4662 if (Dump.isOn("benchmark"))
4663 {
4664 size_t size = assumptions.size();
4665 // the expr already got dumped out if assertion-dumping is on
4666 if (isQuery && size == 1)
4667 {
4668 Dump("benchmark") << QueryCommand(assumptions[0]);
4669 }
4670 else if (size == 0)
4671 {
4672 Dump("benchmark") << CheckSatCommand();
4673 }
4674 else
4675 {
4676 Dump("benchmark") << CheckSatAssumingCommand(d_assumptions,
4677 inUnsatCore);
4678 }
4679 }
4680
4681 // Pop the context
4682 if (didInternalPush)
4683 {
4684 internalPop();
4685 }
4686
4687 // Remember the status
4688 d_status = r;
4689
4690 setProblemExtended(false);
4691
4692 Trace("smt") << "SmtEngine::" << (isQuery ? "query" : "checkSat") << "("
4693 << assumptions << ") => " << r << endl;
4694
4695 // Check that SAT results generate a model correctly.
4696 if(options::checkModels()) {
4697 // TODO (#1693) check model when unknown result?
4698 if (r.asSatisfiabilityResult().isSat() == Result::SAT)
4699 {
4700 checkModel();
4701 }
4702 }
4703 // Check that UNSAT results generate a proof correctly.
4704 if(options::checkProofs()) {
4705 if(r.asSatisfiabilityResult().isSat() == Result::UNSAT) {
4706 TimerStat::CodeTimer checkProofTimer(d_stats->d_checkProofTime);
4707 checkProof();
4708 }
4709 }
4710 // Check that UNSAT results generate an unsat core correctly.
4711 if(options::checkUnsatCores()) {
4712 if(r.asSatisfiabilityResult().isSat() == Result::UNSAT) {
4713 TimerStat::CodeTimer checkUnsatCoreTimer(d_stats->d_checkUnsatCoreTime);
4714 checkUnsatCore();
4715 }
4716 }
4717 // Check that synthesis solutions satisfy the conjecture
4718 if (options::checkSynthSol()
4719 && r.asSatisfiabilityResult().isSat() == Result::UNSAT)
4720 {
4721 checkSynthSolution();
4722 }
4723
4724 return r;
4725 } catch (UnsafeInterruptException& e) {
4726 AlwaysAssert(d_private->getResourceManager()->out());
4727 Result::UnknownExplanation why = d_private->getResourceManager()->outOfResources() ?
4728 Result::RESOURCEOUT : Result::TIMEOUT;
4729 return Result(Result::SAT_UNKNOWN, why, d_filename);
4730 }
4731 }
4732
4733 vector<Expr> SmtEngine::getUnsatAssumptions(void)
4734 {
4735 Trace("smt") << "SMT getUnsatAssumptions()" << endl;
4736 SmtScope smts(this);
4737 if (!options::unsatAssumptions())
4738 {
4739 throw ModalException(
4740 "Cannot get unsat assumptions when produce-unsat-assumptions option "
4741 "is off.");
4742 }
4743 if (d_status.isNull()
4744 || d_status.asSatisfiabilityResult() != Result::UNSAT
4745 || d_problemExtended)
4746 {
4747 throw RecoverableModalException(
4748 "Cannot get unsat assumptions unless immediately preceded by "
4749 "UNSAT/VALID response.");
4750 }
4751 finalOptionsAreSet();
4752 if (Dump.isOn("benchmark"))
4753 {
4754 Dump("benchmark") << GetUnsatCoreCommand();
4755 }
4756 UnsatCore core = getUnsatCore();
4757 vector<Expr> res;
4758 for (const Expr& e : d_assumptions)
4759 {
4760 if (find(core.begin(), core.end(), e) != core.end()) { res.push_back(e); }
4761 }
4762 return res;
4763 }
4764
4765 Result SmtEngine::checkSynth(const Expr& e)
4766 {
4767 SmtScope smts(this);
4768 Trace("smt") << "Check synth: " << e << std::endl;
4769 Trace("smt-synth") << "Check synthesis conjecture: " << e << std::endl;
4770 Expr e_check = e;
4771 if (options::sygusQePreproc())
4772 {
4773 // the following does quantifier elimination as a preprocess step
4774 // for "non-ground single invocation synthesis conjectures":
4775 // exists f. forall xy. P[ f(x), x, y ]
4776 // We run quantifier elimination:
4777 // exists y. P[ z, x, y ] ----> Q[ z, x ]
4778 // Where we replace the original conjecture with:
4779 // exists f. forall x. Q[ f(x), x ]
4780 // For more details, see Example 6 of Reynolds et al. SYNT 2017.
4781 Node conj = Node::fromExpr(e);
4782 if (conj.getKind() == kind::FORALL && conj[1].getKind() == kind::EXISTS)
4783 {
4784 Node conj_se = Node::fromExpr(expandDefinitions(conj[1][1].toExpr()));
4785
4786 Trace("smt-synth") << "Compute single invocation for " << conj_se << "..."
4787 << std::endl;
4788 quantifiers::SingleInvocationPartition sip;
4789 std::vector<Node> funcs;
4790 funcs.insert(funcs.end(), conj[0].begin(), conj[0].end());
4791 sip.init(funcs, conj_se.negate());
4792 Trace("smt-synth") << "...finished, got:" << std::endl;
4793 sip.debugPrint("smt-synth");
4794
4795 if (!sip.isPurelySingleInvocation() && sip.isNonGroundSingleInvocation())
4796 {
4797 // create new smt engine to do quantifier elimination
4798 SmtEngine smt_qe(d_exprManager);
4799 smt_qe.setLogic(getLogicInfo());
4800 Trace("smt-synth") << "Property is non-ground single invocation, run "
4801 "QE to obtain single invocation."
4802 << std::endl;
4803 NodeManager* nm = NodeManager::currentNM();
4804 // partition variables
4805 std::vector<Node> all_vars;
4806 sip.getAllVariables(all_vars);
4807 std::vector<Node> si_vars;
4808 sip.getSingleInvocationVariables(si_vars);
4809 std::vector<Node> qe_vars;
4810 std::vector<Node> nqe_vars;
4811 for (unsigned i = 0, size = all_vars.size(); i < size; i++)
4812 {
4813 Node v = all_vars[i];
4814 if (std::find(si_vars.begin(), si_vars.end(), v) == si_vars.end())
4815 {
4816 qe_vars.push_back(v);
4817 }
4818 else
4819 {
4820 nqe_vars.push_back(v);
4821 }
4822 }
4823 std::vector<Node> orig;
4824 std::vector<Node> subs;
4825 // skolemize non-qe variables
4826 for (unsigned i = 0; i < nqe_vars.size(); i++)
4827 {
4828 Node k = nm->mkSkolem("k",
4829 nqe_vars[i].getType(),
4830 "qe for non-ground single invocation");
4831 orig.push_back(nqe_vars[i]);
4832 subs.push_back(k);
4833 Trace("smt-synth") << " subs : " << nqe_vars[i] << " -> " << k
4834 << std::endl;
4835 }
4836 std::vector<Node> funcs;
4837 sip.getFunctions(funcs);
4838 for (unsigned i = 0, size = funcs.size(); i < size; i++)
4839 {
4840 Node f = funcs[i];
4841 Node fi = sip.getFunctionInvocationFor(f);
4842 Node fv = sip.getFirstOrderVariableForFunction(f);
4843 Assert(!fi.isNull());
4844 orig.push_back(fi);
4845 Node k =
4846 nm->mkSkolem("k",
4847 fv.getType(),
4848 "qe for function in non-ground single invocation");
4849 subs.push_back(k);
4850 Trace("smt-synth") << " subs : " << fi << " -> " << k << std::endl;
4851 }
4852 Node conj_se_ngsi = sip.getFullSpecification();
4853 Trace("smt-synth") << "Full specification is " << conj_se_ngsi
4854 << std::endl;
4855 Node conj_se_ngsi_subs = conj_se_ngsi.substitute(
4856 orig.begin(), orig.end(), subs.begin(), subs.end());
4857 Assert(!qe_vars.empty());
4858 conj_se_ngsi_subs =
4859 nm->mkNode(kind::EXISTS,
4860 nm->mkNode(kind::BOUND_VAR_LIST, qe_vars),
4861 conj_se_ngsi_subs.negate());
4862
4863 Trace("smt-synth") << "Run quantifier elimination on "
4864 << conj_se_ngsi_subs << std::endl;
4865 Expr qe_res = smt_qe.doQuantifierElimination(
4866 conj_se_ngsi_subs.toExpr(), true, false);
4867 Trace("smt-synth") << "Result : " << qe_res << std::endl;
4868
4869 // create single invocation conjecture
4870 Node qe_res_n = Node::fromExpr(qe_res);
4871 qe_res_n = qe_res_n.substitute(
4872 subs.begin(), subs.end(), orig.begin(), orig.end());
4873 if (!nqe_vars.empty())
4874 {
4875 qe_res_n = nm->mkNode(kind::EXISTS,
4876 nm->mkNode(kind::BOUND_VAR_LIST, nqe_vars),
4877 qe_res_n);
4878 }
4879 Assert(conj.getNumChildren() == 3);
4880 qe_res_n = nm->mkNode(kind::FORALL, conj[0], qe_res_n, conj[2]);
4881 Trace("smt-synth") << "Converted conjecture after QE : " << qe_res_n
4882 << std::endl;
4883 e_check = qe_res_n.toExpr();
4884 }
4885 }
4886 }
4887
4888 return checkSatisfiability( e_check, true, false );
4889 }
4890
4891 Result SmtEngine::assertFormula(const Expr& ex, bool inUnsatCore)
4892 {
4893 Assert(ex.getExprManager() == d_exprManager);
4894 SmtScope smts(this);
4895 finalOptionsAreSet();
4896 doPendingPops();
4897
4898 Trace("smt") << "SmtEngine::assertFormula(" << ex << ")" << endl;
4899
4900 if (Dump.isOn("raw-benchmark")) {
4901 Dump("raw-benchmark") << AssertCommand(ex);
4902 }
4903
4904 // Substitute out any abstract values in ex
4905 Expr e = d_private->substituteAbstractValues(Node::fromExpr(ex)).toExpr();
4906
4907 ensureBoolean(e);
4908 if(d_assertionList != NULL) {
4909 d_assertionList->push_back(e);
4910 }
4911 d_private->addFormula(e.getNode(), inUnsatCore);
4912 return quickCheck().asValidityResult();
4913 }/* SmtEngine::assertFormula() */
4914
4915 Node SmtEngine::postprocess(TNode node, TypeNode expectedType) const {
4916 return node;
4917 }
4918
4919 Expr SmtEngine::simplify(const Expr& ex)
4920 {
4921 Assert(ex.getExprManager() == d_exprManager);
4922 SmtScope smts(this);
4923 finalOptionsAreSet();
4924 doPendingPops();
4925 Trace("smt") << "SMT simplify(" << ex << ")" << endl;
4926
4927 if(Dump.isOn("benchmark")) {
4928 Dump("benchmark") << SimplifyCommand(ex);
4929 }
4930
4931 Expr e = d_private->substituteAbstractValues(Node::fromExpr(ex)).toExpr();
4932 if( options::typeChecking() ) {
4933 e.getType(true); // ensure expr is type-checked at this point
4934 }
4935
4936 // Make sure all preprocessing is done
4937 d_private->processAssertions();
4938 Node n = d_private->simplify(Node::fromExpr(e));
4939 n = postprocess(n, TypeNode::fromType(e.getType()));
4940 return n.toExpr();
4941 }
4942
4943 Expr SmtEngine::expandDefinitions(const Expr& ex)
4944 {
4945 d_private->spendResource(options::preprocessStep());
4946
4947 Assert(ex.getExprManager() == d_exprManager);
4948 SmtScope smts(this);
4949 finalOptionsAreSet();
4950 doPendingPops();
4951 Trace("smt") << "SMT expandDefinitions(" << ex << ")" << endl;
4952
4953 // Substitute out any abstract values in ex.
4954 Expr e = d_private->substituteAbstractValues(Node::fromExpr(ex)).toExpr();
4955 if(options::typeChecking()) {
4956 // Ensure expr is type-checked at this point.
4957 e.getType(true);
4958 }
4959 if(Dump.isOn("benchmark")) {
4960 Dump("benchmark") << ExpandDefinitionsCommand(e);
4961 }
4962 unordered_map<Node, Node, NodeHashFunction> cache;
4963 Node n = d_private->expandDefinitions(Node::fromExpr(e), cache, /* expandOnly = */ true);
4964 n = postprocess(n, TypeNode::fromType(e.getType()));
4965
4966 return n.toExpr();
4967 }
4968
4969 // TODO(#1108): Simplify the error reporting of this method.
4970 Expr SmtEngine::getValue(const Expr& ex) const
4971 {
4972 Assert(ex.getExprManager() == d_exprManager);
4973 SmtScope smts(this);
4974
4975 Trace("smt") << "SMT getValue(" << ex << ")" << endl;
4976 if(Dump.isOn("benchmark")) {
4977 Dump("benchmark") << GetValueCommand(ex);
4978 }
4979
4980 if(!options::produceModels()) {
4981 const char* msg =
4982 "Cannot get value when produce-models options is off.";
4983 throw ModalException(msg);
4984 }
4985 if(d_status.isNull() ||
4986 d_status.asSatisfiabilityResult() == Result::UNSAT ||
4987 d_problemExtended) {
4988 const char* msg =
4989 "Cannot get value unless immediately preceded by SAT/INVALID or UNKNOWN response.";
4990 throw RecoverableModalException(msg);
4991 }
4992
4993 // Substitute out any abstract values in ex.
4994 Expr e = d_private->substituteAbstractValues(Node::fromExpr(ex)).toExpr();
4995
4996 // Ensure expr is type-checked at this point.
4997 e.getType(options::typeChecking());
4998
4999 // do not need to apply preprocessing substitutions (should be recorded
5000 // in model already)
5001
5002 Node n = Node::fromExpr(e);
5003 Trace("smt") << "--- getting value of " << n << endl;
5004 TypeNode expectedType = n.getType();
5005
5006 // Expand, then normalize
5007 unordered_map<Node, Node, NodeHashFunction> cache;
5008 n = d_private->expandDefinitions(n, cache);
5009 // There are two ways model values for terms are computed (for historical
5010 // reasons). One way is that used in check-model; the other is that
5011 // used by the Model classes. It's not clear to me exactly how these
5012 // two are different, but they need to be unified. This ugly hack here
5013 // is to fix bug 554 until we can revamp boolean-terms and models [MGD]
5014
5015 //AJR : necessary?
5016 if(!n.getType().isFunction()) {
5017 n = Rewriter::rewrite(n);
5018 }
5019
5020 Trace("smt") << "--- getting value of " << n << endl;
5021 TheoryModel* m = d_theoryEngine->getModel();
5022 Node resultNode;
5023 if(m != NULL) {
5024 resultNode = m->getValue(n);
5025 }
5026 Trace("smt") << "--- got value " << n << " = " << resultNode << endl;
5027 resultNode = postprocess(resultNode, expectedType);
5028 Trace("smt") << "--- model-post returned " << resultNode << endl;
5029 Trace("smt") << "--- model-post returned " << resultNode.getType() << endl;
5030 Trace("smt") << "--- model-post expected " << expectedType << endl;
5031
5032 // type-check the result we got
5033 Assert(resultNode.isNull() || resultNode.getType().isSubtypeOf(expectedType),
5034 "Run with -t smt for details.");
5035
5036 // ensure it's a constant
5037 Assert(resultNode.getKind() == kind::LAMBDA || resultNode.isConst());
5038
5039 if(options::abstractValues() && resultNode.getType().isArray()) {
5040 resultNode = d_private->mkAbstractValue(resultNode);
5041 Trace("smt") << "--- abstract value >> " << resultNode << endl;
5042 }
5043
5044 return resultNode.toExpr();
5045 }
5046
5047 bool SmtEngine::addToAssignment(const Expr& ex) {
5048 SmtScope smts(this);
5049 finalOptionsAreSet();
5050 doPendingPops();
5051 // Substitute out any abstract values in ex
5052 Expr e = d_private->substituteAbstractValues(Node::fromExpr(ex)).toExpr();
5053 Type type = e.getType(options::typeChecking());
5054 // must be Boolean
5055 PrettyCheckArgument(
5056 type.isBoolean(), e,
5057 "expected Boolean-typed variable or function application "
5058 "in addToAssignment()" );
5059 Node n = e.getNode();
5060 // must be an APPLY of a zero-ary defined function, or a variable
5061 PrettyCheckArgument(
5062 ( ( n.getKind() == kind::APPLY &&
5063 ( d_definedFunctions->find(n.getOperator()) !=
5064 d_definedFunctions->end() ) &&
5065 n.getNumChildren() == 0 ) ||
5066 n.isVar() ), e,
5067 "expected variable or defined-function application "
5068 "in addToAssignment(),\ngot %s", e.toString().c_str() );
5069 if(!options::produceAssignments()) {
5070 return false;
5071 }
5072 if(d_assignments == NULL) {
5073 d_assignments = new(true) AssignmentSet(d_context);
5074 }
5075 d_assignments->insert(n);
5076
5077 return true;
5078 }
5079
5080 // TODO(#1108): Simplify the error reporting of this method.
5081 vector<pair<Expr, Expr>> SmtEngine::getAssignment()
5082 {
5083 Trace("smt") << "SMT getAssignment()" << endl;
5084 SmtScope smts(this);
5085 finalOptionsAreSet();
5086 if(Dump.isOn("benchmark")) {
5087 Dump("benchmark") << GetAssignmentCommand();
5088 }
5089 if(!options::produceAssignments()) {
5090 const char* msg =
5091 "Cannot get the current assignment when "
5092 "produce-assignments option is off.";
5093 throw ModalException(msg);
5094 }
5095 if(d_status.isNull() ||
5096 d_status.asSatisfiabilityResult() == Result::UNSAT ||
5097 d_problemExtended) {
5098 const char* msg =
5099 "Cannot get the current assignment unless immediately "
5100 "preceded by SAT/INVALID or UNKNOWN response.";
5101 throw RecoverableModalException(msg);
5102 }
5103
5104 vector<pair<Expr,Expr>> res;
5105 if (d_assignments != nullptr)
5106 {
5107 TypeNode boolType = d_nodeManager->booleanType();
5108 TheoryModel* m = d_theoryEngine->getModel();
5109 for (AssignmentSet::key_iterator i = d_assignments->key_begin(),
5110 iend = d_assignments->key_end();
5111 i != iend;
5112 ++i)
5113 {
5114 Node as = *i;
5115 Assert(as.getType() == boolType);
5116
5117 Trace("smt") << "--- getting value of " << as << endl;
5118
5119 // Expand, then normalize
5120 unordered_map<Node, Node, NodeHashFunction> cache;
5121 Node n = d_private->expandDefinitions(as, cache);
5122 n = Rewriter::rewrite(n);
5123
5124 Trace("smt") << "--- getting value of " << n << endl;
5125 Node resultNode;
5126 if (m != nullptr)
5127 {
5128 resultNode = m->getValue(n);
5129 }
5130
5131 // type-check the result we got
5132 Assert(resultNode.isNull() || resultNode.getType() == boolType);
5133
5134 // ensure it's a constant
5135 Assert(resultNode.isConst());
5136
5137 Assert(as.getKind() == kind::APPLY || as.isVar());
5138 Assert(as.getKind() != kind::APPLY || as.getNumChildren() == 0);
5139 res.emplace_back(as.toExpr(), resultNode.toExpr());
5140 }
5141 }
5142 return res;
5143 }
5144
5145 void SmtEngine::addToModelCommandAndDump(const Command& c, uint32_t flags, bool userVisible, const char* dumpTag) {
5146 Trace("smt") << "SMT addToModelCommandAndDump(" << c << ")" << endl;
5147 SmtScope smts(this);
5148 // If we aren't yet fully inited, the user might still turn on
5149 // produce-models. So let's keep any commands around just in
5150 // case. This is useful in two cases: (1) SMT-LIBv1 auto-declares
5151 // sort "U" in QF_UF before setLogic() is run and we still want to
5152 // support finding card(U) with --finite-model-find, and (2) to
5153 // decouple SmtEngine and ExprManager if the user does a few
5154 // ExprManager::mkSort() before SmtEngine::setOption("produce-models")
5155 // and expects to find their cardinalities in the model.
5156 if(/* userVisible && */
5157 (!d_fullyInited || options::produceModels()) &&
5158 (flags & ExprManager::VAR_FLAG_DEFINED) == 0) {
5159 doPendingPops();
5160 if(flags & ExprManager::VAR_FLAG_GLOBAL) {
5161 d_modelGlobalCommands.push_back(c.clone());
5162 } else {
5163 d_modelCommands->push_back(c.clone());
5164 }
5165 }
5166 if(Dump.isOn(dumpTag)) {
5167 if(d_fullyInited) {
5168 Dump(dumpTag) << c;
5169 } else {
5170 d_dumpCommands.push_back(c.clone());
5171 }
5172 }
5173 }
5174
5175 // TODO(#1108): Simplify the error reporting of this method.
5176 Model* SmtEngine::getModel() {
5177 Trace("smt") << "SMT getModel()" << endl;
5178 SmtScope smts(this);
5179
5180 finalOptionsAreSet();
5181
5182 if(Dump.isOn("benchmark")) {
5183 Dump("benchmark") << GetModelCommand();
5184 }
5185
5186 if(d_status.isNull() ||
5187 d_status.asSatisfiabilityResult() == Result::UNSAT ||
5188 d_problemExtended) {
5189 const char* msg =
5190 "Cannot get the current model unless immediately "
5191 "preceded by SAT/INVALID or UNKNOWN response.";
5192 throw RecoverableModalException(msg);
5193 }
5194 if(!options::produceModels()) {
5195 const char* msg =
5196 "Cannot get model when produce-models options is off.";
5197 throw ModalException(msg);
5198 }
5199 TheoryModel* m = d_theoryEngine->getModel();
5200 m->d_inputName = d_filename;
5201 return m;
5202 }
5203
5204 void SmtEngine::checkUnsatCore() {
5205 Assert(options::unsatCores(), "cannot check unsat core if unsat cores are turned off");
5206
5207 Notice() << "SmtEngine::checkUnsatCore(): generating unsat core" << endl;
5208 UnsatCore core = getUnsatCore();
5209
5210 SmtEngine coreChecker(d_exprManager);
5211 coreChecker.setLogic(getLogicInfo());
5212
5213 PROOF(
5214 std::vector<Command*>::const_iterator itg = d_defineCommands.begin();
5215 for (; itg != d_defineCommands.end(); ++itg) {
5216 (*itg)->invoke(&coreChecker);
5217 }
5218 );
5219
5220 Notice() << "SmtEngine::checkUnsatCore(): pushing core assertions (size == " << core.size() << ")" << endl;
5221 for(UnsatCore::iterator i = core.begin(); i != core.end(); ++i) {
5222 Notice() << "SmtEngine::checkUnsatCore(): pushing core member " << *i << endl;
5223 coreChecker.assertFormula(*i);
5224 }
5225 const bool checkUnsatCores = options::checkUnsatCores();
5226 Result r;
5227 try {
5228 options::checkUnsatCores.set(false);
5229 options::checkProofs.set(false);
5230 r = coreChecker.checkSat();
5231 } catch(...) {
5232 options::checkUnsatCores.set(checkUnsatCores);
5233 throw;
5234 }
5235 Notice() << "SmtEngine::checkUnsatCore(): result is " << r << endl;
5236 if(r.asSatisfiabilityResult().isUnknown()) {
5237 InternalError("SmtEngine::checkUnsatCore(): could not check core result unknown.");
5238 }
5239
5240 if(r.asSatisfiabilityResult().isSat()) {
5241 InternalError("SmtEngine::checkUnsatCore(): produced core was satisfiable.");
5242 }
5243 }
5244
5245 void SmtEngine::checkModel(bool hardFailure) {
5246 // --check-model implies --produce-assertions, which enables the
5247 // assertion list, so we should be ok.
5248 Assert(d_assertionList != NULL, "don't have an assertion list to check in SmtEngine::checkModel()");
5249
5250 TimerStat::CodeTimer checkModelTimer(d_stats->d_checkModelTime);
5251
5252 // Throughout, we use Notice() to give diagnostic output.
5253 //
5254 // If this function is running, the user gave --check-model (or equivalent),
5255 // and if Notice() is on, the user gave --verbose (or equivalent).
5256
5257 Notice() << "SmtEngine::checkModel(): generating model" << endl;
5258 TheoryModel* m = d_theoryEngine->getModel();
5259
5260 // Check individual theory assertions
5261 d_theoryEngine->checkTheoryAssertionsWithModel(hardFailure);
5262
5263 // Output the model
5264 Notice() << *m;
5265
5266 // We have a "fake context" for the substitution map (we don't need it
5267 // to be context-dependent)
5268 context::Context fakeContext;
5269 SubstitutionMap substitutions(&fakeContext, /* substituteUnderQuantifiers = */ false);
5270
5271 for(size_t k = 0; k < m->getNumCommands(); ++k) {
5272 const DeclareFunctionCommand* c = dynamic_cast<const DeclareFunctionCommand*>(m->getCommand(k));
5273 Notice() << "SmtEngine::checkModel(): model command " << k << " : " << m->getCommand(k) << endl;
5274 if(c == NULL) {
5275 // we don't care about DECLARE-DATATYPES, DECLARE-SORT, ...
5276 Notice() << "SmtEngine::checkModel(): skipping..." << endl;
5277 } else {
5278 // We have a DECLARE-FUN:
5279 //
5280 // We'll first do some checks, then add to our substitution map
5281 // the mapping: function symbol |-> value
5282
5283 Expr func = c->getFunction();
5284 Node val = m->getValue(func);
5285
5286 Notice() << "SmtEngine::checkModel(): adding substitution: " << func << " |-> " << val << endl;
5287
5288 // (1) if the value is a lambda, ensure the lambda doesn't contain the
5289 // function symbol (since then the definition is recursive)
5290 if (val.getKind() == kind::LAMBDA) {
5291 // first apply the model substitutions we have so far
5292 Debug("boolean-terms") << "applying subses to " << val[1] << endl;
5293 Node n = substitutions.apply(val[1]);
5294 Debug("boolean-terms") << "++ got " << n << endl;
5295 // now check if n contains func by doing a substitution
5296 // [func->func2] and checking equality of the Nodes.
5297 // (this just a way to check if func is in n.)
5298 SubstitutionMap subs(&fakeContext);
5299 Node func2 = NodeManager::currentNM()->mkSkolem("", TypeNode::fromType(func.getType()), "", NodeManager::SKOLEM_NO_NOTIFY);
5300 subs.addSubstitution(func, func2);
5301 if(subs.apply(n) != n) {
5302 Notice() << "SmtEngine::checkModel(): *** PROBLEM: MODEL VALUE DEFINED IN TERMS OF ITSELF ***" << endl;
5303 stringstream ss;
5304 ss << "SmtEngine::checkModel(): ERRORS SATISFYING ASSERTIONS WITH MODEL:" << endl
5305 << "considering model value for " << func << endl
5306 << "body of lambda is: " << val << endl;
5307 if(n != val[1]) {
5308 ss << "body substitutes to: " << n << endl;
5309 }
5310 ss << "so " << func << " is defined in terms of itself." << endl
5311 << "Run with `--check-models -v' for additional diagnostics.";
5312 InternalError(ss.str());
5313 }
5314 }
5315
5316 // (2) check that the value is actually a value
5317 else if (!val.isConst()) {
5318 Notice() << "SmtEngine::checkModel(): *** PROBLEM: MODEL VALUE NOT A CONSTANT ***" << endl;
5319 stringstream ss;
5320 ss << "SmtEngine::checkModel(): ERRORS SATISFYING ASSERTIONS WITH MODEL:" << endl
5321 << "model value for " << func << endl
5322 << " is " << val << endl
5323 << "and that is not a constant (.isConst() == false)." << endl
5324 << "Run with `--check-models -v' for additional diagnostics.";
5325 InternalError(ss.str());
5326 }
5327
5328 // (3) check that it's the correct (sub)type
5329 // This was intended to be a more general check, but for now we can't do that because
5330 // e.g. "1" is an INT, which isn't a subrange type [1..10] (etc.).
5331 else if(func.getType().isInteger() && !val.getType().isInteger()) {
5332 Notice() << "SmtEngine::checkModel(): *** PROBLEM: MODEL VALUE NOT CORRECT TYPE ***" << endl;
5333 stringstream ss;
5334 ss << "SmtEngine::checkModel(): ERRORS SATISFYING ASSERTIONS WITH MODEL:" << endl
5335 << "model value for " << func << endl
5336 << " is " << val << endl
5337 << "value type is " << val.getType() << endl
5338 << "should be of type " << func.getType() << endl
5339 << "Run with `--check-models -v' for additional diagnostics.";
5340 InternalError(ss.str());
5341 }
5342
5343 // (4) checks complete, add the substitution
5344 Debug("boolean-terms") << "cm: adding subs " << func << " :=> " << val << endl;
5345 substitutions.addSubstitution(func, val);
5346 }
5347 }
5348
5349 // Now go through all our user assertions checking if they're satisfied.
5350 for(AssertionList::const_iterator i = d_assertionList->begin(); i != d_assertionList->end(); ++i) {
5351 Notice() << "SmtEngine::checkModel(): checking assertion " << *i << endl;
5352 Node n = Node::fromExpr(*i);
5353
5354 // Apply any define-funs from the problem.
5355 {
5356 unordered_map<Node, Node, NodeHashFunction> cache;
5357 n = d_private->expandDefinitions(n, cache);
5358 }
5359 Notice() << "SmtEngine::checkModel(): -- expands to " << n << endl;
5360
5361 // Apply our model value substitutions.
5362 Debug("boolean-terms") << "applying subses to " << n << endl;
5363 n = substitutions.apply(n);
5364 Debug("boolean-terms") << "++ got " << n << endl;
5365 Notice() << "SmtEngine::checkModel(): -- substitutes to " << n << endl;
5366
5367 if( n.getKind() != kind::REWRITE_RULE ){
5368 // In case it's a quantifier (or contains one), look up its value before
5369 // simplifying, or the quantifier might be irreparably altered.
5370 n = m->getValue(n);
5371 Notice() << "SmtEngine::checkModel(): -- get value : " << n << std::endl;
5372 } else {
5373 // Note this "skip" is done here, rather than above. This is
5374 // because (1) the quantifier could in principle simplify to false,
5375 // which should be reported, and (2) checking for the quantifier
5376 // above, before simplification, doesn't catch buried quantifiers
5377 // anyway (those not at the top-level).
5378 Notice() << "SmtEngine::checkModel(): -- skipping rewrite-rules assertion"
5379 << endl;
5380 continue;
5381 }
5382
5383 // Simplify the result.
5384 n = d_private->simplify(n);
5385 Notice() << "SmtEngine::checkModel(): -- simplifies to " << n << endl;
5386
5387 // Replace the already-known ITEs (this is important for ground ITEs under quantifiers).
5388 n = d_private->d_iteRemover.replace(n);
5389 Notice() << "SmtEngine::checkModel(): -- ite replacement gives " << n << endl;
5390
5391 // Apply our model value substitutions (again), as things may have been simplified.
5392 Debug("boolean-terms") << "applying subses to " << n << endl;
5393 n = substitutions.apply(n);
5394 Debug("boolean-terms") << "++ got " << n << endl;
5395 Notice() << "SmtEngine::checkModel(): -- re-substitutes to " << n << endl;
5396
5397 // As a last-ditch effort, ask model to simplify it.
5398 // Presently, this is only an issue for quantifiers, which can have a value
5399 // but don't show up in our substitution map above.
5400 n = m->getValue(n);
5401 Notice() << "SmtEngine::checkModel(): -- model-substitutes to " << n << endl;
5402
5403 if( d_logic.isQuantified() ){
5404 // AJR: since quantified formulas are not checkable, we assign them to true/false based on the satisfying assignment.
5405 // however, quantified formulas can be modified during preprocess, so they may not correspond to those in the satisfying assignment.
5406 // hence we use a relaxed version of check model here.
5407 // this is necessary until preprocessing passes explicitly record how they rewrite quantified formulas
5408 if( hardFailure && !n.isConst() && n.getKind() != kind::LAMBDA ){
5409 Notice() << "SmtEngine::checkModel(): -- relax check model wrt quantified formulas..." << endl;
5410 AlwaysAssert( quantifiers::QuantifiersRewriter::containsQuantifiers( n ) );
5411 Warning() << "Warning : SmtEngine::checkModel(): cannot check simplified assertion : " << n << endl;
5412 continue;
5413 }
5414 }else{
5415 AlwaysAssert(!hardFailure || n.isConst() || n.getKind() == kind::LAMBDA);
5416 }
5417 // The result should be == true.
5418 if(n != NodeManager::currentNM()->mkConst(true)) {
5419 Notice() << "SmtEngine::checkModel(): *** PROBLEM: EXPECTED `TRUE' ***"
5420 << endl;
5421 stringstream ss;
5422 ss << "SmtEngine::checkModel(): "
5423 << "ERRORS SATISFYING ASSERTIONS WITH MODEL:" << endl
5424 << "assertion: " << *i << endl
5425 << "simplifies to: " << n << endl
5426 << "expected `true'." << endl
5427 << "Run with `--check-models -v' for additional diagnostics.";
5428 if(hardFailure) {
5429 InternalError(ss.str());
5430 } else {
5431 Warning() << ss.str() << endl;
5432 }
5433 }
5434 }
5435 Notice() << "SmtEngine::checkModel(): all assertions checked out OK !" << endl;
5436 }
5437
5438 void SmtEngine::checkSynthSolution()
5439 {
5440 NodeManager* nm = NodeManager::currentNM();
5441 Notice() << "SmtEngine::checkSynthSolution(): checking synthesis solution" << endl;
5442 map<Node, Node> sol_map;
5443 /* Get solutions and build auxiliary vectors for substituting */
5444 d_theoryEngine->getSynthSolutions(sol_map);
5445 Trace("check-synth-sol") << "Got solution map:\n";
5446 std::vector<Node> function_vars, function_sols;
5447 for (const auto& pair : sol_map)
5448 {
5449 Trace("check-synth-sol") << pair.first << " --> " << pair.second << "\n";
5450 function_vars.push_back(pair.first);
5451 function_sols.push_back(pair.second);
5452 }
5453 Trace("check-synth-sol") << "Starting new SMT Engine\n";
5454 /* Start new SMT engine to check solutions */
5455 SmtEngine solChecker(d_exprManager);
5456 solChecker.setLogic(getLogicInfo());
5457 setOption("check-synth-sol", SExpr("false"));
5458
5459 Trace("check-synth-sol") << "Retrieving assertions\n";
5460 // Build conjecture from original assertions
5461 if (d_assertionList == NULL)
5462 {
5463 Trace("check-synth-sol") << "No assertions to check\n";
5464 return;
5465 }
5466 for (AssertionList::const_iterator i = d_assertionList->begin();
5467 i != d_assertionList->end();
5468 ++i)
5469 {
5470 Notice() << "SmtEngine::checkSynthSolution(): checking assertion " << *i << endl;
5471 Trace("check-synth-sol") << "Retrieving assertion " << *i << "\n";
5472 Node conj = Node::fromExpr(*i);
5473 // Apply any define-funs from the problem.
5474 {
5475 unordered_map<Node, Node, NodeHashFunction> cache;
5476 conj = d_private->expandDefinitions(conj, cache);
5477 }
5478 Notice() << "SmtEngine::checkSynthSolution(): -- expands to " << conj << endl;
5479 Trace("check-synth-sol") << "Expanded assertion " << conj << "\n";
5480
5481 // Apply solution map to conjecture body
5482 Node conjBody;
5483 /* Whether property is quantifier free */
5484 if (conj[1].getKind() != kind::EXISTS)
5485 {
5486 conjBody = conj[1].substitute(function_vars.begin(),
5487 function_vars.end(),
5488 function_sols.begin(),
5489 function_sols.end());
5490 }
5491 else
5492 {
5493 conjBody = conj[1][1].substitute(function_vars.begin(),
5494 function_vars.end(),
5495 function_sols.begin(),
5496 function_sols.end());
5497
5498 /* Skolemize property */
5499 std::vector<Node> vars, skos;
5500 for (unsigned j = 0, size = conj[1][0].getNumChildren(); j < size; ++j)
5501 {
5502 vars.push_back(conj[1][0][j]);
5503 std::stringstream ss;
5504 ss << "sk_" << j;
5505 skos.push_back(nm->mkSkolem(ss.str(), conj[1][0][j].getType()));
5506 Trace("check-synth-sol") << "\tSkolemizing " << conj[1][0][j] << " to "
5507 << skos.back() << "\n";
5508 }
5509 conjBody = conjBody.substitute(
5510 vars.begin(), vars.end(), skos.begin(), skos.end());
5511 }
5512 Notice() << "SmtEngine::checkSynthSolution(): -- body substitutes to "
5513 << conjBody << endl;
5514 Trace("check-synth-sol") << "Substituted body of assertion to " << conjBody
5515 << "\n";
5516 solChecker.assertFormula(conjBody.toExpr());
5517 Result r = solChecker.checkSat();
5518 Notice() << "SmtEngine::checkSynthSolution(): result is " << r << endl;
5519 Trace("check-synth-sol") << "Satsifiability check: " << r << "\n";
5520 if (r.asSatisfiabilityResult().isUnknown())
5521 {
5522 InternalError(
5523 "SmtEngine::checkSynthSolution(): could not check solution, result "
5524 "unknown.");
5525 }
5526 else if (r.asSatisfiabilityResult().isSat())
5527 {
5528 InternalError(
5529 "SmtEngine::checkSynhtSol(): produced solution allows satisfiable "
5530 "negated conjecture.");
5531 }
5532 solChecker.resetAssertions();
5533 }
5534 }
5535
5536 // TODO(#1108): Simplify the error reporting of this method.
5537 UnsatCore SmtEngine::getUnsatCore() {
5538 Trace("smt") << "SMT getUnsatCore()" << endl;
5539 SmtScope smts(this);
5540 finalOptionsAreSet();
5541 if(Dump.isOn("benchmark")) {
5542 Dump("benchmark") << GetUnsatCoreCommand();
5543 }
5544 #if IS_PROOFS_BUILD
5545 if(!options::unsatCores()) {
5546 throw ModalException("Cannot get an unsat core when produce-unsat-cores option is off.");
5547 }
5548 if(d_status.isNull() ||
5549 d_status.asSatisfiabilityResult() != Result::UNSAT ||
5550 d_problemExtended) {
5551 throw RecoverableModalException(
5552 "Cannot get an unsat core unless immediately preceded by UNSAT/VALID "
5553 "response.");
5554 }
5555
5556 d_proofManager->traceUnsatCore();// just to trigger core creation
5557 return UnsatCore(this, d_proofManager->extractUnsatCore());
5558 #else /* IS_PROOFS_BUILD */
5559 throw ModalException("This build of CVC4 doesn't have proof support (required for unsat cores).");
5560 #endif /* IS_PROOFS_BUILD */
5561 }
5562
5563 // TODO(#1108): Simplify the error reporting of this method.
5564 const Proof& SmtEngine::getProof()
5565 {
5566 Trace("smt") << "SMT getProof()" << endl;
5567 SmtScope smts(this);
5568 finalOptionsAreSet();
5569 if(Dump.isOn("benchmark")) {
5570 Dump("benchmark") << GetProofCommand();
5571 }
5572 #if IS_PROOFS_BUILD
5573 if(!options::proof()) {
5574 throw ModalException("Cannot get a proof when produce-proofs option is off.");
5575 }
5576 if(d_status.isNull() ||
5577 d_status.asSatisfiabilityResult() != Result::UNSAT ||
5578 d_problemExtended) {
5579 throw RecoverableModalException(
5580 "Cannot get a proof unless immediately preceded by UNSAT/VALID "
5581 "response.");
5582 }
5583
5584 return ProofManager::getProof(this);
5585 #else /* IS_PROOFS_BUILD */
5586 throw ModalException("This build of CVC4 doesn't have proof support.");
5587 #endif /* IS_PROOFS_BUILD */
5588 }
5589
5590 void SmtEngine::printInstantiations( std::ostream& out ) {
5591 SmtScope smts(this);
5592 if( options::instFormatMode()==INST_FORMAT_MODE_SZS ){
5593 out << "% SZS output start Proof for " << d_filename.c_str() << std::endl;
5594 }
5595 if( d_theoryEngine ){
5596 d_theoryEngine->printInstantiations( out );
5597 }else{
5598 Assert( false );
5599 }
5600 if( options::instFormatMode()==INST_FORMAT_MODE_SZS ){
5601 out << "% SZS output end Proof for " << d_filename.c_str() << std::endl;
5602 }
5603 }
5604
5605 void SmtEngine::printSynthSolution( std::ostream& out ) {
5606 SmtScope smts(this);
5607 if( d_theoryEngine ){
5608 d_theoryEngine->printSynthSolution( out );
5609 }else{
5610 Assert( false );
5611 }
5612 }
5613
5614 Expr SmtEngine::doQuantifierElimination(const Expr& e, bool doFull, bool strict)
5615 {
5616 SmtScope smts(this);
5617 if(!d_logic.isPure(THEORY_ARITH) && strict){
5618 Warning() << "Unexpected logic for quantifier elimination " << d_logic << endl;
5619 }
5620 Trace("smt-qe") << "Do quantifier elimination " << e << std::endl;
5621 Node n_e = Node::fromExpr( e );
5622 if (n_e.getKind() != kind::EXISTS && n_e.getKind() != kind::FORALL)
5623 {
5624 throw ModalException(
5625 "Expecting a quantified formula as argument to get-qe.");
5626 }
5627 //tag the quantified formula with the quant-elim attribute
5628 TypeNode t = NodeManager::currentNM()->booleanType();
5629 Node n_attr = NodeManager::currentNM()->mkSkolem("qe", t, "Auxiliary variable for qe attr.");
5630 std::vector< Node > node_values;
5631 d_theoryEngine->setUserAttribute( doFull ? "quant-elim" : "quant-elim-partial", n_attr, node_values, "");
5632 n_attr = NodeManager::currentNM()->mkNode(kind::INST_ATTRIBUTE, n_attr);
5633 n_attr = NodeManager::currentNM()->mkNode(kind::INST_PATTERN_LIST, n_attr);
5634 std::vector< Node > e_children;
5635 e_children.push_back( n_e[0] );
5636 e_children.push_back(n_e.getKind() == kind::EXISTS ? n_e[1]
5637 : n_e[1].negate());
5638 e_children.push_back( n_attr );
5639 Node nn_e = NodeManager::currentNM()->mkNode( kind::EXISTS, e_children );
5640 Trace("smt-qe-debug") << "Query for quantifier elimination : " << nn_e << std::endl;
5641 Assert( nn_e.getNumChildren()==3 );
5642 Result r = checkSatisfiability(nn_e.toExpr(), true, true);
5643 Trace("smt-qe") << "Query returned " << r << std::endl;
5644 if(r.asSatisfiabilityResult().isSat() != Result::UNSAT ) {
5645 if( r.asSatisfiabilityResult().isSat() != Result::SAT && doFull ){
5646 stringstream ss;
5647 ss << "While performing quantifier elimination, unexpected result : " << r << " for query.";
5648 InternalError(ss.str().c_str());
5649 }
5650 std::vector< Node > inst_qs;
5651 d_theoryEngine->getInstantiatedQuantifiedFormulas( inst_qs );
5652 Assert( inst_qs.size()<=1 );
5653 Node ret_n;
5654 if( inst_qs.size()==1 ){
5655 Node top_q = inst_qs[0];
5656 //Node top_q = Rewriter::rewrite( nn_e ).negate();
5657 Assert( top_q.getKind()==kind::FORALL );
5658 Trace("smt-qe") << "Get qe for " << top_q << std::endl;
5659 ret_n = d_theoryEngine->getInstantiatedConjunction( top_q );
5660 Trace("smt-qe") << "Returned : " << ret_n << std::endl;
5661 if (n_e.getKind() == kind::EXISTS)
5662 {
5663 ret_n = Rewriter::rewrite(ret_n.negate());
5664 }
5665 }else{
5666 ret_n = NodeManager::currentNM()->mkConst(n_e.getKind() != kind::EXISTS);
5667 }
5668 return ret_n.toExpr();
5669 }else {
5670 return NodeManager::currentNM()
5671 ->mkConst(n_e.getKind() == kind::EXISTS)
5672 .toExpr();
5673 }
5674 }
5675
5676 void SmtEngine::getInstantiatedQuantifiedFormulas( std::vector< Expr >& qs ) {
5677 SmtScope smts(this);
5678 if( d_theoryEngine ){
5679 std::vector< Node > qs_n;
5680 d_theoryEngine->getInstantiatedQuantifiedFormulas( qs_n );
5681 for( unsigned i=0; i<qs_n.size(); i++ ){
5682 qs.push_back( qs_n[i].toExpr() );
5683 }
5684 }else{
5685 Assert( false );
5686 }
5687 }
5688
5689 void SmtEngine::getInstantiations( Expr q, std::vector< Expr >& insts ) {
5690 SmtScope smts(this);
5691 if( d_theoryEngine ){
5692 std::vector< Node > insts_n;
5693 d_theoryEngine->getInstantiations( Node::fromExpr( q ), insts_n );
5694 for( unsigned i=0; i<insts_n.size(); i++ ){
5695 insts.push_back( insts_n[i].toExpr() );
5696 }
5697 }else{
5698 Assert( false );
5699 }
5700 }
5701
5702 void SmtEngine::getInstantiationTermVectors( Expr q, std::vector< std::vector< Expr > >& tvecs ) {
5703 SmtScope smts(this);
5704 Assert(options::trackInstLemmas());
5705 if( d_theoryEngine ){
5706 std::vector< std::vector< Node > > tvecs_n;
5707 d_theoryEngine->getInstantiationTermVectors( Node::fromExpr( q ), tvecs_n );
5708 for( unsigned i=0; i<tvecs_n.size(); i++ ){
5709 std::vector< Expr > tvec;
5710 for( unsigned j=0; j<tvecs_n[i].size(); j++ ){
5711 tvec.push_back( tvecs_n[i][j].toExpr() );
5712 }
5713 tvecs.push_back( tvec );
5714 }
5715 }else{
5716 Assert( false );
5717 }
5718 }
5719
5720 vector<Expr> SmtEngine::getAssertions() {
5721 SmtScope smts(this);
5722 finalOptionsAreSet();
5723 doPendingPops();
5724 if(Dump.isOn("benchmark")) {
5725 Dump("benchmark") << GetAssertionsCommand();
5726 }
5727 Trace("smt") << "SMT getAssertions()" << endl;
5728 if(!options::produceAssertions()) {
5729 const char* msg =
5730 "Cannot query the current assertion list when not in produce-assertions mode.";
5731 throw ModalException(msg);
5732 }
5733 Assert(d_assertionList != NULL);
5734 // copy the result out
5735 return vector<Expr>(d_assertionList->begin(), d_assertionList->end());
5736 }
5737
5738 void SmtEngine::push()
5739 {
5740 SmtScope smts(this);
5741 finalOptionsAreSet();
5742 doPendingPops();
5743 Trace("smt") << "SMT push()" << endl;
5744 d_private->notifyPush();
5745 d_private->processAssertions();
5746 if(Dump.isOn("benchmark")) {
5747 Dump("benchmark") << PushCommand();
5748 }
5749 if(!options::incrementalSolving()) {
5750 throw ModalException("Cannot push when not solving incrementally (use --incremental)");
5751 }
5752
5753 // check to see if a postsolve() is pending
5754 if(d_needPostsolve) {
5755 d_theoryEngine->postsolve();
5756 d_needPostsolve = false;
5757 }
5758
5759 // The problem isn't really "extended" yet, but this disallows
5760 // get-model after a push, simplifying our lives somewhat and
5761 // staying symmtric with pop.
5762 setProblemExtended(true);
5763
5764 d_userLevels.push_back(d_userContext->getLevel());
5765 internalPush();
5766 Trace("userpushpop") << "SmtEngine: pushed to level "
5767 << d_userContext->getLevel() << endl;
5768 }
5769
5770 void SmtEngine::pop() {
5771 SmtScope smts(this);
5772 finalOptionsAreSet();
5773 Trace("smt") << "SMT pop()" << endl;
5774 if(Dump.isOn("benchmark")) {
5775 Dump("benchmark") << PopCommand();
5776 }
5777 if(!options::incrementalSolving()) {
5778 throw ModalException("Cannot pop when not solving incrementally (use --incremental)");
5779 }
5780 if(d_userLevels.size() == 0) {
5781 throw ModalException("Cannot pop beyond the first user frame");
5782 }
5783
5784 // check to see if a postsolve() is pending
5785 if(d_needPostsolve) {
5786 d_theoryEngine->postsolve();
5787 d_needPostsolve = false;
5788 }
5789
5790 // The problem isn't really "extended" yet, but this disallows
5791 // get-model after a pop, simplifying our lives somewhat. It might
5792 // not be strictly necessary to do so, since the pops occur lazily,
5793 // but also it would be weird to have a legally-executed (get-model)
5794 // that only returns a subset of the assignment (because the rest
5795 // is no longer in scope!).
5796 setProblemExtended(true);
5797
5798 AlwaysAssert(d_userContext->getLevel() > 0);
5799 AlwaysAssert(d_userLevels.back() < d_userContext->getLevel());
5800 while (d_userLevels.back() < d_userContext->getLevel()) {
5801 internalPop(true);
5802 }
5803 d_userLevels.pop_back();
5804
5805 // Clear out assertion queues etc., in case anything is still in there
5806 d_private->notifyPop();
5807
5808 Trace("userpushpop") << "SmtEngine: popped to level "
5809 << d_userContext->getLevel() << endl;
5810 // FIXME: should we reset d_status here?
5811 // SMT-LIBv2 spec seems to imply no, but it would make sense to..
5812 }
5813
5814 void SmtEngine::internalPush() {
5815 Assert(d_fullyInited);
5816 Trace("smt") << "SmtEngine::internalPush()" << endl;
5817 doPendingPops();
5818 if(options::incrementalSolving()) {
5819 d_private->processAssertions();
5820 TimerStat::CodeTimer pushPopTimer(d_stats->d_pushPopTime);
5821 d_userContext->push();
5822 // the d_context push is done inside of the SAT solver
5823 d_propEngine->push();
5824 }
5825 }
5826
5827 void SmtEngine::internalPop(bool immediate) {
5828 Assert(d_fullyInited);
5829 Trace("smt") << "SmtEngine::internalPop()" << endl;
5830 if(options::incrementalSolving()) {
5831 ++d_pendingPops;
5832 }
5833 if(immediate) {
5834 doPendingPops();
5835 }
5836 }
5837
5838 void SmtEngine::doPendingPops() {
5839 Assert(d_pendingPops == 0 || options::incrementalSolving());
5840 while(d_pendingPops > 0) {
5841 TimerStat::CodeTimer pushPopTimer(d_stats->d_pushPopTime);
5842 d_propEngine->pop();
5843 // the d_context pop is done inside of the SAT solver
5844 d_userContext->pop();
5845 --d_pendingPops;
5846 }
5847 }
5848
5849 void SmtEngine::reset()
5850 {
5851 SmtScope smts(this);
5852 ExprManager *em = d_exprManager;
5853 Trace("smt") << "SMT reset()" << endl;
5854 if(Dump.isOn("benchmark")) {
5855 Dump("benchmark") << ResetCommand();
5856 }
5857 Options opts;
5858 opts.copyValues(d_originalOptions);
5859 this->~SmtEngine();
5860 NodeManager::fromExprManager(em)->getOptions().copyValues(opts);
5861 new(this) SmtEngine(em);
5862 }
5863
5864 void SmtEngine::resetAssertions()
5865 {
5866 SmtScope smts(this);
5867 doPendingPops();
5868
5869 Trace("smt") << "SMT resetAssertions()" << endl;
5870 if(Dump.isOn("benchmark")) {
5871 Dump("benchmark") << ResetAssertionsCommand();
5872 }
5873
5874 while(!d_userLevels.empty()) {
5875 pop();
5876 }
5877
5878 // Also remember the global push/pop around everything.
5879 Assert(d_userLevels.size() == 0 && d_userContext->getLevel() == 1);
5880 d_context->popto(0);
5881 d_userContext->popto(0);
5882 DeleteAndClearCommandVector(d_modelGlobalCommands);
5883 d_userContext->push();
5884 d_context->push();
5885 }
5886
5887 void SmtEngine::interrupt()
5888 {
5889 if(!d_fullyInited) {
5890 return;
5891 }
5892 d_propEngine->interrupt();
5893 d_theoryEngine->interrupt();
5894 }
5895
5896 void SmtEngine::setResourceLimit(unsigned long units, bool cumulative) {
5897 d_private->getResourceManager()->setResourceLimit(units, cumulative);
5898 }
5899 void SmtEngine::setTimeLimit(unsigned long milis, bool cumulative) {
5900 d_private->getResourceManager()->setTimeLimit(milis, cumulative);
5901 }
5902
5903 unsigned long SmtEngine::getResourceUsage() const {
5904 return d_private->getResourceManager()->getResourceUsage();
5905 }
5906
5907 unsigned long SmtEngine::getTimeUsage() const {
5908 return d_private->getResourceManager()->getTimeUsage();
5909 }
5910
5911 unsigned long SmtEngine::getResourceRemaining() const
5912 {
5913 return d_private->getResourceManager()->getResourceRemaining();
5914 }
5915
5916 unsigned long SmtEngine::getTimeRemaining() const
5917 {
5918 return d_private->getResourceManager()->getTimeRemaining();
5919 }
5920
5921 Statistics SmtEngine::getStatistics() const
5922 {
5923 return Statistics(*d_statisticsRegistry);
5924 }
5925
5926 SExpr SmtEngine::getStatistic(std::string name) const
5927 {
5928 return d_statisticsRegistry->getStatistic(name);
5929 }
5930
5931 void SmtEngine::safeFlushStatistics(int fd) const {
5932 d_statisticsRegistry->safeFlushInformation(fd);
5933 }
5934
5935 void SmtEngine::setUserAttribute(const std::string& attr,
5936 Expr expr,
5937 const std::vector<Expr>& expr_values,
5938 const std::string& str_value)
5939 {
5940 SmtScope smts(this);
5941 std::vector<Node> node_values;
5942 for( unsigned i=0; i<expr_values.size(); i++ ){
5943 node_values.push_back( expr_values[i].getNode() );
5944 }
5945 d_theoryEngine->setUserAttribute(attr, expr.getNode(), node_values, str_value);
5946 }
5947
5948 void SmtEngine::setPrintFuncInModel(Expr f, bool p) {
5949 Trace("setp-model") << "Set printInModel " << f << " to " << p << std::endl;
5950 for( unsigned i=0; i<d_modelGlobalCommands.size(); i++ ){
5951 Command * c = d_modelGlobalCommands[i];
5952 DeclareFunctionCommand* dfc = dynamic_cast<DeclareFunctionCommand*>(c);
5953 if(dfc != NULL) {
5954 if( dfc->getFunction()==f ){
5955 dfc->setPrintInModel( p );
5956 }
5957 }
5958 }
5959 for( unsigned i=0; i<d_modelCommands->size(); i++ ){
5960 Command * c = (*d_modelCommands)[i];
5961 DeclareFunctionCommand* dfc = dynamic_cast<DeclareFunctionCommand*>(c);
5962 if(dfc != NULL) {
5963 if( dfc->getFunction()==f ){
5964 dfc->setPrintInModel( p );
5965 }
5966 }
5967 }
5968 }
5969
5970 void SmtEngine::beforeSearch()
5971 {
5972 if(d_fullyInited) {
5973 throw ModalException(
5974 "SmtEngine::beforeSearch called after initialization.");
5975 }
5976 }
5977
5978
5979 void SmtEngine::setOption(const std::string& key, const CVC4::SExpr& value)
5980 {
5981 NodeManagerScope nms(d_nodeManager);
5982 Trace("smt") << "SMT setOption(" << key << ", " << value << ")" << endl;
5983
5984 if(Dump.isOn("benchmark")) {
5985 Dump("benchmark") << SetOptionCommand(key, value);
5986 }
5987
5988 if(key == "command-verbosity") {
5989 if(!value.isAtom()) {
5990 const vector<SExpr>& cs = value.getChildren();
5991 if(cs.size() == 2 &&
5992 (cs[0].isKeyword() || cs[0].isString()) &&
5993 cs[1].isInteger()) {
5994 string c = cs[0].getValue();
5995 const Integer& v = cs[1].getIntegerValue();
5996 if(v < 0 || v > 2) {
5997 throw OptionException("command-verbosity must be 0, 1, or 2");
5998 }
5999 d_commandVerbosity[c] = v;
6000 return;
6001 }
6002 }
6003 throw OptionException("command-verbosity value must be a tuple (command-name, integer)");
6004 }
6005
6006 if(!value.isAtom()) {
6007 throw OptionException("bad value for :" + key);
6008 }
6009
6010 string optionarg = value.getValue();
6011 Options& nodeManagerOptions = NodeManager::currentNM()->getOptions();
6012 nodeManagerOptions.setOption(key, optionarg);
6013 }
6014
6015 CVC4::SExpr SmtEngine::getOption(const std::string& key) const
6016 {
6017 NodeManagerScope nms(d_nodeManager);
6018
6019 Trace("smt") << "SMT getOption(" << key << ")" << endl;
6020
6021 if(key.length() >= 18 &&
6022 key.compare(0, 18, "command-verbosity:") == 0) {
6023 map<string, Integer>::const_iterator i = d_commandVerbosity.find(key.c_str() + 18);
6024 if(i != d_commandVerbosity.end()) {
6025 return SExpr((*i).second);
6026 }
6027 i = d_commandVerbosity.find("*");
6028 if(i != d_commandVerbosity.end()) {
6029 return SExpr((*i).second);
6030 }
6031 return SExpr(Integer(2));
6032 }
6033
6034 if(Dump.isOn("benchmark")) {
6035 Dump("benchmark") << GetOptionCommand(key);
6036 }
6037
6038 if(key == "command-verbosity") {
6039 vector<SExpr> result;
6040 SExpr defaultVerbosity;
6041 for(map<string, Integer>::const_iterator i = d_commandVerbosity.begin();
6042 i != d_commandVerbosity.end();
6043 ++i) {
6044 vector<SExpr> v;
6045 v.push_back(SExpr((*i).first));
6046 v.push_back(SExpr((*i).second));
6047 if((*i).first == "*") {
6048 // put the default at the end of the SExpr
6049 defaultVerbosity = SExpr(v);
6050 } else {
6051 result.push_back(SExpr(v));
6052 }
6053 }
6054 // put the default at the end of the SExpr
6055 if(!defaultVerbosity.isAtom()) {
6056 result.push_back(defaultVerbosity);
6057 } else {
6058 // ensure the default is always listed
6059 vector<SExpr> v;
6060 v.push_back(SExpr("*"));
6061 v.push_back(SExpr(Integer(2)));
6062 result.push_back(SExpr(v));
6063 }
6064 return SExpr(result);
6065 }
6066
6067 Options& nodeManagerOptions = NodeManager::currentNM()->getOptions();
6068 return SExpr::parseAtom(nodeManagerOptions.getOption(key));
6069 }
6070
6071 void SmtEngine::setReplayStream(ExprStream* replayStream) {
6072 AlwaysAssert(!d_fullyInited,
6073 "Cannot set replay stream once fully initialized");
6074 d_replayStream = replayStream;
6075 }
6076
6077 bool SmtEngine::getExpressionName(Expr e, std::string& name) const {
6078 return d_private->getExpressionName(e, name);
6079 }
6080
6081 void SmtEngine::setExpressionName(Expr e, const std::string& name) {
6082 Trace("smt-debug") << "Set expression name " << e << " to " << name << std::endl;
6083 d_private->setExpressionName(e,name);
6084 }
6085
6086 }/* CVC4 namespace */