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