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