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