1 /********************* */
2 /*! \file smt_engine.cpp
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
12 ** \brief The main entry point into the CVC4 library's SMT interface
14 ** The main entry point into the CVC4 library's SMT interface.
17 #include "smt/smt_engine.h"
26 #include <unordered_map>
27 #include <unordered_set>
31 #include "base/configuration.h"
32 #include "base/configuration_private.h"
33 #include "base/exception.h"
34 #include "base/listener.h"
35 #include "base/modal_exception.h"
36 #include "base/output.h"
37 #include "context/cdhashmap.h"
38 #include "context/cdhashset.h"
39 #include "context/cdlist.h"
40 #include "context/context.h"
41 #include "decision/decision_engine.h"
42 #include "expr/attribute.h"
43 #include "expr/expr.h"
44 #include "expr/kind.h"
45 #include "expr/metakind.h"
46 #include "expr/node.h"
47 #include "expr/node_builder.h"
48 #include "expr/node_self_iterator.h"
49 #include "options/arith_options.h"
50 #include "options/arrays_options.h"
51 #include "options/base_options.h"
52 #include "options/booleans_options.h"
53 #include "options/bv_options.h"
54 #include "options/datatypes_options.h"
55 #include "options/decision_mode.h"
56 #include "options/decision_options.h"
57 #include "options/language.h"
58 #include "options/main_options.h"
59 #include "options/open_ostream.h"
60 #include "options/option_exception.h"
61 #include "options/printer_options.h"
62 #include "options/proof_options.h"
63 #include "options/prop_options.h"
64 #include "options/quantifiers_options.h"
65 #include "options/sep_options.h"
66 #include "options/set_language.h"
67 #include "options/smt_options.h"
68 #include "options/strings_options.h"
69 #include "options/theory_options.h"
70 #include "options/uf_options.h"
71 #include "preprocessing/passes/apply_substs.h"
72 #include "preprocessing/passes/bool_to_bv.h"
73 #include "preprocessing/passes/bv_abstraction.h"
74 #include "preprocessing/passes/bv_ackermann.h"
75 #include "preprocessing/passes/bv_gauss.h"
76 #include "preprocessing/passes/bv_intro_pow2.h"
77 #include "preprocessing/passes/bv_to_bool.h"
78 #include "preprocessing/passes/int_to_bv.h"
79 #include "preprocessing/passes/pseudo_boolean_processor.h"
80 #include "preprocessing/passes/real_to_int.h"
81 #include "preprocessing/passes/rewrite.h"
82 #include "preprocessing/passes/sep_skolem_emp.h"
83 #include "preprocessing/passes/static_learning.h"
84 #include "preprocessing/passes/symmetry_breaker.h"
85 #include "preprocessing/passes/symmetry_detect.h"
86 #include "preprocessing/passes/synth_rew_rules.h"
87 #include "preprocessing/preprocessing_pass.h"
88 #include "preprocessing/preprocessing_pass_context.h"
89 #include "preprocessing/preprocessing_pass_registry.h"
90 #include "printer/printer.h"
91 #include "proof/proof.h"
92 #include "proof/proof_manager.h"
93 #include "proof/theory_proof.h"
94 #include "proof/unsat_core.h"
95 #include "prop/prop_engine.h"
96 #include "smt/command.h"
97 #include "smt/command_list.h"
98 #include "smt/logic_request.h"
99 #include "smt/managed_ostreams.h"
100 #include "smt/smt_engine_scope.h"
101 #include "smt/term_formula_removal.h"
102 #include "smt/update_ostream.h"
103 #include "smt_util/boolean_simplification.h"
104 #include "smt_util/nary_builder.h"
105 #include "smt_util/node_visitor.h"
106 #include "theory/booleans/circuit_propagator.h"
107 #include "theory/bv/theory_bv_rewriter.h"
108 #include "theory/logic_info.h"
109 #include "theory/quantifiers/fun_def_process.h"
110 #include "theory/quantifiers/global_negate.h"
111 #include "theory/quantifiers/macros.h"
112 #include "theory/quantifiers/quantifiers_rewriter.h"
113 #include "theory/quantifiers/single_inv_partition.h"
114 #include "theory/quantifiers/sygus/ce_guided_instantiation.h"
115 #include "theory/quantifiers/sygus_inference.h"
116 #include "theory/quantifiers/term_util.h"
117 #include "theory/rewriter.h"
118 #include "theory/sort_inference.h"
119 #include "theory/strings/theory_strings.h"
120 #include "theory/substitutions.h"
121 #include "theory/theory_engine.h"
122 #include "theory/theory_model.h"
123 #include "theory/theory_traits.h"
124 #include "util/hash.h"
125 #include "util/proof.h"
126 #include "util/random.h"
127 #include "util/resource_manager.h"
130 using namespace CVC4
;
131 using namespace CVC4::smt
;
132 using namespace CVC4::preprocessing
;
133 using namespace CVC4::preprocessing::passes
;
134 using namespace CVC4::prop
;
135 using namespace CVC4::context
;
136 using namespace CVC4::theory
;
141 struct DeleteCommandFunction
: public std::unary_function
<const Command
*, void>
143 void operator()(const Command
* command
) { delete command
; }
146 void DeleteAndClearCommandVector(std::vector
<Command
*>& commands
) {
147 std::for_each(commands
.begin(), commands
.end(), DeleteCommandFunction());
151 /** Useful for counting the number of recursive calls. */
156 ScopeCounter(unsigned& d
) : d_depth(d
) {
165 * Representation of a defined function. We keep these around in
166 * SmtEngine to permit expanding definitions late (and lazily), to
167 * support getValue() over defined functions, to support user output
168 * in terms of defined functions, etc.
170 class DefinedFunction
{
172 vector
<Node
> d_formals
;
176 DefinedFunction(Node func
, vector
<Node
> formals
, Node formula
) :
181 Node
getFunction() const { return d_func
; }
182 vector
<Node
> getFormals() const { return d_formals
; }
183 Node
getFormula() const { return d_formula
; }
184 };/* class DefinedFunction */
186 struct SmtEngineStatistics
{
187 /** time spent in gaussian elimination */
188 TimerStat d_gaussElimTime
;
189 /** time spent in definition-expansion */
190 TimerStat d_definitionExpansionTime
;
191 /** time spent in non-clausal simplification */
192 TimerStat d_nonclausalSimplificationTime
;
193 /** time spent in miplib pass */
194 TimerStat d_miplibPassTime
;
195 /** number of assertions removed by miplib pass */
196 IntStat d_numMiplibAssertionsRemoved
;
197 /** number of constant propagations found during nonclausal simp */
198 IntStat d_numConstantProps
;
199 /** time spent in simplifying ITEs */
200 TimerStat d_simpITETime
;
201 /** time spent in simplifying ITEs */
202 TimerStat d_unconstrainedSimpTime
;
203 /** time spent removing ITEs */
204 TimerStat d_iteRemovalTime
;
205 /** time spent in theory preprocessing */
206 TimerStat d_theoryPreprocessTime
;
207 /** time spent in theory preprocessing */
208 TimerStat d_rewriteApplyToConstTime
;
209 /** time spent converting to CNF */
210 TimerStat d_cnfConversionTime
;
211 /** Num of assertions before ite removal */
212 IntStat d_numAssertionsPre
;
213 /** Num of assertions after ite removal */
214 IntStat d_numAssertionsPost
;
215 /** time spent in checkModel() */
216 TimerStat d_checkModelTime
;
217 /** time spent in checkProof() */
218 TimerStat d_checkProofTime
;
219 /** time spent in checkUnsatCore() */
220 TimerStat d_checkUnsatCoreTime
;
221 /** time spent in PropEngine::checkSat() */
222 TimerStat d_solveTime
;
223 /** time spent in pushing/popping */
224 TimerStat d_pushPopTime
;
225 /** time spent in processAssertions() */
226 TimerStat d_processAssertionsTime
;
228 /** Has something simplified to false? */
229 IntStat d_simplifiedToFalse
;
230 /** Number of resource units spent. */
231 ReferenceStat
<uint64_t> d_resourceUnitsUsed
;
233 SmtEngineStatistics() :
234 d_gaussElimTime("smt::SmtEngine::gaussElimTime"),
235 d_definitionExpansionTime("smt::SmtEngine::definitionExpansionTime"),
236 d_nonclausalSimplificationTime("smt::SmtEngine::nonclausalSimplificationTime"),
237 d_miplibPassTime("smt::SmtEngine::miplibPassTime"),
238 d_numMiplibAssertionsRemoved("smt::SmtEngine::numMiplibAssertionsRemoved", 0),
239 d_numConstantProps("smt::SmtEngine::numConstantProps", 0),
240 d_simpITETime("smt::SmtEngine::simpITETime"),
241 d_unconstrainedSimpTime("smt::SmtEngine::unconstrainedSimpTime"),
242 d_iteRemovalTime("smt::SmtEngine::iteRemovalTime"),
243 d_theoryPreprocessTime("smt::SmtEngine::theoryPreprocessTime"),
244 d_rewriteApplyToConstTime("smt::SmtEngine::rewriteApplyToConstTime"),
245 d_cnfConversionTime("smt::SmtEngine::cnfConversionTime"),
246 d_numAssertionsPre("smt::SmtEngine::numAssertionsPreITERemoval", 0),
247 d_numAssertionsPost("smt::SmtEngine::numAssertionsPostITERemoval", 0),
248 d_checkModelTime("smt::SmtEngine::checkModelTime"),
249 d_checkProofTime("smt::SmtEngine::checkProofTime"),
250 d_checkUnsatCoreTime("smt::SmtEngine::checkUnsatCoreTime"),
251 d_solveTime("smt::SmtEngine::solveTime"),
252 d_pushPopTime("smt::SmtEngine::pushPopTime"),
253 d_processAssertionsTime("smt::SmtEngine::processAssertionsTime"),
254 d_simplifiedToFalse("smt::SmtEngine::simplifiedToFalse", 0),
255 d_resourceUnitsUsed("smt::SmtEngine::resourceUnitsUsed")
258 smtStatisticsRegistry()->registerStat(&d_gaussElimTime
);
259 smtStatisticsRegistry()->registerStat(&d_definitionExpansionTime
);
260 smtStatisticsRegistry()->registerStat(&d_nonclausalSimplificationTime
);
261 smtStatisticsRegistry()->registerStat(&d_miplibPassTime
);
262 smtStatisticsRegistry()->registerStat(&d_numMiplibAssertionsRemoved
);
263 smtStatisticsRegistry()->registerStat(&d_numConstantProps
);
264 smtStatisticsRegistry()->registerStat(&d_simpITETime
);
265 smtStatisticsRegistry()->registerStat(&d_unconstrainedSimpTime
);
266 smtStatisticsRegistry()->registerStat(&d_iteRemovalTime
);
267 smtStatisticsRegistry()->registerStat(&d_theoryPreprocessTime
);
268 smtStatisticsRegistry()->registerStat(&d_rewriteApplyToConstTime
);
269 smtStatisticsRegistry()->registerStat(&d_cnfConversionTime
);
270 smtStatisticsRegistry()->registerStat(&d_numAssertionsPre
);
271 smtStatisticsRegistry()->registerStat(&d_numAssertionsPost
);
272 smtStatisticsRegistry()->registerStat(&d_checkModelTime
);
273 smtStatisticsRegistry()->registerStat(&d_checkProofTime
);
274 smtStatisticsRegistry()->registerStat(&d_checkUnsatCoreTime
);
275 smtStatisticsRegistry()->registerStat(&d_solveTime
);
276 smtStatisticsRegistry()->registerStat(&d_pushPopTime
);
277 smtStatisticsRegistry()->registerStat(&d_processAssertionsTime
);
278 smtStatisticsRegistry()->registerStat(&d_simplifiedToFalse
);
279 smtStatisticsRegistry()->registerStat(&d_resourceUnitsUsed
);
282 ~SmtEngineStatistics() {
283 smtStatisticsRegistry()->unregisterStat(&d_gaussElimTime
);
284 smtStatisticsRegistry()->unregisterStat(&d_definitionExpansionTime
);
285 smtStatisticsRegistry()->unregisterStat(&d_nonclausalSimplificationTime
);
286 smtStatisticsRegistry()->unregisterStat(&d_miplibPassTime
);
287 smtStatisticsRegistry()->unregisterStat(&d_numMiplibAssertionsRemoved
);
288 smtStatisticsRegistry()->unregisterStat(&d_numConstantProps
);
289 smtStatisticsRegistry()->unregisterStat(&d_simpITETime
);
290 smtStatisticsRegistry()->unregisterStat(&d_unconstrainedSimpTime
);
291 smtStatisticsRegistry()->unregisterStat(&d_iteRemovalTime
);
292 smtStatisticsRegistry()->unregisterStat(&d_theoryPreprocessTime
);
293 smtStatisticsRegistry()->unregisterStat(&d_rewriteApplyToConstTime
);
294 smtStatisticsRegistry()->unregisterStat(&d_cnfConversionTime
);
295 smtStatisticsRegistry()->unregisterStat(&d_numAssertionsPre
);
296 smtStatisticsRegistry()->unregisterStat(&d_numAssertionsPost
);
297 smtStatisticsRegistry()->unregisterStat(&d_checkModelTime
);
298 smtStatisticsRegistry()->unregisterStat(&d_checkProofTime
);
299 smtStatisticsRegistry()->unregisterStat(&d_checkUnsatCoreTime
);
300 smtStatisticsRegistry()->unregisterStat(&d_solveTime
);
301 smtStatisticsRegistry()->unregisterStat(&d_pushPopTime
);
302 smtStatisticsRegistry()->unregisterStat(&d_processAssertionsTime
);
303 smtStatisticsRegistry()->unregisterStat(&d_simplifiedToFalse
);
304 smtStatisticsRegistry()->unregisterStat(&d_resourceUnitsUsed
);
306 };/* struct SmtEngineStatistics */
309 class SoftResourceOutListener
: public Listener
{
311 SoftResourceOutListener(SmtEngine
& smt
) : d_smt(&smt
) {}
312 void notify() override
314 SmtScope
scope(d_smt
);
315 Assert(smt::smtEngineInScope());
320 }; /* class SoftResourceOutListener */
323 class HardResourceOutListener
: public Listener
{
325 HardResourceOutListener(SmtEngine
& smt
) : d_smt(&smt
) {}
326 void notify() override
328 SmtScope
scope(d_smt
);
329 theory::Rewriter::clearCaches();
333 }; /* class HardResourceOutListener */
335 class SetLogicListener
: public Listener
{
337 SetLogicListener(SmtEngine
& smt
) : d_smt(&smt
) {}
338 void notify() override
340 LogicInfo
inOptions(options::forceLogicString());
341 d_smt
->setLogic(inOptions
);
345 }; /* class SetLogicListener */
347 class BeforeSearchListener
: public Listener
{
349 BeforeSearchListener(SmtEngine
& smt
) : d_smt(&smt
) {}
350 void notify() override
{ d_smt
->beforeSearch(); }
354 }; /* class BeforeSearchListener */
356 class UseTheoryListListener
: public Listener
{
358 UseTheoryListListener(TheoryEngine
* theoryEngine
)
359 : d_theoryEngine(theoryEngine
)
362 void notify() override
364 std::stringstream
commaList(options::useTheoryList());
367 Debug("UseTheoryListListener") << "UseTheoryListListener::notify() "
368 << options::useTheoryList() << std::endl
;
370 while(std::getline(commaList
, token
, ',')){
371 if(token
== "help") {
372 puts(theory::useTheoryHelp
);
375 if(theory::useTheoryValidate(token
)) {
376 d_theoryEngine
->enableTheoryAlternative(token
);
378 throw OptionException(
379 std::string("unknown option for --use-theory : `") + token
+
380 "'. Try --use-theory=help.");
386 TheoryEngine
* d_theoryEngine
;
387 }; /* class UseTheoryListListener */
390 class SetDefaultExprDepthListener
: public Listener
{
392 void notify() override
394 int depth
= options::defaultExprDepth();
395 Debug
.getStream() << expr::ExprSetDepth(depth
);
396 Trace
.getStream() << expr::ExprSetDepth(depth
);
397 Notice
.getStream() << expr::ExprSetDepth(depth
);
398 Chat
.getStream() << expr::ExprSetDepth(depth
);
399 Message
.getStream() << expr::ExprSetDepth(depth
);
400 Warning
.getStream() << expr::ExprSetDepth(depth
);
401 // intentionally exclude Dump stream from this list
405 class SetDefaultExprDagListener
: public Listener
{
407 void notify() override
409 int dag
= options::defaultDagThresh();
410 Debug
.getStream() << expr::ExprDag(dag
);
411 Trace
.getStream() << expr::ExprDag(dag
);
412 Notice
.getStream() << expr::ExprDag(dag
);
413 Chat
.getStream() << expr::ExprDag(dag
);
414 Message
.getStream() << expr::ExprDag(dag
);
415 Warning
.getStream() << expr::ExprDag(dag
);
416 Dump
.getStream() << expr::ExprDag(dag
);
420 class SetPrintExprTypesListener
: public Listener
{
422 void notify() override
424 bool value
= options::printExprTypes();
425 Debug
.getStream() << expr::ExprPrintTypes(value
);
426 Trace
.getStream() << expr::ExprPrintTypes(value
);
427 Notice
.getStream() << expr::ExprPrintTypes(value
);
428 Chat
.getStream() << expr::ExprPrintTypes(value
);
429 Message
.getStream() << expr::ExprPrintTypes(value
);
430 Warning
.getStream() << expr::ExprPrintTypes(value
);
431 // intentionally exclude Dump stream from this list
435 class DumpModeListener
: public Listener
{
437 void notify() override
439 const std::string
& value
= options::dumpModeString();
440 Dump
.setDumpFromString(value
);
444 class PrintSuccessListener
: public Listener
{
446 void notify() override
448 bool value
= options::printSuccess();
449 Debug
.getStream() << Command::printsuccess(value
);
450 Trace
.getStream() << Command::printsuccess(value
);
451 Notice
.getStream() << Command::printsuccess(value
);
452 Chat
.getStream() << Command::printsuccess(value
);
453 Message
.getStream() << Command::printsuccess(value
);
454 Warning
.getStream() << Command::printsuccess(value
);
455 *options::out() << Command::printsuccess(value
);
462 * This is an inelegant solution, but for the present, it will work.
463 * The point of this is to separate the public and private portions of
464 * the SmtEngine class, so that smt_engine.h doesn't
465 * include "expr/node.h", which is a private CVC4 header (and can lead
466 * to linking errors due to the improper inlining of non-visible symbols
469 * The "real" solution (that which is usually implemented) is to move
470 * ALL the implementation to SmtEnginePrivate and maintain a
471 * heap-allocated instance of it in SmtEngine. SmtEngine (the public
472 * one) becomes an "interface shell" which simply acts as a forwarder
475 class SmtEnginePrivate
: public NodeManagerListener
{
478 typedef unordered_map
<Node
, Node
, NodeHashFunction
> NodeToNodeHashMap
;
479 typedef unordered_map
<Node
, bool, NodeHashFunction
> NodeToBoolHashMap
;
482 * Manager for limiting time and abstract resource usage.
484 ResourceManager
* d_resourceManager
;
486 /** Manager for the memory of regular-output-channel. */
487 ManagedRegularOutputChannel d_managedRegularChannel
;
489 /** Manager for the memory of diagnostic-output-channel. */
490 ManagedDiagnosticOutputChannel d_managedDiagnosticChannel
;
492 /** Manager for the memory of --dump-to. */
493 ManagedDumpOStream d_managedDumpChannel
;
495 /** Manager for --replay-log. */
496 ManagedReplayLogOstream d_managedReplayLog
;
499 * This list contains:
503 * beforeSearchListener
504 * UseTheoryListListener
506 * This needs to be deleted before both NodeManager's Options,
507 * SmtEngine, d_resourceManager, and TheoryEngine.
509 ListenerRegistrationList
* d_listenerRegistrations
;
511 /** Learned literals */
512 vector
<Node
> d_nonClausalLearnedLiterals
;
514 /** Size of assertions array when preprocessing starts */
515 unsigned d_realAssertionsEnd
;
517 /** A circuit propagator for non-clausal propositional deduction */
518 booleans::CircuitPropagator d_propagator
;
519 bool d_propagatorNeedsFinish
;
520 std::vector
<Node
> d_boolVars
;
522 /** Assertions in the preprocessing pipeline */
523 AssertionPipeline d_assertions
;
525 /** Whether any assertions have been processed */
526 CDO
<bool> d_assertionsProcessed
;
532 * A context that never pushes/pops, for use by CD structures (like
533 * SubstitutionMaps) that should be "global".
535 context::Context d_fakeContext
;
538 * A map of AbsractValues to their actual constants. Only used if
539 * options::abstractValues() is on.
541 SubstitutionMap d_abstractValueMap
;
544 * A mapping of all abstract values (actual value |-> abstract) that
545 * we've handed out. This is necessary to ensure that we give the
546 * same AbstractValues for the same real constants. Only used if
547 * options::abstractValues() is on.
549 NodeToNodeHashMap d_abstractValues
;
551 /** Number of calls of simplify assertions active.
553 unsigned d_simplifyAssertionsDepth
;
555 /** TODO: whether certain preprocess steps are necessary */
556 //bool d_needsExpandDefs;
558 //------------------------------- expression names
559 /** mapping from expressions to name */
560 context::CDHashMap
< Node
, std::string
, NodeHashFunction
> d_exprNames
;
561 //------------------------------- end expression names
564 * Map from skolem variables to index in d_assertions containing
565 * corresponding introduced Boolean ite
567 IteSkolemMap d_iteSkolemMap
;
569 /** Instance of the ITE remover */
570 RemoveTermFormulas d_iteRemover
;
572 /* Finishes the initialization of the private portion of SMTEngine. */
576 std::unique_ptr
<PreprocessingPassContext
> d_preprocessingPassContext
;
577 PreprocessingPassRegistry d_preprocessingPassRegistry
;
579 static const bool d_doConstantProp
= true;
582 * Runs the nonclausal solver and tries to solve all the assigned
585 * Returns false if the formula simplifies to "false"
587 bool nonClausalSimplify();
590 * Performs static learning on the assertions.
592 void staticLearning();
595 * Remove ITEs from the assertions.
599 Node
realToInt(TNode n
, NodeToNodeHashMap
& cache
, std::vector
< Node
>& var_eq
);
600 Node
purifyNlTerms(TNode n
, NodeToNodeHashMap
& cache
, NodeToNodeHashMap
& bcache
, std::vector
< Node
>& var_eq
, bool beneathMult
= false);
603 * Helper function to fix up assertion list to restore invariants needed after
606 void collectSkolems(TNode n
, set
<TNode
>& skolemSet
, NodeToBoolHashMap
& cache
);
609 * Helper function to fix up assertion list to restore invariants needed after
612 bool checkForBadSkolems(TNode n
, TNode skolem
, NodeToBoolHashMap
& cache
);
614 // Simplify ITE structure
617 // Simplify based on unconstrained values
618 void unconstrainedSimp();
621 * Ensures the assertions asserted after before now effectively come before
622 * d_realAssertionsEnd.
624 void compressBeforeRealAssertions(size_t before
);
627 * Trace nodes back to their assertions using CircuitPropagator's
630 void traceBackToAssertions(const std::vector
<Node
>& nodes
,
631 std::vector
<TNode
>& assertions
);
634 * Remove conjuncts in toRemove from conjunction n. Return # of removed
637 size_t removeFromConjunction(Node
& n
,
638 const std::unordered_set
<unsigned long>& toRemove
);
640 /** Scrub miplib encodings. */
641 void doMiplibTrick();
644 * Perform non-clausal simplification of a Node. This involves
645 * Theory implementations, but does NOT involve the SAT solver in
648 * Returns false if the formula simplifies to "false"
650 bool simplifyAssertions();
653 SmtEnginePrivate(SmtEngine
& smt
)
655 d_managedRegularChannel(),
656 d_managedDiagnosticChannel(),
657 d_managedDumpChannel(),
658 d_managedReplayLog(),
659 d_listenerRegistrations(new ListenerRegistrationList()),
660 d_nonClausalLearnedLiterals(),
661 d_realAssertionsEnd(0),
662 d_propagator(d_nonClausalLearnedLiterals
, true, true),
663 d_propagatorNeedsFinish(false),
664 d_assertions(d_smt
.d_userContext
),
665 d_assertionsProcessed(smt
.d_userContext
, false),
667 d_abstractValueMap(&d_fakeContext
),
669 d_simplifyAssertionsDepth(0),
670 // d_needsExpandDefs(true), //TODO?
671 d_exprNames(smt
.d_userContext
),
673 d_iteRemover(smt
.d_userContext
)
675 d_smt
.d_nodeManager
->subscribeEvents(this);
676 d_true
= NodeManager::currentNM()->mkConst(true);
677 d_resourceManager
= NodeManager::currentResourceManager();
679 d_listenerRegistrations
->add(d_resourceManager
->registerSoftListener(
680 new SoftResourceOutListener(d_smt
)));
682 d_listenerRegistrations
->add(d_resourceManager
->registerHardListener(
683 new HardResourceOutListener(d_smt
)));
685 Options
& nodeManagerOptions
= NodeManager::currentNM()->getOptions();
686 d_listenerRegistrations
->add(
687 nodeManagerOptions
.registerForceLogicListener(
688 new SetLogicListener(d_smt
), true));
690 // Multiple options reuse BeforeSearchListener so registration requires an
691 // extra bit of care.
692 // We can safely not call notify on this before search listener at
693 // registration time. This d_smt cannot be beforeSearch at construction
694 // time. Therefore the BeforeSearchListener is a no-op. Therefore it does
695 // not have to be called.
696 d_listenerRegistrations
->add(
697 nodeManagerOptions
.registerBeforeSearchListener(
698 new BeforeSearchListener(d_smt
)));
700 // These do need registration calls.
701 d_listenerRegistrations
->add(
702 nodeManagerOptions
.registerSetDefaultExprDepthListener(
703 new SetDefaultExprDepthListener(), true));
704 d_listenerRegistrations
->add(
705 nodeManagerOptions
.registerSetDefaultExprDagListener(
706 new SetDefaultExprDagListener(), true));
707 d_listenerRegistrations
->add(
708 nodeManagerOptions
.registerSetPrintExprTypesListener(
709 new SetPrintExprTypesListener(), true));
710 d_listenerRegistrations
->add(
711 nodeManagerOptions
.registerSetDumpModeListener(
712 new DumpModeListener(), true));
713 d_listenerRegistrations
->add(
714 nodeManagerOptions
.registerSetPrintSuccessListener(
715 new PrintSuccessListener(), true));
716 d_listenerRegistrations
->add(
717 nodeManagerOptions
.registerSetRegularOutputChannelListener(
718 new SetToDefaultSourceListener(&d_managedRegularChannel
), true));
719 d_listenerRegistrations
->add(
720 nodeManagerOptions
.registerSetDiagnosticOutputChannelListener(
721 new SetToDefaultSourceListener(&d_managedDiagnosticChannel
), true));
722 d_listenerRegistrations
->add(
723 nodeManagerOptions
.registerDumpToFileNameListener(
724 new SetToDefaultSourceListener(&d_managedDumpChannel
), true));
725 d_listenerRegistrations
->add(
726 nodeManagerOptions
.registerSetReplayLogFilename(
727 new SetToDefaultSourceListener(&d_managedReplayLog
), true));
732 delete d_listenerRegistrations
;
734 if(d_propagatorNeedsFinish
) {
735 d_propagator
.finish();
736 d_propagatorNeedsFinish
= false;
738 d_smt
.d_nodeManager
->unsubscribeEvents(this);
741 void unregisterPreprocessingPasses()
743 d_preprocessingPassRegistry
.unregisterPasses();
746 ResourceManager
* getResourceManager() { return d_resourceManager
; }
747 void spendResource(unsigned amount
)
749 d_resourceManager
->spendResource(amount
);
752 void nmNotifyNewSort(TypeNode tn
, uint32_t flags
) override
754 DeclareTypeCommand
c(tn
.getAttribute(expr::VarNameAttr()),
757 if((flags
& ExprManager::SORT_FLAG_PLACEHOLDER
) == 0) {
758 d_smt
.addToModelCommandAndDump(c
, flags
);
762 void nmNotifyNewSortConstructor(TypeNode tn
, uint32_t flags
) override
764 DeclareTypeCommand
c(tn
.getAttribute(expr::VarNameAttr()),
765 tn
.getAttribute(expr::SortArityAttr()),
767 if ((flags
& ExprManager::SORT_FLAG_PLACEHOLDER
) == 0)
769 d_smt
.addToModelCommandAndDump(c
);
773 void nmNotifyNewDatatypes(const std::vector
<DatatypeType
>& dtts
) override
775 DatatypeDeclarationCommand
c(dtts
);
776 d_smt
.addToModelCommandAndDump(c
);
779 void nmNotifyNewVar(TNode n
, uint32_t flags
) override
781 DeclareFunctionCommand
c(n
.getAttribute(expr::VarNameAttr()),
783 n
.getType().toType());
784 if((flags
& ExprManager::VAR_FLAG_DEFINED
) == 0) {
785 d_smt
.addToModelCommandAndDump(c
, flags
);
787 if(n
.getType().isBoolean() && !options::incrementalSolving()) {
788 d_boolVars
.push_back(n
);
792 void nmNotifyNewSkolem(TNode n
,
793 const std::string
& comment
,
794 uint32_t flags
) override
796 string id
= n
.getAttribute(expr::VarNameAttr());
797 DeclareFunctionCommand
c(id
, n
.toExpr(), n
.getType().toType());
798 if(Dump
.isOn("skolems") && comment
!= "") {
799 Dump("skolems") << CommentCommand(id
+ " is " + comment
);
801 if((flags
& ExprManager::VAR_FLAG_DEFINED
) == 0) {
802 d_smt
.addToModelCommandAndDump(c
, flags
, false, "skolems");
804 if(n
.getType().isBoolean() && !options::incrementalSolving()) {
805 d_boolVars
.push_back(n
);
809 void nmNotifyDeleteNode(TNode n
) override
{}
811 Node
applySubstitutions(TNode node
)
813 return Rewriter::rewrite(
814 d_assertions
.getTopLevelSubstitutions().apply(node
));
818 * Process the assertions that have been asserted.
820 void processAssertions();
822 /** Process a user push.
829 * Process a user pop. Clears out the non-context-dependent stuff in this
830 * SmtEnginePrivate. Necessary to clear out our assertion vectors in case
831 * someone does a push-assert-pop without a check-sat. It also pops the
832 * last map of expression names from notifyPush.
835 d_assertions
.clear();
836 d_nonClausalLearnedLiterals
.clear();
837 d_realAssertionsEnd
= 0;
838 d_iteSkolemMap
.clear();
842 * Adds a formula to the current context. Action here depends on
843 * the SimplificationMode (in the current Options scope); the
844 * formula might be pushed out to the propositional layer
845 * immediately, or it might be simplified and kept, or it might not
846 * even be simplified.
847 * the 2nd and 3rd arguments added for bookkeeping for proofs
849 void addFormula(TNode n
, bool inUnsatCore
, bool inInput
= true);
851 /** Expand definitions in n. */
852 Node
expandDefinitions(TNode n
,
853 NodeToNodeHashMap
& cache
,
854 bool expandOnly
= false);
857 * Simplify node "in" by expanding definitions and applying any
858 * substitutions learned from preprocessing.
860 Node
simplify(TNode in
) {
861 // Substitute out any abstract values in ex.
862 // Expand definitions.
863 NodeToNodeHashMap cache
;
864 Node n
= expandDefinitions(in
, cache
).toExpr();
865 // Make sure we've done all preprocessing, etc.
866 Assert(d_assertions
.size() == 0);
867 return applySubstitutions(n
).toExpr();
871 * Substitute away all AbstractValues in a node.
873 Node
substituteAbstractValues(TNode n
) {
874 // We need to do this even if options::abstractValues() is off,
875 // since the setting might have changed after we already gave out
876 // some abstract values.
877 return d_abstractValueMap
.apply(n
);
881 * Make a new (or return an existing) abstract value for a node.
882 * Can only use this if options::abstractValues() is on.
884 Node
mkAbstractValue(TNode n
) {
885 Assert(options::abstractValues());
886 Node
& val
= d_abstractValues
[n
];
888 val
= d_smt
.d_nodeManager
->mkAbstractValue(n
.getType());
889 d_abstractValueMap
.addSubstitution(val
, n
);
891 // We are supposed to ascribe types to all abstract values that go out.
892 NodeManager
* current
= d_smt
.d_nodeManager
;
893 Node ascription
= current
->mkConst(AscriptionType(n
.getType().toType()));
894 Node retval
= current
->mkNode(kind::APPLY_TYPE_ASCRIPTION
, ascription
, val
);
898 NodeToNodeHashMap d_rewriteApplyToConstCache
;
899 Node
rewriteApplyToConst(TNode n
) {
900 Trace("rewriteApplyToConst") << "rewriteApplyToConst :: " << n
<< std::endl
;
902 if(n
.getMetaKind() == kind::metakind::CONSTANT
||
903 n
.getMetaKind() == kind::metakind::VARIABLE
||
904 n
.getMetaKind() == kind::metakind::NULLARY_OPERATOR
)
909 if(d_rewriteApplyToConstCache
.find(n
) != d_rewriteApplyToConstCache
.end()) {
910 Trace("rewriteApplyToConst") << "in cache :: "
911 << d_rewriteApplyToConstCache
[n
]
913 return d_rewriteApplyToConstCache
[n
];
916 if(n
.getKind() == kind::APPLY_UF
) {
917 if(n
.getNumChildren() == 1 && n
[0].isConst() &&
918 n
[0].getType().isInteger())
921 ss
<< n
.getOperator() << "_";
922 if(n
[0].getConst
<Rational
>() < 0) {
923 ss
<< "m" << -n
[0].getConst
<Rational
>();
927 Node newvar
= NodeManager::currentNM()->mkSkolem(
928 ss
.str(), n
.getType(), "rewriteApplyToConst skolem",
929 NodeManager::SKOLEM_EXACT_NAME
);
930 d_rewriteApplyToConstCache
[n
] = newvar
;
931 Trace("rewriteApplyToConst") << "made :: " << newvar
<< std::endl
;
935 ss
<< "The rewrite-apply-to-const preprocessor is currently limited;"
937 << "it only works if all function symbols are unary and with Integer"
939 << "domain, and all applications are to integer values." << std::endl
940 << "Found application: " << n
;
945 NodeBuilder
<> builder(n
.getKind());
946 if(n
.getMetaKind() == kind::metakind::PARAMETERIZED
) {
947 builder
<< n
.getOperator();
949 for(unsigned i
= 0; i
< n
.getNumChildren(); ++i
) {
950 builder
<< rewriteApplyToConst(n
[i
]);
953 d_rewriteApplyToConstCache
[n
] = rewr
;
954 Trace("rewriteApplyToConst") << "built :: " << rewr
<< std::endl
;
958 void addUseTheoryListListener(TheoryEngine
* theoryEngine
){
959 Options
& nodeManagerOptions
= NodeManager::currentNM()->getOptions();
960 d_listenerRegistrations
->add(
961 nodeManagerOptions
.registerUseTheoryListListener(
962 new UseTheoryListListener(theoryEngine
), true));
965 std::ostream
* getReplayLog() const {
966 return d_managedReplayLog
.getReplayLog();
969 //------------------------------- expression names
970 // implements setExpressionName, as described in smt_engine.h
971 void setExpressionName(Expr e
, std::string name
) {
972 d_exprNames
[Node::fromExpr(e
)] = name
;
975 // implements getExpressionName, as described in smt_engine.h
976 bool getExpressionName(Expr e
, std::string
& name
) const {
977 context::CDHashMap
< Node
, std::string
, NodeHashFunction
>::const_iterator it
= d_exprNames
.find(e
);
978 if(it
!=d_exprNames
.end()) {
985 //------------------------------- end expression names
987 };/* class SmtEnginePrivate */
989 }/* namespace CVC4::smt */
991 SmtEngine::SmtEngine(ExprManager
* em
)
992 : d_context(new Context()),
994 d_userContext(new UserContext()),
996 d_nodeManager(d_exprManager
->getNodeManager()),
997 d_decisionEngine(NULL
),
998 d_theoryEngine(NULL
),
1000 d_proofManager(NULL
),
1001 d_definedFunctions(NULL
),
1002 d_fmfRecFunctionsDefined(NULL
),
1003 d_assertionList(NULL
),
1004 d_assignments(NULL
),
1005 d_modelGlobalCommands(),
1006 d_modelCommands(NULL
),
1010 d_originalOptions(),
1012 d_fullyInited(false),
1013 d_problemExtended(false),
1015 d_needPostsolve(false),
1016 d_earlyTheoryPP(true),
1017 d_globalNegation(false),
1019 d_replayStream(NULL
),
1021 d_statisticsRegistry(NULL
),
1023 d_channels(new LemmaChannels())
1025 SmtScope
smts(this);
1026 d_originalOptions
.copyValues(em
->getOptions());
1027 d_private
= new smt::SmtEnginePrivate(*this);
1028 d_statisticsRegistry
= new StatisticsRegistry();
1029 d_stats
= new SmtEngineStatistics();
1030 d_stats
->d_resourceUnitsUsed
.setData(
1031 d_private
->getResourceManager()->getResourceUsage());
1033 // The ProofManager is constructed before any other proof objects such as
1034 // SatProof and TheoryProofs. The TheoryProofEngine and the SatProof are
1035 // initialized in TheoryEngine and PropEngine respectively.
1036 Assert(d_proofManager
== NULL
);
1038 // d_proofManager must be created before Options has been finished
1039 // being parsed from the input file. Because of this, we cannot trust
1040 // that options::proof() is set correctly yet.
1042 d_proofManager
= new ProofManager(d_userContext
);
1045 // We have mutual dependency here, so we add the prop engine to the theory
1046 // engine later (it is non-essential there)
1047 d_theoryEngine
= new TheoryEngine(d_context
, d_userContext
,
1048 d_private
->d_iteRemover
,
1049 const_cast<const LogicInfo
&>(d_logic
),
1053 for(TheoryId id
= theory::THEORY_FIRST
; id
< theory::THEORY_LAST
; ++id
) {
1054 TheoryConstructor::addTheory(d_theoryEngine
, id
);
1055 //register with proof engine if applicable
1057 ProofManager::currentPM()->getTheoryProofEngine()->registerTheory(d_theoryEngine
->theoryOf(id
));
1061 d_private
->addUseTheoryListListener(d_theoryEngine
);
1063 // global push/pop around everything, to ensure proper destruction
1064 // of context-dependent data structures
1065 d_userContext
->push();
1068 d_definedFunctions
= new(true) DefinedFunctionMap(d_userContext
);
1069 d_fmfRecFunctionsDefined
= new(true) NodeList(d_userContext
);
1070 d_modelCommands
= new(true) smt::CommandList(d_userContext
);
1073 void SmtEngine::finishInit() {
1074 Trace("smt-debug") << "SmtEngine::finishInit" << std::endl
;
1075 // ensure that our heuristics are properly set up
1078 Trace("smt-debug") << "Making decision engine..." << std::endl
;
1080 d_decisionEngine
= new DecisionEngine(d_context
, d_userContext
);
1081 d_decisionEngine
->init(); // enable appropriate strategies
1083 Trace("smt-debug") << "Making prop engine..." << std::endl
;
1084 d_propEngine
= new PropEngine(d_theoryEngine
, d_decisionEngine
, d_context
,
1085 d_userContext
, d_private
->getReplayLog(),
1086 d_replayStream
, d_channels
);
1088 Trace("smt-debug") << "Setting up theory engine..." << std::endl
;
1089 d_theoryEngine
->setPropEngine(d_propEngine
);
1090 d_theoryEngine
->setDecisionEngine(d_decisionEngine
);
1091 Trace("smt-debug") << "Finishing init for theory engine..." << std::endl
;
1092 d_theoryEngine
->finishInit();
1094 Trace("smt-debug") << "Set up assertion list..." << std::endl
;
1095 // [MGD 10/20/2011] keep around in incremental mode, due to a
1096 // cleanup ordering issue and Nodes/TNodes. If SAT is popped
1097 // first, some user-context-dependent TNodes might still exist
1099 if(options::produceAssertions() ||
1100 options::incrementalSolving()) {
1101 // In the case of incremental solving, we appear to need these to
1102 // ensure the relevant Nodes remain live.
1103 d_assertionList
= new(true) AssertionList(d_userContext
);
1106 // dump out a set-logic command
1107 if(Dump
.isOn("benchmark")) {
1108 if (Dump
.isOn("raw-benchmark")) {
1109 Dump("raw-benchmark") << SetBenchmarkLogicCommand(d_logic
.getLogicString());
1111 LogicInfo everything
;
1113 Dump("benchmark") << CommentCommand("CVC4 always dumps the most general, all-supported logic (below), as some internals might require the use of a logic more general than the input.")
1114 << SetBenchmarkLogicCommand(everything
.getLogicString());
1118 Trace("smt-debug") << "Dump declaration commands..." << std::endl
;
1119 // dump out any pending declaration commands
1120 for(unsigned i
= 0; i
< d_dumpCommands
.size(); ++i
) {
1121 Dump("declarations") << *d_dumpCommands
[i
];
1122 delete d_dumpCommands
[i
];
1124 d_dumpCommands
.clear();
1126 PROOF( ProofManager::currentPM()->setLogic(d_logic
); );
1128 for(TheoryId id
= theory::THEORY_FIRST
; id
< theory::THEORY_LAST
; ++id
) {
1129 ProofManager::currentPM()->getTheoryProofEngine()->
1130 finishRegisterTheory(d_theoryEngine
->theoryOf(id
));
1133 d_private
->finishInit();
1134 Trace("smt-debug") << "SmtEngine::finishInit done" << std::endl
;
1137 void SmtEngine::finalOptionsAreSet() {
1142 if(! d_logic
.isLocked()) {
1146 // finish initialization, create the prop engine, etc.
1149 AlwaysAssert( d_propEngine
->getAssertionLevel() == 0,
1150 "The PropEngine has pushed but the SmtEngine "
1151 "hasn't finished initializing!" );
1153 d_fullyInited
= true;
1154 Assert(d_logic
.isLocked());
1156 d_propEngine
->assertFormula(NodeManager::currentNM()->mkConst
<bool>(true));
1157 d_propEngine
->assertFormula(NodeManager::currentNM()->mkConst
<bool>(false).notNode());
1160 void SmtEngine::shutdown() {
1163 while(options::incrementalSolving() && d_userContext
->getLevel() > 1) {
1167 // check to see if a postsolve() is pending
1168 if(d_needPostsolve
) {
1169 d_theoryEngine
->postsolve();
1170 d_needPostsolve
= false;
1173 if(d_propEngine
!= NULL
) {
1174 d_propEngine
->shutdown();
1176 if(d_theoryEngine
!= NULL
) {
1177 d_theoryEngine
->shutdown();
1179 if(d_decisionEngine
!= NULL
) {
1180 d_decisionEngine
->shutdown();
1184 SmtEngine::~SmtEngine()
1186 SmtScope
smts(this);
1191 // global push/pop around everything, to ensure proper destruction
1192 // of context-dependent data structures
1193 d_context
->popto(0);
1194 d_userContext
->popto(0);
1196 if(d_assignments
!= NULL
) {
1197 d_assignments
->deleteSelf();
1200 if(d_assertionList
!= NULL
) {
1201 d_assertionList
->deleteSelf();
1204 for(unsigned i
= 0; i
< d_dumpCommands
.size(); ++i
) {
1205 delete d_dumpCommands
[i
];
1206 d_dumpCommands
[i
] = NULL
;
1208 d_dumpCommands
.clear();
1210 DeleteAndClearCommandVector(d_modelGlobalCommands
);
1212 if(d_modelCommands
!= NULL
) {
1213 d_modelCommands
->deleteSelf();
1216 d_definedFunctions
->deleteSelf();
1217 d_fmfRecFunctionsDefined
->deleteSelf();
1219 //destroy all passes before destroying things that they refer to
1220 d_private
->unregisterPreprocessingPasses();
1222 delete d_theoryEngine
;
1223 d_theoryEngine
= NULL
;
1224 delete d_propEngine
;
1225 d_propEngine
= NULL
;
1226 delete d_decisionEngine
;
1227 d_decisionEngine
= NULL
;
1230 // d_proofManager is always created when proofs are enabled at configure time.
1231 // Becuase of this, this code should not be wrapped in PROOF() which
1232 // additionally checks flags such as options::proof().
1234 delete d_proofManager
;
1235 d_proofManager
= NULL
;
1240 delete d_statisticsRegistry
;
1241 d_statisticsRegistry
= NULL
;
1246 delete d_userContext
;
1247 d_userContext
= NULL
;
1254 } catch(Exception
& e
) {
1255 Warning() << "CVC4 threw an exception during cleanup." << endl
1260 void SmtEngine::setLogic(const LogicInfo
& logic
)
1262 SmtScope
smts(this);
1264 throw ModalException("Cannot set logic in SmtEngine after the engine has "
1265 "finished initializing.");
1271 void SmtEngine::setLogic(const std::string
& s
)
1273 SmtScope
smts(this);
1275 setLogic(LogicInfo(s
));
1276 } catch(IllegalArgumentException
& e
) {
1277 throw LogicException(e
.what());
1281 void SmtEngine::setLogic(const char* logic
) { setLogic(string(logic
)); }
1282 LogicInfo
SmtEngine::getLogicInfo() const {
1285 void SmtEngine::setLogicInternal()
1287 Assert(!d_fullyInited
, "setting logic in SmtEngine but the engine has already"
1288 " finished initializing for this run");
1292 void SmtEngine::setDefaults() {
1293 Random::getRandom().setSeed(options::seed());
1294 // Language-based defaults
1295 if (!options::bitvectorDivByZeroConst
.wasSetByUser())
1297 options::bitvectorDivByZeroConst
.set(
1298 language::isInputLang_smt2_6(options::inputLanguage()));
1300 bool is_sygus
= false;
1301 if (options::inputLanguage() == language::input::LANG_SYGUS
)
1304 if (!options::ceGuidedInst
.wasSetByUser())
1306 options::ceGuidedInst
.set(true);
1308 // must use Ferrante/Rackoff for real arithmetic
1309 if (!options::cbqiMidpoint
.wasSetByUser())
1311 options::cbqiMidpoint
.set(true);
1313 if (options::sygusRepairConst())
1315 if (!options::cbqi
.wasSetByUser())
1317 options::cbqi
.set(true);
1322 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER
)
1324 if (options::produceModels()
1325 && (d_logic
.isTheoryEnabled(THEORY_ARRAYS
)
1326 || d_logic
.isTheoryEnabled(THEORY_UF
)))
1328 if (options::bitblastMode
.wasSetByUser()
1329 || options::produceModels
.wasSetByUser())
1331 throw OptionException(std::string(
1332 "Eager bit-blasting currently does not support model generation "
1333 "for the combination of bit-vectors with arrays or uinterpreted "
1334 "functions. Try --bitblast=lazy"));
1336 Notice() << "SmtEngine: setting bit-blast mode to lazy to support model"
1337 << "generation" << endl
;
1338 setOption("bitblastMode", SExpr("lazy"));
1341 if (options::incrementalSolving() && !d_logic
.isPure(THEORY_BV
))
1343 throw OptionException(
1344 "Incremental eager bit-blasting is currently "
1345 "only supported for QF_BV. Try --bitblast=lazy.");
1349 if(options::forceLogicString
.wasSetByUser()) {
1350 d_logic
= LogicInfo(options::forceLogicString());
1351 }else if (options::solveIntAsBV() > 0) {
1352 d_logic
= LogicInfo("QF_BV");
1353 }else if (d_logic
.getLogicString() == "QF_NRA" && options::solveRealAsInt()) {
1354 d_logic
= LogicInfo("QF_NIA");
1355 } else if ((d_logic
.getLogicString() == "QF_UFBV" ||
1356 d_logic
.getLogicString() == "QF_ABV") &&
1357 options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER
) {
1358 d_logic
= LogicInfo("QF_BV");
1362 /* - disabled for 1.4 release [MGD 2014.06.25]
1363 if(!d_logic.hasEverything() && d_logic.isTheoryEnabled(THEORY_STRINGS) ) {
1364 if(! options::stringExp.wasSetByUser()) {
1365 options::stringExp.set( true );
1366 Trace("smt") << "turning on strings-exp, for the theory of strings" << std::endl;
1371 if(options::stringExp()) {
1372 if( !d_logic
.isQuantified() ) {
1373 d_logic
= d_logic
.getUnlockedCopy();
1374 d_logic
.enableQuantifiers();
1376 Trace("smt") << "turning on quantifier logic, for strings-exp"
1379 if(! options::fmfBound
.wasSetByUser()) {
1380 options::fmfBound
.set( true );
1381 Trace("smt") << "turning on fmf-bound-int, for strings-exp" << std::endl
;
1383 if(! options::fmfInstEngine
.wasSetByUser()) {
1384 options::fmfInstEngine
.set( true );
1385 Trace("smt") << "turning on fmf-inst-engine, for strings-exp" << std::endl
;
1388 if(! options::rewriteDivk.wasSetByUser()) {
1389 options::rewriteDivk.set( true );
1390 Trace("smt") << "turning on rewrite-divk, for strings-exp" << std::endl;
1393 if(! options::stringFMF.wasSetByUser()) {
1394 options::stringFMF.set( true );
1395 Trace("smt") << "turning on strings-fmf, for strings-exp" << std::endl;
1400 // sygus inference may require datatypes
1401 if (options::sygusInference())
1403 d_logic
= d_logic
.getUnlockedCopy();
1404 d_logic
.enableTheory(THEORY_DATATYPES
);
1406 // since we are trying to recast as sygus, we assume the input is sygus
1410 if ((options::checkModels() || options::checkSynthSol())
1411 && !options::produceAssertions())
1413 Notice() << "SmtEngine: turning on produce-assertions to support "
1414 << "check-models or check-synth-sol." << endl
;
1415 setOption("produce-assertions", SExpr("true"));
1418 // Disable options incompatible with incremental solving, unsat cores, and
1419 // proofs or output an error if enabled explicitly
1420 if (options::incrementalSolving() || options::unsatCores()
1421 || options::proof())
1423 if (options::unconstrainedSimp())
1425 if (options::unconstrainedSimp
.wasSetByUser())
1427 throw OptionException(
1428 "unconstrained simplification not supported with unsat "
1429 "cores/proofs/incremental solving");
1431 Notice() << "SmtEngine: turning off unconstrained simplification to "
1432 "support unsat cores/proofs/incremental solving"
1434 options::unconstrainedSimp
.set(false);
1439 // Turn on unconstrained simplification for QF_AUFBV
1440 if (!options::unconstrainedSimp
.wasSetByUser())
1442 // bool qf_sat = d_logic.isPure(THEORY_BOOL) &&
1443 // !d_logic.isQuantified(); bool uncSimp = false && !qf_sat &&
1444 // !options::incrementalSolving();
1445 bool uncSimp
= !d_logic
.isQuantified() && !options::produceModels()
1446 && !options::produceAssignments()
1447 && !options::checkModels()
1448 && (d_logic
.isTheoryEnabled(THEORY_ARRAYS
)
1449 && d_logic
.isTheoryEnabled(THEORY_BV
));
1450 Trace("smt") << "setting unconstrained simplification to " << uncSimp
1452 options::unconstrainedSimp
.set(uncSimp
);
1456 // Disable options incompatible with unsat cores and proofs or output an
1457 // error if enabled explicitly
1458 if (options::unsatCores() || options::proof())
1460 if (options::simplificationMode() != SIMPLIFICATION_MODE_NONE
)
1462 if (options::simplificationMode
.wasSetByUser())
1464 throw OptionException(
1465 "simplification not supported with unsat cores/proofs");
1467 Notice() << "SmtEngine: turning off simplification to support unsat "
1470 options::simplificationMode
.set(SIMPLIFICATION_MODE_NONE
);
1473 if (options::pbRewrites())
1475 if (options::pbRewrites
.wasSetByUser())
1477 throw OptionException(
1478 "pseudoboolean rewrites not supported with unsat cores/proofs");
1480 Notice() << "SmtEngine: turning off pseudoboolean rewrites to support "
1481 "unsat cores/proofs"
1483 setOption("pb-rewrites", false);
1486 if (options::sortInference())
1488 if (options::sortInference
.wasSetByUser())
1490 throw OptionException(
1491 "sort inference not supported with unsat cores/proofs");
1493 Notice() << "SmtEngine: turning off sort inference to support unsat "
1496 options::sortInference
.set(false);
1499 if (options::preSkolemQuant())
1501 if (options::preSkolemQuant
.wasSetByUser())
1503 throw OptionException(
1504 "pre-skolemization not supported with unsat cores/proofs");
1506 Notice() << "SmtEngine: turning off pre-skolemization to support unsat "
1509 options::preSkolemQuant
.set(false);
1512 if (options::bitvectorToBool())
1514 if (options::bitvectorToBool
.wasSetByUser())
1516 throw OptionException(
1517 "bv-to-bool not supported with unsat cores/proofs");
1519 Notice() << "SmtEngine: turning off bitvector-to-bool to support unsat "
1522 options::bitvectorToBool
.set(false);
1525 if (options::boolToBitvector())
1527 if (options::boolToBitvector
.wasSetByUser())
1529 throw OptionException(
1530 "bool-to-bv not supported with unsat cores/proofs");
1532 Notice() << "SmtEngine: turning off bool-to-bitvector to support unsat "
1535 options::boolToBitvector
.set(false);
1538 if (options::bvIntroducePow2())
1540 if (options::bvIntroducePow2
.wasSetByUser())
1542 throw OptionException(
1543 "bv-intro-pow2 not supported with unsat cores/proofs");
1545 Notice() << "SmtEngine: turning off bv-intro-pow2 to support "
1546 "unsat-cores/proofs"
1548 setOption("bv-intro-pow2", false);
1551 if (options::repeatSimp())
1553 if (options::repeatSimp
.wasSetByUser())
1555 throw OptionException(
1556 "repeat-simp not supported with unsat cores/proofs");
1558 Notice() << "SmtEngine: turning off repeat-simp to support unsat "
1561 setOption("repeat-simp", false);
1564 if (options::globalNegate())
1566 if (options::globalNegate
.wasSetByUser())
1568 throw OptionException(
1569 "global-negate not supported with unsat cores/proofs");
1571 Notice() << "SmtEngine: turning off global-negate to support unsat "
1574 setOption("global-negate", false);
1579 // by default, nonclausal simplification is off for QF_SAT
1580 if (!options::simplificationMode
.wasSetByUser())
1582 bool qf_sat
= d_logic
.isPure(THEORY_BOOL
) && !d_logic
.isQuantified();
1583 Trace("smt") << "setting simplification mode to <"
1584 << d_logic
.getLogicString() << "> " << (!qf_sat
) << endl
;
1585 // simplification=none works better for SMT LIB benchmarks with
1586 // quantifiers, not others options::simplificationMode.set(qf_sat ||
1587 // quantifiers ? SIMPLIFICATION_MODE_NONE : SIMPLIFICATION_MODE_BATCH);
1588 options::simplificationMode
.set(qf_sat
? SIMPLIFICATION_MODE_NONE
1589 : SIMPLIFICATION_MODE_BATCH
);
1593 if (options::cbqiBv() && d_logic
.isQuantified())
1595 if(options::boolToBitvector
.wasSetByUser()) {
1596 throw OptionException(
1597 "bool-to-bv not supported with CBQI BV for quantified logics");
1599 Notice() << "SmtEngine: turning off bool-to-bitvector to support CBQI BV"
1601 options::boolToBitvector
.set(false);
1604 // cases where we need produce models
1605 if (!options::produceModels()
1606 && (options::produceAssignments() || options::sygusRewSynthCheck()
1609 Notice() << "SmtEngine: turning on produce-models" << endl
;
1610 setOption("produce-models", SExpr("true"));
1613 // Set the options for the theoryOf
1614 if(!options::theoryOfMode
.wasSetByUser()) {
1615 if(d_logic
.isSharingEnabled() &&
1616 !d_logic
.isTheoryEnabled(THEORY_BV
) &&
1617 !d_logic
.isTheoryEnabled(THEORY_STRINGS
) &&
1618 !d_logic
.isTheoryEnabled(THEORY_SETS
) ) {
1619 Trace("smt") << "setting theoryof-mode to term-based" << endl
;
1620 options::theoryOfMode
.set(THEORY_OF_TERM_BASED
);
1624 // strings require LIA, UF; widen the logic
1625 if(d_logic
.isTheoryEnabled(THEORY_STRINGS
)) {
1626 LogicInfo
log(d_logic
.getUnlockedCopy());
1627 // Strings requires arith for length constraints, and also UF
1628 if(!d_logic
.isTheoryEnabled(THEORY_UF
)) {
1629 Trace("smt") << "because strings are enabled, also enabling UF" << endl
;
1630 log
.enableTheory(THEORY_UF
);
1632 if(!d_logic
.isTheoryEnabled(THEORY_ARITH
) || d_logic
.isDifferenceLogic() || !d_logic
.areIntegersUsed()) {
1633 Trace("smt") << "because strings are enabled, also enabling linear integer arithmetic" << endl
;
1634 log
.enableTheory(THEORY_ARITH
);
1635 log
.enableIntegers();
1636 log
.arithOnlyLinear();
1641 if(d_logic
.isTheoryEnabled(THEORY_ARRAYS
) || d_logic
.isTheoryEnabled(THEORY_DATATYPES
) || d_logic
.isTheoryEnabled(THEORY_SETS
)) {
1642 if(!d_logic
.isTheoryEnabled(THEORY_UF
)) {
1643 LogicInfo
log(d_logic
.getUnlockedCopy());
1644 Trace("smt") << "because a theory that permits Boolean terms is enabled, also enabling UF" << endl
;
1645 log
.enableTheory(THEORY_UF
);
1651 // by default, symmetry breaker is on only for non-incremental QF_UF
1652 if(! options::ufSymmetryBreaker
.wasSetByUser()) {
1653 bool qf_uf_noinc
= d_logic
.isPure(THEORY_UF
) && !d_logic
.isQuantified()
1654 && !options::incrementalSolving() && !options::proof()
1655 && !options::unsatCores();
1656 Trace("smt") << "setting uf symmetry breaker to " << qf_uf_noinc
<< endl
;
1657 options::ufSymmetryBreaker
.set(qf_uf_noinc
);
1660 // If in arrays, set the UF handler to arrays
1661 if(d_logic
.isTheoryEnabled(THEORY_ARRAYS
) && ( !d_logic
.isQuantified() ||
1662 (d_logic
.isQuantified() && !d_logic
.isTheoryEnabled(THEORY_UF
)))) {
1663 Theory::setUninterpretedSortOwner(THEORY_ARRAYS
);
1665 Theory::setUninterpretedSortOwner(THEORY_UF
);
1668 // Turn on ite simplification for QF_LIA and QF_AUFBV
1669 // WARNING: These checks match much more than just QF_AUFBV and
1670 // QF_LIA logics. --K [2014/10/15]
1671 if(! options::doITESimp
.wasSetByUser()) {
1672 bool qf_aufbv
= !d_logic
.isQuantified() &&
1673 d_logic
.isTheoryEnabled(THEORY_ARRAYS
) &&
1674 d_logic
.isTheoryEnabled(THEORY_UF
) &&
1675 d_logic
.isTheoryEnabled(THEORY_BV
);
1676 bool qf_lia
= !d_logic
.isQuantified() &&
1677 d_logic
.isPure(THEORY_ARITH
) &&
1678 d_logic
.isLinear() &&
1679 !d_logic
.isDifferenceLogic() &&
1680 !d_logic
.areRealsUsed();
1682 bool iteSimp
= (qf_aufbv
|| qf_lia
);
1683 Trace("smt") << "setting ite simplification to " << iteSimp
<< endl
;
1684 options::doITESimp
.set(iteSimp
);
1686 if(! options::compressItes
.wasSetByUser() ){
1687 bool qf_lia
= !d_logic
.isQuantified() &&
1688 d_logic
.isPure(THEORY_ARITH
) &&
1689 d_logic
.isLinear() &&
1690 !d_logic
.isDifferenceLogic() &&
1691 !d_logic
.areRealsUsed();
1693 bool compressIte
= qf_lia
;
1694 Trace("smt") << "setting ite compression to " << compressIte
<< endl
;
1695 options::compressItes
.set(compressIte
);
1697 if(! options::simplifyWithCareEnabled
.wasSetByUser() ){
1698 bool qf_aufbv
= !d_logic
.isQuantified() &&
1699 d_logic
.isTheoryEnabled(THEORY_ARRAYS
) &&
1700 d_logic
.isTheoryEnabled(THEORY_UF
) &&
1701 d_logic
.isTheoryEnabled(THEORY_BV
);
1703 bool withCare
= qf_aufbv
;
1704 Trace("smt") << "setting ite simplify with care to " << withCare
<< endl
;
1705 options::simplifyWithCareEnabled
.set(withCare
);
1707 // Turn off array eager index splitting for QF_AUFLIA
1708 if(! options::arraysEagerIndexSplitting
.wasSetByUser()) {
1709 if (not d_logic
.isQuantified() &&
1710 d_logic
.isTheoryEnabled(THEORY_ARRAYS
) &&
1711 d_logic
.isTheoryEnabled(THEORY_UF
) &&
1712 d_logic
.isTheoryEnabled(THEORY_ARITH
)) {
1713 Trace("smt") << "setting array eager index splitting to false" << endl
;
1714 options::arraysEagerIndexSplitting
.set(false);
1717 // Turn on model-based arrays for QF_AX (unless models are enabled)
1718 // if(! options::arraysModelBased.wasSetByUser()) {
1719 // if (not d_logic.isQuantified() &&
1720 // d_logic.isTheoryEnabled(THEORY_ARRAYS) &&
1721 // d_logic.isPure(THEORY_ARRAYS) &&
1722 // !options::produceModels() &&
1723 // !options::checkModels()) {
1724 // Trace("smt") << "turning on model-based array solver" << endl;
1725 // options::arraysModelBased.set(true);
1728 // Turn on multiple-pass non-clausal simplification for QF_AUFBV
1729 if(! options::repeatSimp
.wasSetByUser()) {
1730 bool repeatSimp
= !d_logic
.isQuantified() &&
1731 (d_logic
.isTheoryEnabled(THEORY_ARRAYS
) &&
1732 d_logic
.isTheoryEnabled(THEORY_UF
) &&
1733 d_logic
.isTheoryEnabled(THEORY_BV
)) &&
1734 !options::unsatCores();
1735 Trace("smt") << "setting repeat simplification to " << repeatSimp
<< endl
;
1736 options::repeatSimp
.set(repeatSimp
);
1738 // Unconstrained simp currently does *not* support model generation
1739 if (options::unconstrainedSimp
.wasSetByUser() && options::unconstrainedSimp()) {
1740 if (options::produceModels()) {
1741 if (options::produceModels
.wasSetByUser()) {
1742 throw OptionException("Cannot use unconstrained-simp with model generation.");
1744 Notice() << "SmtEngine: turning off produce-models to support unconstrainedSimp" << endl
;
1745 setOption("produce-models", SExpr("false"));
1747 if (options::produceAssignments()) {
1748 if (options::produceAssignments
.wasSetByUser()) {
1749 throw OptionException("Cannot use unconstrained-simp with model generation (produce-assignments).");
1751 Notice() << "SmtEngine: turning off produce-assignments to support unconstrainedSimp" << endl
;
1752 setOption("produce-assignments", SExpr("false"));
1754 if (options::checkModels()) {
1755 if (options::checkModels
.wasSetByUser()) {
1756 throw OptionException("Cannot use unconstrained-simp with model generation (check-models).");
1758 Notice() << "SmtEngine: turning off check-models to support unconstrainedSimp" << endl
;
1759 setOption("check-models", SExpr("false"));
1763 if (! options::bvEagerExplanations
.wasSetByUser() &&
1764 d_logic
.isTheoryEnabled(THEORY_ARRAYS
) &&
1765 d_logic
.isTheoryEnabled(THEORY_BV
)) {
1766 Trace("smt") << "enabling eager bit-vector explanations " << endl
;
1767 options::bvEagerExplanations
.set(true);
1770 // Turn on arith rewrite equalities only for pure arithmetic
1771 if(! options::arithRewriteEq
.wasSetByUser()) {
1772 bool arithRewriteEq
= d_logic
.isPure(THEORY_ARITH
) && d_logic
.isLinear() && !d_logic
.isQuantified();
1773 Trace("smt") << "setting arith rewrite equalities " << arithRewriteEq
<< endl
;
1774 options::arithRewriteEq
.set(arithRewriteEq
);
1776 if(! options::arithHeuristicPivots
.wasSetByUser()) {
1777 int16_t heuristicPivots
= 5;
1778 if(d_logic
.isPure(THEORY_ARITH
) && !d_logic
.isQuantified()) {
1779 if(d_logic
.isDifferenceLogic()) {
1780 heuristicPivots
= -1;
1781 } else if(!d_logic
.areIntegersUsed()) {
1782 heuristicPivots
= 0;
1785 Trace("smt") << "setting arithHeuristicPivots " << heuristicPivots
<< endl
;
1786 options::arithHeuristicPivots
.set(heuristicPivots
);
1788 if(! options::arithPivotThreshold
.wasSetByUser()){
1789 uint16_t pivotThreshold
= 2;
1790 if(d_logic
.isPure(THEORY_ARITH
) && !d_logic
.isQuantified()){
1791 if(d_logic
.isDifferenceLogic()){
1792 pivotThreshold
= 16;
1795 Trace("smt") << "setting arith arithPivotThreshold " << pivotThreshold
<< endl
;
1796 options::arithPivotThreshold
.set(pivotThreshold
);
1798 if(! options::arithStandardCheckVarOrderPivots
.wasSetByUser()){
1799 int16_t varOrderPivots
= -1;
1800 if(d_logic
.isPure(THEORY_ARITH
) && !d_logic
.isQuantified()){
1801 varOrderPivots
= 200;
1803 Trace("smt") << "setting arithStandardCheckVarOrderPivots " << varOrderPivots
<< endl
;
1804 options::arithStandardCheckVarOrderPivots
.set(varOrderPivots
);
1806 // Turn off early theory preprocessing if arithRewriteEq is on
1807 if (options::arithRewriteEq()) {
1808 d_earlyTheoryPP
= false;
1810 if (d_logic
.isPure(THEORY_ARITH
) && !d_logic
.areRealsUsed())
1812 if (!options::nlExtTangentPlanesInterleave
.wasSetByUser())
1814 Trace("smt") << "setting nlExtTangentPlanesInterleave to true" << endl
;
1815 options::nlExtTangentPlanesInterleave
.set(true);
1819 // Set decision mode based on logic (if not set by user)
1820 if(!options::decisionMode
.wasSetByUser()) {
1821 decision::DecisionMode decMode
=
1823 d_logic
.hasEverything() ? decision::DECISION_STRATEGY_JUSTIFICATION
:
1825 (not d_logic
.isQuantified() &&
1826 d_logic
.isPure(THEORY_BV
)
1828 // QF_AUFBV or QF_ABV or QF_UFBV
1829 (not d_logic
.isQuantified() &&
1830 (d_logic
.isTheoryEnabled(THEORY_ARRAYS
) ||
1831 d_logic
.isTheoryEnabled(THEORY_UF
)) &&
1832 d_logic
.isTheoryEnabled(THEORY_BV
)
1834 // QF_AUFLIA (and may be ends up enabling QF_AUFLRA?)
1835 (not d_logic
.isQuantified() &&
1836 d_logic
.isTheoryEnabled(THEORY_ARRAYS
) &&
1837 d_logic
.isTheoryEnabled(THEORY_UF
) &&
1838 d_logic
.isTheoryEnabled(THEORY_ARITH
)
1841 (not d_logic
.isQuantified() &&
1842 d_logic
.isPure(THEORY_ARITH
) && d_logic
.isLinear() && !d_logic
.isDifferenceLogic() && !d_logic
.areIntegersUsed()
1845 d_logic
.isQuantified() ||
1847 d_logic
.isTheoryEnabled(THEORY_STRINGS
)
1848 ? decision::DECISION_STRATEGY_JUSTIFICATION
1849 : decision::DECISION_STRATEGY_INTERNAL
1854 d_logic
.hasEverything() || d_logic
.isTheoryEnabled(THEORY_STRINGS
) ? false :
1856 (not d_logic
.isQuantified() &&
1857 d_logic
.isTheoryEnabled(THEORY_ARRAYS
) &&
1858 d_logic
.isTheoryEnabled(THEORY_UF
) &&
1859 d_logic
.isTheoryEnabled(THEORY_ARITH
)
1862 (not d_logic
.isQuantified() &&
1863 d_logic
.isPure(THEORY_ARITH
) && d_logic
.isLinear() && !d_logic
.isDifferenceLogic() && !d_logic
.areIntegersUsed()
1868 Trace("smt") << "setting decision mode to " << decMode
<< endl
;
1869 options::decisionMode
.set(decMode
);
1870 options::decisionStopOnly
.set(stoponly
);
1872 if( options::incrementalSolving() ){
1873 //disable modes not supported by incremental
1874 options::sortInference
.set( false );
1875 options::ufssFairnessMonotone
.set( false );
1876 options::quantEpr
.set( false );
1877 options::globalNegate
.set(false);
1879 if( d_logic
.hasCardinalityConstraints() ){
1880 //must have finite model finding on
1881 options::finiteModelFind
.set( true );
1884 //if it contains a theory with non-termination, do not strictly enforce that quantifiers and theory combination must be interleaved
1885 if( d_logic
.isTheoryEnabled(THEORY_STRINGS
) || (d_logic
.isTheoryEnabled(THEORY_ARITH
) && !d_logic
.isLinear()) ){
1886 if( !options::instWhenStrictInterleave
.wasSetByUser() ){
1887 options::instWhenStrictInterleave
.set( false );
1891 //local theory extensions
1892 if( options::localTheoryExt() ){
1893 if( !options::instMaxLevel
.wasSetByUser() ){
1894 options::instMaxLevel
.set( 0 );
1897 if( options::instMaxLevel()!=-1 ){
1898 Notice() << "SmtEngine: turning off cbqi to support instMaxLevel" << endl
;
1899 options::cbqi
.set(false);
1901 //track instantiations?
1902 if( options::cbqiNestedQE() || ( options::proof() && !options::trackInstLemmas
.wasSetByUser() ) ){
1903 options::trackInstLemmas
.set( true );
1906 if( ( options::fmfBoundLazy
.wasSetByUser() && options::fmfBoundLazy() ) ||
1907 ( options::fmfBoundInt
.wasSetByUser() && options::fmfBoundInt() ) ) {
1908 options::fmfBound
.set( true );
1910 //now have determined whether fmfBoundInt is on/off
1911 //apply fmfBoundInt options
1912 if( options::fmfBound() ){
1913 //must have finite model finding on
1914 options::finiteModelFind
.set( true );
1915 if (!options::mbqiMode
.wasSetByUser()
1916 || (options::mbqiMode() != quantifiers::MBQI_NONE
1917 && options::mbqiMode() != quantifiers::MBQI_FMC
))
1919 //if bounded integers are set, use no MBQI by default
1920 options::mbqiMode
.set( quantifiers::MBQI_NONE
);
1922 if( ! options::prenexQuant
.wasSetByUser() ){
1923 options::prenexQuant
.set( quantifiers::PRENEX_QUANT_NONE
);
1926 if( options::ufHo() ){
1927 //if higher-order, then current variants of model-based instantiation cannot be used
1928 if( options::mbqiMode()!=quantifiers::MBQI_NONE
){
1929 options::mbqiMode
.set( quantifiers::MBQI_NONE
);
1932 if( options::mbqiMode()==quantifiers::MBQI_ABS
){
1933 if( !d_logic
.isPure(THEORY_UF
) ){
1934 //MBQI_ABS is only supported in pure quantified UF
1935 options::mbqiMode
.set( quantifiers::MBQI_FMC
);
1938 if( options::fmfFunWellDefinedRelevant() ){
1939 if( !options::fmfFunWellDefined
.wasSetByUser() ){
1940 options::fmfFunWellDefined
.set( true );
1943 if( options::fmfFunWellDefined() ){
1944 if( !options::finiteModelFind
.wasSetByUser() ){
1945 options::finiteModelFind
.set( true );
1949 if( options::quantEpr() ){
1950 if( !options::preSkolemQuant
.wasSetByUser() ){
1951 options::preSkolemQuant
.set( true );
1955 //now, have determined whether finite model find is on/off
1956 //apply finite model finding options
1957 if( options::finiteModelFind() ){
1958 //apply conservative quantifiers splitting
1959 if( !options::quantDynamicSplit
.wasSetByUser() ){
1960 options::quantDynamicSplit
.set( quantifiers::QUANT_DSPLIT_MODE_DEFAULT
);
1962 //do not eliminate extended arithmetic symbols from quantified formulas
1963 if( !options::elimExtArithQuant
.wasSetByUser() ){
1964 options::elimExtArithQuant
.set( false );
1966 if( !options::eMatching
.wasSetByUser() ){
1967 options::eMatching
.set( options::fmfInstEngine() );
1969 if( !options::instWhenMode
.wasSetByUser() ){
1970 //instantiate only on last call
1971 if( options::eMatching() ){
1972 options::instWhenMode
.set( quantifiers::INST_WHEN_LAST_CALL
);
1975 if( options::mbqiMode()==quantifiers::MBQI_ABS
){
1976 if( !options::preSkolemQuant
.wasSetByUser() ){
1977 options::preSkolemQuant
.set( true );
1979 if( !options::preSkolemQuantNested
.wasSetByUser() ){
1980 options::preSkolemQuantNested
.set( true );
1982 if( !options::fmfOneInstPerRound
.wasSetByUser() ){
1983 options::fmfOneInstPerRound
.set( true );
1988 //apply counterexample guided instantiation options
1989 // if we are attempting to rewrite everything to SyGuS, use ceGuidedInst
1990 if (options::sygusInference())
1992 if (!options::ceGuidedInst
.wasSetByUser())
1994 options::ceGuidedInst
.set(true);
1996 // optimization: apply preskolemization, makes it succeed more often
1997 if (!options::preSkolemQuant
.wasSetByUser())
1999 options::preSkolemQuant
.set(true);
2001 if (!options::preSkolemQuantNested
.wasSetByUser())
2003 options::preSkolemQuantNested
.set(true);
2006 if( options::cegqiSingleInvMode()!=quantifiers::CEGQI_SI_MODE_NONE
){
2007 if( !options::ceGuidedInst
.wasSetByUser() ){
2008 options::ceGuidedInst
.set( true );
2011 if( options::ceGuidedInst() ){
2012 //counterexample-guided instantiation for sygus
2013 if( !options::cegqiSingleInvMode
.wasSetByUser() ){
2014 options::cegqiSingleInvMode
.set( quantifiers::CEGQI_SI_MODE_USE
);
2016 if( !options::quantConflictFind
.wasSetByUser() ){
2017 options::quantConflictFind
.set( false );
2019 if( !options::instNoEntail
.wasSetByUser() ){
2020 options::instNoEntail
.set( false );
2022 if (options::sygusRew())
2024 options::sygusRewSynth
.set(true);
2025 options::sygusRewVerify
.set(true);
2027 if (options::sygusRewSynth() || options::sygusRewVerify())
2029 // rewrite rule synthesis implies that sygus stream must be true
2030 options::sygusStream
.set(true);
2032 if (options::sygusStream())
2034 // PBE and streaming modes are incompatible
2035 if (!options::sygusSymBreakPbe
.wasSetByUser())
2037 options::sygusSymBreakPbe
.set(false);
2039 if (!options::sygusUnifPbe
.wasSetByUser())
2041 options::sygusUnifPbe
.set(false);
2044 //do not allow partial functions
2045 if( !options::bitvectorDivByZeroConst
.wasSetByUser() ){
2046 options::bitvectorDivByZeroConst
.set( true );
2048 if( !options::dtRewriteErrorSel
.wasSetByUser() ){
2049 options::dtRewriteErrorSel
.set( true );
2052 if( !options::miniscopeQuant
.wasSetByUser() ){
2053 options::miniscopeQuant
.set( false );
2055 if( !options::miniscopeQuantFreeVar
.wasSetByUser() ){
2056 options::miniscopeQuantFreeVar
.set( false );
2058 if (!options::quantSplit
.wasSetByUser())
2060 options::quantSplit
.set(false);
2063 if( !options::rewriteDivk
.wasSetByUser()) {
2064 options::rewriteDivk
.set( true );
2067 if( !options::macrosQuant
.wasSetByUser()) {
2068 options::macrosQuant
.set( false );
2070 if( !options::cbqiPreRegInst
.wasSetByUser()) {
2071 options::cbqiPreRegInst
.set( true );
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()))
2085 if( !options::cbqi
.wasSetByUser() ){
2086 options::cbqi
.set( true );
2088 // check whether we should apply full cbqi
2089 if (d_logic
.isPure(THEORY_BV
))
2091 if (!options::cbqiFullEffort
.wasSetByUser())
2093 options::cbqiFullEffort
.set(true);
2097 if( options::cbqi() ){
2099 if( !options::rewriteDivk
.wasSetByUser()) {
2100 options::rewriteDivk
.set( true );
2102 if (options::incrementalSolving())
2104 // cannot do nested quantifier elimination in incremental mode
2105 options::cbqiNestedQE
.set(false);
2107 if (d_logic
.isPure(THEORY_ARITH
) || d_logic
.isPure(THEORY_BV
))
2109 options::cbqiAll
.set( false );
2110 if( !options::quantConflictFind
.wasSetByUser() ){
2111 options::quantConflictFind
.set( false );
2113 if( !options::instNoEntail
.wasSetByUser() ){
2114 options::instNoEntail
.set( false );
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
);
2121 // only supported in pure arithmetic or pure BV
2122 options::cbqiNestedQE
.set(false);
2125 if (options::cbqiNestedQE()
2126 || options::decisionMode() == decision::DECISION_STRATEGY_INTERNAL
)
2128 // only complete with prenex = disj_normal or normal
2129 if (options::prenexQuant() <= quantifiers::PRENEX_QUANT_DISJ_NORMAL
)
2131 options::prenexQuant
.set(quantifiers::PRENEX_QUANT_DISJ_NORMAL
);
2134 else if (options::globalNegate())
2136 if (!options::prenexQuant
.wasSetByUser())
2138 options::prenexQuant
.set(quantifiers::PRENEX_QUANT_NONE
);
2142 //implied options...
2143 if( options::strictTriggers() ){
2144 if( !options::userPatternsQuant
.wasSetByUser() ){
2145 options::userPatternsQuant
.set( quantifiers::USER_PAT_MODE_TRUST
);
2148 if( options::qcfMode
.wasSetByUser() || options::qcfTConstraint() ){
2149 options::quantConflictFind
.set( true );
2151 if( options::cbqiNestedQE() ){
2152 options::prenexQuantUser
.set( true );
2153 if( !options::preSkolemQuant
.wasSetByUser() ){
2154 options::preSkolemQuant
.set( true );
2157 //for induction techniques
2158 if( options::quantInduction() ){
2159 if( !options::dtStcInduction
.wasSetByUser() ){
2160 options::dtStcInduction
.set( true );
2162 if( !options::intWfInduction
.wasSetByUser() ){
2163 options::intWfInduction
.set( true );
2166 if( options::dtStcInduction() ){
2167 //try to remove ITEs from quantified formulas
2168 if( !options::iteDtTesterSplitQuant
.wasSetByUser() ){
2169 options::iteDtTesterSplitQuant
.set( true );
2171 if( !options::iteLiftQuant
.wasSetByUser() ){
2172 options::iteLiftQuant
.set( quantifiers::ITE_LIFT_QUANT_MODE_ALL
);
2175 if( options::intWfInduction() ){
2176 if( !options::purifyTriggers
.wasSetByUser() ){
2177 options::purifyTriggers
.set( true );
2180 if( options::conjectureNoFilter() ){
2181 if( !options::conjectureFilterActiveTerms
.wasSetByUser() ){
2182 options::conjectureFilterActiveTerms
.set( false );
2184 if( !options::conjectureFilterCanonical
.wasSetByUser() ){
2185 options::conjectureFilterCanonical
.set( false );
2187 if( !options::conjectureFilterModel
.wasSetByUser() ){
2188 options::conjectureFilterModel
.set( false );
2191 if( options::conjectureGenPerRound
.wasSetByUser() ){
2192 if( options::conjectureGenPerRound()>0 ){
2193 options::conjectureGen
.set( true );
2195 options::conjectureGen
.set( false );
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 );
2204 if( !d_logic
.isTheoryEnabled(THEORY_DATATYPES
) ){
2205 options::quantDynamicSplit
.set( quantifiers::QUANT_DSPLIT_MODE_NONE
);
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()))
2219 options::minisatUseElim
.set( false );
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"));
2227 if (options::produceAssignments()) {
2228 Notice() << "SmtEngine: turning off produce-assignments to support minisatUseElim" << endl
;
2229 setOption("produce-assignments", SExpr("false"));
2231 if (options::checkModels()) {
2232 Notice() << "SmtEngine: turning off check-models to support minisatUseElim" << endl
;
2233 setOption("check-models", SExpr("false"));
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);
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())
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
));
2256 << "SmtEngine: turning off produce-models because unsupported for "
2258 setOption("produce-models", SExpr("false"));
2260 if (options::produceAssignments()) {
2261 if(options::produceAssignments
.wasSetByUser()) {
2262 throw OptionException(
2263 std::string("produce-assignments not supported with " + reason
));
2265 Warning() << "SmtEngine: turning off produce-assignments because "
2268 setOption("produce-assignments", SExpr("false"));
2270 if (options::checkModels()) {
2271 if(options::checkModels
.wasSetByUser()) {
2272 throw OptionException(
2273 std::string("check-models not supported with " + reason
));
2276 << "SmtEngine: turning off check-models because unsupported for "
2278 setOption("check-models", SExpr("false"));
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"));
2287 if (options::proof())
2289 if (options::bitvectorAlgebraicSolver())
2291 if (options::bitvectorAlgebraicSolver
.wasSetByUser())
2293 throw OptionException(
2294 "--bv-algebraic-solver is not supported with proofs");
2296 Notice() << "SmtEngine: turning off bv algebraic solver to support proofs"
2298 options::bitvectorAlgebraicSolver
.set(false);
2300 if (options::bitvectorEqualitySolver())
2302 if (options::bitvectorEqualitySolver
.wasSetByUser())
2304 throw OptionException("--bv-eq-solver is not supported with proofs");
2306 Notice() << "SmtEngine: turning off bv eq solver to support proofs"
2308 options::bitvectorEqualitySolver
.set(false);
2310 if (options::bitvectorInequalitySolver())
2312 if (options::bitvectorInequalitySolver
.wasSetByUser())
2314 throw OptionException(
2315 "--bv-inequality-solver is not supported with proofs");
2317 Notice() << "SmtEngine: turning off bv ineq solver to support proofs"
2319 options::bitvectorInequalitySolver
.set(false);
2323 if (!options::bitvectorEqualitySolver())
2325 if (options::bvLazyRewriteExtf())
2327 if (options::bvLazyRewriteExtf
.wasSetByUser())
2329 throw OptionException(
2330 "--bv-lazy-rewrite-extf requires --bv-eq-solver to be set");
2334 << "disabling bvLazyRewriteExtf since equality solver is disabled"
2336 options::bvLazyRewriteExtf
.set(false);
2340 void SmtEngine::setProblemExtended(bool value
)
2342 d_problemExtended
= value
;
2343 if (value
) { d_assumptions
.clear(); }
2346 void SmtEngine::setInfo(const std::string
& key
, const CVC4::SExpr
& value
)
2348 SmtScope
smts(this);
2350 Trace("smt") << "SMT setInfo(" << key
<< ", " << value
<< ")" << endl
;
2352 if(Dump
.isOn("benchmark")) {
2353 if(key
== "status") {
2354 string s
= value
.getValue();
2355 BenchmarkStatus status
=
2356 (s
== "sat") ? SMT_SATISFIABLE
:
2357 ((s
== "unsat") ? SMT_UNSATISFIABLE
: SMT_UNKNOWN
);
2358 Dump("benchmark") << SetBenchmarkStatusCommand(status
);
2360 Dump("benchmark") << SetInfoCommand(key
, value
);
2364 // Check for CVC4-specific info keys (prefixed with "cvc4-" or "cvc4_")
2365 if(key
.length() > 5) {
2366 string prefix
= key
.substr(0, 5);
2367 if(prefix
== "cvc4-" || prefix
== "cvc4_") {
2368 string cvc4key
= key
.substr(5);
2369 if(cvc4key
== "logic") {
2370 if(! value
.isAtom()) {
2371 throw OptionException("argument to (set-info :cvc4-logic ..) must be a string");
2373 SmtScope
smts(this);
2374 d_logic
= value
.getValue();
2378 throw UnrecognizedOptionException();
2383 // Check for standard info keys (SMT-LIB v1, SMT-LIB v2, ...)
2385 || key
== "category"
2386 || key
== "difficulty"
2388 || key
== "license")
2392 } else if(key
== "name") {
2393 d_filename
= value
.getValue();
2396 else if (key
== "smt-lib-version" && !options::inputLanguage
.wasSetByUser())
2398 language::input::Language ilang
= language::input::LANG_AUTO
;
2399 if( (value
.isInteger() && value
.getIntegerValue() == Integer(2)) ||
2400 (value
.isRational() && value
.getRationalValue() == Rational(2)) ||
2401 value
.getValue() == "2" ||
2402 value
.getValue() == "2.0" ) {
2403 ilang
= language::input::LANG_SMTLIB_V2_0
;
2404 } else if( (value
.isRational() && value
.getRationalValue() == Rational(5, 2)) ||
2405 value
.getValue() == "2.5" ) {
2406 ilang
= language::input::LANG_SMTLIB_V2_5
;
2407 } else if( (value
.isRational() && value
.getRationalValue() == Rational(13, 5)) ||
2408 value
.getValue() == "2.6" ) {
2409 ilang
= language::input::LANG_SMTLIB_V2_6
;
2411 else if (value
.getValue() == "2.6.1")
2413 ilang
= language::input::LANG_SMTLIB_V2_6_1
;
2417 Warning() << "Warning: unsupported smt-lib-version: " << value
<< endl
;
2418 throw UnrecognizedOptionException();
2420 options::inputLanguage
.set(ilang
);
2421 // also update the output language
2422 if (!options::outputLanguage
.wasSetByUser())
2424 language::output::Language olang
= language::toOutputLanguage(ilang
);
2425 if (options::outputLanguage() != olang
)
2427 options::outputLanguage
.set(olang
);
2428 *options::out() << language::SetLanguage(olang
);
2432 } else if(key
== "status") {
2434 if(value
.isAtom()) {
2435 s
= value
.getValue();
2437 if(s
!= "sat" && s
!= "unsat" && s
!= "unknown") {
2438 throw OptionException("argument to (set-info :status ..) must be "
2439 "`sat' or `unsat' or `unknown'");
2441 d_status
= Result(s
, d_filename
);
2444 throw UnrecognizedOptionException();
2447 CVC4::SExpr
SmtEngine::getInfo(const std::string
& key
) const {
2449 SmtScope
smts(this);
2451 Trace("smt") << "SMT getInfo(" << key
<< ")" << endl
;
2452 if(key
== "all-statistics") {
2453 vector
<SExpr
> stats
;
2454 for(StatisticsRegistry::const_iterator i
= NodeManager::fromExprManager(d_exprManager
)->getStatisticsRegistry()->begin();
2455 i
!= NodeManager::fromExprManager(d_exprManager
)->getStatisticsRegistry()->end();
2458 v
.push_back((*i
).first
);
2459 v
.push_back((*i
).second
);
2462 for(StatisticsRegistry::const_iterator i
= d_statisticsRegistry
->begin();
2463 i
!= d_statisticsRegistry
->end();
2466 v
.push_back((*i
).first
);
2467 v
.push_back((*i
).second
);
2470 return SExpr(stats
);
2471 } else if(key
== "error-behavior") {
2472 // immediate-exit | continued-execution
2473 if( options::continuedExecution() || options::interactive() ) {
2474 return SExpr(SExpr::Keyword("continued-execution"));
2476 return SExpr(SExpr::Keyword("immediate-exit"));
2478 } else if(key
== "name") {
2479 return SExpr(Configuration::getName());
2480 } else if(key
== "version") {
2481 return SExpr(Configuration::getVersionString());
2482 } else if(key
== "authors") {
2483 return SExpr(Configuration::about());
2484 } else if(key
== "status") {
2485 // sat | unsat | unknown
2486 switch(d_status
.asSatisfiabilityResult().isSat()) {
2488 return SExpr(SExpr::Keyword("sat"));
2490 return SExpr(SExpr::Keyword("unsat"));
2492 return SExpr(SExpr::Keyword("unknown"));
2494 } else if(key
== "reason-unknown") {
2495 if(!d_status
.isNull() && d_status
.isUnknown()) {
2497 ss
<< d_status
.whyUnknown();
2498 string s
= ss
.str();
2499 transform(s
.begin(), s
.end(), s
.begin(), ::tolower
);
2500 return SExpr(SExpr::Keyword(s
));
2502 throw ModalException("Can't get-info :reason-unknown when the "
2503 "last result wasn't unknown!");
2505 } else if(key
== "assertion-stack-levels") {
2506 AlwaysAssert(d_userLevels
.size() <=
2507 std::numeric_limits
<unsigned long int>::max());
2508 return SExpr(static_cast<unsigned long int>(d_userLevels
.size()));
2509 } else if(key
== "all-options") {
2510 // get the options, like all-statistics
2511 std::vector
< std::vector
<std::string
> > current_options
=
2512 Options::current()->getOptions();
2513 return SExpr::parseListOfListOfAtoms(current_options
);
2515 throw UnrecognizedOptionException();
2519 void SmtEngine::debugCheckFormals(const std::vector
<Expr
>& formals
, Expr func
)
2521 for(std::vector
<Expr
>::const_iterator i
= formals
.begin(); i
!= formals
.end(); ++i
) {
2522 if((*i
).getKind() != kind::BOUND_VARIABLE
) {
2524 ss
<< "All formal arguments to defined functions must be BOUND_VARIABLEs, but in the\n"
2525 << "definition of function " << func
<< ", formal\n"
2526 << " " << *i
<< "\n"
2527 << "has kind " << (*i
).getKind();
2528 throw TypeCheckingException(func
, ss
.str());
2533 void SmtEngine::debugCheckFunctionBody(Expr formula
,
2534 const std::vector
<Expr
>& formals
,
2537 Type formulaType
= formula
.getType(options::typeChecking());
2538 Type funcType
= func
.getType();
2539 // We distinguish here between definitions of constants and functions,
2540 // because the type checking for them is subtly different. Perhaps we
2541 // should instead have SmtEngine::defineFunction() and
2542 // SmtEngine::defineConstant() for better clarity, although then that
2543 // doesn't match the SMT-LIBv2 standard...
2544 if(formals
.size() > 0) {
2545 Type rangeType
= FunctionType(funcType
).getRangeType();
2546 if(! formulaType
.isComparableTo(rangeType
)) {
2548 ss
<< "Type of defined function does not match its declaration\n"
2549 << "The function : " << func
<< "\n"
2550 << "Declared type : " << rangeType
<< "\n"
2551 << "The body : " << formula
<< "\n"
2552 << "Body type : " << formulaType
;
2553 throw TypeCheckingException(func
, ss
.str());
2556 if(! formulaType
.isComparableTo(funcType
)) {
2558 ss
<< "Declared type of defined constant does not match its definition\n"
2559 << "The constant : " << func
<< "\n"
2560 << "Declared type : " << funcType
<< " " << Type::getTypeNode(funcType
)->getId() << "\n"
2561 << "The definition : " << formula
<< "\n"
2562 << "Definition type: " << formulaType
<< " " << Type::getTypeNode(formulaType
)->getId();
2563 throw TypeCheckingException(func
, ss
.str());
2568 void SmtEngine::defineFunction(Expr func
,
2569 const std::vector
<Expr
>& formals
,
2572 SmtScope
smts(this);
2574 Trace("smt") << "SMT defineFunction(" << func
<< ")" << endl
;
2575 debugCheckFormals(formals
, func
);
2578 ss
<< language::SetLanguage(
2579 language::SetLanguage::getLanguage(Dump
.getStream()))
2581 DefineFunctionCommand
c(ss
.str(), func
, formals
, formula
);
2582 addToModelCommandAndDump(
2583 c
, ExprManager::VAR_FLAG_DEFINED
, true, "declarations");
2585 PROOF(if (options::checkUnsatCores()) {
2586 d_defineCommands
.push_back(c
.clone());
2590 debugCheckFunctionBody(formula
, formals
, func
);
2592 // Substitute out any abstract values in formula
2594 d_private
->substituteAbstractValues(Node::fromExpr(formula
)).toExpr();
2596 TNode funcNode
= func
.getTNode();
2597 vector
<Node
> formalsNodes
;
2598 for(vector
<Expr
>::const_iterator i
= formals
.begin(),
2599 iend
= formals
.end();
2602 formalsNodes
.push_back((*i
).getNode());
2604 TNode formNode
= form
.getTNode();
2605 DefinedFunction
def(funcNode
, formalsNodes
, formNode
);
2606 // Permit (check-sat) (define-fun ...) (get-value ...) sequences.
2607 // Otherwise, (check-sat) (get-value ((! foo :named bar))) breaks
2608 // d_haveAdditions = true;
2609 Debug("smt") << "definedFunctions insert " << funcNode
<< " " << formNode
<< endl
;
2610 d_definedFunctions
->insert(funcNode
, def
);
2613 void SmtEngine::defineFunctionsRec(
2614 const std::vector
<Expr
>& funcs
,
2615 const std::vector
<std::vector
<Expr
> >& formals
,
2616 const std::vector
<Expr
>& formulas
)
2618 SmtScope
smts(this);
2619 finalOptionsAreSet();
2621 Trace("smt") << "SMT defineFunctionsRec(...)" << endl
;
2623 if (funcs
.size() != formals
.size() && funcs
.size() != formulas
.size())
2626 ss
<< "Number of functions, formals, and function bodies passed to "
2627 "defineFunctionsRec do not match:"
2629 << " #functions : " << funcs
.size() << "\n"
2630 << " #arg lists : " << formals
.size() << "\n"
2631 << " #function bodies : " << formulas
.size() << "\n";
2632 throw ModalException(ss
.str());
2634 for (unsigned i
= 0, size
= funcs
.size(); i
< size
; i
++)
2636 // check formal argument list
2637 debugCheckFormals(formals
[i
], funcs
[i
]);
2639 debugCheckFunctionBody(formulas
[i
], formals
[i
], funcs
[i
]);
2642 if (Dump
.isOn("raw-benchmark"))
2644 Dump("raw-benchmark") << DefineFunctionRecCommand(funcs
, formals
, formulas
);
2647 ExprManager
* em
= getExprManager();
2648 for (unsigned i
= 0, size
= funcs
.size(); i
< size
; i
++)
2650 // we assert a quantified formula
2652 // make the function application
2653 if (formals
[i
].empty())
2655 // it has no arguments
2656 func_app
= funcs
[i
];
2660 std::vector
<Expr
> children
;
2661 children
.push_back(funcs
[i
]);
2662 children
.insert(children
.end(), formals
[i
].begin(), formals
[i
].end());
2663 func_app
= em
->mkExpr(kind::APPLY_UF
, children
);
2665 Expr lem
= em
->mkExpr(kind::EQUAL
, func_app
, formulas
[i
]);
2666 if (!formals
[i
].empty())
2668 // set the attribute to denote this is a function definition
2669 std::string
attr_name("fun-def");
2670 Expr aexpr
= em
->mkExpr(kind::INST_ATTRIBUTE
, func_app
);
2671 aexpr
= em
->mkExpr(kind::INST_PATTERN_LIST
, aexpr
);
2672 std::vector
<Expr
> expr_values
;
2673 std::string str_value
;
2674 setUserAttribute(attr_name
, func_app
, expr_values
, str_value
);
2675 // make the quantified formula
2676 Expr boundVars
= em
->mkExpr(kind::BOUND_VAR_LIST
, formals
[i
]);
2677 lem
= em
->mkExpr(kind::FORALL
, boundVars
, lem
, aexpr
);
2679 // assert the quantified formula
2680 // notice we don't call assertFormula directly, since this would
2681 // duplicate the output on raw-benchmark.
2682 Expr e
= d_private
->substituteAbstractValues(Node::fromExpr(lem
)).toExpr();
2683 if (d_assertionList
!= NULL
)
2685 d_assertionList
->push_back(e
);
2687 d_private
->addFormula(e
.getNode(), false);
2691 void SmtEngine::defineFunctionRec(Expr func
,
2692 const std::vector
<Expr
>& formals
,
2695 std::vector
<Expr
> funcs
;
2696 funcs
.push_back(func
);
2697 std::vector
<std::vector
<Expr
> > formals_multi
;
2698 formals_multi
.push_back(formals
);
2699 std::vector
<Expr
> formulas
;
2700 formulas
.push_back(formula
);
2701 defineFunctionsRec(funcs
, formals_multi
, formulas
);
2704 bool SmtEngine::isDefinedFunction( Expr func
){
2705 Node nf
= Node::fromExpr( func
);
2706 Debug("smt") << "isDefined function " << nf
<< "?" << std::endl
;
2707 return d_definedFunctions
->find(nf
) != d_definedFunctions
->end();
2710 void SmtEnginePrivate::finishInit()
2712 d_preprocessingPassContext
.reset(
2713 new PreprocessingPassContext(&d_smt
, d_resourceManager
));
2714 // TODO: register passes here (this will likely change when we add support for
2715 // actually assembling preprocessing pipelines).
2716 std::unique_ptr
<ApplySubsts
> applySubsts(
2717 new ApplySubsts(d_preprocessingPassContext
.get()));
2718 std::unique_ptr
<BoolToBV
> boolToBv(
2719 new BoolToBV(d_preprocessingPassContext
.get()));
2720 std::unique_ptr
<BvAbstraction
> bvAbstract(
2721 new BvAbstraction(d_preprocessingPassContext
.get()));
2722 std::unique_ptr
<BVAckermann
> bvAckermann(
2723 new BVAckermann(d_preprocessingPassContext
.get()));
2724 std::unique_ptr
<BVGauss
> bvGauss(
2725 new BVGauss(d_preprocessingPassContext
.get()));
2726 std::unique_ptr
<BvIntroPow2
> bvIntroPow2(
2727 new BvIntroPow2(d_preprocessingPassContext
.get()));
2728 std::unique_ptr
<BVToBool
> bvToBool(
2729 new BVToBool(d_preprocessingPassContext
.get()));
2730 std::unique_ptr
<IntToBV
> intToBV(
2731 new IntToBV(d_preprocessingPassContext
.get()));
2732 std::unique_ptr
<PseudoBooleanProcessor
> pbProc(
2733 new PseudoBooleanProcessor(d_preprocessingPassContext
.get()));
2734 std::unique_ptr
<RealToInt
> realToInt(
2735 new RealToInt(d_preprocessingPassContext
.get()));
2736 std::unique_ptr
<Rewrite
> rewrite(
2737 new Rewrite(d_preprocessingPassContext
.get()));
2738 std::unique_ptr
<StaticLearning
> staticLearning(
2739 new StaticLearning(d_preprocessingPassContext
.get()));
2740 std::unique_ptr
<SymBreakerPass
> sbProc(
2741 new SymBreakerPass(d_preprocessingPassContext
.get()));
2742 std::unique_ptr
<SynthRewRulesPass
> srrProc(
2743 new SynthRewRulesPass(d_preprocessingPassContext
.get()));
2744 std::unique_ptr
<SepSkolemEmp
> sepSkolemEmp(
2745 new SepSkolemEmp(d_preprocessingPassContext
.get()));
2746 d_preprocessingPassRegistry
.registerPass("apply-substs",
2747 std::move(applySubsts
));
2748 d_preprocessingPassRegistry
.registerPass("bool-to-bv", std::move(boolToBv
));
2749 d_preprocessingPassRegistry
.registerPass("bv-abstraction",
2750 std::move(bvAbstract
));
2751 d_preprocessingPassRegistry
.registerPass("bv-ackermann",
2752 std::move(bvAckermann
));
2753 d_preprocessingPassRegistry
.registerPass("bv-gauss", std::move(bvGauss
));
2754 d_preprocessingPassRegistry
.registerPass("bv-intro-pow2",
2755 std::move(bvIntroPow2
));
2756 d_preprocessingPassRegistry
.registerPass("bv-to-bool", std::move(bvToBool
));
2757 d_preprocessingPassRegistry
.registerPass("int-to-bv", std::move(intToBV
));
2758 d_preprocessingPassRegistry
.registerPass("pseudo-boolean-processor",
2760 d_preprocessingPassRegistry
.registerPass("real-to-int", std::move(realToInt
));
2761 d_preprocessingPassRegistry
.registerPass("rewrite", std::move(rewrite
));
2762 d_preprocessingPassRegistry
.registerPass("sep-skolem-emp",
2763 std::move(sepSkolemEmp
));
2764 d_preprocessingPassRegistry
.registerPass("static-learning",
2765 std::move(staticLearning
));
2766 d_preprocessingPassRegistry
.registerPass("sym-break", std::move(sbProc
));
2767 d_preprocessingPassRegistry
.registerPass("synth-rr", std::move(srrProc
));
2770 Node
SmtEnginePrivate::expandDefinitions(TNode n
, unordered_map
<Node
, Node
, NodeHashFunction
>& cache
, bool expandOnly
)
2772 stack
< triple
<Node
, Node
, bool> > worklist
;
2774 worklist
.push(make_triple(Node(n
), Node(n
), false));
2775 // The worklist is made of triples, each is input / original node then the output / rewritten node
2776 // and finally a flag tracking whether the children have been explored (i.e. if this is a downward
2780 spendResource(options::preprocessStep());
2781 n
= worklist
.top().first
; // n is the input / original
2782 Node node
= worklist
.top().second
; // node is the output / result
2783 bool childrenPushed
= worklist
.top().third
;
2786 // Working downwards
2787 if(!childrenPushed
) {
2788 Kind k
= n
.getKind();
2790 // we can short circuit (variable) leaves
2792 SmtEngine::DefinedFunctionMap::const_iterator i
= d_smt
.d_definedFunctions
->find(n
);
2793 if(i
!= d_smt
.d_definedFunctions
->end()) {
2794 // replacement must be closed
2795 if((*i
).second
.getFormals().size() > 0) {
2796 result
.push(d_smt
.d_nodeManager
->mkNode(kind::LAMBDA
, d_smt
.d_nodeManager
->mkNode(kind::BOUND_VAR_LIST
, (*i
).second
.getFormals()), (*i
).second
.getFormula()));
2799 // don't bother putting in the cache
2800 result
.push((*i
).second
.getFormula());
2803 // don't bother putting in the cache
2808 // maybe it's in the cache
2809 unordered_map
<Node
, Node
, NodeHashFunction
>::iterator cacheHit
= cache
.find(n
);
2810 if(cacheHit
!= cache
.end()) {
2811 TNode ret
= (*cacheHit
).second
;
2812 result
.push(ret
.isNull() ? n
: ret
);
2816 // otherwise expand it
2817 bool doExpand
= false;
2818 if (k
== kind::APPLY
)
2822 else if (k
== kind::APPLY_UF
)
2824 // Always do beta-reduction here. The reason is that there may be
2825 // operators such as INTS_MODULUS in the body of the lambda that would
2826 // otherwise be introduced by beta-reduction via the rewriter, but are
2827 // not expanded here since the traversal in this function does not
2828 // traverse the operators of nodes. Hence, we beta-reduce here to
2829 // ensure terms in the body of the lambda are expanded during this
2831 if (n
.getOperator().getKind() == kind::LAMBDA
)
2835 else if (options::macrosQuant() || options::sygusInference())
2837 // The above options assign substitutions to APPLY_UF, thus we check
2838 // here and expand if this operator corresponds to a defined function.
2839 doExpand
= d_smt
.isDefinedFunction(n
.getOperator().toExpr());
2843 vector
<Node
> formals
;
2845 if( n
.getOperator().getKind() == kind::LAMBDA
){
2846 TNode op
= n
.getOperator();
2848 for( unsigned i
=0; i
<op
[0].getNumChildren(); i
++ ){
2849 formals
.push_back( op
[0][i
] );
2853 // application of a user-defined symbol
2854 TNode func
= n
.getOperator();
2855 SmtEngine::DefinedFunctionMap::const_iterator i
= d_smt
.d_definedFunctions
->find(func
);
2856 if(i
== d_smt
.d_definedFunctions
->end()) {
2857 throw TypeCheckingException(n
.toExpr(), string("Undefined function: `") + func
.toString() + "'");
2859 DefinedFunction def
= (*i
).second
;
2860 formals
= def
.getFormals();
2862 if(Debug
.isOn("expand")) {
2863 Debug("expand") << "found: " << n
<< endl
;
2864 Debug("expand") << " func: " << func
<< endl
;
2865 string name
= func
.getAttribute(expr::VarNameAttr());
2866 Debug("expand") << " : \"" << name
<< "\"" << endl
;
2868 if(Debug
.isOn("expand")) {
2869 Debug("expand") << " defn: " << def
.getFunction() << endl
2871 if(formals
.size() > 0) {
2872 copy( formals
.begin(), formals
.end() - 1,
2873 ostream_iterator
<Node
>(Debug("expand"), ", ") );
2874 Debug("expand") << formals
.back();
2876 Debug("expand") << "]" << endl
2877 << " " << def
.getFunction().getType() << endl
2878 << " " << def
.getFormula() << endl
;
2881 fm
= def
.getFormula();
2884 Node instance
= fm
.substitute(formals
.begin(),
2887 n
.begin() + formals
.size());
2888 Debug("expand") << "made : " << instance
<< endl
;
2890 Node expanded
= expandDefinitions(instance
, cache
, expandOnly
);
2891 cache
[n
] = (n
== expanded
? Node::null() : expanded
);
2892 result
.push(expanded
);
2895 } else if(! expandOnly
) {
2896 // do not do any theory stuff if expandOnly is true
2898 theory::Theory
* t
= d_smt
.d_theoryEngine
->theoryOf(node
);
2901 LogicRequest
req(d_smt
);
2902 node
= t
->expandDefinition(req
, n
);
2905 // the partial functions can fall through, in which case we still
2906 // consider their children
2907 worklist
.push(make_triple(Node(n
), node
, true)); // Original and rewritten result
2909 for(size_t i
= 0; i
< node
.getNumChildren(); ++i
) {
2910 worklist
.push(make_triple(node
[i
], node
[i
], false)); // Rewrite the children of the result only
2915 // Reconstruct the node from it's (now rewritten) children on the stack
2917 Debug("expand") << "cons : " << node
<< endl
;
2918 if(node
.getNumChildren()>0) {
2919 //cout << "cons : " << node << endl;
2920 NodeBuilder
<> nb(node
.getKind());
2921 if(node
.getMetaKind() == kind::metakind::PARAMETERIZED
) {
2922 Debug("expand") << "op : " << node
.getOperator() << endl
;
2923 //cout << "op : " << node.getOperator() << endl;
2924 nb
<< node
.getOperator();
2926 for(size_t i
= 0; i
< node
.getNumChildren(); ++i
) {
2927 Assert(!result
.empty());
2928 Node expanded
= result
.top();
2930 //cout << "exchld : " << expanded << endl;
2931 Debug("expand") << "exchld : " << expanded
<< endl
;
2936 cache
[n
] = n
== node
? Node::null() : node
; // Only cache once all subterms are expanded
2939 } while(!worklist
.empty());
2941 AlwaysAssert(result
.size() == 1);
2943 return result
.top();
2946 typedef std::unordered_map
<Node
, Node
, NodeHashFunction
> NodeMap
;
2948 Node
SmtEnginePrivate::purifyNlTerms(TNode n
, NodeMap
& cache
, NodeMap
& bcache
, std::vector
< Node
>& var_eq
, bool beneathMult
) {
2950 NodeMap::iterator find
= bcache
.find(n
);
2951 if (find
!= bcache
.end()) {
2952 return (*find
).second
;
2955 NodeMap::iterator find
= cache
.find(n
);
2956 if (find
!= cache
.end()) {
2957 return (*find
).second
;
2961 if( n
.getNumChildren()>0 ){
2963 && (n
.getKind() == kind::PLUS
|| n
.getKind() == kind::MINUS
))
2965 // don't do it if it rewrites to a constant
2966 Node nr
= Rewriter::rewrite(n
);
2969 // return the rewritten constant
2975 ret
= NodeManager::currentNM()->mkSkolem(
2978 "Variable introduced in purifyNl pass");
2979 Node np
= purifyNlTerms(n
, cache
, bcache
, var_eq
, false);
2980 var_eq
.push_back(np
.eqNode(ret
));
2981 Trace("nl-ext-purify")
2982 << "Purify : " << ret
<< " -> " << np
<< std::endl
;
2987 bool beneathMultNew
= beneathMult
|| n
.getKind()==kind::MULT
;
2988 bool childChanged
= false;
2989 std::vector
< Node
> children
;
2990 for( unsigned i
=0; i
<n
.getNumChildren(); i
++ ){
2991 Node nc
= purifyNlTerms( n
[i
], cache
, bcache
, var_eq
, beneathMultNew
);
2992 childChanged
= childChanged
|| nc
!=n
[i
];
2993 children
.push_back( nc
);
2996 ret
= NodeManager::currentNM()->mkNode( n
.getKind(), children
);
3008 void SmtEnginePrivate::removeITEs() {
3009 d_smt
.finalOptionsAreSet();
3010 spendResource(options::preprocessStep());
3011 Trace("simplify") << "SmtEnginePrivate::removeITEs()" << endl
;
3013 // Remove all of the ITE occurrences and normalize
3014 d_iteRemover
.run(d_assertions
.ref(), d_iteSkolemMap
, true);
3015 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
3016 d_assertions
.replace(i
, Rewriter::rewrite(d_assertions
[i
]));
3022 // do dumping (before/after any preprocessing pass)
3023 static void dumpAssertions(const char* key
,
3024 const AssertionPipeline
& assertionList
) {
3025 if( Dump
.isOn("assertions") &&
3026 Dump
.isOn(string("assertions:") + key
) ) {
3027 // Push the simplified assertions to the dump output stream
3028 for(unsigned i
= 0; i
< assertionList
.size(); ++ i
) {
3029 TNode n
= assertionList
[i
];
3030 Dump("assertions") << AssertCommand(Expr(n
.toExpr()));
3035 // returns false if it learns a conflict
3036 bool SmtEnginePrivate::nonClausalSimplify() {
3037 spendResource(options::preprocessStep());
3038 d_smt
.finalOptionsAreSet();
3040 if(options::unsatCores() || options::fewerPreprocessingHoles()) {
3044 TimerStat::CodeTimer
nonclausalTimer(d_smt
.d_stats
->d_nonclausalSimplificationTime
);
3046 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify()" << endl
;
3047 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
3048 Trace("simplify") << "Assertion #" << i
<< " : " << d_assertions
[i
] << std::endl
;
3051 if(d_propagatorNeedsFinish
) {
3052 d_propagator
.finish();
3053 d_propagatorNeedsFinish
= false;
3055 d_propagator
.initialize();
3057 // Assert all the assertions to the propagator
3058 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
3059 << "asserting to propagator" << endl
;
3060 CDO
<unsigned>& substs_index
= d_assertions
.getSubstitutionsIndex();
3061 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
3062 Assert(Rewriter::rewrite(d_assertions
[i
]) == d_assertions
[i
]);
3063 // Don't reprocess substitutions
3064 if (substs_index
> 0 && i
== substs_index
)
3068 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): asserting " << d_assertions
[i
] << endl
;
3069 Debug("cores") << "d_propagator assertTrue: " << d_assertions
[i
] << std::endl
;
3070 d_propagator
.assertTrue(d_assertions
[i
]);
3073 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
3074 << "propagating" << endl
;
3075 if (d_propagator
.propagate()) {
3076 // If in conflict, just return false
3077 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
3078 << "conflict in non-clausal propagation" << endl
;
3079 Node falseNode
= NodeManager::currentNM()->mkConst
<bool>(false);
3080 Assert(!options::unsatCores() && !options::fewerPreprocessingHoles());
3081 d_assertions
.clear();
3082 addFormula(falseNode
, false, false);
3083 d_propagatorNeedsFinish
= true;
3088 Trace("simplify") << "Iterate through " << d_nonClausalLearnedLiterals
.size() << " learned literals." << std::endl
;
3089 // No conflict, go through the literals and solve them
3090 SubstitutionMap
& top_level_substs
= d_assertions
.getTopLevelSubstitutions();
3091 SubstitutionMap
constantPropagations(d_smt
.d_context
);
3092 SubstitutionMap
newSubstitutions(d_smt
.d_context
);
3093 SubstitutionMap::iterator pos
;
3095 for(unsigned i
= 0, i_end
= d_nonClausalLearnedLiterals
.size(); i
< i_end
; ++ i
) {
3096 // Simplify the literal we learned wrt previous substitutions
3097 Node learnedLiteral
= d_nonClausalLearnedLiterals
[i
];
3098 Assert(Rewriter::rewrite(learnedLiteral
) == learnedLiteral
);
3099 Assert(top_level_substs
.apply(learnedLiteral
) == learnedLiteral
);
3100 Trace("simplify") << "Process learnedLiteral : " << learnedLiteral
<< std::endl
;
3101 Node learnedLiteralNew
= newSubstitutions
.apply(learnedLiteral
);
3102 if (learnedLiteral
!= learnedLiteralNew
) {
3103 learnedLiteral
= Rewriter::rewrite(learnedLiteralNew
);
3105 Trace("simplify") << "Process learnedLiteral, after newSubs : " << learnedLiteral
<< std::endl
;
3107 learnedLiteralNew
= constantPropagations
.apply(learnedLiteral
);
3108 if (learnedLiteralNew
== learnedLiteral
) {
3111 ++d_smt
.d_stats
->d_numConstantProps
;
3112 learnedLiteral
= Rewriter::rewrite(learnedLiteralNew
);
3114 Trace("simplify") << "Process learnedLiteral, after constProp : " << learnedLiteral
<< std::endl
;
3115 // It might just simplify to a constant
3116 if (learnedLiteral
.isConst()) {
3117 if (learnedLiteral
.getConst
<bool>()) {
3118 // If the learned literal simplifies to true, it's redundant
3121 // If the learned literal simplifies to false, we're in conflict
3122 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
3124 << d_nonClausalLearnedLiterals
[i
] << endl
;
3125 Assert(!options::unsatCores());
3126 d_assertions
.clear();
3127 addFormula(NodeManager::currentNM()->mkConst
<bool>(false), false, false);
3128 d_propagatorNeedsFinish
= true;
3133 // Solve it with the corresponding theory, possibly adding new
3134 // substitutions to newSubstitutions
3135 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
3136 << "solving " << learnedLiteral
<< endl
;
3138 Theory::PPAssertStatus solveStatus
=
3139 d_smt
.d_theoryEngine
->solve(learnedLiteral
, newSubstitutions
);
3141 switch (solveStatus
) {
3142 case Theory::PP_ASSERT_STATUS_SOLVED
: {
3143 // The literal should rewrite to true
3144 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
3145 << "solved " << learnedLiteral
<< endl
;
3146 Assert(Rewriter::rewrite(newSubstitutions
.apply(learnedLiteral
)).isConst());
3147 // vector<pair<Node, Node> > equations;
3148 // constantPropagations.simplifyLHS(top_level_substs, equations,
3149 // true); if (equations.empty()) {
3152 // Assert(equations[0].first.isConst() &&
3153 // equations[0].second.isConst() && equations[0].first !=
3154 // equations[0].second);
3155 // else fall through
3158 case Theory::PP_ASSERT_STATUS_CONFLICT
:
3159 // If in conflict, we return false
3160 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
3161 << "conflict while solving "
3162 << learnedLiteral
<< endl
;
3163 Assert(!options::unsatCores());
3164 d_assertions
.clear();
3165 addFormula(NodeManager::currentNM()->mkConst
<bool>(false), false, false);
3166 d_propagatorNeedsFinish
= true;
3169 if (d_doConstantProp
&& learnedLiteral
.getKind() == kind::EQUAL
&& (learnedLiteral
[0].isConst() || learnedLiteral
[1].isConst())) {
3170 // constant propagation
3173 if (learnedLiteral
[0].isConst()) {
3174 t
= learnedLiteral
[1];
3175 c
= learnedLiteral
[0];
3178 t
= learnedLiteral
[0];
3179 c
= learnedLiteral
[1];
3181 Assert(!t
.isConst());
3182 Assert(constantPropagations
.apply(t
) == t
);
3183 Assert(top_level_substs
.apply(t
) == t
);
3184 Assert(newSubstitutions
.apply(t
) == t
);
3185 constantPropagations
.addSubstitution(t
, c
);
3186 // vector<pair<Node,Node> > equations;
3187 // constantPropagations.simplifyLHS(t, c, equations, true);
3188 // if (!equations.empty()) {
3189 // Assert(equations[0].first.isConst() &&
3190 // equations[0].second.isConst() && equations[0].first !=
3191 // equations[0].second); d_assertions.clear();
3192 // addFormula(NodeManager::currentNM()->mkConst<bool>(false), false,
3195 // top_level_substs.simplifyRHS(constantPropagations);
3199 d_nonClausalLearnedLiterals
[j
++] = d_nonClausalLearnedLiterals
[i
];
3205 #ifdef CVC4_ASSERTIONS
3206 // NOTE: When debugging this code, consider moving this check inside of the
3207 // loop over d_nonClausalLearnedLiterals. This check has been moved outside
3208 // because it is costly for certain inputs (see bug 508).
3210 // Check data structure invariants:
3211 // 1. for each lhs of top_level_substs, does not appear anywhere in rhs of
3212 // top_level_substs or anywhere in constantPropagations
3213 // 2. each lhs of constantPropagations rewrites to itself
3214 // 3. if l -> r is a constant propagation and l is a subterm of l' with l' ->
3215 // r' another constant propagation, then l'[l/r] -> r' should be a
3216 // constant propagation too
3217 // 4. each lhs of constantPropagations is different from each rhs
3218 for (pos
= newSubstitutions
.begin(); pos
!= newSubstitutions
.end(); ++pos
) {
3219 Assert((*pos
).first
.isVar());
3220 Assert(top_level_substs
.apply((*pos
).first
) == (*pos
).first
);
3221 Assert(top_level_substs
.apply((*pos
).second
) == (*pos
).second
);
3222 Assert(newSubstitutions
.apply(newSubstitutions
.apply((*pos
).second
)) == newSubstitutions
.apply((*pos
).second
));
3224 for (pos
= constantPropagations
.begin(); pos
!= constantPropagations
.end(); ++pos
) {
3225 Assert((*pos
).second
.isConst());
3226 Assert(Rewriter::rewrite((*pos
).first
) == (*pos
).first
);
3227 // Node newLeft = top_level_substs.apply((*pos).first);
3228 // if (newLeft != (*pos).first) {
3229 // newLeft = Rewriter::rewrite(newLeft);
3230 // Assert(newLeft == (*pos).second ||
3231 // (constantPropagations.hasSubstitution(newLeft) &&
3232 // constantPropagations.apply(newLeft) == (*pos).second));
3234 // newLeft = constantPropagations.apply((*pos).first);
3235 // if (newLeft != (*pos).first) {
3236 // newLeft = Rewriter::rewrite(newLeft);
3237 // Assert(newLeft == (*pos).second ||
3238 // (constantPropagations.hasSubstitution(newLeft) &&
3239 // constantPropagations.apply(newLeft) == (*pos).second));
3241 Assert(constantPropagations
.apply((*pos
).second
) == (*pos
).second
);
3243 #endif /* CVC4_ASSERTIONS */
3245 // Resize the learnt
3246 Trace("simplify") << "Resize non-clausal learned literals to " << j
<< std::endl
;
3247 d_nonClausalLearnedLiterals
.resize(j
);
3249 unordered_set
<TNode
, TNodeHashFunction
> s
;
3250 Trace("debugging") << "NonClausal simplify pre-preprocess\n";
3251 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
3252 Node assertion
= d_assertions
[i
];
3253 Node assertionNew
= newSubstitutions
.apply(assertion
);
3254 Trace("debugging") << "assertion = " << assertion
<< endl
;
3255 Trace("debugging") << "assertionNew = " << assertionNew
<< endl
;
3256 if (assertion
!= assertionNew
) {
3257 assertion
= Rewriter::rewrite(assertionNew
);
3258 Trace("debugging") << "rewrite(assertion) = " << assertion
<< endl
;
3260 Assert(Rewriter::rewrite(assertion
) == assertion
);
3262 assertionNew
= constantPropagations
.apply(assertion
);
3263 if (assertionNew
== assertion
) {
3266 ++d_smt
.d_stats
->d_numConstantProps
;
3267 Trace("debugging") << "assertionNew = " << assertionNew
<< endl
;
3268 assertion
= Rewriter::rewrite(assertionNew
);
3269 Trace("debugging") << "assertionNew = " << assertionNew
<< endl
;
3271 Trace("debugging") << "\n";
3272 s
.insert(assertion
);
3273 d_assertions
.replace(i
, assertion
);
3274 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
3275 << "non-clausal preprocessed: "
3276 << assertion
<< endl
;
3279 // If in incremental mode, add substitutions to the list of assertions
3280 if (substs_index
> 0)
3282 NodeBuilder
<> substitutionsBuilder(kind::AND
);
3283 substitutionsBuilder
<< d_assertions
[substs_index
];
3284 pos
= newSubstitutions
.begin();
3285 for (; pos
!= newSubstitutions
.end(); ++pos
) {
3286 // Add back this substitution as an assertion
3287 TNode lhs
= (*pos
).first
, rhs
= newSubstitutions
.apply((*pos
).second
);
3288 Node n
= NodeManager::currentNM()->mkNode(kind::EQUAL
, lhs
, rhs
);
3289 substitutionsBuilder
<< n
;
3290 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): will notify SAT layer of substitution: " << n
<< endl
;
3292 if (substitutionsBuilder
.getNumChildren() > 1) {
3293 d_assertions
.replace(substs_index
,
3294 Rewriter::rewrite(Node(substitutionsBuilder
)));
3297 // If not in incremental mode, must add substitutions to model
3298 TheoryModel
* m
= d_smt
.d_theoryEngine
->getModel();
3300 for(pos
= newSubstitutions
.begin(); pos
!= newSubstitutions
.end(); ++pos
) {
3301 Node n
= (*pos
).first
;
3302 Node v
= newSubstitutions
.apply((*pos
).second
);
3303 Trace("model") << "Add substitution : " << n
<< " " << v
<< endl
;
3304 m
->addSubstitution( n
, v
);
3309 NodeBuilder
<> learnedBuilder(kind::AND
);
3310 Assert(d_realAssertionsEnd
<= d_assertions
.size());
3311 learnedBuilder
<< d_assertions
[d_realAssertionsEnd
- 1];
3313 for (unsigned i
= 0; i
< d_nonClausalLearnedLiterals
.size(); ++ i
) {
3314 Node learned
= d_nonClausalLearnedLiterals
[i
];
3315 Assert(top_level_substs
.apply(learned
) == learned
);
3316 Node learnedNew
= newSubstitutions
.apply(learned
);
3317 if (learned
!= learnedNew
) {
3318 learned
= Rewriter::rewrite(learnedNew
);
3320 Assert(Rewriter::rewrite(learned
) == learned
);
3322 learnedNew
= constantPropagations
.apply(learned
);
3323 if (learnedNew
== learned
) {
3326 ++d_smt
.d_stats
->d_numConstantProps
;
3327 learned
= Rewriter::rewrite(learnedNew
);
3329 if (s
.find(learned
) != s
.end()) {
3333 learnedBuilder
<< learned
;
3334 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
3335 << "non-clausal learned : "
3338 d_nonClausalLearnedLiterals
.clear();
3340 for (pos
= constantPropagations
.begin(); pos
!= constantPropagations
.end(); ++pos
) {
3341 Node cProp
= (*pos
).first
.eqNode((*pos
).second
);
3342 Assert(top_level_substs
.apply(cProp
) == cProp
);
3343 Node cPropNew
= newSubstitutions
.apply(cProp
);
3344 if (cProp
!= cPropNew
) {
3345 cProp
= Rewriter::rewrite(cPropNew
);
3346 Assert(Rewriter::rewrite(cProp
) == cProp
);
3348 if (s
.find(cProp
) != s
.end()) {
3352 learnedBuilder
<< cProp
;
3353 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
3354 << "non-clausal constant propagation : "
3358 // Add new substitutions to topLevelSubstitutions
3359 // Note that we don't have to keep rhs's in full solved form
3360 // because SubstitutionMap::apply does a fixed-point iteration when substituting
3361 top_level_substs
.addSubstitutions(newSubstitutions
);
3363 if(learnedBuilder
.getNumChildren() > 1) {
3364 d_assertions
.replace(d_realAssertionsEnd
- 1,
3365 Rewriter::rewrite(Node(learnedBuilder
)));
3368 d_propagatorNeedsFinish
= true;
3372 bool SmtEnginePrivate::simpITE() {
3373 TimerStat::CodeTimer
simpITETimer(d_smt
.d_stats
->d_simpITETime
);
3375 spendResource(options::preprocessStep());
3377 Trace("simplify") << "SmtEnginePrivate::simpITE()" << endl
;
3379 unsigned numAssertionOnEntry
= d_assertions
.size();
3380 for (unsigned i
= 0; i
< d_assertions
.size(); ++i
) {
3381 spendResource(options::preprocessStep());
3382 Node result
= d_smt
.d_theoryEngine
->ppSimpITE(d_assertions
[i
]);
3383 d_assertions
.replace(i
, result
);
3384 if(result
.isConst() && !result
.getConst
<bool>()){
3388 bool result
= d_smt
.d_theoryEngine
->donePPSimpITE(d_assertions
.ref());
3389 if(numAssertionOnEntry
< d_assertions
.size()){
3390 compressBeforeRealAssertions(numAssertionOnEntry
);
3395 void SmtEnginePrivate::compressBeforeRealAssertions(size_t before
){
3396 size_t curr
= d_assertions
.size();
3397 if(before
>= curr
||
3398 d_realAssertionsEnd
<= 0 ||
3399 d_realAssertionsEnd
>= curr
){
3404 // original: [0 ... d_realAssertionsEnd)
3406 // ites skolems [d_realAssertionsEnd, before)
3408 // added [before, curr)
3410 Assert(0 < d_realAssertionsEnd
);
3411 Assert(d_realAssertionsEnd
<= before
);
3412 Assert(before
< curr
);
3414 std::vector
<Node
> intoConjunction
;
3415 for(size_t i
= before
; i
<curr
; ++i
){
3416 intoConjunction
.push_back(d_assertions
[i
]);
3418 d_assertions
.resize(before
);
3419 size_t lastBeforeItes
= d_realAssertionsEnd
- 1;
3420 intoConjunction
.push_back(d_assertions
[lastBeforeItes
]);
3421 Node newLast
= util::NaryBuilder::mkAssoc(kind::AND
, intoConjunction
);
3422 d_assertions
.replace(lastBeforeItes
, newLast
);
3423 Assert(d_assertions
.size() == before
);
3426 void SmtEnginePrivate::unconstrainedSimp() {
3427 TimerStat::CodeTimer
unconstrainedSimpTimer(d_smt
.d_stats
->d_unconstrainedSimpTime
);
3428 spendResource(options::preprocessStep());
3429 Trace("simplify") << "SmtEnginePrivate::unconstrainedSimp()" << endl
;
3430 d_smt
.d_theoryEngine
->ppUnconstrainedSimp(d_assertions
.ref());
3433 void SmtEnginePrivate::traceBackToAssertions(const std::vector
<Node
>& nodes
, std::vector
<TNode
>& assertions
) {
3434 const booleans::CircuitPropagator::BackEdgesMap
& backEdges
= d_propagator
.getBackEdges();
3435 for(vector
<Node
>::const_iterator i
= nodes
.begin(); i
!= nodes
.end(); ++i
) {
3436 booleans::CircuitPropagator::BackEdgesMap::const_iterator j
= backEdges
.find(*i
);
3437 // term must appear in map, otherwise how did we get here?!
3438 Assert(j
!= backEdges
.end());
3439 // if term maps to empty, that means it's a top-level assertion
3440 if(!(*j
).second
.empty()) {
3441 traceBackToAssertions((*j
).second
, assertions
);
3443 assertions
.push_back(*i
);
3448 size_t SmtEnginePrivate::removeFromConjunction(Node
& n
, const std::unordered_set
<unsigned long>& toRemove
) {
3449 Assert(n
.getKind() == kind::AND
);
3450 size_t removals
= 0;
3451 for(Node::iterator j
= n
.begin(); j
!= n
.end(); ++j
) {
3452 size_t subremovals
= 0;
3454 if(toRemove
.find(sub
.getId()) != toRemove
.end() ||
3455 (sub
.getKind() == kind::AND
&& (subremovals
= removeFromConjunction(sub
, toRemove
)) > 0)) {
3456 NodeBuilder
<> b(kind::AND
);
3457 b
.append(n
.begin(), j
);
3458 if(subremovals
> 0) {
3459 removals
+= subremovals
;
3464 for(++j
; j
!= n
.end(); ++j
) {
3465 if(toRemove
.find((*j
).getId()) != toRemove
.end()) {
3467 } else if((*j
).getKind() == kind::AND
) {
3469 if((subremovals
= removeFromConjunction(sub
, toRemove
)) > 0) {
3470 removals
+= subremovals
;
3479 if(b
.getNumChildren() == 0) {
3482 } else if(b
.getNumChildren() == 1) {
3488 n
= Rewriter::rewrite(n
);
3493 Assert(removals
== 0);
3497 void SmtEnginePrivate::doMiplibTrick() {
3498 Assert(d_realAssertionsEnd
== d_assertions
.size());
3499 Assert(!options::incrementalSolving());
3501 const booleans::CircuitPropagator::BackEdgesMap
& backEdges
= d_propagator
.getBackEdges();
3502 unordered_set
<unsigned long> removeAssertions
;
3504 NodeManager
* nm
= NodeManager::currentNM();
3505 Node zero
= nm
->mkConst(Rational(0)), one
= nm
->mkConst(Rational(1));
3507 SubstitutionMap
& top_level_substs
= d_assertions
.getTopLevelSubstitutions();
3508 unordered_map
<TNode
, Node
, TNodeHashFunction
> intVars
;
3509 for(vector
<Node
>::const_iterator i
= d_boolVars
.begin(); i
!= d_boolVars
.end(); ++i
) {
3510 if(d_propagator
.isAssigned(*i
)) {
3511 Debug("miplib") << "ineligible: " << *i
<< " because assigned " << d_propagator
.getAssignment(*i
) << endl
;
3515 vector
<TNode
> assertions
;
3516 booleans::CircuitPropagator::BackEdgesMap::const_iterator j
= backEdges
.find(*i
);
3517 // if not in back edges map, the bool var is unconstrained, showing up in no assertions.
3518 // if maps to an empty vector, that means the bool var was asserted itself.
3519 if(j
!= backEdges
.end()) {
3520 if(!(*j
).second
.empty()) {
3521 traceBackToAssertions((*j
).second
, assertions
);
3523 assertions
.push_back(*i
);
3526 Debug("miplib") << "for " << *i
<< endl
;
3527 bool eligible
= true;
3528 map
<pair
<Node
, Node
>, uint64_t> marks
;
3529 map
<pair
<Node
, Node
>, vector
<Rational
> > coef
;
3530 map
<pair
<Node
, Node
>, vector
<Rational
> > checks
;
3531 map
<pair
<Node
, Node
>, vector
<TNode
> > asserts
;
3532 for(vector
<TNode
>::const_iterator j
= assertions
.begin(); j
!= assertions
.end(); ++j
) {
3533 Debug("miplib") << " found: " << *j
<< endl
;
3534 if((*j
).getKind() != kind::IMPLIES
) {
3536 Debug("miplib") << " -- INELIGIBLE -- (not =>)" << endl
;
3539 Node conj
= BooleanSimplification::simplify((*j
)[0]);
3540 if(conj
.getKind() == kind::AND
&& conj
.getNumChildren() > 6) {
3542 Debug("miplib") << " -- INELIGIBLE -- (N-ary /\\ too big)" << endl
;
3545 if(conj
.getKind() != kind::AND
&& !conj
.isVar() && !(conj
.getKind() == kind::NOT
&& conj
[0].isVar())) {
3547 Debug("miplib") << " -- INELIGIBLE -- (not /\\ or literal)" << endl
;
3550 if((*j
)[1].getKind() != kind::EQUAL
||
3551 !( ( (*j
)[1][0].isVar() &&
3552 (*j
)[1][1].getKind() == kind::CONST_RATIONAL
) ||
3553 ( (*j
)[1][0].getKind() == kind::CONST_RATIONAL
&&
3554 (*j
)[1][1].isVar() ) )) {
3556 Debug("miplib") << " -- INELIGIBLE -- (=> (and X X) X)" << endl
;
3559 if(conj
.getKind() == kind::AND
) {
3561 bool found_x
= false;
3562 map
<TNode
, bool> neg
;
3563 for(Node::iterator ii
= conj
.begin(); ii
!= conj
.end(); ++ii
) {
3565 posv
.push_back(*ii
);
3567 found_x
= found_x
|| *i
== *ii
;
3568 } else if((*ii
).getKind() == kind::NOT
&& (*ii
)[0].isVar()) {
3569 posv
.push_back((*ii
)[0]);
3570 neg
[(*ii
)[0]] = true;
3571 found_x
= found_x
|| *i
== (*ii
)[0];
3574 Debug("miplib") << " -- INELIGIBLE -- (non-var: " << *ii
<< ")" << endl
;
3577 if(d_propagator
.isAssigned(posv
.back())) {
3579 Debug("miplib") << " -- INELIGIBLE -- (" << posv
.back() << " asserted)" << endl
;
3588 Debug("miplib") << " --INELIGIBLE -- (couldn't find " << *i
<< " in conjunction)" << endl
;
3591 sort(posv
.begin(), posv
.end());
3592 const Node pos
= NodeManager::currentNM()->mkNode(kind::AND
, posv
);
3593 const TNode var
= ((*j
)[1][0].getKind() == kind::CONST_RATIONAL
) ? (*j
)[1][1] : (*j
)[1][0];
3594 const pair
<Node
, Node
> pos_var(pos
, var
);
3595 const Rational
& constant
= ((*j
)[1][0].getKind() == kind::CONST_RATIONAL
) ? (*j
)[1][0].getConst
<Rational
>() : (*j
)[1][1].getConst
<Rational
>();
3597 unsigned countneg
= 0, thepos
= 0;
3598 for(unsigned ii
= 0; ii
< pos
.getNumChildren(); ++ii
) {
3603 mark
|= (0x1 << ii
);
3606 if((marks
[pos_var
] & (1lu << mark
)) != 0) {
3608 Debug("miplib") << " -- INELIGIBLE -- (remarked)" << endl
;
3611 Debug("miplib") << "mark is " << mark
<< " -- " << (1lu << mark
) << endl
;
3612 marks
[pos_var
] |= (1lu << mark
);
3613 Debug("miplib") << "marks[" << pos
<< "," << var
<< "] now " << marks
[pos_var
] << endl
;
3614 if(countneg
== pos
.getNumChildren()) {
3617 Debug("miplib") << " -- INELIGIBLE -- (nonzero constant)" << endl
;
3620 } else if(countneg
== pos
.getNumChildren() - 1) {
3621 Assert(coef
[pos_var
].size() <= 6 && thepos
< 6);
3622 if(coef
[pos_var
].size() <= thepos
) {
3623 coef
[pos_var
].resize(thepos
+ 1);
3625 coef
[pos_var
][thepos
] = constant
;
3627 if(checks
[pos_var
].size() <= mark
) {
3628 checks
[pos_var
].resize(mark
+ 1);
3630 checks
[pos_var
][mark
] = constant
;
3632 asserts
[pos_var
].push_back(*j
);
3635 if(x
!= *i
&& x
!= (*i
).notNode()) {
3637 Debug("miplib") << " -- INELIGIBLE -- (x not present where I expect it)" << endl
;
3640 const bool xneg
= (x
.getKind() == kind::NOT
);
3641 x
= xneg
? x
[0] : x
;
3642 Debug("miplib") << " x:" << x
<< " " << xneg
<< endl
;
3643 const TNode var
= ((*j
)[1][0].getKind() == kind::CONST_RATIONAL
) ? (*j
)[1][1] : (*j
)[1][0];
3644 const pair
<Node
, Node
> x_var(x
, var
);
3645 const Rational
& constant
= ((*j
)[1][0].getKind() == kind::CONST_RATIONAL
) ? (*j
)[1][0].getConst
<Rational
>() : (*j
)[1][1].getConst
<Rational
>();
3646 unsigned mark
= (xneg
? 0 : 1);
3647 if((marks
[x_var
] & (1u << mark
)) != 0) {
3649 Debug("miplib") << " -- INELIGIBLE -- (remarked)" << endl
;
3652 marks
[x_var
] |= (1u << mark
);
3656 Debug("miplib") << " -- INELIGIBLE -- (nonzero constant)" << endl
;
3660 Assert(coef
[x_var
].size() <= 6);
3661 coef
[x_var
].resize(6);
3662 coef
[x_var
][0] = constant
;
3664 asserts
[x_var
].push_back(*j
);
3668 for(map
<pair
<Node
, Node
>, uint64_t>::const_iterator j
= marks
.begin(); j
!= marks
.end(); ++j
) {
3669 const TNode pos
= (*j
).first
.first
;
3670 const TNode var
= (*j
).first
.second
;
3671 const pair
<Node
, Node
>& pos_var
= (*j
).first
;
3672 const uint64_t mark
= (*j
).second
;
3673 const unsigned numVars
= pos
.getKind() == kind::AND
? pos
.getNumChildren() : 1;
3674 uint64_t expected
= (uint64_t(1) << (1 << numVars
)) - 1;
3675 expected
= (expected
== 0) ? -1 : expected
; // fix for overflow
3676 Debug("miplib") << "[" << pos
<< "] => " << hex
<< mark
<< " expect " << expected
<< dec
<< endl
;
3677 Assert(pos
.getKind() == kind::AND
|| pos
.isVar());
3678 if(mark
!= expected
) {
3679 Debug("miplib") << " -- INELIGIBLE " << pos
<< " -- (insufficiently marked, got " << mark
<< " for " << numVars
<< " vars, expected " << expected
<< endl
;
3681 if(mark
!= 3) { // exclude single-var case; nothing to check there
3682 uint64_t sz
= (uint64_t(1) << checks
[pos_var
].size()) - 1;
3683 sz
= (sz
== 0) ? -1 : sz
; // fix for overflow
3684 Assert(sz
== mark
, "expected size %u == mark %u", sz
, mark
);
3685 for(size_t k
= 0; k
< checks
[pos_var
].size(); ++k
) {
3686 if((k
& (k
- 1)) != 0) {
3688 Debug("miplib") << k
<< " => " << checks
[pos_var
][k
] << endl
;
3689 for(size_t v
= 1, kk
= k
; kk
!= 0; ++v
, kk
>>= 1) {
3690 if((kk
& 0x1) == 1) {
3691 Assert(pos
.getKind() == kind::AND
);
3692 Debug("miplib") << "var " << v
<< " : " << pos
[v
- 1] << " coef:" << coef
[pos_var
][v
- 1] << endl
;
3693 sum
+= coef
[pos_var
][v
- 1];
3696 Debug("miplib") << "checkSum is " << sum
<< " input says " << checks
[pos_var
][k
] << endl
;
3697 if(sum
!= checks
[pos_var
][k
]) {
3699 Debug("miplib") << " -- INELIGIBLE " << pos
<< " -- (nonlinear combination)" << endl
;
3703 Assert(checks
[pos_var
][k
] == 0, "checks[(%s,%s)][%u] should be 0, but it's %s", pos
.toString().c_str(), var
.toString().c_str(), k
, checks
[pos_var
][k
].toString().c_str()); // we never set for single-positive-var
3708 eligible
= true; // next is still eligible
3712 Debug("miplib") << " -- ELIGIBLE " << *i
<< " , " << pos
<< " --" << endl
;
3713 vector
<Node
> newVars
;
3714 expr::NodeSelfIterator ii
, iiend
;
3715 if(pos
.getKind() == kind::AND
) {
3719 ii
= expr::NodeSelfIterator::self(pos
);
3720 iiend
= expr::NodeSelfIterator::selfEnd(pos
);
3722 for(; ii
!= iiend
; ++ii
) {
3723 Node
& varRef
= intVars
[*ii
];
3724 if(varRef
.isNull()) {
3726 ss
<< "mipvar_" << *ii
;
3727 Node newVar
= nm
->mkSkolem(ss
.str(), nm
->integerType(), "a variable introduced due to scrubbing a miplib encoding", NodeManager::SKOLEM_EXACT_NAME
);
3728 Node geq
= Rewriter::rewrite(nm
->mkNode(kind::GEQ
, newVar
, zero
));
3729 Node leq
= Rewriter::rewrite(nm
->mkNode(kind::LEQ
, newVar
, one
));
3730 addFormula(Rewriter::rewrite(geq
.andNode(leq
)), false, false);
3731 SubstitutionMap
nullMap(&d_fakeContext
);
3732 Theory::PPAssertStatus status CVC4_UNUSED
; // just for assertions
3733 status
= d_smt
.d_theoryEngine
->solve(geq
, nullMap
);
3734 Assert(status
== Theory::PP_ASSERT_STATUS_UNSOLVED
,
3735 "unexpected solution from arith's ppAssert()");
3736 Assert(nullMap
.empty(),
3737 "unexpected substitution from arith's ppAssert()");
3738 status
= d_smt
.d_theoryEngine
->solve(leq
, nullMap
);
3739 Assert(status
== Theory::PP_ASSERT_STATUS_UNSOLVED
,
3740 "unexpected solution from arith's ppAssert()");
3741 Assert(nullMap
.empty(),
3742 "unexpected substitution from arith's ppAssert()");
3743 d_smt
.d_theoryEngine
->getModel()->addSubstitution(*ii
, newVar
.eqNode(one
));
3744 newVars
.push_back(newVar
);
3747 newVars
.push_back(varRef
);
3749 if(!d_smt
.d_logic
.areIntegersUsed()) {
3750 d_smt
.d_logic
= d_smt
.d_logic
.getUnlockedCopy();
3751 d_smt
.d_logic
.enableIntegers();
3752 d_smt
.d_logic
.lock();
3756 if(pos
.getKind() == kind::AND
) {
3757 NodeBuilder
<> sumb(kind::PLUS
);
3758 for(size_t ii
= 0; ii
< pos
.getNumChildren(); ++ii
) {
3759 sumb
<< nm
->mkNode(kind::MULT
, nm
->mkConst(coef
[pos_var
][ii
]), newVars
[ii
]);
3763 sum
= nm
->mkNode(kind::MULT
, nm
->mkConst(coef
[pos_var
][0]), newVars
[0]);
3765 Debug("miplib") << "vars[] " << var
<< endl
3766 << " eq " << Rewriter::rewrite(sum
) << endl
;
3767 Node newAssertion
= var
.eqNode(Rewriter::rewrite(sum
));
3768 if (top_level_substs
.hasSubstitution(newAssertion
[0]))
3770 // Warning() << "RE-SUBSTITUTION " << newAssertion[0] << endl;
3771 // Warning() << "REPLACE " << newAssertion[1] << endl;
3772 // Warning() << "ORIG " <<
3773 // top_level_substs.getSubstitution(newAssertion[0]) << endl;
3774 Assert(top_level_substs
.getSubstitution(newAssertion
[0])
3775 == newAssertion
[1]);
3776 } else if(pos
.getNumChildren() <= options::arithMLTrickSubstitutions()) {
3777 top_level_substs
.addSubstitution(newAssertion
[0], newAssertion
[1]);
3778 Debug("miplib") << "addSubs: " << newAssertion
[0] << " to " << newAssertion
[1] << endl
;
3780 Debug("miplib") << "skipSubs: " << newAssertion
[0] << " to " << newAssertion
[1] << " (threshold is " << options::arithMLTrickSubstitutions() << ")" << endl
;
3782 newAssertion
= Rewriter::rewrite(newAssertion
);
3783 Debug("miplib") << " " << newAssertion
<< endl
;
3784 addFormula(newAssertion
, false, false);
3785 Debug("miplib") << " assertions to remove: " << endl
;
3786 for(vector
<TNode
>::const_iterator k
= asserts
[pos_var
].begin(), k_end
= asserts
[pos_var
].end(); k
!= k_end
; ++k
) {
3787 Debug("miplib") << " " << *k
<< endl
;
3788 removeAssertions
.insert((*k
).getId());
3794 if(!removeAssertions
.empty()) {
3795 Debug("miplib") << "SmtEnginePrivate::simplify(): scrubbing miplib encoding..." << endl
;
3796 for(size_t i
= 0; i
< d_realAssertionsEnd
; ++i
) {
3797 if(removeAssertions
.find(d_assertions
[i
].getId()) != removeAssertions
.end()) {
3798 Debug("miplib") << "SmtEnginePrivate::simplify(): - removing " << d_assertions
[i
] << endl
;
3799 d_assertions
[i
] = d_true
;
3800 ++d_smt
.d_stats
->d_numMiplibAssertionsRemoved
;
3801 } else if(d_assertions
[i
].getKind() == kind::AND
) {
3802 size_t removals
= removeFromConjunction(d_assertions
[i
], removeAssertions
);
3804 Debug("miplib") << "SmtEnginePrivate::simplify(): - reduced " << d_assertions
[i
] << endl
;
3805 Debug("miplib") << "SmtEnginePrivate::simplify(): - by " << removals
<< " conjuncts" << endl
;
3806 d_smt
.d_stats
->d_numMiplibAssertionsRemoved
+= removals
;
3809 Debug("miplib") << "had: " << d_assertions
[i
] << endl
;
3811 Rewriter::rewrite(top_level_substs
.apply(d_assertions
[i
]));
3812 Debug("miplib") << "now: " << d_assertions
[i
] << endl
;
3815 Debug("miplib") << "SmtEnginePrivate::simplify(): miplib pass found nothing." << endl
;
3817 d_realAssertionsEnd
= d_assertions
.size();
3821 // returns false if simplification led to "false"
3822 bool SmtEnginePrivate::simplifyAssertions()
3824 spendResource(options::preprocessStep());
3825 Assert(d_smt
.d_pendingPops
== 0);
3827 ScopeCounter
depth(d_simplifyAssertionsDepth
);
3829 Trace("simplify") << "SmtEnginePrivate::simplify()" << endl
;
3831 dumpAssertions("pre-nonclausal", d_assertions
);
3833 if(options::simplificationMode() != SIMPLIFICATION_MODE_NONE
) {
3834 // Perform non-clausal simplification
3835 Chat() << "...performing nonclausal simplification..." << endl
;
3836 Trace("simplify") << "SmtEnginePrivate::simplify(): "
3837 << "performing non-clausal simplification" << endl
;
3838 bool noConflict
= nonClausalSimplify();
3843 // We piggy-back off of the BackEdgesMap in the CircuitPropagator to
3844 // do the miplib trick.
3845 if( // check that option is on
3846 options::arithMLTrick() &&
3847 // miplib rewrites aren't safe in incremental mode
3848 ! options::incrementalSolving() &&
3849 // only useful in arith
3850 d_smt
.d_logic
.isTheoryEnabled(THEORY_ARITH
) &&
3851 // we add new assertions and need this (in practice, this
3852 // restriction only disables miplib processing during
3853 // re-simplification, which we don't expect to be useful anyway)
3854 d_realAssertionsEnd
== d_assertions
.size() ) {
3855 Chat() << "...fixing miplib encodings..." << endl
;
3856 Trace("simplify") << "SmtEnginePrivate::simplify(): "
3857 << "looking for miplib pseudobooleans..." << endl
;
3859 TimerStat::CodeTimer
miplibTimer(d_smt
.d_stats
->d_miplibPassTime
);
3863 Trace("simplify") << "SmtEnginePrivate::simplify(): "
3864 << "skipping miplib pseudobooleans pass (either incrementalSolving is on, or miplib pbs are turned off)..." << endl
;
3868 dumpAssertions("post-nonclausal", d_assertions
);
3869 Trace("smt") << "POST nonClausalSimplify" << endl
;
3870 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
3872 // before ppRewrite check if only core theory for BV theory
3873 d_smt
.d_theoryEngine
->staticInitializeBVOptions(d_assertions
.ref());
3875 dumpAssertions("pre-theorypp", d_assertions
);
3877 // Theory preprocessing
3878 if (d_smt
.d_earlyTheoryPP
) {
3879 Chat() << "...doing early theory preprocessing..." << endl
;
3880 TimerStat::CodeTimer
codeTimer(d_smt
.d_stats
->d_theoryPreprocessTime
);
3881 // Call the theory preprocessors
3882 d_smt
.d_theoryEngine
->preprocessStart();
3883 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
3884 Assert(Rewriter::rewrite(d_assertions
[i
]) == d_assertions
[i
]);
3885 d_assertions
.replace(i
, d_smt
.d_theoryEngine
->preprocess(d_assertions
[i
]));
3886 Assert(Rewriter::rewrite(d_assertions
[i
]) == d_assertions
[i
]);
3890 dumpAssertions("post-theorypp", d_assertions
);
3891 Trace("smt") << "POST theoryPP" << endl
;
3892 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
3894 // ITE simplification
3895 if(options::doITESimp() &&
3896 (d_simplifyAssertionsDepth
<= 1 || options::doITESimpOnRepeat())) {
3897 Chat() << "...doing ITE simplification..." << endl
;
3898 bool noConflict
= simpITE();
3900 Chat() << "...ITE simplification found unsat..." << endl
;
3905 dumpAssertions("post-itesimp", d_assertions
);
3906 Trace("smt") << "POST iteSimp" << endl
;
3907 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
3909 // Unconstrained simplification
3910 if(options::unconstrainedSimp()) {
3911 Chat() << "...doing unconstrained simplification..." << endl
;
3912 unconstrainedSimp();
3915 dumpAssertions("post-unconstrained", d_assertions
);
3916 Trace("smt") << "POST unconstrainedSimp" << endl
;
3917 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
3919 if(options::repeatSimp() && options::simplificationMode() != SIMPLIFICATION_MODE_NONE
) {
3920 Chat() << "...doing another round of nonclausal simplification..." << endl
;
3921 Trace("simplify") << "SmtEnginePrivate::simplify(): "
3922 << " doing repeated simplification" << endl
;
3923 bool noConflict
= nonClausalSimplify();
3929 dumpAssertions("post-repeatsimp", d_assertions
);
3930 Trace("smt") << "POST repeatSimp" << endl
;
3931 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
3933 } catch(TypeCheckingExceptionPrivate
& tcep
) {
3934 // Calls to this function should have already weeded out any
3935 // typechecking exceptions via (e.g.) ensureBoolean(). But a
3936 // theory could still create a new expression that isn't
3937 // well-typed, and we don't want the C++ runtime to abort our
3938 // process without any error notice.
3940 ss
<< "A bad expression was produced. Original exception follows:\n"
3942 InternalError(ss
.str().c_str());
3947 Result
SmtEngine::check() {
3948 Assert(d_fullyInited
);
3949 Assert(d_pendingPops
== 0);
3951 Trace("smt") << "SmtEngine::check()" << endl
;
3953 ResourceManager
* resourceManager
= d_private
->getResourceManager();
3955 resourceManager
->beginCall();
3957 // Only way we can be out of resource is if cumulative budget is on
3958 if (resourceManager
->cumulativeLimitOn() &&
3959 resourceManager
->out()) {
3960 Result::UnknownExplanation why
= resourceManager
->outOfResources() ?
3961 Result::RESOURCEOUT
: Result::TIMEOUT
;
3962 return Result(Result::VALIDITY_UNKNOWN
, why
, d_filename
);
3965 // Make sure the prop layer has all of the assertions
3966 Trace("smt") << "SmtEngine::check(): processing assertions" << endl
;
3967 d_private
->processAssertions();
3968 Trace("smt") << "SmtEngine::check(): done processing assertions" << endl
;
3970 // Turn off stop only for QF_LRA
3971 // TODO: Bring up in a meeting where to put this
3972 if(options::decisionStopOnly() && !options::decisionMode
.wasSetByUser() ){
3974 (not d_logic
.isQuantified() &&
3975 d_logic
.isPure(THEORY_ARITH
) && d_logic
.isLinear() && !d_logic
.isDifferenceLogic() && !d_logic
.areIntegersUsed()
3977 if(d_private
->d_iteSkolemMap
.empty()){
3978 options::decisionStopOnly
.set(false);
3979 d_decisionEngine
->clearStrategies();
3980 Trace("smt") << "SmtEngine::check(): turning off stop only" << endl
;
3985 TimerStat::CodeTimer
solveTimer(d_stats
->d_solveTime
);
3987 Chat() << "solving..." << endl
;
3988 Trace("smt") << "SmtEngine::check(): running check" << endl
;
3989 Result result
= d_propEngine
->checkSat();
3991 resourceManager
->endCall();
3992 Trace("limit") << "SmtEngine::check(): cumulative millis " << resourceManager
->getTimeUsage()
3993 << ", resources " << resourceManager
->getResourceUsage() << endl
;
3996 return Result(result
, d_filename
);
3999 Result
SmtEngine::quickCheck() {
4000 Assert(d_fullyInited
);
4001 Trace("smt") << "SMT quickCheck()" << endl
;
4002 return Result(Result::VALIDITY_UNKNOWN
, Result::REQUIRES_FULL_CHECK
, d_filename
);
4006 void SmtEnginePrivate::collectSkolems(TNode n
, set
<TNode
>& skolemSet
, unordered_map
<Node
, bool, NodeHashFunction
>& cache
)
4008 unordered_map
<Node
, bool, NodeHashFunction
>::iterator it
;
4010 if (it
!= cache
.end()) {
4014 size_t sz
= n
.getNumChildren();
4016 IteSkolemMap::iterator it
= d_iteSkolemMap
.find(n
);
4017 if (it
!= d_iteSkolemMap
.end()) {
4018 skolemSet
.insert(n
);
4025 for (; k
< sz
; ++k
) {
4026 collectSkolems(n
[k
], skolemSet
, cache
);
4032 bool SmtEnginePrivate::checkForBadSkolems(TNode n
, TNode skolem
, unordered_map
<Node
, bool, NodeHashFunction
>& cache
)
4034 unordered_map
<Node
, bool, NodeHashFunction
>::iterator it
;
4036 if (it
!= cache
.end()) {
4037 return (*it
).second
;
4040 size_t sz
= n
.getNumChildren();
4042 IteSkolemMap::iterator it
= d_iteSkolemMap
.find(n
);
4044 if (it
!= d_iteSkolemMap
.end()) {
4045 if (!((*it
).first
< n
)) {
4054 for (; k
< sz
; ++k
) {
4055 if (checkForBadSkolems(n
[k
], skolem
, cache
)) {
4065 void SmtEnginePrivate::processAssertions() {
4066 TimerStat::CodeTimer
paTimer(d_smt
.d_stats
->d_processAssertionsTime
);
4067 spendResource(options::preprocessStep());
4068 Assert(d_smt
.d_fullyInited
);
4069 Assert(d_smt
.d_pendingPops
== 0);
4070 SubstitutionMap
& top_level_substs
= d_assertions
.getTopLevelSubstitutions();
4072 // Dump the assertions
4073 dumpAssertions("pre-everything", d_assertions
);
4075 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() begin" << endl
;
4076 Trace("smt") << "SmtEnginePrivate::processAssertions()" << endl
;
4078 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
4080 if (d_assertions
.size() == 0) {
4085 if (options::bvGaussElim())
4087 TimerStat::CodeTimer
gaussElimTimer(d_smt
.d_stats
->d_gaussElimTime
);
4088 d_preprocessingPassRegistry
.getPass("bv-gauss")->apply(&d_assertions
);
4091 if (d_assertionsProcessed
&& options::incrementalSolving()) {
4092 // TODO(b/1255): Substitutions in incremental mode should be managed with a
4093 // proper data structure.
4095 // Placeholder for storing substitutions
4096 d_assertions
.getSubstitutionsIndex() = d_assertions
.size();
4097 d_assertions
.push_back(NodeManager::currentNM()->mkConst
<bool>(true));
4100 // Add dummy assertion in last position - to be used as a
4101 // placeholder for any new assertions to get added
4102 d_assertions
.push_back(NodeManager::currentNM()->mkConst
<bool>(true));
4103 // any assertions added beyond realAssertionsEnd must NOT affect the
4104 // equisatisfiability
4105 d_realAssertionsEnd
= d_assertions
.size();
4107 // Assertions are NOT guaranteed to be rewritten by this point
4109 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-definition-expansion" << endl
;
4110 dumpAssertions("pre-definition-expansion", d_assertions
);
4112 Chat() << "expanding definitions..." << endl
;
4113 Trace("simplify") << "SmtEnginePrivate::simplify(): expanding definitions" << endl
;
4114 TimerStat::CodeTimer
codeTimer(d_smt
.d_stats
->d_definitionExpansionTime
);
4115 unordered_map
<Node
, Node
, NodeHashFunction
> cache
;
4116 for(unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
4117 d_assertions
.replace(i
, expandDefinitions(d_assertions
[i
], cache
));
4120 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-definition-expansion" << endl
;
4121 dumpAssertions("post-definition-expansion", d_assertions
);
4123 // save the assertions now
4126 for (unsigned i
= 0; i
< d_assertions
.size(); ++i
) {
4127 ProofManager::currentPM()->addAssertion(d_assertions
[i
].toExpr());
4131 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
4133 if (options::globalNegate())
4135 // global negation of the formula
4136 quantifiers::GlobalNegate gn
;
4137 gn
.simplify(d_assertions
.ref());
4138 d_smt
.d_globalNegation
= !d_smt
.d_globalNegation
;
4141 if( options::nlExtPurify() ){
4142 unordered_map
<Node
, Node
, NodeHashFunction
> cache
;
4143 unordered_map
<Node
, Node
, NodeHashFunction
> bcache
;
4144 std::vector
< Node
> var_eq
;
4145 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
4146 Node a
= d_assertions
[i
];
4147 d_assertions
.replace(i
, purifyNlTerms(a
, cache
, bcache
, var_eq
));
4148 Trace("nl-ext-purify")
4149 << "Purify : " << a
<< " -> " << d_assertions
[i
] << std::endl
;
4151 if( !var_eq
.empty() ){
4152 unsigned lastIndex
= d_assertions
.size()-1;
4153 var_eq
.insert( var_eq
.begin(), d_assertions
[lastIndex
] );
4154 d_assertions
.replace(lastIndex
, NodeManager::currentNM()->mkNode( kind::AND
, var_eq
) );
4158 if( options::ceGuidedInst() ){
4159 //register sygus conjecture pre-rewrite (motivated by solution reconstruction)
4160 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
4161 d_smt
.d_theoryEngine
->getQuantifiersEngine()->getCegInstantiation()->preregisterAssertion( d_assertions
[i
] );
4165 if (options::solveRealAsInt()) {
4166 d_preprocessingPassRegistry
.getPass("real-to-int")->apply(&d_assertions
);
4169 if (options::solveIntAsBV() > 0)
4171 d_preprocessingPassRegistry
.getPass("int-to-bv")->apply(&d_assertions
);
4174 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER
&&
4175 !d_smt
.d_logic
.isPure(THEORY_BV
) &&
4176 d_smt
.d_logic
.getLogicString() != "QF_UFBV" &&
4177 d_smt
.d_logic
.getLogicString() != "QF_ABV") {
4178 throw ModalException("Eager bit-blasting does not currently support theory combination. "
4179 "Note that in a QF_BV problem UF symbols can be introduced for division. "
4180 "Try --bv-div-zero-const to interpret division by zero as a constant.");
4183 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER
4184 && !options::incrementalSolving())
4186 d_preprocessingPassRegistry
.getPass("bv-ackermann")->apply(&d_assertions
);
4189 if (options::bvAbstraction() && !options::incrementalSolving())
4191 d_preprocessingPassRegistry
.getPass("bv-abstraction")->apply(&d_assertions
);
4194 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
4196 bool noConflict
= true;
4198 if (options::extRewPrep())
4200 theory::quantifiers::ExtendedRewriter
extr(options::extRewPrepAgg());
4201 for (unsigned i
= 0; i
< d_assertions
.size(); ++i
)
4203 Node a
= d_assertions
[i
];
4204 d_assertions
.replace(i
, extr
.extendedRewrite(a
));
4208 // Unconstrained simplification
4209 if(options::unconstrainedSimp()) {
4210 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-unconstrained-simp" << endl
;
4211 dumpAssertions("pre-unconstrained-simp", d_assertions
);
4212 d_preprocessingPassRegistry
.getPass("rewrite")->apply(&d_assertions
);
4213 unconstrainedSimp();
4214 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-unconstrained-simp" << endl
;
4215 dumpAssertions("post-unconstrained-simp", d_assertions
);
4218 if(options::bvIntroducePow2())
4220 d_preprocessingPassRegistry
.getPass("bv-intro-pow2")->apply(&d_assertions
);
4223 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-substitution" << endl
;
4224 dumpAssertions("pre-substitution", d_assertions
);
4226 if (options::unsatCores())
4228 // special rewriting pass for unsat cores, since many of the passes below
4230 d_preprocessingPassRegistry
.getPass("rewrite")->apply(&d_assertions
);
4234 d_preprocessingPassRegistry
.getPass("apply-substs")->apply(&d_assertions
);
4236 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-substitution" << endl
;
4237 dumpAssertions("post-substitution", d_assertions
);
4239 // Assertions ARE guaranteed to be rewritten by this point
4240 #ifdef CVC4_ASSERTIONS
4241 for (unsigned i
= 0; i
< d_assertions
.size(); ++i
)
4243 Assert(Rewriter::rewrite(d_assertions
[i
]) == d_assertions
[i
]);
4247 // Lift bit-vectors of size 1 to bool
4248 if(options::bitvectorToBool()) {
4249 dumpAssertions("pre-bv-to-bool", d_assertions
);
4250 Chat() << "...doing bvToBool..." << endl
;
4251 d_preprocessingPassRegistry
.getPass("bv-to-bool")->apply(&d_assertions
);
4252 dumpAssertions("post-bv-to-bool", d_assertions
);
4253 Trace("smt") << "POST bvToBool" << endl
;
4255 // Convert non-top-level Booleans to bit-vectors of size 1
4256 if(options::boolToBitvector()) {
4257 dumpAssertions("pre-bool-to-bv", d_assertions
);
4258 Chat() << "...doing boolToBv..." << endl
;
4259 d_preprocessingPassRegistry
.getPass("bool-to-bv")->apply(&d_assertions
);
4260 dumpAssertions("post-bool-to-bv", d_assertions
);
4261 Trace("smt") << "POST boolToBv" << endl
;
4263 if(options::sepPreSkolemEmp()) {
4264 d_preprocessingPassRegistry
.getPass("sep-skolem-emp")->apply(&d_assertions
);
4267 if( d_smt
.d_logic
.isQuantified() ){
4268 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-quant-preprocess" << endl
;
4270 dumpAssertions("pre-skolem-quant", d_assertions
);
4271 //remove rewrite rules, apply pre-skolemization to existential quantifiers
4272 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
4273 Node prev
= d_assertions
[i
];
4274 Node next
= quantifiers::QuantifiersRewriter::preprocess( prev
);
4276 d_assertions
.replace( i
, Rewriter::rewrite( next
) );
4277 Trace("quantifiers-preprocess") << "*** Pre-skolemize " << prev
<< endl
;
4278 Trace("quantifiers-preprocess") << " ...got " << d_assertions
[i
] << endl
;
4281 dumpAssertions("post-skolem-quant", d_assertions
);
4282 if( options::macrosQuant() ){
4283 //quantifiers macro expansion
4284 quantifiers::QuantifierMacros
qm( d_smt
.d_theoryEngine
->getQuantifiersEngine() );
4287 success
= qm
.simplify( d_assertions
.ref(), true );
4289 //finalize the definitions
4290 qm
.finalizeDefinitions();
4293 //fmf-fun : assume admissible functions, applying preprocessing reduction to FMF
4294 if( options::fmfFunWellDefined() ){
4295 quantifiers::FunDefFmf fdf
;
4296 Assert( d_smt
.d_fmfRecFunctionsDefined
!=NULL
);
4297 //must carry over current definitions (for incremental)
4298 for( context::CDList
<Node
>::const_iterator fit
= d_smt
.d_fmfRecFunctionsDefined
->begin();
4299 fit
!= d_smt
.d_fmfRecFunctionsDefined
->end(); ++fit
) {
4301 Assert( d_smt
.d_fmfRecFunctionsAbs
.find( f
)!=d_smt
.d_fmfRecFunctionsAbs
.end() );
4302 TypeNode ft
= d_smt
.d_fmfRecFunctionsAbs
[f
];
4303 fdf
.d_sorts
[f
] = ft
;
4304 std::map
< Node
, std::vector
< Node
> >::iterator fcit
= d_smt
.d_fmfRecFunctionsConcrete
.find( f
);
4305 Assert( fcit
!=d_smt
.d_fmfRecFunctionsConcrete
.end() );
4306 for( unsigned j
=0; j
<fcit
->second
.size(); j
++ ){
4307 fdf
.d_input_arg_inj
[f
].push_back( fcit
->second
[j
] );
4310 fdf
.simplify( d_assertions
.ref() );
4311 //must store new definitions (for incremental)
4312 for( unsigned i
=0; i
<fdf
.d_funcs
.size(); i
++ ){
4313 Node f
= fdf
.d_funcs
[i
];
4314 d_smt
.d_fmfRecFunctionsAbs
[f
] = fdf
.d_sorts
[f
];
4315 d_smt
.d_fmfRecFunctionsConcrete
[f
].clear();
4316 for( unsigned j
=0; j
<fdf
.d_input_arg_inj
[f
].size(); j
++ ){
4317 d_smt
.d_fmfRecFunctionsConcrete
[f
].push_back( fdf
.d_input_arg_inj
[f
][j
] );
4319 d_smt
.d_fmfRecFunctionsDefined
->push_back( f
);
4322 if (options::sygusInference())
4324 // try recast as sygus
4325 quantifiers::SygusInference si
;
4326 if (si
.simplify(d_assertions
.ref()))
4328 Trace("smt-proc") << "...converted to sygus conjecture." << std::endl
;
4331 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-quant-preprocess" << endl
;
4334 if( options::sortInference() || options::ufssFairnessMonotone() ){
4335 //sort inference technique
4336 SortInference
* si
= d_smt
.d_theoryEngine
->getSortInference();
4337 si
->simplify( d_assertions
.ref(), options::sortInference(), options::ufssFairnessMonotone() );
4338 for( std::map
< Node
, Node
>::iterator it
= si
->d_model_replace_f
.begin(); it
!= si
->d_model_replace_f
.end(); ++it
){
4339 d_smt
.setPrintFuncInModel( it
->first
.toExpr(), false );
4340 d_smt
.setPrintFuncInModel( it
->second
.toExpr(), true );
4344 if( options::pbRewrites() ){
4345 d_preprocessingPassRegistry
.getPass("pseudo-boolean-processor")
4346 ->apply(&d_assertions
);
4349 if (options::synthRrPrep())
4351 // do candidate rewrite rule synthesis
4352 d_preprocessingPassRegistry
.getPass("synth-rr")->apply(&d_assertions
);
4355 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-simplify" << endl
;
4356 dumpAssertions("pre-simplify", d_assertions
);
4357 Chat() << "simplifying assertions..." << endl
;
4358 noConflict
= simplifyAssertions();
4360 ++(d_smt
.d_stats
->d_simplifiedToFalse
);
4362 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-simplify" << endl
;
4363 dumpAssertions("post-simplify", d_assertions
);
4365 if (options::symmetryBreakerExp() && !options::incrementalSolving())
4367 // apply symmetry breaking if not in incremental mode
4368 d_preprocessingPassRegistry
.getPass("sym-break")->apply(&d_assertions
);
4371 if(options::doStaticLearning()) {
4372 d_preprocessingPassRegistry
.getPass("static-learning")
4373 ->apply(&d_assertions
);
4375 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
4377 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-ite-removal" << endl
;
4378 dumpAssertions("pre-ite-removal", d_assertions
);
4380 Chat() << "removing term ITEs..." << endl
;
4381 TimerStat::CodeTimer
codeTimer(d_smt
.d_stats
->d_iteRemovalTime
);
4382 // Remove ITEs, updating d_iteSkolemMap
4383 d_smt
.d_stats
->d_numAssertionsPre
+= d_assertions
.size();
4385 // This is needed because when solving incrementally, removeITEs may introduce
4386 // skolems that were solved for earlier and thus appear in the substitution
4388 d_preprocessingPassRegistry
.getPass("apply-substs")->apply(&d_assertions
);
4389 d_smt
.d_stats
->d_numAssertionsPost
+= d_assertions
.size();
4391 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-ite-removal" << endl
;
4392 dumpAssertions("post-ite-removal", d_assertions
);
4394 dumpAssertions("pre-repeat-simplify", d_assertions
);
4395 if(options::repeatSimp()) {
4396 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-repeat-simplify" << endl
;
4397 Chat() << "re-simplifying assertions..." << endl
;
4398 ScopeCounter
depth(d_simplifyAssertionsDepth
);
4399 noConflict
&= simplifyAssertions();
4401 // Need to fix up assertion list to maintain invariants:
4402 // Let Sk be the set of Skolem variables introduced by ITE's. Let <_sk be the order in which these variables were introduced
4403 // during ite removal.
4404 // For each skolem variable sk, let iteExpr = iteMap(sk) be the ite expr mapped to by sk.
4406 // cache for expression traversal
4407 unordered_map
<Node
, bool, NodeHashFunction
> cache
;
4409 // First, find all skolems that appear in the substitution map - their associated iteExpr will need
4410 // to be moved to the main assertion set
4411 set
<TNode
> skolemSet
;
4412 SubstitutionMap::iterator pos
= top_level_substs
.begin();
4413 for (; pos
!= top_level_substs
.end(); ++pos
)
4415 collectSkolems((*pos
).first
, skolemSet
, cache
);
4416 collectSkolems((*pos
).second
, skolemSet
, cache
);
4419 // We need to ensure:
4420 // 1. iteExpr has the form (ite cond (sk = t) (sk = e))
4421 // 2. if some sk' in Sk appears in cond, t, or e, then sk' <_sk sk
4422 // If either of these is violated, we must add iteExpr as a proper assertion
4423 IteSkolemMap::iterator it
= d_iteSkolemMap
.begin();
4424 IteSkolemMap::iterator iend
= d_iteSkolemMap
.end();
4425 NodeBuilder
<> builder(kind::AND
);
4426 builder
<< d_assertions
[d_realAssertionsEnd
- 1];
4427 vector
<TNode
> toErase
;
4428 for (; it
!= iend
; ++it
) {
4429 if (skolemSet
.find((*it
).first
) == skolemSet
.end()) {
4430 TNode iteExpr
= d_assertions
[(*it
).second
];
4431 if (iteExpr
.getKind() == kind::ITE
&&
4432 iteExpr
[1].getKind() == kind::EQUAL
&&
4433 iteExpr
[1][0] == (*it
).first
&&
4434 iteExpr
[2].getKind() == kind::EQUAL
&&
4435 iteExpr
[2][0] == (*it
).first
) {
4437 bool bad
= checkForBadSkolems(iteExpr
[0], (*it
).first
, cache
);
4438 bad
= bad
|| checkForBadSkolems(iteExpr
[1][1], (*it
).first
, cache
);
4439 bad
= bad
|| checkForBadSkolems(iteExpr
[2][1], (*it
).first
, cache
);
4445 // Move this iteExpr into the main assertions
4446 builder
<< d_assertions
[(*it
).second
];
4447 d_assertions
[(*it
).second
] = NodeManager::currentNM()->mkConst
<bool>(true);
4448 toErase
.push_back((*it
).first
);
4450 if(builder
.getNumChildren() > 1) {
4451 while (!toErase
.empty()) {
4452 d_iteSkolemMap
.erase(toErase
.back());
4455 d_assertions
[d_realAssertionsEnd
- 1] = Rewriter::rewrite(Node(builder
));
4457 // TODO(b/1256): For some reason this is needed for some benchmarks, such as
4458 // QF_AUFBV/dwp_formulas/try5_small_difret_functions_dwp_tac.re_node_set_remove_at.il.dwp.smt2
4460 d_preprocessingPassRegistry
.getPass("apply-substs")->apply(&d_assertions
);
4461 // Assert(iteRewriteAssertionsEnd == d_assertions.size());
4463 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-repeat-simplify" << endl
;
4465 dumpAssertions("post-repeat-simplify", d_assertions
);
4467 dumpAssertions("pre-rewrite-apply-to-const", d_assertions
);
4468 if(options::rewriteApplyToConst()) {
4469 Chat() << "Rewriting applies to constants..." << endl
;
4470 TimerStat::CodeTimer
codeTimer(d_smt
.d_stats
->d_rewriteApplyToConstTime
);
4471 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
4472 d_assertions
[i
] = Rewriter::rewrite(rewriteApplyToConst(d_assertions
[i
]));
4475 dumpAssertions("post-rewrite-apply-to-const", d_assertions
);
4477 // begin: INVARIANT to maintain: no reordering of assertions or
4478 // introducing new ones
4479 #ifdef CVC4_ASSERTIONS
4480 unsigned iteRewriteAssertionsEnd
= d_assertions
.size();
4483 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
4485 Debug("smt") << "SmtEnginePrivate::processAssertions() POST SIMPLIFICATION" << endl
;
4486 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
4488 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-theory-preprocessing" << endl
;
4489 dumpAssertions("pre-theory-preprocessing", d_assertions
);
4491 Chat() << "theory preprocessing..." << endl
;
4492 TimerStat::CodeTimer
codeTimer(d_smt
.d_stats
->d_theoryPreprocessTime
);
4493 // Call the theory preprocessors
4494 d_smt
.d_theoryEngine
->preprocessStart();
4495 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
4496 d_assertions
.replace(i
, d_smt
.d_theoryEngine
->preprocess(d_assertions
[i
]));
4499 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-theory-preprocessing" << endl
;
4500 dumpAssertions("post-theory-preprocessing", d_assertions
);
4502 // If we are using eager bit-blasting wrap assertions in fake atom so that
4503 // everything gets bit-blasted to internal SAT solver
4504 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER
) {
4505 for (unsigned i
= 0; i
< d_assertions
.size(); ++i
) {
4506 TNode atom
= d_assertions
[i
];
4507 Node eager_atom
= NodeManager::currentNM()->mkNode(kind::BITVECTOR_EAGER_ATOM
, atom
);
4508 d_assertions
.replace(i
, eager_atom
);
4509 TheoryModel
* m
= d_smt
.d_theoryEngine
->getModel();
4510 m
->addSubstitution(eager_atom
, atom
);
4514 //notify theory engine new preprocessed assertions
4515 d_smt
.d_theoryEngine
->notifyPreprocessedAssertions( d_assertions
.ref() );
4517 // Push the formula to decision engine
4519 Chat() << "pushing to decision engine..." << endl
;
4520 Assert(iteRewriteAssertionsEnd
== d_assertions
.size());
4521 d_smt
.d_decisionEngine
->addAssertions
4522 (d_assertions
.ref(), d_realAssertionsEnd
, d_iteSkolemMap
);
4525 // end: INVARIANT to maintain: no reordering of assertions or
4526 // introducing new ones
4528 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() end" << endl
;
4529 dumpAssertions("post-everything", d_assertions
);
4531 // Push the formula to SAT
4533 Chat() << "converting to CNF..." << endl
;
4534 TimerStat::CodeTimer
codeTimer(d_smt
.d_stats
->d_cnfConversionTime
);
4535 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
4536 Chat() << "+ " << d_assertions
[i
] << std::endl
;
4537 d_smt
.d_propEngine
->assertFormula(d_assertions
[i
]);
4541 d_assertionsProcessed
= true;
4543 d_assertions
.clear();
4544 d_iteSkolemMap
.clear();
4547 void SmtEnginePrivate::addFormula(TNode n
, bool inUnsatCore
, bool inInput
)
4554 Trace("smt") << "SmtEnginePrivate::addFormula(" << n
<< "), inUnsatCore = " << inUnsatCore
<< ", inInput = " << inInput
<< endl
;
4556 // Give it to proof manager
4559 // n is an input assertion
4560 if (inUnsatCore
|| options::unsatCores() || options::dumpUnsatCores() || options::checkUnsatCores() || options::fewerPreprocessingHoles()) {
4562 ProofManager::currentPM()->addCoreAssertion(n
.toExpr());
4565 // n is the result of an unknown preprocessing step, add it to dependency map to null
4566 ProofManager::currentPM()->addDependence(n
, Node::null());
4568 // rewrite rules are by default in the unsat core because
4569 // they need to be applied until saturation
4570 if(options::unsatCores() &&
4571 n
.getKind() == kind::REWRITE_RULE
){
4572 ProofManager::currentPM()->addUnsatCore(n
.toExpr());
4576 // Add the normalized formula to the queue
4577 d_assertions
.push_back(n
);
4578 //d_assertions.push_back(Rewriter::rewrite(n));
4581 void SmtEngine::ensureBoolean(const Expr
& e
)
4583 Type type
= e
.getType(options::typeChecking());
4584 Type boolType
= d_exprManager
->booleanType();
4585 if(type
!= boolType
) {
4587 ss
<< "Expected " << boolType
<< "\n"
4588 << "The assertion : " << e
<< "\n"
4589 << "Its type : " << type
;
4590 throw TypeCheckingException(e
, ss
.str());
4594 Result
SmtEngine::checkSat(const Expr
& assumption
, bool inUnsatCore
)
4596 return checkSatisfiability(assumption
, inUnsatCore
, false);
4599 Result
SmtEngine::checkSat(const vector
<Expr
>& assumptions
, bool inUnsatCore
)
4601 return checkSatisfiability(assumptions
, inUnsatCore
, false);
4604 Result
SmtEngine::query(const Expr
& assumption
, bool inUnsatCore
)
4606 Assert(!assumption
.isNull());
4607 return checkSatisfiability(assumption
, inUnsatCore
, true);
4610 Result
SmtEngine::query(const vector
<Expr
>& assumptions
, bool inUnsatCore
)
4612 return checkSatisfiability(assumptions
, inUnsatCore
, true);
4615 Result
SmtEngine::checkSatisfiability(const Expr
& expr
,
4619 return checkSatisfiability(
4620 expr
.isNull() ? vector
<Expr
>() : vector
<Expr
>{expr
},
4625 Result
SmtEngine::checkSatisfiability(const vector
<Expr
>& assumptions
,
4631 SmtScope
smts(this);
4632 finalOptionsAreSet();
4635 Trace("smt") << "SmtEngine::" << (isQuery
? "query" : "checkSat") << "("
4636 << assumptions
<< ")" << endl
;
4638 if(d_queryMade
&& !options::incrementalSolving()) {
4639 throw ModalException("Cannot make multiple queries unless "
4640 "incremental solving is enabled "
4641 "(try --incremental)");
4644 // check to see if a postsolve() is pending
4645 if(d_needPostsolve
) {
4646 d_theoryEngine
->postsolve();
4647 d_needPostsolve
= false;
4649 // Note that a query has been made
4651 // reset global negation
4652 d_globalNegation
= false;
4654 bool didInternalPush
= false;
4656 setProblemExtended(true);
4660 size_t size
= assumptions
.size();
4663 /* Assume: not (BIGAND assumptions) */
4664 d_assumptions
.push_back(
4665 d_exprManager
->mkExpr(kind::AND
, assumptions
).notExpr());
4669 /* Assume: not expr */
4670 d_assumptions
.push_back(assumptions
[0].notExpr());
4675 /* Assume: BIGAND assumptions */
4676 d_assumptions
= assumptions
;
4679 if (!d_assumptions
.empty())
4682 didInternalPush
= true;
4685 Result
r(Result::SAT_UNKNOWN
, Result::UNKNOWN_REASON
);
4686 for (Expr e
: d_assumptions
)
4688 // Substitute out any abstract values in ex.
4689 e
= d_private
->substituteAbstractValues(Node::fromExpr(e
)).toExpr();
4690 Assert(e
.getExprManager() == d_exprManager
);
4691 // Ensure expr is type-checked at this point.
4694 /* Add assumption */
4695 if (d_assertionList
!= NULL
)
4697 d_assertionList
->push_back(e
);
4699 d_private
->addFormula(e
.getNode(), inUnsatCore
);
4702 r
= isQuery
? check().asValidityResult() : check().asSatisfiabilityResult();
4704 if ((options::solveRealAsInt() || options::solveIntAsBV() > 0)
4705 && r
.asSatisfiabilityResult().isSat() == Result::UNSAT
)
4707 r
= Result(Result::SAT_UNKNOWN
, Result::UNKNOWN_REASON
);
4709 // flipped if we did a global negation
4710 if (d_globalNegation
)
4712 Trace("smt") << "SmtEngine::process global negate " << r
<< std::endl
;
4713 if (r
.asSatisfiabilityResult().isSat() == Result::UNSAT
)
4715 r
= Result(Result::SAT
);
4717 else if (r
.asSatisfiabilityResult().isSat() == Result::SAT
)
4719 // only if satisfaction complete
4720 if (d_logic
.isPure(THEORY_ARITH
) || d_logic
.isPure(THEORY_BV
))
4722 r
= Result(Result::UNSAT
);
4726 r
= Result(Result::SAT_UNKNOWN
, Result::UNKNOWN_REASON
);
4729 Trace("smt") << "SmtEngine::global negate returned " << r
<< std::endl
;
4732 d_needPostsolve
= true;
4734 // Dump the query if requested
4735 if (Dump
.isOn("benchmark"))
4737 size_t size
= assumptions
.size();
4738 // the expr already got dumped out if assertion-dumping is on
4739 if (isQuery
&& size
== 1)
4741 Dump("benchmark") << QueryCommand(assumptions
[0]);
4745 Dump("benchmark") << CheckSatCommand();
4749 Dump("benchmark") << CheckSatAssumingCommand(d_assumptions
,
4754 d_propEngine
->resetTrail();
4757 if (didInternalPush
)
4762 // Remember the status
4765 setProblemExtended(false);
4767 Trace("smt") << "SmtEngine::" << (isQuery
? "query" : "checkSat") << "("
4768 << assumptions
<< ") => " << r
<< endl
;
4770 // Check that SAT results generate a model correctly.
4771 if(options::checkModels()) {
4772 // TODO (#1693) check model when unknown result?
4773 if (r
.asSatisfiabilityResult().isSat() == Result::SAT
)
4778 // Check that UNSAT results generate a proof correctly.
4779 if(options::checkProofs()) {
4780 if(r
.asSatisfiabilityResult().isSat() == Result::UNSAT
) {
4781 TimerStat::CodeTimer
checkProofTimer(d_stats
->d_checkProofTime
);
4785 // Check that UNSAT results generate an unsat core correctly.
4786 if(options::checkUnsatCores()) {
4787 if(r
.asSatisfiabilityResult().isSat() == Result::UNSAT
) {
4788 TimerStat::CodeTimer
checkUnsatCoreTimer(d_stats
->d_checkUnsatCoreTime
);
4792 // Check that synthesis solutions satisfy the conjecture
4793 if (options::checkSynthSol()
4794 && r
.asSatisfiabilityResult().isSat() == Result::UNSAT
)
4796 checkSynthSolution();
4800 } catch (UnsafeInterruptException
& e
) {
4801 AlwaysAssert(d_private
->getResourceManager()->out());
4802 Result::UnknownExplanation why
= d_private
->getResourceManager()->outOfResources() ?
4803 Result::RESOURCEOUT
: Result::TIMEOUT
;
4804 return Result(Result::SAT_UNKNOWN
, why
, d_filename
);
4808 vector
<Expr
> SmtEngine::getUnsatAssumptions(void)
4810 Trace("smt") << "SMT getUnsatAssumptions()" << endl
;
4811 SmtScope
smts(this);
4812 if (!options::unsatAssumptions())
4814 throw ModalException(
4815 "Cannot get unsat assumptions when produce-unsat-assumptions option "
4818 if (d_status
.isNull()
4819 || d_status
.asSatisfiabilityResult() != Result::UNSAT
4820 || d_problemExtended
)
4822 throw RecoverableModalException(
4823 "Cannot get unsat assumptions unless immediately preceded by "
4824 "UNSAT/VALID response.");
4826 finalOptionsAreSet();
4827 if (Dump
.isOn("benchmark"))
4829 Dump("benchmark") << GetUnsatAssumptionsCommand();
4831 UnsatCore core
= getUnsatCoreInternal();
4833 for (const Expr
& e
: d_assumptions
)
4835 if (find(core
.begin(), core
.end(), e
) != core
.end()) { res
.push_back(e
); }
4840 Result
SmtEngine::checkSynth(const Expr
& e
)
4842 SmtScope
smts(this);
4843 Trace("smt") << "Check synth: " << e
<< std::endl
;
4844 Trace("smt-synth") << "Check synthesis conjecture: " << e
<< std::endl
;
4845 return checkSatisfiability(e
, true, false);
4848 Result
SmtEngine::assertFormula(const Expr
& ex
, bool inUnsatCore
)
4850 Assert(ex
.getExprManager() == d_exprManager
);
4851 SmtScope
smts(this);
4852 finalOptionsAreSet();
4855 Trace("smt") << "SmtEngine::assertFormula(" << ex
<< ")" << endl
;
4857 if (Dump
.isOn("raw-benchmark")) {
4858 Dump("raw-benchmark") << AssertCommand(ex
);
4861 // Substitute out any abstract values in ex
4862 Expr e
= d_private
->substituteAbstractValues(Node::fromExpr(ex
)).toExpr();
4865 if(d_assertionList
!= NULL
) {
4866 d_assertionList
->push_back(e
);
4868 d_private
->addFormula(e
.getNode(), inUnsatCore
);
4869 return quickCheck().asValidityResult();
4870 }/* SmtEngine::assertFormula() */
4872 Node
SmtEngine::postprocess(TNode node
, TypeNode expectedType
) const {
4876 Expr
SmtEngine::simplify(const Expr
& ex
)
4878 Assert(ex
.getExprManager() == d_exprManager
);
4879 SmtScope
smts(this);
4880 finalOptionsAreSet();
4882 Trace("smt") << "SMT simplify(" << ex
<< ")" << endl
;
4884 if(Dump
.isOn("benchmark")) {
4885 Dump("benchmark") << SimplifyCommand(ex
);
4888 Expr e
= d_private
->substituteAbstractValues(Node::fromExpr(ex
)).toExpr();
4889 if( options::typeChecking() ) {
4890 e
.getType(true); // ensure expr is type-checked at this point
4893 // Make sure all preprocessing is done
4894 d_private
->processAssertions();
4895 Node n
= d_private
->simplify(Node::fromExpr(e
));
4896 n
= postprocess(n
, TypeNode::fromType(e
.getType()));
4900 Expr
SmtEngine::expandDefinitions(const Expr
& ex
)
4902 d_private
->spendResource(options::preprocessStep());
4904 Assert(ex
.getExprManager() == d_exprManager
);
4905 SmtScope
smts(this);
4906 finalOptionsAreSet();
4908 Trace("smt") << "SMT expandDefinitions(" << ex
<< ")" << endl
;
4910 // Substitute out any abstract values in ex.
4911 Expr e
= d_private
->substituteAbstractValues(Node::fromExpr(ex
)).toExpr();
4912 if(options::typeChecking()) {
4913 // Ensure expr is type-checked at this point.
4916 if(Dump
.isOn("benchmark")) {
4917 Dump("benchmark") << ExpandDefinitionsCommand(e
);
4919 unordered_map
<Node
, Node
, NodeHashFunction
> cache
;
4920 Node n
= d_private
->expandDefinitions(Node::fromExpr(e
), cache
, /* expandOnly = */ true);
4921 n
= postprocess(n
, TypeNode::fromType(e
.getType()));
4926 // TODO(#1108): Simplify the error reporting of this method.
4927 Expr
SmtEngine::getValue(const Expr
& ex
) const
4929 Assert(ex
.getExprManager() == d_exprManager
);
4930 SmtScope
smts(this);
4932 Trace("smt") << "SMT getValue(" << ex
<< ")" << endl
;
4933 if(Dump
.isOn("benchmark")) {
4934 Dump("benchmark") << GetValueCommand(ex
);
4937 if(!options::produceModels()) {
4939 "Cannot get value when produce-models options is off.";
4940 throw ModalException(msg
);
4942 if(d_status
.isNull() ||
4943 d_status
.asSatisfiabilityResult() == Result::UNSAT
||
4944 d_problemExtended
) {
4946 "Cannot get value unless immediately preceded by SAT/INVALID or UNKNOWN response.";
4947 throw RecoverableModalException(msg
);
4950 // Substitute out any abstract values in ex.
4951 Expr e
= d_private
->substituteAbstractValues(Node::fromExpr(ex
)).toExpr();
4953 // Ensure expr is type-checked at this point.
4954 e
.getType(options::typeChecking());
4956 // do not need to apply preprocessing substitutions (should be recorded
4957 // in model already)
4959 Node n
= Node::fromExpr(e
);
4960 Trace("smt") << "--- getting value of " << n
<< endl
;
4961 TypeNode expectedType
= n
.getType();
4963 // Expand, then normalize
4964 unordered_map
<Node
, Node
, NodeHashFunction
> cache
;
4965 n
= d_private
->expandDefinitions(n
, cache
);
4966 // There are two ways model values for terms are computed (for historical
4967 // reasons). One way is that used in check-model; the other is that
4968 // used by the Model classes. It's not clear to me exactly how these
4969 // two are different, but they need to be unified. This ugly hack here
4970 // is to fix bug 554 until we can revamp boolean-terms and models [MGD]
4973 if(!n
.getType().isFunction()) {
4974 n
= Rewriter::rewrite(n
);
4977 Trace("smt") << "--- getting value of " << n
<< endl
;
4978 TheoryModel
* m
= d_theoryEngine
->getModel();
4981 resultNode
= m
->getValue(n
);
4983 Trace("smt") << "--- got value " << n
<< " = " << resultNode
<< endl
;
4984 resultNode
= postprocess(resultNode
, expectedType
);
4985 Trace("smt") << "--- model-post returned " << resultNode
<< endl
;
4986 Trace("smt") << "--- model-post returned " << resultNode
.getType() << endl
;
4987 Trace("smt") << "--- model-post expected " << expectedType
<< endl
;
4989 // type-check the result we got
4990 Assert(resultNode
.isNull() || resultNode
.getType().isSubtypeOf(expectedType
),
4991 "Run with -t smt for details.");
4993 // ensure it's a constant
4994 Assert(resultNode
.getKind() == kind::LAMBDA
|| resultNode
.isConst());
4996 if(options::abstractValues() && resultNode
.getType().isArray()) {
4997 resultNode
= d_private
->mkAbstractValue(resultNode
);
4998 Trace("smt") << "--- abstract value >> " << resultNode
<< endl
;
5001 return resultNode
.toExpr();
5004 bool SmtEngine::addToAssignment(const Expr
& ex
) {
5005 SmtScope
smts(this);
5006 finalOptionsAreSet();
5008 // Substitute out any abstract values in ex
5009 Expr e
= d_private
->substituteAbstractValues(Node::fromExpr(ex
)).toExpr();
5010 Type type
= e
.getType(options::typeChecking());
5012 PrettyCheckArgument(
5013 type
.isBoolean(), e
,
5014 "expected Boolean-typed variable or function application "
5015 "in addToAssignment()" );
5016 Node n
= e
.getNode();
5017 // must be an APPLY of a zero-ary defined function, or a variable
5018 PrettyCheckArgument(
5019 ( ( n
.getKind() == kind::APPLY
&&
5020 ( d_definedFunctions
->find(n
.getOperator()) !=
5021 d_definedFunctions
->end() ) &&
5022 n
.getNumChildren() == 0 ) ||
5024 "expected variable or defined-function application "
5025 "in addToAssignment(),\ngot %s", e
.toString().c_str() );
5026 if(!options::produceAssignments()) {
5029 if(d_assignments
== NULL
) {
5030 d_assignments
= new(true) AssignmentSet(d_context
);
5032 d_assignments
->insert(n
);
5037 // TODO(#1108): Simplify the error reporting of this method.
5038 vector
<pair
<Expr
, Expr
>> SmtEngine::getAssignment()
5040 Trace("smt") << "SMT getAssignment()" << endl
;
5041 SmtScope
smts(this);
5042 finalOptionsAreSet();
5043 if(Dump
.isOn("benchmark")) {
5044 Dump("benchmark") << GetAssignmentCommand();
5046 if(!options::produceAssignments()) {
5048 "Cannot get the current assignment when "
5049 "produce-assignments option is off.";
5050 throw ModalException(msg
);
5052 if(d_status
.isNull() ||
5053 d_status
.asSatisfiabilityResult() == Result::UNSAT
||
5054 d_problemExtended
) {
5056 "Cannot get the current assignment unless immediately "
5057 "preceded by SAT/INVALID or UNKNOWN response.";
5058 throw RecoverableModalException(msg
);
5061 vector
<pair
<Expr
,Expr
>> res
;
5062 if (d_assignments
!= nullptr)
5064 TypeNode boolType
= d_nodeManager
->booleanType();
5065 TheoryModel
* m
= d_theoryEngine
->getModel();
5066 for (AssignmentSet::key_iterator i
= d_assignments
->key_begin(),
5067 iend
= d_assignments
->key_end();
5072 Assert(as
.getType() == boolType
);
5074 Trace("smt") << "--- getting value of " << as
<< endl
;
5076 // Expand, then normalize
5077 unordered_map
<Node
, Node
, NodeHashFunction
> cache
;
5078 Node n
= d_private
->expandDefinitions(as
, cache
);
5079 n
= Rewriter::rewrite(n
);
5081 Trace("smt") << "--- getting value of " << n
<< endl
;
5085 resultNode
= m
->getValue(n
);
5088 // type-check the result we got
5089 Assert(resultNode
.isNull() || resultNode
.getType() == boolType
);
5091 // ensure it's a constant
5092 Assert(resultNode
.isConst());
5094 Assert(as
.getKind() == kind::APPLY
|| as
.isVar());
5095 Assert(as
.getKind() != kind::APPLY
|| as
.getNumChildren() == 0);
5096 res
.emplace_back(as
.toExpr(), resultNode
.toExpr());
5102 void SmtEngine::addToModelCommandAndDump(const Command
& c
, uint32_t flags
, bool userVisible
, const char* dumpTag
) {
5103 Trace("smt") << "SMT addToModelCommandAndDump(" << c
<< ")" << endl
;
5104 SmtScope
smts(this);
5105 // If we aren't yet fully inited, the user might still turn on
5106 // produce-models. So let's keep any commands around just in
5107 // case. This is useful in two cases: (1) SMT-LIBv1 auto-declares
5108 // sort "U" in QF_UF before setLogic() is run and we still want to
5109 // support finding card(U) with --finite-model-find, and (2) to
5110 // decouple SmtEngine and ExprManager if the user does a few
5111 // ExprManager::mkSort() before SmtEngine::setOption("produce-models")
5112 // and expects to find their cardinalities in the model.
5113 if(/* userVisible && */
5114 (!d_fullyInited
|| options::produceModels()) &&
5115 (flags
& ExprManager::VAR_FLAG_DEFINED
) == 0) {
5117 if(flags
& ExprManager::VAR_FLAG_GLOBAL
) {
5118 d_modelGlobalCommands
.push_back(c
.clone());
5120 d_modelCommands
->push_back(c
.clone());
5123 if(Dump
.isOn(dumpTag
)) {
5127 d_dumpCommands
.push_back(c
.clone());
5132 // TODO(#1108): Simplify the error reporting of this method.
5133 Model
* SmtEngine::getModel() {
5134 Trace("smt") << "SMT getModel()" << endl
;
5135 SmtScope
smts(this);
5137 finalOptionsAreSet();
5139 if(Dump
.isOn("benchmark")) {
5140 Dump("benchmark") << GetModelCommand();
5143 if (!options::assignFunctionValues())
5146 "Cannot get the model when --assign-function-values is false.";
5147 throw RecoverableModalException(msg
);
5150 if(d_status
.isNull() ||
5151 d_status
.asSatisfiabilityResult() == Result::UNSAT
||
5152 d_problemExtended
) {
5154 "Cannot get the current model unless immediately "
5155 "preceded by SAT/INVALID or UNKNOWN response.";
5156 throw RecoverableModalException(msg
);
5158 if(!options::produceModels()) {
5160 "Cannot get model when produce-models options is off.";
5161 throw ModalException(msg
);
5163 TheoryModel
* m
= d_theoryEngine
->getModel();
5164 m
->d_inputName
= d_filename
;
5168 std::pair
<Expr
, Expr
> SmtEngine::getSepHeapAndNilExpr(void)
5170 if (!d_logic
.isTheoryEnabled(THEORY_SEP
))
5173 "Cannot obtain separation logic expressions if not using the "
5174 "separation logic theory.";
5175 throw RecoverableModalException(msg
);
5177 NodeManagerScope
nms(d_nodeManager
);
5180 Model
* m
= getModel();
5181 if (m
->getHeapModel(heap
, nil
))
5183 return std::make_pair(heap
, nil
);
5186 "SmtEngine::getSepHeapAndNilExpr(): failed to obtain heap/nil "
5187 "expressions from theory model.");
5190 Expr
SmtEngine::getSepHeapExpr() { return getSepHeapAndNilExpr().first
; }
5192 Expr
SmtEngine::getSepNilExpr() { return getSepHeapAndNilExpr().second
; }
5194 UnsatCore
SmtEngine::getUnsatCoreInternal()
5197 if (!options::unsatCores())
5199 throw ModalException(
5200 "Cannot get an unsat core when produce-unsat-cores option is off.");
5202 if (d_status
.isNull() || d_status
.asSatisfiabilityResult() != Result::UNSAT
5203 || d_problemExtended
)
5205 throw RecoverableModalException(
5206 "Cannot get an unsat core unless immediately preceded by UNSAT/VALID "
5210 d_proofManager
->traceUnsatCore(); // just to trigger core creation
5211 return UnsatCore(this, d_proofManager
->extractUnsatCore());
5212 #else /* IS_PROOFS_BUILD */
5213 throw ModalException(
5214 "This build of CVC4 doesn't have proof support (required for unsat "
5216 #endif /* IS_PROOFS_BUILD */
5219 void SmtEngine::checkUnsatCore() {
5220 Assert(options::unsatCores(), "cannot check unsat core if unsat cores are turned off");
5222 Notice() << "SmtEngine::checkUnsatCore(): generating unsat core" << endl
;
5223 UnsatCore core
= getUnsatCore();
5225 SmtEngine
coreChecker(d_exprManager
);
5226 coreChecker
.setLogic(getLogicInfo());
5229 std::vector
<Command
*>::const_iterator itg
= d_defineCommands
.begin();
5230 for (; itg
!= d_defineCommands
.end(); ++itg
) {
5231 (*itg
)->invoke(&coreChecker
);
5235 Notice() << "SmtEngine::checkUnsatCore(): pushing core assertions (size == " << core
.size() << ")" << endl
;
5236 for(UnsatCore::iterator i
= core
.begin(); i
!= core
.end(); ++i
) {
5237 Notice() << "SmtEngine::checkUnsatCore(): pushing core member " << *i
<< endl
;
5238 coreChecker
.assertFormula(*i
);
5240 const bool checkUnsatCores
= options::checkUnsatCores();
5243 options::checkUnsatCores
.set(false);
5244 options::checkProofs
.set(false);
5245 r
= coreChecker
.checkSat();
5247 options::checkUnsatCores
.set(checkUnsatCores
);
5250 Notice() << "SmtEngine::checkUnsatCore(): result is " << r
<< endl
;
5251 if(r
.asSatisfiabilityResult().isUnknown()) {
5252 InternalError("SmtEngine::checkUnsatCore(): could not check core result unknown.");
5255 if(r
.asSatisfiabilityResult().isSat()) {
5256 InternalError("SmtEngine::checkUnsatCore(): produced core was satisfiable.");
5260 void SmtEngine::checkModel(bool hardFailure
) {
5261 // --check-model implies --produce-assertions, which enables the
5262 // assertion list, so we should be ok.
5263 Assert(d_assertionList
!= NULL
, "don't have an assertion list to check in SmtEngine::checkModel()");
5265 TimerStat::CodeTimer
checkModelTimer(d_stats
->d_checkModelTime
);
5267 // Throughout, we use Notice() to give diagnostic output.
5269 // If this function is running, the user gave --check-model (or equivalent),
5270 // and if Notice() is on, the user gave --verbose (or equivalent).
5272 Notice() << "SmtEngine::checkModel(): generating model" << endl
;
5273 TheoryModel
* m
= d_theoryEngine
->getModel();
5275 // check-model is not guaranteed to succeed if approximate values were used
5276 if (m
->hasApproximations())
5279 << "WARNING: running check-model on a model with approximate values..."
5283 // Check individual theory assertions
5284 d_theoryEngine
->checkTheoryAssertionsWithModel(hardFailure
);
5289 // We have a "fake context" for the substitution map (we don't need it
5290 // to be context-dependent)
5291 context::Context fakeContext
;
5292 SubstitutionMap
substitutions(&fakeContext
, /* substituteUnderQuantifiers = */ false);
5294 for(size_t k
= 0; k
< m
->getNumCommands(); ++k
) {
5295 const DeclareFunctionCommand
* c
= dynamic_cast<const DeclareFunctionCommand
*>(m
->getCommand(k
));
5296 Notice() << "SmtEngine::checkModel(): model command " << k
<< " : " << m
->getCommand(k
) << endl
;
5298 // we don't care about DECLARE-DATATYPES, DECLARE-SORT, ...
5299 Notice() << "SmtEngine::checkModel(): skipping..." << endl
;
5301 // We have a DECLARE-FUN:
5303 // We'll first do some checks, then add to our substitution map
5304 // the mapping: function symbol |-> value
5306 Expr func
= c
->getFunction();
5307 Node val
= m
->getValue(func
);
5309 Notice() << "SmtEngine::checkModel(): adding substitution: " << func
<< " |-> " << val
<< endl
;
5311 // (1) if the value is a lambda, ensure the lambda doesn't contain the
5312 // function symbol (since then the definition is recursive)
5313 if (val
.getKind() == kind::LAMBDA
) {
5314 // first apply the model substitutions we have so far
5315 Debug("boolean-terms") << "applying subses to " << val
[1] << endl
;
5316 Node n
= substitutions
.apply(val
[1]);
5317 Debug("boolean-terms") << "++ got " << n
<< endl
;
5318 // now check if n contains func by doing a substitution
5319 // [func->func2] and checking equality of the Nodes.
5320 // (this just a way to check if func is in n.)
5321 SubstitutionMap
subs(&fakeContext
);
5322 Node func2
= NodeManager::currentNM()->mkSkolem("", TypeNode::fromType(func
.getType()), "", NodeManager::SKOLEM_NO_NOTIFY
);
5323 subs
.addSubstitution(func
, func2
);
5324 if(subs
.apply(n
) != n
) {
5325 Notice() << "SmtEngine::checkModel(): *** PROBLEM: MODEL VALUE DEFINED IN TERMS OF ITSELF ***" << endl
;
5327 ss
<< "SmtEngine::checkModel(): ERRORS SATISFYING ASSERTIONS WITH MODEL:" << endl
5328 << "considering model value for " << func
<< endl
5329 << "body of lambda is: " << val
<< endl
;
5331 ss
<< "body substitutes to: " << n
<< endl
;
5333 ss
<< "so " << func
<< " is defined in terms of itself." << endl
5334 << "Run with `--check-models -v' for additional diagnostics.";
5335 InternalError(ss
.str());
5339 // (2) check that the value is actually a value
5340 else if (!val
.isConst()) {
5341 Notice() << "SmtEngine::checkModel(): *** PROBLEM: MODEL VALUE NOT A CONSTANT ***" << endl
;
5343 ss
<< "SmtEngine::checkModel(): ERRORS SATISFYING ASSERTIONS WITH MODEL:" << endl
5344 << "model value for " << func
<< endl
5345 << " is " << val
<< endl
5346 << "and that is not a constant (.isConst() == false)." << endl
5347 << "Run with `--check-models -v' for additional diagnostics.";
5348 InternalError(ss
.str());
5351 // (3) check that it's the correct (sub)type
5352 // This was intended to be a more general check, but for now we can't do that because
5353 // e.g. "1" is an INT, which isn't a subrange type [1..10] (etc.).
5354 else if(func
.getType().isInteger() && !val
.getType().isInteger()) {
5355 Notice() << "SmtEngine::checkModel(): *** PROBLEM: MODEL VALUE NOT CORRECT TYPE ***" << endl
;
5357 ss
<< "SmtEngine::checkModel(): ERRORS SATISFYING ASSERTIONS WITH MODEL:" << endl
5358 << "model value for " << func
<< endl
5359 << " is " << val
<< endl
5360 << "value type is " << val
.getType() << endl
5361 << "should be of type " << func
.getType() << endl
5362 << "Run with `--check-models -v' for additional diagnostics.";
5363 InternalError(ss
.str());
5366 // (4) checks complete, add the substitution
5367 Debug("boolean-terms") << "cm: adding subs " << func
<< " :=> " << val
<< endl
;
5368 substitutions
.addSubstitution(func
, val
);
5372 // Now go through all our user assertions checking if they're satisfied.
5373 for(AssertionList::const_iterator i
= d_assertionList
->begin(); i
!= d_assertionList
->end(); ++i
) {
5374 Notice() << "SmtEngine::checkModel(): checking assertion " << *i
<< endl
;
5375 Node n
= Node::fromExpr(*i
);
5377 // Apply any define-funs from the problem.
5379 unordered_map
<Node
, Node
, NodeHashFunction
> cache
;
5380 n
= d_private
->expandDefinitions(n
, cache
);
5382 Notice() << "SmtEngine::checkModel(): -- expands to " << n
<< endl
;
5384 // Apply our model value substitutions.
5385 Debug("boolean-terms") << "applying subses to " << n
<< endl
;
5386 n
= substitutions
.apply(n
);
5387 Debug("boolean-terms") << "++ got " << n
<< endl
;
5388 Notice() << "SmtEngine::checkModel(): -- substitutes to " << n
<< endl
;
5390 if( n
.getKind() != kind::REWRITE_RULE
){
5391 // In case it's a quantifier (or contains one), look up its value before
5392 // simplifying, or the quantifier might be irreparably altered.
5394 Notice() << "SmtEngine::checkModel(): -- get value : " << n
<< std::endl
;
5396 // Note this "skip" is done here, rather than above. This is
5397 // because (1) the quantifier could in principle simplify to false,
5398 // which should be reported, and (2) checking for the quantifier
5399 // above, before simplification, doesn't catch buried quantifiers
5400 // anyway (those not at the top-level).
5401 Notice() << "SmtEngine::checkModel(): -- skipping rewrite-rules assertion"
5406 // Simplify the result.
5407 n
= d_private
->simplify(n
);
5408 Notice() << "SmtEngine::checkModel(): -- simplifies to " << n
<< endl
;
5410 // Replace the already-known ITEs (this is important for ground ITEs under quantifiers).
5411 n
= d_private
->d_iteRemover
.replace(n
);
5412 Notice() << "SmtEngine::checkModel(): -- ite replacement gives " << n
<< endl
;
5414 // Apply our model value substitutions (again), as things may have been simplified.
5415 Debug("boolean-terms") << "applying subses to " << n
<< endl
;
5416 n
= substitutions
.apply(n
);
5417 Debug("boolean-terms") << "++ got " << n
<< endl
;
5418 Notice() << "SmtEngine::checkModel(): -- re-substitutes to " << n
<< endl
;
5420 // As a last-ditch effort, ask model to simplify it.
5421 // Presently, this is only an issue for quantifiers, which can have a value
5422 // but don't show up in our substitution map above.
5424 Notice() << "SmtEngine::checkModel(): -- model-substitutes to " << n
<< endl
;
5426 if( d_logic
.isQuantified() ){
5427 // AJR: since quantified formulas are not checkable, we assign them to true/false based on the satisfying assignment.
5428 // however, quantified formulas can be modified during preprocess, so they may not correspond to those in the satisfying assignment.
5429 // hence we use a relaxed version of check model here.
5430 // this is necessary until preprocessing passes explicitly record how they rewrite quantified formulas
5431 if( hardFailure
&& !n
.isConst() && n
.getKind() != kind::LAMBDA
){
5432 Notice() << "SmtEngine::checkModel(): -- relax check model wrt quantified formulas..." << endl
;
5433 AlwaysAssert( quantifiers::QuantifiersRewriter::containsQuantifiers( n
) );
5434 Warning() << "Warning : SmtEngine::checkModel(): cannot check simplified assertion : " << n
<< endl
;
5438 AlwaysAssert(!hardFailure
|| n
.isConst() || n
.getKind() == kind::LAMBDA
);
5440 // The result should be == true.
5441 if(n
!= NodeManager::currentNM()->mkConst(true)) {
5442 Notice() << "SmtEngine::checkModel(): *** PROBLEM: EXPECTED `TRUE' ***"
5445 ss
<< "SmtEngine::checkModel(): "
5446 << "ERRORS SATISFYING ASSERTIONS WITH MODEL:" << endl
5447 << "assertion: " << *i
<< endl
5448 << "simplifies to: " << n
<< endl
5449 << "expected `true'." << endl
5450 << "Run with `--check-models -v' for additional diagnostics.";
5452 InternalError(ss
.str());
5454 Warning() << ss
.str() << endl
;
5458 Notice() << "SmtEngine::checkModel(): all assertions checked out OK !" << endl
;
5461 void SmtEngine::checkSynthSolution()
5463 NodeManager
* nm
= NodeManager::currentNM();
5464 Notice() << "SmtEngine::checkSynthSolution(): checking synthesis solution" << endl
;
5465 map
<Node
, Node
> sol_map
;
5466 /* Get solutions and build auxiliary vectors for substituting */
5467 d_theoryEngine
->getSynthSolutions(sol_map
);
5468 if (sol_map
.empty())
5470 Trace("check-synth-sol") << "No solution to check!\n";
5473 Trace("check-synth-sol") << "Got solution map:\n";
5474 std::vector
<Node
> function_vars
, function_sols
;
5475 for (const auto& pair
: sol_map
)
5477 Trace("check-synth-sol") << pair
.first
<< " --> " << pair
.second
<< "\n";
5478 function_vars
.push_back(pair
.first
);
5479 function_sols
.push_back(pair
.second
);
5481 Trace("check-synth-sol") << "Starting new SMT Engine\n";
5482 /* Start new SMT engine to check solutions */
5483 SmtEngine
solChecker(d_exprManager
);
5484 solChecker
.setLogic(getLogicInfo());
5485 setOption("check-synth-sol", SExpr("false"));
5487 Trace("check-synth-sol") << "Retrieving assertions\n";
5488 // Build conjecture from original assertions
5489 if (d_assertionList
== NULL
)
5491 Trace("check-synth-sol") << "No assertions to check\n";
5494 for (AssertionList::const_iterator i
= d_assertionList
->begin();
5495 i
!= d_assertionList
->end();
5498 Notice() << "SmtEngine::checkSynthSolution(): checking assertion " << *i
<< endl
;
5499 Trace("check-synth-sol") << "Retrieving assertion " << *i
<< "\n";
5500 Node conj
= Node::fromExpr(*i
);
5501 // Apply any define-funs from the problem.
5503 unordered_map
<Node
, Node
, NodeHashFunction
> cache
;
5504 conj
= d_private
->expandDefinitions(conj
, cache
);
5506 Notice() << "SmtEngine::checkSynthSolution(): -- expands to " << conj
<< endl
;
5507 Trace("check-synth-sol") << "Expanded assertion " << conj
<< "\n";
5508 if (conj
.getKind() != kind::FORALL
)
5510 Trace("check-synth-sol") << "Not a checkable assertion.\n";
5514 // Apply solution map to conjecture body
5516 /* Whether property is quantifier free */
5517 if (conj
[1].getKind() != kind::EXISTS
)
5519 conjBody
= conj
[1].substitute(function_vars
.begin(),
5520 function_vars
.end(),
5521 function_sols
.begin(),
5522 function_sols
.end());
5526 conjBody
= conj
[1][1].substitute(function_vars
.begin(),
5527 function_vars
.end(),
5528 function_sols
.begin(),
5529 function_sols
.end());
5531 /* Skolemize property */
5532 std::vector
<Node
> vars
, skos
;
5533 for (unsigned j
= 0, size
= conj
[1][0].getNumChildren(); j
< size
; ++j
)
5535 vars
.push_back(conj
[1][0][j
]);
5536 std::stringstream ss
;
5538 skos
.push_back(nm
->mkSkolem(ss
.str(), conj
[1][0][j
].getType()));
5539 Trace("check-synth-sol") << "\tSkolemizing " << conj
[1][0][j
] << " to "
5540 << skos
.back() << "\n";
5542 conjBody
= conjBody
.substitute(
5543 vars
.begin(), vars
.end(), skos
.begin(), skos
.end());
5545 Notice() << "SmtEngine::checkSynthSolution(): -- body substitutes to "
5546 << conjBody
<< endl
;
5547 Trace("check-synth-sol") << "Substituted body of assertion to " << conjBody
5549 solChecker
.assertFormula(conjBody
.toExpr());
5550 Result r
= solChecker
.checkSat();
5551 Notice() << "SmtEngine::checkSynthSolution(): result is " << r
<< endl
;
5552 Trace("check-synth-sol") << "Satsifiability check: " << r
<< "\n";
5553 if (r
.asSatisfiabilityResult().isUnknown())
5556 "SmtEngine::checkSynthSolution(): could not check solution, result "
5559 else if (r
.asSatisfiabilityResult().isSat())
5562 "SmtEngine::checkSynthSolution(): produced solution leads to "
5563 "satisfiable negated conjecture.");
5565 solChecker
.resetAssertions();
5569 // TODO(#1108): Simplify the error reporting of this method.
5570 UnsatCore
SmtEngine::getUnsatCore() {
5571 Trace("smt") << "SMT getUnsatCore()" << endl
;
5572 SmtScope
smts(this);
5573 finalOptionsAreSet();
5574 if(Dump
.isOn("benchmark")) {
5575 Dump("benchmark") << GetUnsatCoreCommand();
5577 return getUnsatCoreInternal();
5580 // TODO(#1108): Simplify the error reporting of this method.
5581 const Proof
& SmtEngine::getProof()
5583 Trace("smt") << "SMT getProof()" << endl
;
5584 SmtScope
smts(this);
5585 finalOptionsAreSet();
5586 if(Dump
.isOn("benchmark")) {
5587 Dump("benchmark") << GetProofCommand();
5590 if(!options::proof()) {
5591 throw ModalException("Cannot get a proof when produce-proofs option is off.");
5593 if(d_status
.isNull() ||
5594 d_status
.asSatisfiabilityResult() != Result::UNSAT
||
5595 d_problemExtended
) {
5596 throw RecoverableModalException(
5597 "Cannot get a proof unless immediately preceded by UNSAT/VALID "
5601 return ProofManager::getProof(this);
5602 #else /* IS_PROOFS_BUILD */
5603 throw ModalException("This build of CVC4 doesn't have proof support.");
5604 #endif /* IS_PROOFS_BUILD */
5607 void SmtEngine::printInstantiations( std::ostream
& out
) {
5608 SmtScope
smts(this);
5609 if( options::instFormatMode()==INST_FORMAT_MODE_SZS
){
5610 out
<< "% SZS output start Proof for " << d_filename
.c_str() << std::endl
;
5612 if( d_theoryEngine
){
5613 d_theoryEngine
->printInstantiations( out
);
5617 if( options::instFormatMode()==INST_FORMAT_MODE_SZS
){
5618 out
<< "% SZS output end Proof for " << d_filename
.c_str() << std::endl
;
5622 void SmtEngine::printSynthSolution( std::ostream
& out
) {
5623 SmtScope
smts(this);
5624 if( d_theoryEngine
){
5625 d_theoryEngine
->printSynthSolution( out
);
5631 void SmtEngine::getSynthSolutions(std::map
<Expr
, Expr
>& sol_map
)
5633 SmtScope
smts(this);
5634 map
<Node
, Node
> sol_mapn
;
5635 Assert(d_theoryEngine
!= nullptr);
5636 d_theoryEngine
->getSynthSolutions(sol_mapn
);
5637 for (std::pair
<const Node
, Node
>& s
: sol_mapn
)
5639 sol_map
[s
.first
.toExpr()] = s
.second
.toExpr();
5643 Expr
SmtEngine::doQuantifierElimination(const Expr
& e
, bool doFull
, bool strict
)
5645 SmtScope
smts(this);
5646 if(!d_logic
.isPure(THEORY_ARITH
) && strict
){
5647 Warning() << "Unexpected logic for quantifier elimination " << d_logic
<< endl
;
5649 Trace("smt-qe") << "Do quantifier elimination " << e
<< std::endl
;
5650 Node n_e
= Node::fromExpr( e
);
5651 if (n_e
.getKind() != kind::EXISTS
&& n_e
.getKind() != kind::FORALL
)
5653 throw ModalException(
5654 "Expecting a quantified formula as argument to get-qe.");
5656 //tag the quantified formula with the quant-elim attribute
5657 TypeNode t
= NodeManager::currentNM()->booleanType();
5658 Node n_attr
= NodeManager::currentNM()->mkSkolem("qe", t
, "Auxiliary variable for qe attr.");
5659 std::vector
< Node
> node_values
;
5660 d_theoryEngine
->setUserAttribute( doFull
? "quant-elim" : "quant-elim-partial", n_attr
, node_values
, "");
5661 n_attr
= NodeManager::currentNM()->mkNode(kind::INST_ATTRIBUTE
, n_attr
);
5662 n_attr
= NodeManager::currentNM()->mkNode(kind::INST_PATTERN_LIST
, n_attr
);
5663 std::vector
< Node
> e_children
;
5664 e_children
.push_back( n_e
[0] );
5665 e_children
.push_back(n_e
.getKind() == kind::EXISTS
? n_e
[1]
5667 e_children
.push_back( n_attr
);
5668 Node nn_e
= NodeManager::currentNM()->mkNode( kind::EXISTS
, e_children
);
5669 Trace("smt-qe-debug") << "Query for quantifier elimination : " << nn_e
<< std::endl
;
5670 Assert( nn_e
.getNumChildren()==3 );
5671 Result r
= checkSatisfiability(nn_e
.toExpr(), true, true);
5672 Trace("smt-qe") << "Query returned " << r
<< std::endl
;
5673 if(r
.asSatisfiabilityResult().isSat() != Result::UNSAT
) {
5674 if( r
.asSatisfiabilityResult().isSat() != Result::SAT
&& doFull
){
5676 ss
<< "While performing quantifier elimination, unexpected result : " << r
<< " for query.";
5677 InternalError(ss
.str().c_str());
5679 std::vector
< Node
> inst_qs
;
5680 d_theoryEngine
->getInstantiatedQuantifiedFormulas( inst_qs
);
5681 Assert( inst_qs
.size()<=1 );
5683 if( inst_qs
.size()==1 ){
5684 Node top_q
= inst_qs
[0];
5685 //Node top_q = Rewriter::rewrite( nn_e ).negate();
5686 Assert( top_q
.getKind()==kind::FORALL
);
5687 Trace("smt-qe") << "Get qe for " << top_q
<< std::endl
;
5688 ret_n
= d_theoryEngine
->getInstantiatedConjunction( top_q
);
5689 Trace("smt-qe") << "Returned : " << ret_n
<< std::endl
;
5690 if (n_e
.getKind() == kind::EXISTS
)
5692 ret_n
= Rewriter::rewrite(ret_n
.negate());
5695 ret_n
= NodeManager::currentNM()->mkConst(n_e
.getKind() != kind::EXISTS
);
5697 // do extended rewrite to minimize the size of the formula aggressively
5698 theory::quantifiers::ExtendedRewriter
extr(true);
5699 ret_n
= extr
.extendedRewrite(ret_n
);
5700 return ret_n
.toExpr();
5702 return NodeManager::currentNM()
5703 ->mkConst(n_e
.getKind() == kind::EXISTS
)
5708 void SmtEngine::getInstantiatedQuantifiedFormulas( std::vector
< Expr
>& qs
) {
5709 SmtScope
smts(this);
5710 if( d_theoryEngine
){
5711 std::vector
< Node
> qs_n
;
5712 d_theoryEngine
->getInstantiatedQuantifiedFormulas( qs_n
);
5713 for( unsigned i
=0; i
<qs_n
.size(); i
++ ){
5714 qs
.push_back( qs_n
[i
].toExpr() );
5721 void SmtEngine::getInstantiations( Expr q
, std::vector
< Expr
>& insts
) {
5722 SmtScope
smts(this);
5723 if( d_theoryEngine
){
5724 std::vector
< Node
> insts_n
;
5725 d_theoryEngine
->getInstantiations( Node::fromExpr( q
), insts_n
);
5726 for( unsigned i
=0; i
<insts_n
.size(); i
++ ){
5727 insts
.push_back( insts_n
[i
].toExpr() );
5734 void SmtEngine::getInstantiationTermVectors( Expr q
, std::vector
< std::vector
< Expr
> >& tvecs
) {
5735 SmtScope
smts(this);
5736 Assert(options::trackInstLemmas());
5737 if( d_theoryEngine
){
5738 std::vector
< std::vector
< Node
> > tvecs_n
;
5739 d_theoryEngine
->getInstantiationTermVectors( Node::fromExpr( q
), tvecs_n
);
5740 for( unsigned i
=0; i
<tvecs_n
.size(); i
++ ){
5741 std::vector
< Expr
> tvec
;
5742 for( unsigned j
=0; j
<tvecs_n
[i
].size(); j
++ ){
5743 tvec
.push_back( tvecs_n
[i
][j
].toExpr() );
5745 tvecs
.push_back( tvec
);
5752 vector
<Expr
> SmtEngine::getAssertions() {
5753 SmtScope
smts(this);
5754 finalOptionsAreSet();
5756 if(Dump
.isOn("benchmark")) {
5757 Dump("benchmark") << GetAssertionsCommand();
5759 Trace("smt") << "SMT getAssertions()" << endl
;
5760 if(!options::produceAssertions()) {
5762 "Cannot query the current assertion list when not in produce-assertions mode.";
5763 throw ModalException(msg
);
5765 Assert(d_assertionList
!= NULL
);
5766 // copy the result out
5767 return vector
<Expr
>(d_assertionList
->begin(), d_assertionList
->end());
5770 void SmtEngine::push()
5772 SmtScope
smts(this);
5773 finalOptionsAreSet();
5775 Trace("smt") << "SMT push()" << endl
;
5776 d_private
->notifyPush();
5777 d_private
->processAssertions();
5778 if(Dump
.isOn("benchmark")) {
5779 Dump("benchmark") << PushCommand();
5781 if(!options::incrementalSolving()) {
5782 throw ModalException("Cannot push when not solving incrementally (use --incremental)");
5785 // check to see if a postsolve() is pending
5786 if(d_needPostsolve
) {
5787 d_theoryEngine
->postsolve();
5788 d_needPostsolve
= false;
5791 // The problem isn't really "extended" yet, but this disallows
5792 // get-model after a push, simplifying our lives somewhat and
5793 // staying symmtric with pop.
5794 setProblemExtended(true);
5796 d_userLevels
.push_back(d_userContext
->getLevel());
5798 Trace("userpushpop") << "SmtEngine: pushed to level "
5799 << d_userContext
->getLevel() << endl
;
5802 void SmtEngine::pop() {
5803 SmtScope
smts(this);
5804 finalOptionsAreSet();
5805 Trace("smt") << "SMT pop()" << endl
;
5806 if(Dump
.isOn("benchmark")) {
5807 Dump("benchmark") << PopCommand();
5809 if(!options::incrementalSolving()) {
5810 throw ModalException("Cannot pop when not solving incrementally (use --incremental)");
5812 if(d_userLevels
.size() == 0) {
5813 throw ModalException("Cannot pop beyond the first user frame");
5816 // check to see if a postsolve() is pending
5817 if(d_needPostsolve
) {
5818 d_theoryEngine
->postsolve();
5819 d_needPostsolve
= false;
5822 // The problem isn't really "extended" yet, but this disallows
5823 // get-model after a pop, simplifying our lives somewhat. It might
5824 // not be strictly necessary to do so, since the pops occur lazily,
5825 // but also it would be weird to have a legally-executed (get-model)
5826 // that only returns a subset of the assignment (because the rest
5827 // is no longer in scope!).
5828 setProblemExtended(true);
5830 AlwaysAssert(d_userContext
->getLevel() > 0);
5831 AlwaysAssert(d_userLevels
.back() < d_userContext
->getLevel());
5832 while (d_userLevels
.back() < d_userContext
->getLevel()) {
5835 d_userLevels
.pop_back();
5837 // Clear out assertion queues etc., in case anything is still in there
5838 d_private
->notifyPop();
5840 Trace("userpushpop") << "SmtEngine: popped to level "
5841 << d_userContext
->getLevel() << endl
;
5842 // FIXME: should we reset d_status here?
5843 // SMT-LIBv2 spec seems to imply no, but it would make sense to..
5846 void SmtEngine::internalPush() {
5847 Assert(d_fullyInited
);
5848 Trace("smt") << "SmtEngine::internalPush()" << endl
;
5850 if(options::incrementalSolving()) {
5851 d_private
->processAssertions();
5852 TimerStat::CodeTimer
pushPopTimer(d_stats
->d_pushPopTime
);
5853 d_userContext
->push();
5854 // the d_context push is done inside of the SAT solver
5855 d_propEngine
->push();
5859 void SmtEngine::internalPop(bool immediate
) {
5860 Assert(d_fullyInited
);
5861 Trace("smt") << "SmtEngine::internalPop()" << endl
;
5862 if(options::incrementalSolving()) {
5870 void SmtEngine::doPendingPops() {
5871 Assert(d_pendingPops
== 0 || options::incrementalSolving());
5872 while(d_pendingPops
> 0) {
5873 TimerStat::CodeTimer
pushPopTimer(d_stats
->d_pushPopTime
);
5874 d_propEngine
->pop();
5875 // the d_context pop is done inside of the SAT solver
5876 d_userContext
->pop();
5881 void SmtEngine::reset()
5883 SmtScope
smts(this);
5884 ExprManager
*em
= d_exprManager
;
5885 Trace("smt") << "SMT reset()" << endl
;
5886 if(Dump
.isOn("benchmark")) {
5887 Dump("benchmark") << ResetCommand();
5890 opts
.copyValues(d_originalOptions
);
5892 NodeManager::fromExprManager(em
)->getOptions().copyValues(opts
);
5893 new(this) SmtEngine(em
);
5896 void SmtEngine::resetAssertions()
5898 SmtScope
smts(this);
5901 Trace("smt") << "SMT resetAssertions()" << endl
;
5902 if(Dump
.isOn("benchmark")) {
5903 Dump("benchmark") << ResetAssertionsCommand();
5906 while(!d_userLevels
.empty()) {
5910 // Also remember the global push/pop around everything.
5911 Assert(d_userLevels
.size() == 0 && d_userContext
->getLevel() == 1);
5912 d_context
->popto(0);
5913 d_userContext
->popto(0);
5914 DeleteAndClearCommandVector(d_modelGlobalCommands
);
5915 d_userContext
->push();
5919 void SmtEngine::interrupt()
5921 if(!d_fullyInited
) {
5924 d_propEngine
->interrupt();
5925 d_theoryEngine
->interrupt();
5928 void SmtEngine::setResourceLimit(unsigned long units
, bool cumulative
) {
5929 d_private
->getResourceManager()->setResourceLimit(units
, cumulative
);
5931 void SmtEngine::setTimeLimit(unsigned long milis
, bool cumulative
) {
5932 d_private
->getResourceManager()->setTimeLimit(milis
, cumulative
);
5935 unsigned long SmtEngine::getResourceUsage() const {
5936 return d_private
->getResourceManager()->getResourceUsage();
5939 unsigned long SmtEngine::getTimeUsage() const {
5940 return d_private
->getResourceManager()->getTimeUsage();
5943 unsigned long SmtEngine::getResourceRemaining() const
5945 return d_private
->getResourceManager()->getResourceRemaining();
5948 unsigned long SmtEngine::getTimeRemaining() const
5950 return d_private
->getResourceManager()->getTimeRemaining();
5953 Statistics
SmtEngine::getStatistics() const
5955 return Statistics(*d_statisticsRegistry
);
5958 SExpr
SmtEngine::getStatistic(std::string name
) const
5960 return d_statisticsRegistry
->getStatistic(name
);
5963 void SmtEngine::safeFlushStatistics(int fd
) const {
5964 d_statisticsRegistry
->safeFlushInformation(fd
);
5967 void SmtEngine::setUserAttribute(const std::string
& attr
,
5969 const std::vector
<Expr
>& expr_values
,
5970 const std::string
& str_value
)
5972 SmtScope
smts(this);
5973 std::vector
<Node
> node_values
;
5974 for( unsigned i
=0; i
<expr_values
.size(); i
++ ){
5975 node_values
.push_back( expr_values
[i
].getNode() );
5977 d_theoryEngine
->setUserAttribute(attr
, expr
.getNode(), node_values
, str_value
);
5980 void SmtEngine::setPrintFuncInModel(Expr f
, bool p
) {
5981 Trace("setp-model") << "Set printInModel " << f
<< " to " << p
<< std::endl
;
5982 for( unsigned i
=0; i
<d_modelGlobalCommands
.size(); i
++ ){
5983 Command
* c
= d_modelGlobalCommands
[i
];
5984 DeclareFunctionCommand
* dfc
= dynamic_cast<DeclareFunctionCommand
*>(c
);
5986 if( dfc
->getFunction()==f
){
5987 dfc
->setPrintInModel( p
);
5991 for( unsigned i
=0; i
<d_modelCommands
->size(); i
++ ){
5992 Command
* c
= (*d_modelCommands
)[i
];
5993 DeclareFunctionCommand
* dfc
= dynamic_cast<DeclareFunctionCommand
*>(c
);
5995 if( dfc
->getFunction()==f
){
5996 dfc
->setPrintInModel( p
);
6002 void SmtEngine::beforeSearch()
6005 throw ModalException(
6006 "SmtEngine::beforeSearch called after initialization.");
6011 void SmtEngine::setOption(const std::string
& key
, const CVC4::SExpr
& value
)
6013 NodeManagerScope
nms(d_nodeManager
);
6014 Trace("smt") << "SMT setOption(" << key
<< ", " << value
<< ")" << endl
;
6016 if(Dump
.isOn("benchmark")) {
6017 Dump("benchmark") << SetOptionCommand(key
, value
);
6020 if(key
== "command-verbosity") {
6021 if(!value
.isAtom()) {
6022 const vector
<SExpr
>& cs
= value
.getChildren();
6023 if(cs
.size() == 2 &&
6024 (cs
[0].isKeyword() || cs
[0].isString()) &&
6025 cs
[1].isInteger()) {
6026 string c
= cs
[0].getValue();
6027 const Integer
& v
= cs
[1].getIntegerValue();
6028 if(v
< 0 || v
> 2) {
6029 throw OptionException("command-verbosity must be 0, 1, or 2");
6031 d_commandVerbosity
[c
] = v
;
6035 throw OptionException("command-verbosity value must be a tuple (command-name, integer)");
6038 if(!value
.isAtom()) {
6039 throw OptionException("bad value for :" + key
);
6042 string optionarg
= value
.getValue();
6043 Options
& nodeManagerOptions
= NodeManager::currentNM()->getOptions();
6044 nodeManagerOptions
.setOption(key
, optionarg
);
6047 CVC4::SExpr
SmtEngine::getOption(const std::string
& key
) const
6049 NodeManagerScope
nms(d_nodeManager
);
6051 Trace("smt") << "SMT getOption(" << key
<< ")" << endl
;
6053 if(key
.length() >= 18 &&
6054 key
.compare(0, 18, "command-verbosity:") == 0) {
6055 map
<string
, Integer
>::const_iterator i
= d_commandVerbosity
.find(key
.c_str() + 18);
6056 if(i
!= d_commandVerbosity
.end()) {
6057 return SExpr((*i
).second
);
6059 i
= d_commandVerbosity
.find("*");
6060 if(i
!= d_commandVerbosity
.end()) {
6061 return SExpr((*i
).second
);
6063 return SExpr(Integer(2));
6066 if(Dump
.isOn("benchmark")) {
6067 Dump("benchmark") << GetOptionCommand(key
);
6070 if(key
== "command-verbosity") {
6071 vector
<SExpr
> result
;
6072 SExpr defaultVerbosity
;
6073 for(map
<string
, Integer
>::const_iterator i
= d_commandVerbosity
.begin();
6074 i
!= d_commandVerbosity
.end();
6077 v
.push_back(SExpr((*i
).first
));
6078 v
.push_back(SExpr((*i
).second
));
6079 if((*i
).first
== "*") {
6080 // put the default at the end of the SExpr
6081 defaultVerbosity
= SExpr(v
);
6083 result
.push_back(SExpr(v
));
6086 // put the default at the end of the SExpr
6087 if(!defaultVerbosity
.isAtom()) {
6088 result
.push_back(defaultVerbosity
);
6090 // ensure the default is always listed
6092 v
.push_back(SExpr("*"));
6093 v
.push_back(SExpr(Integer(2)));
6094 result
.push_back(SExpr(v
));
6096 return SExpr(result
);
6099 Options
& nodeManagerOptions
= NodeManager::currentNM()->getOptions();
6100 return SExpr::parseAtom(nodeManagerOptions
.getOption(key
));
6103 void SmtEngine::setReplayStream(ExprStream
* replayStream
) {
6104 AlwaysAssert(!d_fullyInited
,
6105 "Cannot set replay stream once fully initialized");
6106 d_replayStream
= replayStream
;
6109 bool SmtEngine::getExpressionName(Expr e
, std::string
& name
) const {
6110 return d_private
->getExpressionName(e
, name
);
6113 void SmtEngine::setExpressionName(Expr e
, const std::string
& name
) {
6114 Trace("smt-debug") << "Set expression name " << e
<< " to " << name
<< std::endl
;
6115 d_private
->setExpressionName(e
,name
);
6118 }/* CVC4 namespace */