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