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"
27 #include <unordered_map>
28 #include <unordered_set>
32 #include "base/configuration.h"
33 #include "base/configuration_private.h"
34 #include "base/exception.h"
35 #include "base/listener.h"
36 #include "base/modal_exception.h"
37 #include "base/output.h"
38 #include "context/cdhashmap.h"
39 #include "context/cdhashset.h"
40 #include "context/cdlist.h"
41 #include "context/context.h"
42 #include "decision/decision_engine.h"
43 #include "expr/attribute.h"
44 #include "expr/expr.h"
45 #include "expr/kind.h"
46 #include "expr/metakind.h"
47 #include "expr/node.h"
48 #include "expr/node_algorithm.h"
49 #include "expr/node_builder.h"
50 #include "expr/node_self_iterator.h"
51 #include "options/arith_options.h"
52 #include "options/arrays_options.h"
53 #include "options/base_options.h"
54 #include "options/booleans_options.h"
55 #include "options/bv_options.h"
56 #include "options/datatypes_options.h"
57 #include "options/decision_mode.h"
58 #include "options/decision_options.h"
59 #include "options/language.h"
60 #include "options/main_options.h"
61 #include "options/open_ostream.h"
62 #include "options/option_exception.h"
63 #include "options/printer_options.h"
64 #include "options/proof_options.h"
65 #include "options/prop_options.h"
66 #include "options/quantifiers_options.h"
67 #include "options/sep_options.h"
68 #include "options/set_language.h"
69 #include "options/smt_options.h"
70 #include "options/strings_options.h"
71 #include "options/theory_options.h"
72 #include "options/uf_options.h"
73 #include "preprocessing/preprocessing_pass.h"
74 #include "preprocessing/preprocessing_pass_context.h"
75 #include "preprocessing/preprocessing_pass_registry.h"
76 #include "printer/printer.h"
77 #include "proof/proof.h"
78 #include "proof/proof_manager.h"
79 #include "proof/theory_proof.h"
80 #include "proof/unsat_core.h"
81 #include "prop/prop_engine.h"
82 #include "smt/command.h"
83 #include "smt/command_list.h"
84 #include "smt/logic_request.h"
85 #include "smt/managed_ostreams.h"
86 #include "smt/model_core_builder.h"
87 #include "smt/smt_engine_scope.h"
88 #include "smt/term_formula_removal.h"
89 #include "smt/update_ostream.h"
90 #include "smt_util/boolean_simplification.h"
91 #include "smt_util/nary_builder.h"
92 #include "smt_util/node_visitor.h"
93 #include "theory/booleans/circuit_propagator.h"
94 #include "theory/bv/theory_bv_rewriter.h"
95 #include "theory/logic_info.h"
96 #include "theory/quantifiers/fun_def_process.h"
97 #include "theory/quantifiers/quantifiers_rewriter.h"
98 #include "theory/quantifiers/single_inv_partition.h"
99 #include "theory/quantifiers/sygus/synth_engine.h"
100 #include "theory/quantifiers/term_util.h"
101 #include "theory/rewriter.h"
102 #include "theory/sort_inference.h"
103 #include "theory/strings/theory_strings.h"
104 #include "theory/substitutions.h"
105 #include "theory/theory_engine.h"
106 #include "theory/theory_model.h"
107 #include "theory/theory_traits.h"
108 #include "util/hash.h"
109 #include "util/proof.h"
110 #include "util/random.h"
111 #include "util/resource_manager.h"
114 using namespace CVC4
;
115 using namespace CVC4::smt
;
116 using namespace CVC4::preprocessing
;
117 using namespace CVC4::prop
;
118 using namespace CVC4::context
;
119 using namespace CVC4::theory
;
124 struct DeleteCommandFunction
: public std::unary_function
<const Command
*, void>
126 void operator()(const Command
* command
) { delete command
; }
129 void DeleteAndClearCommandVector(std::vector
<Command
*>& commands
) {
130 std::for_each(commands
.begin(), commands
.end(), DeleteCommandFunction());
134 /** Useful for counting the number of recursive calls. */
139 ScopeCounter(unsigned& d
) : d_depth(d
) {
148 * Representation of a defined function. We keep these around in
149 * SmtEngine to permit expanding definitions late (and lazily), to
150 * support getValue() over defined functions, to support user output
151 * in terms of defined functions, etc.
153 class DefinedFunction
{
155 vector
<Node
> d_formals
;
159 DefinedFunction(Node func
, vector
<Node
> formals
, Node formula
) :
164 Node
getFunction() const { return d_func
; }
165 vector
<Node
> getFormals() const { return d_formals
; }
166 Node
getFormula() const { return d_formula
; }
167 };/* class DefinedFunction */
169 struct SmtEngineStatistics
{
170 /** time spent in definition-expansion */
171 TimerStat d_definitionExpansionTime
;
172 /** number of constant propagations found during nonclausal simp */
173 IntStat d_numConstantProps
;
174 /** time spent converting to CNF */
175 TimerStat d_cnfConversionTime
;
176 /** Num of assertions before ite removal */
177 IntStat d_numAssertionsPre
;
178 /** Num of assertions after ite removal */
179 IntStat d_numAssertionsPost
;
180 /** time spent in checkModel() */
181 TimerStat d_checkModelTime
;
182 /** time spent in checkProof() */
183 TimerStat d_checkProofTime
;
184 /** time spent in checkUnsatCore() */
185 TimerStat d_checkUnsatCoreTime
;
186 /** time spent in PropEngine::checkSat() */
187 TimerStat d_solveTime
;
188 /** time spent in pushing/popping */
189 TimerStat d_pushPopTime
;
190 /** time spent in processAssertions() */
191 TimerStat d_processAssertionsTime
;
193 /** Has something simplified to false? */
194 IntStat d_simplifiedToFalse
;
195 /** Number of resource units spent. */
196 ReferenceStat
<uint64_t> d_resourceUnitsUsed
;
198 SmtEngineStatistics() :
199 d_definitionExpansionTime("smt::SmtEngine::definitionExpansionTime"),
200 d_numConstantProps("smt::SmtEngine::numConstantProps", 0),
201 d_cnfConversionTime("smt::SmtEngine::cnfConversionTime"),
202 d_numAssertionsPre("smt::SmtEngine::numAssertionsPreITERemoval", 0),
203 d_numAssertionsPost("smt::SmtEngine::numAssertionsPostITERemoval", 0),
204 d_checkModelTime("smt::SmtEngine::checkModelTime"),
205 d_checkProofTime("smt::SmtEngine::checkProofTime"),
206 d_checkUnsatCoreTime("smt::SmtEngine::checkUnsatCoreTime"),
207 d_solveTime("smt::SmtEngine::solveTime"),
208 d_pushPopTime("smt::SmtEngine::pushPopTime"),
209 d_processAssertionsTime("smt::SmtEngine::processAssertionsTime"),
210 d_simplifiedToFalse("smt::SmtEngine::simplifiedToFalse", 0),
211 d_resourceUnitsUsed("smt::SmtEngine::resourceUnitsUsed")
213 smtStatisticsRegistry()->registerStat(&d_definitionExpansionTime
);
214 smtStatisticsRegistry()->registerStat(&d_numConstantProps
);
215 smtStatisticsRegistry()->registerStat(&d_cnfConversionTime
);
216 smtStatisticsRegistry()->registerStat(&d_numAssertionsPre
);
217 smtStatisticsRegistry()->registerStat(&d_numAssertionsPost
);
218 smtStatisticsRegistry()->registerStat(&d_checkModelTime
);
219 smtStatisticsRegistry()->registerStat(&d_checkProofTime
);
220 smtStatisticsRegistry()->registerStat(&d_checkUnsatCoreTime
);
221 smtStatisticsRegistry()->registerStat(&d_solveTime
);
222 smtStatisticsRegistry()->registerStat(&d_pushPopTime
);
223 smtStatisticsRegistry()->registerStat(&d_processAssertionsTime
);
224 smtStatisticsRegistry()->registerStat(&d_simplifiedToFalse
);
225 smtStatisticsRegistry()->registerStat(&d_resourceUnitsUsed
);
228 ~SmtEngineStatistics() {
229 smtStatisticsRegistry()->unregisterStat(&d_definitionExpansionTime
);
230 smtStatisticsRegistry()->unregisterStat(&d_numConstantProps
);
231 smtStatisticsRegistry()->unregisterStat(&d_cnfConversionTime
);
232 smtStatisticsRegistry()->unregisterStat(&d_numAssertionsPre
);
233 smtStatisticsRegistry()->unregisterStat(&d_numAssertionsPost
);
234 smtStatisticsRegistry()->unregisterStat(&d_checkModelTime
);
235 smtStatisticsRegistry()->unregisterStat(&d_checkProofTime
);
236 smtStatisticsRegistry()->unregisterStat(&d_checkUnsatCoreTime
);
237 smtStatisticsRegistry()->unregisterStat(&d_solveTime
);
238 smtStatisticsRegistry()->unregisterStat(&d_pushPopTime
);
239 smtStatisticsRegistry()->unregisterStat(&d_processAssertionsTime
);
240 smtStatisticsRegistry()->unregisterStat(&d_simplifiedToFalse
);
241 smtStatisticsRegistry()->unregisterStat(&d_resourceUnitsUsed
);
243 };/* struct SmtEngineStatistics */
246 class SoftResourceOutListener
: public Listener
{
248 SoftResourceOutListener(SmtEngine
& smt
) : d_smt(&smt
) {}
249 void notify() override
251 SmtScope
scope(d_smt
);
252 Assert(smt::smtEngineInScope());
257 }; /* class SoftResourceOutListener */
260 class HardResourceOutListener
: public Listener
{
262 HardResourceOutListener(SmtEngine
& smt
) : d_smt(&smt
) {}
263 void notify() override
265 SmtScope
scope(d_smt
);
266 theory::Rewriter::clearCaches();
270 }; /* class HardResourceOutListener */
272 class SetLogicListener
: public Listener
{
274 SetLogicListener(SmtEngine
& smt
) : d_smt(&smt
) {}
275 void notify() override
277 LogicInfo
inOptions(options::forceLogicString());
278 d_smt
->setLogic(inOptions
);
282 }; /* class SetLogicListener */
284 class BeforeSearchListener
: public Listener
{
286 BeforeSearchListener(SmtEngine
& smt
) : d_smt(&smt
) {}
287 void notify() override
{ d_smt
->beforeSearch(); }
291 }; /* class BeforeSearchListener */
293 class UseTheoryListListener
: public Listener
{
295 UseTheoryListListener(TheoryEngine
* theoryEngine
)
296 : d_theoryEngine(theoryEngine
)
299 void notify() override
301 std::stringstream
commaList(options::useTheoryList());
304 Debug("UseTheoryListListener") << "UseTheoryListListener::notify() "
305 << options::useTheoryList() << std::endl
;
307 while(std::getline(commaList
, token
, ',')){
308 if(token
== "help") {
309 puts(theory::useTheoryHelp
);
312 if(theory::useTheoryValidate(token
)) {
313 d_theoryEngine
->enableTheoryAlternative(token
);
315 throw OptionException(
316 std::string("unknown option for --use-theory : `") + token
+
317 "'. Try --use-theory=help.");
323 TheoryEngine
* d_theoryEngine
;
324 }; /* class UseTheoryListListener */
327 class SetDefaultExprDepthListener
: public Listener
{
329 void notify() override
331 int depth
= options::defaultExprDepth();
332 Debug
.getStream() << expr::ExprSetDepth(depth
);
333 Trace
.getStream() << expr::ExprSetDepth(depth
);
334 Notice
.getStream() << expr::ExprSetDepth(depth
);
335 Chat
.getStream() << expr::ExprSetDepth(depth
);
336 Message
.getStream() << expr::ExprSetDepth(depth
);
337 Warning
.getStream() << expr::ExprSetDepth(depth
);
338 // intentionally exclude Dump stream from this list
342 class SetDefaultExprDagListener
: public Listener
{
344 void notify() override
346 int dag
= options::defaultDagThresh();
347 Debug
.getStream() << expr::ExprDag(dag
);
348 Trace
.getStream() << expr::ExprDag(dag
);
349 Notice
.getStream() << expr::ExprDag(dag
);
350 Chat
.getStream() << expr::ExprDag(dag
);
351 Message
.getStream() << expr::ExprDag(dag
);
352 Warning
.getStream() << expr::ExprDag(dag
);
353 Dump
.getStream() << expr::ExprDag(dag
);
357 class SetPrintExprTypesListener
: public Listener
{
359 void notify() override
361 bool value
= options::printExprTypes();
362 Debug
.getStream() << expr::ExprPrintTypes(value
);
363 Trace
.getStream() << expr::ExprPrintTypes(value
);
364 Notice
.getStream() << expr::ExprPrintTypes(value
);
365 Chat
.getStream() << expr::ExprPrintTypes(value
);
366 Message
.getStream() << expr::ExprPrintTypes(value
);
367 Warning
.getStream() << expr::ExprPrintTypes(value
);
368 // intentionally exclude Dump stream from this list
372 class DumpModeListener
: public Listener
{
374 void notify() override
376 const std::string
& value
= options::dumpModeString();
377 Dump
.setDumpFromString(value
);
381 class PrintSuccessListener
: public Listener
{
383 void notify() override
385 bool value
= options::printSuccess();
386 Debug
.getStream() << Command::printsuccess(value
);
387 Trace
.getStream() << Command::printsuccess(value
);
388 Notice
.getStream() << Command::printsuccess(value
);
389 Chat
.getStream() << Command::printsuccess(value
);
390 Message
.getStream() << Command::printsuccess(value
);
391 Warning
.getStream() << Command::printsuccess(value
);
392 *options::out() << Command::printsuccess(value
);
399 * This is an inelegant solution, but for the present, it will work.
400 * The point of this is to separate the public and private portions of
401 * the SmtEngine class, so that smt_engine.h doesn't
402 * include "expr/node.h", which is a private CVC4 header (and can lead
403 * to linking errors due to the improper inlining of non-visible symbols
406 * The "real" solution (that which is usually implemented) is to move
407 * ALL the implementation to SmtEnginePrivate and maintain a
408 * heap-allocated instance of it in SmtEngine. SmtEngine (the public
409 * one) becomes an "interface shell" which simply acts as a forwarder
412 class SmtEnginePrivate
: public NodeManagerListener
{
415 typedef unordered_map
<Node
, Node
, NodeHashFunction
> NodeToNodeHashMap
;
416 typedef unordered_map
<Node
, bool, NodeHashFunction
> NodeToBoolHashMap
;
419 * Manager for limiting time and abstract resource usage.
421 ResourceManager
* d_resourceManager
;
423 /** Manager for the memory of regular-output-channel. */
424 ManagedRegularOutputChannel d_managedRegularChannel
;
426 /** Manager for the memory of diagnostic-output-channel. */
427 ManagedDiagnosticOutputChannel d_managedDiagnosticChannel
;
429 /** Manager for the memory of --dump-to. */
430 ManagedDumpOStream d_managedDumpChannel
;
432 /** Manager for --replay-log. */
433 ManagedReplayLogOstream d_managedReplayLog
;
436 * This list contains:
440 * beforeSearchListener
441 * UseTheoryListListener
443 * This needs to be deleted before both NodeManager's Options,
444 * SmtEngine, d_resourceManager, and TheoryEngine.
446 ListenerRegistrationList
* d_listenerRegistrations
;
448 /** A circuit propagator for non-clausal propositional deduction */
449 booleans::CircuitPropagator d_propagator
;
451 /** Assertions in the preprocessing pipeline */
452 AssertionPipeline d_assertions
;
454 /** Whether any assertions have been processed */
455 CDO
<bool> d_assertionsProcessed
;
461 * A context that never pushes/pops, for use by CD structures (like
462 * SubstitutionMaps) that should be "global".
464 context::Context d_fakeContext
;
467 * A map of AbsractValues to their actual constants. Only used if
468 * options::abstractValues() is on.
470 SubstitutionMap d_abstractValueMap
;
473 * A mapping of all abstract values (actual value |-> abstract) that
474 * we've handed out. This is necessary to ensure that we give the
475 * same AbstractValues for the same real constants. Only used if
476 * options::abstractValues() is on.
478 NodeToNodeHashMap d_abstractValues
;
480 /** Number of calls of simplify assertions active.
482 unsigned d_simplifyAssertionsDepth
;
484 /** TODO: whether certain preprocess steps are necessary */
485 //bool d_needsExpandDefs;
487 //------------------------------- expression names
488 /** mapping from expressions to name */
489 context::CDHashMap
< Node
, std::string
, NodeHashFunction
> d_exprNames
;
490 //------------------------------- end expression names
492 IteSkolemMap
& getIteSkolemMap() { return d_assertions
.getIteSkolemMap(); }
494 /** Instance of the ITE remover */
495 RemoveTermFormulas d_iteRemover
;
497 /* Finishes the initialization of the private portion of SMTEngine. */
501 std::unique_ptr
<PreprocessingPassContext
> d_preprocessingPassContext
;
504 * Map of preprocessing pass instances, mapping from names to preprocessing
507 std::unordered_map
<std::string
, std::unique_ptr
<PreprocessingPass
>> d_passes
;
510 * Helper function to fix up assertion list to restore invariants needed after
513 void collectSkolems(TNode n
, set
<TNode
>& skolemSet
, NodeToBoolHashMap
& cache
);
516 * Helper function to fix up assertion list to restore invariants needed after
519 bool checkForBadSkolems(TNode n
, TNode skolem
, NodeToBoolHashMap
& cache
);
522 * Perform non-clausal simplification of a Node. This involves
523 * Theory implementations, but does NOT involve the SAT solver in
526 * Returns false if the formula simplifies to "false"
528 bool simplifyAssertions();
531 SmtEnginePrivate(SmtEngine
& smt
)
533 d_managedRegularChannel(),
534 d_managedDiagnosticChannel(),
535 d_managedDumpChannel(),
536 d_managedReplayLog(),
537 d_listenerRegistrations(new ListenerRegistrationList()),
538 d_propagator(true, true),
540 d_assertionsProcessed(smt
.d_userContext
, false),
542 d_abstractValueMap(&d_fakeContext
),
544 d_simplifyAssertionsDepth(0),
545 // d_needsExpandDefs(true), //TODO?
546 d_exprNames(smt
.d_userContext
),
547 d_iteRemover(smt
.d_userContext
)
549 d_smt
.d_nodeManager
->subscribeEvents(this);
550 d_true
= NodeManager::currentNM()->mkConst(true);
551 d_resourceManager
= NodeManager::currentResourceManager();
553 d_listenerRegistrations
->add(d_resourceManager
->registerSoftListener(
554 new SoftResourceOutListener(d_smt
)));
556 d_listenerRegistrations
->add(d_resourceManager
->registerHardListener(
557 new HardResourceOutListener(d_smt
)));
559 Options
& nodeManagerOptions
= NodeManager::currentNM()->getOptions();
560 d_listenerRegistrations
->add(
561 nodeManagerOptions
.registerForceLogicListener(
562 new SetLogicListener(d_smt
), true));
564 // Multiple options reuse BeforeSearchListener so registration requires an
565 // extra bit of care.
566 // We can safely not call notify on this before search listener at
567 // registration time. This d_smt cannot be beforeSearch at construction
568 // time. Therefore the BeforeSearchListener is a no-op. Therefore it does
569 // not have to be called.
570 d_listenerRegistrations
->add(
571 nodeManagerOptions
.registerBeforeSearchListener(
572 new BeforeSearchListener(d_smt
)));
574 // These do need registration calls.
575 d_listenerRegistrations
->add(
576 nodeManagerOptions
.registerSetDefaultExprDepthListener(
577 new SetDefaultExprDepthListener(), true));
578 d_listenerRegistrations
->add(
579 nodeManagerOptions
.registerSetDefaultExprDagListener(
580 new SetDefaultExprDagListener(), true));
581 d_listenerRegistrations
->add(
582 nodeManagerOptions
.registerSetPrintExprTypesListener(
583 new SetPrintExprTypesListener(), true));
584 d_listenerRegistrations
->add(
585 nodeManagerOptions
.registerSetDumpModeListener(
586 new DumpModeListener(), true));
587 d_listenerRegistrations
->add(
588 nodeManagerOptions
.registerSetPrintSuccessListener(
589 new PrintSuccessListener(), true));
590 d_listenerRegistrations
->add(
591 nodeManagerOptions
.registerSetRegularOutputChannelListener(
592 new SetToDefaultSourceListener(&d_managedRegularChannel
), true));
593 d_listenerRegistrations
->add(
594 nodeManagerOptions
.registerSetDiagnosticOutputChannelListener(
595 new SetToDefaultSourceListener(&d_managedDiagnosticChannel
), true));
596 d_listenerRegistrations
->add(
597 nodeManagerOptions
.registerDumpToFileNameListener(
598 new SetToDefaultSourceListener(&d_managedDumpChannel
), true));
599 d_listenerRegistrations
->add(
600 nodeManagerOptions
.registerSetReplayLogFilename(
601 new SetToDefaultSourceListener(&d_managedReplayLog
), true));
606 delete d_listenerRegistrations
;
608 if(d_propagator
.getNeedsFinish()) {
609 d_propagator
.finish();
610 d_propagator
.setNeedsFinish(false);
612 d_smt
.d_nodeManager
->unsubscribeEvents(this);
615 void cleanupPreprocessingPasses() { d_passes
.clear(); }
617 ResourceManager
* getResourceManager() { return d_resourceManager
; }
618 void spendResource(unsigned amount
)
620 d_resourceManager
->spendResource(amount
);
623 void nmNotifyNewSort(TypeNode tn
, uint32_t flags
) override
625 DeclareTypeCommand
c(tn
.getAttribute(expr::VarNameAttr()),
628 if((flags
& ExprManager::SORT_FLAG_PLACEHOLDER
) == 0) {
629 d_smt
.addToModelCommandAndDump(c
, flags
);
633 void nmNotifyNewSortConstructor(TypeNode tn
, uint32_t flags
) override
635 DeclareTypeCommand
c(tn
.getAttribute(expr::VarNameAttr()),
636 tn
.getAttribute(expr::SortArityAttr()),
638 if ((flags
& ExprManager::SORT_FLAG_PLACEHOLDER
) == 0)
640 d_smt
.addToModelCommandAndDump(c
);
644 void nmNotifyNewDatatypes(const std::vector
<DatatypeType
>& dtts
,
645 uint32_t flags
) override
647 if ((flags
& ExprManager::DATATYPE_FLAG_PLACEHOLDER
) == 0)
649 DatatypeDeclarationCommand
c(dtts
);
650 d_smt
.addToModelCommandAndDump(c
);
654 void nmNotifyNewVar(TNode n
, uint32_t flags
) override
656 DeclareFunctionCommand
c(n
.getAttribute(expr::VarNameAttr()),
658 n
.getType().toType());
659 if((flags
& ExprManager::VAR_FLAG_DEFINED
) == 0) {
660 d_smt
.addToModelCommandAndDump(c
, flags
);
664 void nmNotifyNewSkolem(TNode n
,
665 const std::string
& comment
,
666 uint32_t flags
) override
668 string id
= n
.getAttribute(expr::VarNameAttr());
669 DeclareFunctionCommand
c(id
, n
.toExpr(), n
.getType().toType());
670 if(Dump
.isOn("skolems") && comment
!= "") {
671 Dump("skolems") << CommentCommand(id
+ " is " + comment
);
673 if((flags
& ExprManager::VAR_FLAG_DEFINED
) == 0) {
674 d_smt
.addToModelCommandAndDump(c
, flags
, false, "skolems");
678 void nmNotifyDeleteNode(TNode n
) override
{}
680 Node
applySubstitutions(TNode node
)
682 return Rewriter::rewrite(
683 d_preprocessingPassContext
->getTopLevelSubstitutions().apply(node
));
687 * Process the assertions that have been asserted.
689 void processAssertions();
691 /** Process a user push.
698 * Process a user pop. Clears out the non-context-dependent stuff in this
699 * SmtEnginePrivate. Necessary to clear out our assertion vectors in case
700 * someone does a push-assert-pop without a check-sat. It also pops the
701 * last map of expression names from notifyPush.
704 d_assertions
.clear();
705 d_propagator
.getLearnedLiterals().clear();
706 getIteSkolemMap().clear();
710 * Adds a formula to the current context. Action here depends on
711 * the SimplificationMode (in the current Options scope); the
712 * formula might be pushed out to the propositional layer
713 * immediately, or it might be simplified and kept, or it might not
714 * even be simplified.
715 * the 2nd and 3rd arguments added for bookkeeping for proofs
717 void addFormula(TNode n
, bool inUnsatCore
, bool inInput
= true);
719 /** Expand definitions in n. */
720 Node
expandDefinitions(TNode n
,
721 NodeToNodeHashMap
& cache
,
722 bool expandOnly
= false);
725 * Simplify node "in" by expanding definitions and applying any
726 * substitutions learned from preprocessing.
728 Node
simplify(TNode in
) {
729 // Substitute out any abstract values in ex.
730 // Expand definitions.
731 NodeToNodeHashMap cache
;
732 Node n
= expandDefinitions(in
, cache
).toExpr();
733 // Make sure we've done all preprocessing, etc.
734 Assert(d_assertions
.size() == 0);
735 return applySubstitutions(n
).toExpr();
739 * Substitute away all AbstractValues in a node.
741 Node
substituteAbstractValues(TNode n
) {
742 // We need to do this even if options::abstractValues() is off,
743 // since the setting might have changed after we already gave out
744 // some abstract values.
745 return d_abstractValueMap
.apply(n
);
749 * Make a new (or return an existing) abstract value for a node.
750 * Can only use this if options::abstractValues() is on.
752 Node
mkAbstractValue(TNode n
) {
753 Assert(options::abstractValues());
754 Node
& val
= d_abstractValues
[n
];
756 val
= d_smt
.d_nodeManager
->mkAbstractValue(n
.getType());
757 d_abstractValueMap
.addSubstitution(val
, n
);
759 // We are supposed to ascribe types to all abstract values that go out.
760 NodeManager
* current
= d_smt
.d_nodeManager
;
761 Node ascription
= current
->mkConst(AscriptionType(n
.getType().toType()));
762 Node retval
= current
->mkNode(kind::APPLY_TYPE_ASCRIPTION
, ascription
, val
);
766 void addUseTheoryListListener(TheoryEngine
* theoryEngine
){
767 Options
& nodeManagerOptions
= NodeManager::currentNM()->getOptions();
768 d_listenerRegistrations
->add(
769 nodeManagerOptions
.registerUseTheoryListListener(
770 new UseTheoryListListener(theoryEngine
), true));
773 std::ostream
* getReplayLog() const {
774 return d_managedReplayLog
.getReplayLog();
777 //------------------------------- expression names
778 // implements setExpressionName, as described in smt_engine.h
779 void setExpressionName(Expr e
, std::string name
) {
780 d_exprNames
[Node::fromExpr(e
)] = name
;
783 // implements getExpressionName, as described in smt_engine.h
784 bool getExpressionName(Expr e
, std::string
& name
) const {
785 context::CDHashMap
< Node
, std::string
, NodeHashFunction
>::const_iterator it
= d_exprNames
.find(e
);
786 if(it
!=d_exprNames
.end()) {
793 //------------------------------- end expression names
794 };/* class SmtEnginePrivate */
796 }/* namespace CVC4::smt */
798 SmtEngine::SmtEngine(ExprManager
* em
)
799 : d_context(new Context()),
801 d_userContext(new UserContext()),
803 d_nodeManager(d_exprManager
->getNodeManager()),
804 d_decisionEngine(NULL
),
805 d_theoryEngine(NULL
),
807 d_proofManager(NULL
),
808 d_definedFunctions(NULL
),
809 d_fmfRecFunctionsDefined(NULL
),
810 d_assertionList(NULL
),
812 d_modelGlobalCommands(),
813 d_modelCommands(NULL
),
819 d_fullyInited(false),
820 d_problemExtended(false),
822 d_needPostsolve(false),
823 d_earlyTheoryPP(true),
824 d_globalNegation(false),
826 d_replayStream(NULL
),
828 d_statisticsRegistry(NULL
),
830 d_channels(new LemmaChannels())
833 d_originalOptions
.copyValues(em
->getOptions());
834 d_private
= new smt::SmtEnginePrivate(*this);
835 d_statisticsRegistry
= new StatisticsRegistry();
836 d_stats
= new SmtEngineStatistics();
837 d_stats
->d_resourceUnitsUsed
.setData(
838 d_private
->getResourceManager()->getResourceUsage());
840 // The ProofManager is constructed before any other proof objects such as
841 // SatProof and TheoryProofs. The TheoryProofEngine and the SatProof are
842 // initialized in TheoryEngine and PropEngine respectively.
843 Assert(d_proofManager
== NULL
);
845 // d_proofManager must be created before Options has been finished
846 // being parsed from the input file. Because of this, we cannot trust
847 // that options::proof() is set correctly yet.
849 d_proofManager
= new ProofManager(d_userContext
);
852 // We have mutual dependency here, so we add the prop engine to the theory
853 // engine later (it is non-essential there)
854 d_theoryEngine
= new TheoryEngine(d_context
,
856 d_private
->d_iteRemover
,
857 const_cast<const LogicInfo
&>(d_logic
),
861 for(TheoryId id
= theory::THEORY_FIRST
; id
< theory::THEORY_LAST
; ++id
) {
862 TheoryConstructor::addTheory(d_theoryEngine
, id
);
863 //register with proof engine if applicable
865 ProofManager::currentPM()->getTheoryProofEngine()->registerTheory(d_theoryEngine
->theoryOf(id
));
869 d_private
->addUseTheoryListListener(d_theoryEngine
);
871 // global push/pop around everything, to ensure proper destruction
872 // of context-dependent data structures
873 d_userContext
->push();
876 d_definedFunctions
= new(true) DefinedFunctionMap(d_userContext
);
877 d_fmfRecFunctionsDefined
= new(true) NodeList(d_userContext
);
878 d_modelCommands
= new(true) smt::CommandList(d_userContext
);
881 void SmtEngine::finishInit() {
882 Trace("smt-debug") << "SmtEngine::finishInit" << std::endl
;
883 // ensure that our heuristics are properly set up
886 Trace("smt-debug") << "Making decision engine..." << std::endl
;
888 d_decisionEngine
= new DecisionEngine(d_context
, d_userContext
);
889 d_decisionEngine
->init(); // enable appropriate strategies
891 Trace("smt-debug") << "Making prop engine..." << std::endl
;
892 d_propEngine
= new PropEngine(d_theoryEngine
, d_decisionEngine
, d_context
,
893 d_userContext
, d_private
->getReplayLog(),
894 d_replayStream
, d_channels
);
896 Trace("smt-debug") << "Setting up theory engine..." << std::endl
;
897 d_theoryEngine
->setPropEngine(d_propEngine
);
898 d_theoryEngine
->setDecisionEngine(d_decisionEngine
);
899 Trace("smt-debug") << "Finishing init for theory engine..." << std::endl
;
900 d_theoryEngine
->finishInit();
902 Trace("smt-debug") << "Set up assertion list..." << std::endl
;
903 // [MGD 10/20/2011] keep around in incremental mode, due to a
904 // cleanup ordering issue and Nodes/TNodes. If SAT is popped
905 // first, some user-context-dependent TNodes might still exist
907 if(options::produceAssertions() ||
908 options::incrementalSolving()) {
909 // In the case of incremental solving, we appear to need these to
910 // ensure the relevant Nodes remain live.
911 d_assertionList
= new(true) AssertionList(d_userContext
);
914 // dump out a set-logic command
915 if(Dump
.isOn("benchmark")) {
916 if (Dump
.isOn("raw-benchmark")) {
917 Dump("raw-benchmark") << SetBenchmarkLogicCommand(d_logic
.getLogicString());
919 LogicInfo everything
;
921 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.")
922 << SetBenchmarkLogicCommand(everything
.getLogicString());
926 Trace("smt-debug") << "Dump declaration commands..." << std::endl
;
927 // dump out any pending declaration commands
928 for(unsigned i
= 0; i
< d_dumpCommands
.size(); ++i
) {
929 Dump("declarations") << *d_dumpCommands
[i
];
930 delete d_dumpCommands
[i
];
932 d_dumpCommands
.clear();
934 PROOF( ProofManager::currentPM()->setLogic(d_logic
); );
936 for(TheoryId id
= theory::THEORY_FIRST
; id
< theory::THEORY_LAST
; ++id
) {
937 ProofManager::currentPM()->getTheoryProofEngine()->
938 finishRegisterTheory(d_theoryEngine
->theoryOf(id
));
941 d_private
->finishInit();
942 Trace("smt-debug") << "SmtEngine::finishInit done" << std::endl
;
945 void SmtEngine::finalOptionsAreSet() {
950 if(! d_logic
.isLocked()) {
954 // finish initialization, create the prop engine, etc.
957 AlwaysAssert( d_propEngine
->getAssertionLevel() == 0,
958 "The PropEngine has pushed but the SmtEngine "
959 "hasn't finished initializing!" );
961 d_fullyInited
= true;
962 Assert(d_logic
.isLocked());
964 d_propEngine
->assertFormula(NodeManager::currentNM()->mkConst
<bool>(true));
965 d_propEngine
->assertFormula(NodeManager::currentNM()->mkConst
<bool>(false).notNode());
968 void SmtEngine::shutdown() {
971 while(options::incrementalSolving() && d_userContext
->getLevel() > 1) {
975 // check to see if a postsolve() is pending
976 if(d_needPostsolve
) {
977 d_theoryEngine
->postsolve();
978 d_needPostsolve
= false;
981 if(d_propEngine
!= NULL
) {
982 d_propEngine
->shutdown();
984 if(d_theoryEngine
!= NULL
) {
985 d_theoryEngine
->shutdown();
987 if(d_decisionEngine
!= NULL
) {
988 d_decisionEngine
->shutdown();
992 SmtEngine::~SmtEngine()
999 // global push/pop around everything, to ensure proper destruction
1000 // of context-dependent data structures
1001 d_context
->popto(0);
1002 d_userContext
->popto(0);
1004 if(d_assignments
!= NULL
) {
1005 d_assignments
->deleteSelf();
1008 if(d_assertionList
!= NULL
) {
1009 d_assertionList
->deleteSelf();
1012 for(unsigned i
= 0; i
< d_dumpCommands
.size(); ++i
) {
1013 delete d_dumpCommands
[i
];
1014 d_dumpCommands
[i
] = NULL
;
1016 d_dumpCommands
.clear();
1018 DeleteAndClearCommandVector(d_modelGlobalCommands
);
1020 if(d_modelCommands
!= NULL
) {
1021 d_modelCommands
->deleteSelf();
1024 d_definedFunctions
->deleteSelf();
1025 d_fmfRecFunctionsDefined
->deleteSelf();
1027 //destroy all passes before destroying things that they refer to
1028 d_private
->cleanupPreprocessingPasses();
1030 delete d_theoryEngine
;
1031 d_theoryEngine
= NULL
;
1032 delete d_propEngine
;
1033 d_propEngine
= NULL
;
1034 delete d_decisionEngine
;
1035 d_decisionEngine
= NULL
;
1038 // d_proofManager is always created when proofs are enabled at configure time.
1039 // Becuase of this, this code should not be wrapped in PROOF() which
1040 // additionally checks flags such as options::proof().
1042 delete d_proofManager
;
1043 d_proofManager
= NULL
;
1048 delete d_statisticsRegistry
;
1049 d_statisticsRegistry
= NULL
;
1054 delete d_userContext
;
1055 d_userContext
= NULL
;
1062 } catch(Exception
& e
) {
1063 Warning() << "CVC4 threw an exception during cleanup." << endl
1068 void SmtEngine::setLogic(const LogicInfo
& logic
)
1070 SmtScope
smts(this);
1072 throw ModalException("Cannot set logic in SmtEngine after the engine has "
1073 "finished initializing.");
1079 void SmtEngine::setLogic(const std::string
& s
)
1081 SmtScope
smts(this);
1083 setLogic(LogicInfo(s
));
1084 } catch(IllegalArgumentException
& e
) {
1085 throw LogicException(e
.what());
1089 void SmtEngine::setLogic(const char* logic
) { setLogic(string(logic
)); }
1090 LogicInfo
SmtEngine::getLogicInfo() const {
1093 void SmtEngine::setFilename(std::string filename
) { d_filename
= filename
; }
1094 std::string
SmtEngine::getFilename() const { return d_filename
; }
1095 void SmtEngine::setLogicInternal()
1097 Assert(!d_fullyInited
, "setting logic in SmtEngine but the engine has already"
1098 " finished initializing for this run");
1102 void SmtEngine::setDefaults() {
1103 Random::getRandom().setSeed(options::seed());
1104 // Language-based defaults
1105 if (!options::bitvectorDivByZeroConst
.wasSetByUser())
1107 // Bitvector-divide-by-zero changed semantics in SMT LIB 2.6, thus we
1108 // set this option if the input format is SMT LIB 2.6. We also set this
1109 // option if we are sygus, since we assume SMT LIB 2.6 semantics for sygus.
1110 options::bitvectorDivByZeroConst
.set(
1111 language::isInputLang_smt2_6(options::inputLanguage())
1112 || options::inputLanguage() == language::input::LANG_SYGUS
);
1114 bool is_sygus
= false;
1115 if (options::inputLanguage() == language::input::LANG_SYGUS
)
1118 if (!options::ceGuidedInst
.wasSetByUser())
1120 options::ceGuidedInst
.set(true);
1122 // must use Ferrante/Rackoff for real arithmetic
1123 if (!options::cbqiMidpoint
.wasSetByUser())
1125 options::cbqiMidpoint
.set(true);
1127 if (options::sygusRepairConst())
1129 if (!options::cbqi
.wasSetByUser())
1131 options::cbqi
.set(true);
1136 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER
)
1138 if (options::produceModels()
1139 && (d_logic
.isTheoryEnabled(THEORY_ARRAYS
)
1140 || d_logic
.isTheoryEnabled(THEORY_UF
)))
1142 if (options::bitblastMode
.wasSetByUser()
1143 || options::produceModels
.wasSetByUser())
1145 throw OptionException(std::string(
1146 "Eager bit-blasting currently does not support model generation "
1147 "for the combination of bit-vectors with arrays or uinterpreted "
1148 "functions. Try --bitblast=lazy"));
1150 Notice() << "SmtEngine: setting bit-blast mode to lazy to support model"
1151 << "generation" << endl
;
1152 setOption("bitblastMode", SExpr("lazy"));
1155 if (options::incrementalSolving() && !d_logic
.isPure(THEORY_BV
))
1157 throw OptionException(
1158 "Incremental eager bit-blasting is currently "
1159 "only supported for QF_BV. Try --bitblast=lazy.");
1163 if(options::forceLogicString
.wasSetByUser()) {
1164 d_logic
= LogicInfo(options::forceLogicString());
1165 }else if (options::solveIntAsBV() > 0) {
1166 d_logic
= LogicInfo("QF_BV");
1167 }else if (d_logic
.getLogicString() == "QF_NRA" && options::solveRealAsInt()) {
1168 d_logic
= LogicInfo("QF_NIA");
1169 } else if ((d_logic
.getLogicString() == "QF_UFBV" ||
1170 d_logic
.getLogicString() == "QF_ABV") &&
1171 options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER
) {
1172 d_logic
= LogicInfo("QF_BV");
1176 /* - disabled for 1.4 release [MGD 2014.06.25]
1177 if(!d_logic.hasEverything() && d_logic.isTheoryEnabled(THEORY_STRINGS) ) {
1178 if(! options::stringExp.wasSetByUser()) {
1179 options::stringExp.set( true );
1180 Trace("smt") << "turning on strings-exp, for the theory of strings" << std::endl;
1185 if(options::stringExp()) {
1186 if( !d_logic
.isQuantified() ) {
1187 d_logic
= d_logic
.getUnlockedCopy();
1188 d_logic
.enableQuantifiers();
1190 Trace("smt") << "turning on quantifier logic, for strings-exp"
1193 if(! options::fmfBound
.wasSetByUser()) {
1194 options::fmfBound
.set( true );
1195 Trace("smt") << "turning on fmf-bound-int, for strings-exp" << std::endl
;
1197 if(! options::fmfInstEngine
.wasSetByUser()) {
1198 options::fmfInstEngine
.set( true );
1199 Trace("smt") << "turning on fmf-inst-engine, for strings-exp" << std::endl
;
1202 if(! options::rewriteDivk.wasSetByUser()) {
1203 options::rewriteDivk.set( true );
1204 Trace("smt") << "turning on rewrite-divk, for strings-exp" << std::endl;
1207 if(! options::stringFMF.wasSetByUser()) {
1208 options::stringFMF.set( true );
1209 Trace("smt") << "turning on strings-fmf, for strings-exp" << std::endl;
1214 // sygus inference may require datatypes
1215 if (options::sygusInference())
1217 d_logic
= d_logic
.getUnlockedCopy();
1218 d_logic
.enableTheory(THEORY_DATATYPES
);
1220 // since we are trying to recast as sygus, we assume the input is sygus
1224 if ((options::checkModels() || options::checkSynthSol()
1225 || options::produceModelCores())
1226 && !options::produceAssertions())
1228 Notice() << "SmtEngine: turning on produce-assertions to support "
1229 << "check-models, check-synth-sol or produce-model-cores." << endl
;
1230 setOption("produce-assertions", SExpr("true"));
1233 // Disable options incompatible with incremental solving, unsat cores, and
1234 // proofs or output an error if enabled explicitly
1235 if (options::incrementalSolving() || options::unsatCores()
1236 || options::proof())
1238 if (options::unconstrainedSimp())
1240 if (options::unconstrainedSimp
.wasSetByUser())
1242 throw OptionException(
1243 "unconstrained simplification not supported with unsat "
1244 "cores/proofs/incremental solving");
1246 Notice() << "SmtEngine: turning off unconstrained simplification to "
1247 "support unsat cores/proofs/incremental solving"
1249 options::unconstrainedSimp
.set(false);
1254 // Turn on unconstrained simplification for QF_AUFBV
1255 if (!options::unconstrainedSimp
.wasSetByUser())
1257 // bool qf_sat = d_logic.isPure(THEORY_BOOL) &&
1258 // !d_logic.isQuantified(); bool uncSimp = false && !qf_sat &&
1259 // !options::incrementalSolving();
1260 bool uncSimp
= !d_logic
.isQuantified() && !options::produceModels()
1261 && !options::produceAssignments()
1262 && !options::checkModels()
1263 && (d_logic
.isTheoryEnabled(THEORY_ARRAYS
)
1264 && d_logic
.isTheoryEnabled(THEORY_BV
));
1265 Trace("smt") << "setting unconstrained simplification to " << uncSimp
1267 options::unconstrainedSimp
.set(uncSimp
);
1271 // Disable options incompatible with unsat cores and proofs or output an
1272 // error if enabled explicitly
1273 if (options::unsatCores() || options::proof())
1275 if (options::simplificationMode() != SIMPLIFICATION_MODE_NONE
)
1277 if (options::simplificationMode
.wasSetByUser())
1279 throw OptionException(
1280 "simplification not supported with unsat cores/proofs");
1282 Notice() << "SmtEngine: turning off simplification to support unsat "
1285 options::simplificationMode
.set(SIMPLIFICATION_MODE_NONE
);
1288 if (options::pbRewrites())
1290 if (options::pbRewrites
.wasSetByUser())
1292 throw OptionException(
1293 "pseudoboolean rewrites not supported with unsat cores/proofs");
1295 Notice() << "SmtEngine: turning off pseudoboolean rewrites to support "
1296 "unsat cores/proofs"
1298 setOption("pb-rewrites", false);
1301 if (options::sortInference())
1303 if (options::sortInference
.wasSetByUser())
1305 throw OptionException(
1306 "sort inference not supported with unsat cores/proofs");
1308 Notice() << "SmtEngine: turning off sort inference to support unsat "
1311 options::sortInference
.set(false);
1314 if (options::preSkolemQuant())
1316 if (options::preSkolemQuant
.wasSetByUser())
1318 throw OptionException(
1319 "pre-skolemization not supported with unsat cores/proofs");
1321 Notice() << "SmtEngine: turning off pre-skolemization to support unsat "
1324 options::preSkolemQuant
.set(false);
1327 if (options::bitvectorToBool())
1329 if (options::bitvectorToBool
.wasSetByUser())
1331 throw OptionException(
1332 "bv-to-bool not supported with unsat cores/proofs");
1334 Notice() << "SmtEngine: turning off bitvector-to-bool to support unsat "
1337 options::bitvectorToBool
.set(false);
1340 if (options::boolToBitvector())
1342 if (options::boolToBitvector
.wasSetByUser())
1344 throw OptionException(
1345 "bool-to-bv not supported with unsat cores/proofs");
1347 Notice() << "SmtEngine: turning off bool-to-bitvector to support unsat "
1350 options::boolToBitvector
.set(false);
1353 if (options::bvIntroducePow2())
1355 if (options::bvIntroducePow2
.wasSetByUser())
1357 throw OptionException(
1358 "bv-intro-pow2 not supported with unsat cores/proofs");
1360 Notice() << "SmtEngine: turning off bv-intro-pow2 to support "
1361 "unsat-cores/proofs"
1363 setOption("bv-intro-pow2", false);
1366 if (options::repeatSimp())
1368 if (options::repeatSimp
.wasSetByUser())
1370 throw OptionException(
1371 "repeat-simp not supported with unsat cores/proofs");
1373 Notice() << "SmtEngine: turning off repeat-simp to support unsat "
1376 setOption("repeat-simp", false);
1379 if (options::globalNegate())
1381 if (options::globalNegate
.wasSetByUser())
1383 throw OptionException(
1384 "global-negate not supported with unsat cores/proofs");
1386 Notice() << "SmtEngine: turning off global-negate to support unsat "
1389 setOption("global-negate", false);
1394 // by default, nonclausal simplification is off for QF_SAT
1395 if (!options::simplificationMode
.wasSetByUser())
1397 bool qf_sat
= d_logic
.isPure(THEORY_BOOL
) && !d_logic
.isQuantified();
1398 Trace("smt") << "setting simplification mode to <"
1399 << d_logic
.getLogicString() << "> " << (!qf_sat
) << endl
;
1400 // simplification=none works better for SMT LIB benchmarks with
1401 // quantifiers, not others options::simplificationMode.set(qf_sat ||
1402 // quantifiers ? SIMPLIFICATION_MODE_NONE : SIMPLIFICATION_MODE_BATCH);
1403 options::simplificationMode
.set(qf_sat
? SIMPLIFICATION_MODE_NONE
1404 : SIMPLIFICATION_MODE_BATCH
);
1408 if (options::cbqiBv() && d_logic
.isQuantified())
1410 if(options::boolToBitvector
.wasSetByUser()) {
1411 throw OptionException(
1412 "bool-to-bv not supported with CBQI BV for quantified logics");
1414 Notice() << "SmtEngine: turning off bool-to-bitvector to support CBQI BV"
1416 options::boolToBitvector
.set(false);
1419 // cases where we need produce models
1420 if (!options::produceModels()
1421 && (options::produceAssignments() || options::sygusRewSynthCheck()
1422 || options::produceModelCores() || is_sygus
))
1424 Notice() << "SmtEngine: turning on produce-models" << endl
;
1425 setOption("produce-models", SExpr("true"));
1428 // Set the options for the theoryOf
1429 if(!options::theoryOfMode
.wasSetByUser()) {
1430 if(d_logic
.isSharingEnabled() &&
1431 !d_logic
.isTheoryEnabled(THEORY_BV
) &&
1432 !d_logic
.isTheoryEnabled(THEORY_STRINGS
) &&
1433 !d_logic
.isTheoryEnabled(THEORY_SETS
) ) {
1434 Trace("smt") << "setting theoryof-mode to term-based" << endl
;
1435 options::theoryOfMode
.set(THEORY_OF_TERM_BASED
);
1439 // strings require LIA, UF; widen the logic
1440 if(d_logic
.isTheoryEnabled(THEORY_STRINGS
)) {
1441 LogicInfo
log(d_logic
.getUnlockedCopy());
1442 // Strings requires arith for length constraints, and also UF
1443 if(!d_logic
.isTheoryEnabled(THEORY_UF
)) {
1444 Trace("smt") << "because strings are enabled, also enabling UF" << endl
;
1445 log
.enableTheory(THEORY_UF
);
1447 if(!d_logic
.isTheoryEnabled(THEORY_ARITH
) || d_logic
.isDifferenceLogic() || !d_logic
.areIntegersUsed()) {
1448 Trace("smt") << "because strings are enabled, also enabling linear integer arithmetic" << endl
;
1449 log
.enableTheory(THEORY_ARITH
);
1450 log
.enableIntegers();
1451 log
.arithOnlyLinear();
1456 if(d_logic
.isTheoryEnabled(THEORY_ARRAYS
) || d_logic
.isTheoryEnabled(THEORY_DATATYPES
) || d_logic
.isTheoryEnabled(THEORY_SETS
)) {
1457 if(!d_logic
.isTheoryEnabled(THEORY_UF
)) {
1458 LogicInfo
log(d_logic
.getUnlockedCopy());
1459 Trace("smt") << "because a theory that permits Boolean terms is enabled, also enabling UF" << endl
;
1460 log
.enableTheory(THEORY_UF
);
1466 // by default, symmetry breaker is on only for non-incremental QF_UF
1467 if(! options::ufSymmetryBreaker
.wasSetByUser()) {
1468 bool qf_uf_noinc
= d_logic
.isPure(THEORY_UF
) && !d_logic
.isQuantified()
1469 && !options::incrementalSolving() && !options::proof()
1470 && !options::unsatCores();
1471 Trace("smt") << "setting uf symmetry breaker to " << qf_uf_noinc
<< endl
;
1472 options::ufSymmetryBreaker
.set(qf_uf_noinc
);
1475 // If in arrays, set the UF handler to arrays
1476 if(d_logic
.isTheoryEnabled(THEORY_ARRAYS
) && ( !d_logic
.isQuantified() ||
1477 (d_logic
.isQuantified() && !d_logic
.isTheoryEnabled(THEORY_UF
)))) {
1478 Theory::setUninterpretedSortOwner(THEORY_ARRAYS
);
1480 Theory::setUninterpretedSortOwner(THEORY_UF
);
1483 // Turn on ite simplification for QF_LIA and QF_AUFBV
1484 // WARNING: These checks match much more than just QF_AUFBV and
1485 // QF_LIA logics. --K [2014/10/15]
1486 if(! options::doITESimp
.wasSetByUser()) {
1487 bool qf_aufbv
= !d_logic
.isQuantified() &&
1488 d_logic
.isTheoryEnabled(THEORY_ARRAYS
) &&
1489 d_logic
.isTheoryEnabled(THEORY_UF
) &&
1490 d_logic
.isTheoryEnabled(THEORY_BV
);
1491 bool qf_lia
= !d_logic
.isQuantified() &&
1492 d_logic
.isPure(THEORY_ARITH
) &&
1493 d_logic
.isLinear() &&
1494 !d_logic
.isDifferenceLogic() &&
1495 !d_logic
.areRealsUsed();
1497 bool iteSimp
= (qf_aufbv
|| qf_lia
);
1498 Trace("smt") << "setting ite simplification to " << iteSimp
<< endl
;
1499 options::doITESimp
.set(iteSimp
);
1501 if(! options::compressItes
.wasSetByUser() ){
1502 bool qf_lia
= !d_logic
.isQuantified() &&
1503 d_logic
.isPure(THEORY_ARITH
) &&
1504 d_logic
.isLinear() &&
1505 !d_logic
.isDifferenceLogic() &&
1506 !d_logic
.areRealsUsed();
1508 bool compressIte
= qf_lia
;
1509 Trace("smt") << "setting ite compression to " << compressIte
<< endl
;
1510 options::compressItes
.set(compressIte
);
1512 if(! options::simplifyWithCareEnabled
.wasSetByUser() ){
1513 bool qf_aufbv
= !d_logic
.isQuantified() &&
1514 d_logic
.isTheoryEnabled(THEORY_ARRAYS
) &&
1515 d_logic
.isTheoryEnabled(THEORY_UF
) &&
1516 d_logic
.isTheoryEnabled(THEORY_BV
);
1518 bool withCare
= qf_aufbv
;
1519 Trace("smt") << "setting ite simplify with care to " << withCare
<< endl
;
1520 options::simplifyWithCareEnabled
.set(withCare
);
1522 // Turn off array eager index splitting for QF_AUFLIA
1523 if(! options::arraysEagerIndexSplitting
.wasSetByUser()) {
1524 if (not d_logic
.isQuantified() &&
1525 d_logic
.isTheoryEnabled(THEORY_ARRAYS
) &&
1526 d_logic
.isTheoryEnabled(THEORY_UF
) &&
1527 d_logic
.isTheoryEnabled(THEORY_ARITH
)) {
1528 Trace("smt") << "setting array eager index splitting to false" << endl
;
1529 options::arraysEagerIndexSplitting
.set(false);
1532 // Turn on model-based arrays for QF_AX (unless models are enabled)
1533 // if(! options::arraysModelBased.wasSetByUser()) {
1534 // if (not d_logic.isQuantified() &&
1535 // d_logic.isTheoryEnabled(THEORY_ARRAYS) &&
1536 // d_logic.isPure(THEORY_ARRAYS) &&
1537 // !options::produceModels() &&
1538 // !options::checkModels()) {
1539 // Trace("smt") << "turning on model-based array solver" << endl;
1540 // options::arraysModelBased.set(true);
1543 // Turn on multiple-pass non-clausal simplification for QF_AUFBV
1544 if(! options::repeatSimp
.wasSetByUser()) {
1545 bool repeatSimp
= !d_logic
.isQuantified() &&
1546 (d_logic
.isTheoryEnabled(THEORY_ARRAYS
) &&
1547 d_logic
.isTheoryEnabled(THEORY_UF
) &&
1548 d_logic
.isTheoryEnabled(THEORY_BV
)) &&
1549 !options::unsatCores();
1550 Trace("smt") << "setting repeat simplification to " << repeatSimp
<< endl
;
1551 options::repeatSimp
.set(repeatSimp
);
1553 // Unconstrained simp currently does *not* support model generation
1554 if (options::unconstrainedSimp
.wasSetByUser() && options::unconstrainedSimp()) {
1555 if (options::produceModels()) {
1556 if (options::produceModels
.wasSetByUser()) {
1557 throw OptionException("Cannot use unconstrained-simp with model generation.");
1559 Notice() << "SmtEngine: turning off produce-models to support unconstrainedSimp" << endl
;
1560 setOption("produce-models", SExpr("false"));
1562 if (options::produceAssignments()) {
1563 if (options::produceAssignments
.wasSetByUser()) {
1564 throw OptionException("Cannot use unconstrained-simp with model generation (produce-assignments).");
1566 Notice() << "SmtEngine: turning off produce-assignments to support unconstrainedSimp" << endl
;
1567 setOption("produce-assignments", SExpr("false"));
1569 if (options::checkModels()) {
1570 if (options::checkModels
.wasSetByUser()) {
1571 throw OptionException("Cannot use unconstrained-simp with model generation (check-models).");
1573 Notice() << "SmtEngine: turning off check-models to support unconstrainedSimp" << endl
;
1574 setOption("check-models", SExpr("false"));
1578 if (! options::bvEagerExplanations
.wasSetByUser() &&
1579 d_logic
.isTheoryEnabled(THEORY_ARRAYS
) &&
1580 d_logic
.isTheoryEnabled(THEORY_BV
)) {
1581 Trace("smt") << "enabling eager bit-vector explanations " << endl
;
1582 options::bvEagerExplanations
.set(true);
1585 // Turn on arith rewrite equalities only for pure arithmetic
1586 if(! options::arithRewriteEq
.wasSetByUser()) {
1587 bool arithRewriteEq
= d_logic
.isPure(THEORY_ARITH
) && d_logic
.isLinear() && !d_logic
.isQuantified();
1588 Trace("smt") << "setting arith rewrite equalities " << arithRewriteEq
<< endl
;
1589 options::arithRewriteEq
.set(arithRewriteEq
);
1591 if(! options::arithHeuristicPivots
.wasSetByUser()) {
1592 int16_t heuristicPivots
= 5;
1593 if(d_logic
.isPure(THEORY_ARITH
) && !d_logic
.isQuantified()) {
1594 if(d_logic
.isDifferenceLogic()) {
1595 heuristicPivots
= -1;
1596 } else if(!d_logic
.areIntegersUsed()) {
1597 heuristicPivots
= 0;
1600 Trace("smt") << "setting arithHeuristicPivots " << heuristicPivots
<< endl
;
1601 options::arithHeuristicPivots
.set(heuristicPivots
);
1603 if(! options::arithPivotThreshold
.wasSetByUser()){
1604 uint16_t pivotThreshold
= 2;
1605 if(d_logic
.isPure(THEORY_ARITH
) && !d_logic
.isQuantified()){
1606 if(d_logic
.isDifferenceLogic()){
1607 pivotThreshold
= 16;
1610 Trace("smt") << "setting arith arithPivotThreshold " << pivotThreshold
<< endl
;
1611 options::arithPivotThreshold
.set(pivotThreshold
);
1613 if(! options::arithStandardCheckVarOrderPivots
.wasSetByUser()){
1614 int16_t varOrderPivots
= -1;
1615 if(d_logic
.isPure(THEORY_ARITH
) && !d_logic
.isQuantified()){
1616 varOrderPivots
= 200;
1618 Trace("smt") << "setting arithStandardCheckVarOrderPivots " << varOrderPivots
<< endl
;
1619 options::arithStandardCheckVarOrderPivots
.set(varOrderPivots
);
1621 // Turn off early theory preprocessing if arithRewriteEq is on
1622 if (options::arithRewriteEq()) {
1623 d_earlyTheoryPP
= false;
1625 if (d_logic
.isPure(THEORY_ARITH
) && !d_logic
.areRealsUsed())
1627 if (!options::nlExtTangentPlanesInterleave
.wasSetByUser())
1629 Trace("smt") << "setting nlExtTangentPlanesInterleave to true" << endl
;
1630 options::nlExtTangentPlanesInterleave
.set(true);
1634 // Set decision mode based on logic (if not set by user)
1635 if(!options::decisionMode
.wasSetByUser()) {
1636 decision::DecisionMode decMode
=
1637 // sygus uses internal
1638 is_sygus
? decision::DECISION_STRATEGY_INTERNAL
:
1640 d_logic
.hasEverything()
1641 ? decision::DECISION_STRATEGY_JUSTIFICATION
1643 (not d_logic
.isQuantified() && d_logic
.isPure(THEORY_BV
))
1645 // QF_AUFBV or QF_ABV or QF_UFBV
1646 (not d_logic
.isQuantified()
1647 && (d_logic
.isTheoryEnabled(THEORY_ARRAYS
)
1648 || d_logic
.isTheoryEnabled(THEORY_UF
))
1649 && d_logic
.isTheoryEnabled(THEORY_BV
))
1651 // QF_AUFLIA (and may be ends up enabling
1653 (not d_logic
.isQuantified()
1654 && d_logic
.isTheoryEnabled(THEORY_ARRAYS
)
1655 && d_logic
.isTheoryEnabled(THEORY_UF
)
1656 && d_logic
.isTheoryEnabled(THEORY_ARITH
))
1659 (not d_logic
.isQuantified()
1660 && d_logic
.isPure(THEORY_ARITH
)
1661 && d_logic
.isLinear()
1662 && !d_logic
.isDifferenceLogic()
1663 && !d_logic
.areIntegersUsed())
1666 d_logic
.isQuantified() ||
1668 d_logic
.isTheoryEnabled(THEORY_STRINGS
)
1669 ? decision::DECISION_STRATEGY_JUSTIFICATION
1670 : decision::DECISION_STRATEGY_INTERNAL
);
1674 d_logic
.hasEverything() || d_logic
.isTheoryEnabled(THEORY_STRINGS
) ? false :
1676 (not d_logic
.isQuantified() &&
1677 d_logic
.isTheoryEnabled(THEORY_ARRAYS
) &&
1678 d_logic
.isTheoryEnabled(THEORY_UF
) &&
1679 d_logic
.isTheoryEnabled(THEORY_ARITH
)
1682 (not d_logic
.isQuantified() &&
1683 d_logic
.isPure(THEORY_ARITH
) && d_logic
.isLinear() && !d_logic
.isDifferenceLogic() && !d_logic
.areIntegersUsed()
1688 Trace("smt") << "setting decision mode to " << decMode
<< endl
;
1689 options::decisionMode
.set(decMode
);
1690 options::decisionStopOnly
.set(stoponly
);
1692 if( options::incrementalSolving() ){
1693 //disable modes not supported by incremental
1694 options::sortInference
.set( false );
1695 options::ufssFairnessMonotone
.set( false );
1696 options::quantEpr
.set( false );
1697 options::globalNegate
.set(false);
1699 if( d_logic
.hasCardinalityConstraints() ){
1700 //must have finite model finding on
1701 options::finiteModelFind
.set( true );
1704 //if it contains a theory with non-termination, do not strictly enforce that quantifiers and theory combination must be interleaved
1705 if( d_logic
.isTheoryEnabled(THEORY_STRINGS
) || (d_logic
.isTheoryEnabled(THEORY_ARITH
) && !d_logic
.isLinear()) ){
1706 if( !options::instWhenStrictInterleave
.wasSetByUser() ){
1707 options::instWhenStrictInterleave
.set( false );
1711 //local theory extensions
1712 if( options::localTheoryExt() ){
1713 if( !options::instMaxLevel
.wasSetByUser() ){
1714 options::instMaxLevel
.set( 0 );
1717 if( options::instMaxLevel()!=-1 ){
1718 Notice() << "SmtEngine: turning off cbqi to support instMaxLevel" << endl
;
1719 options::cbqi
.set(false);
1721 //track instantiations?
1722 if( options::cbqiNestedQE() || ( options::proof() && !options::trackInstLemmas
.wasSetByUser() ) ){
1723 options::trackInstLemmas
.set( true );
1726 if( ( options::fmfBoundLazy
.wasSetByUser() && options::fmfBoundLazy() ) ||
1727 ( options::fmfBoundInt
.wasSetByUser() && options::fmfBoundInt() ) ) {
1728 options::fmfBound
.set( true );
1730 //now have determined whether fmfBoundInt is on/off
1731 //apply fmfBoundInt options
1732 if( options::fmfBound() ){
1733 //must have finite model finding on
1734 options::finiteModelFind
.set( true );
1735 if (!options::mbqiMode
.wasSetByUser()
1736 || (options::mbqiMode() != quantifiers::MBQI_NONE
1737 && options::mbqiMode() != quantifiers::MBQI_FMC
))
1739 //if bounded integers are set, use no MBQI by default
1740 options::mbqiMode
.set( quantifiers::MBQI_NONE
);
1742 if( ! options::prenexQuant
.wasSetByUser() ){
1743 options::prenexQuant
.set( quantifiers::PRENEX_QUANT_NONE
);
1746 if( options::ufHo() ){
1747 //if higher-order, then current variants of model-based instantiation cannot be used
1748 if( options::mbqiMode()!=quantifiers::MBQI_NONE
){
1749 options::mbqiMode
.set( quantifiers::MBQI_NONE
);
1752 if( options::mbqiMode()==quantifiers::MBQI_ABS
){
1753 if( !d_logic
.isPure(THEORY_UF
) ){
1754 //MBQI_ABS is only supported in pure quantified UF
1755 options::mbqiMode
.set( quantifiers::MBQI_FMC
);
1758 if( options::fmfFunWellDefinedRelevant() ){
1759 if( !options::fmfFunWellDefined
.wasSetByUser() ){
1760 options::fmfFunWellDefined
.set( true );
1763 if( options::fmfFunWellDefined() ){
1764 if( !options::finiteModelFind
.wasSetByUser() ){
1765 options::finiteModelFind
.set( true );
1769 if( options::quantEpr() ){
1770 if( !options::preSkolemQuant
.wasSetByUser() ){
1771 options::preSkolemQuant
.set( true );
1775 //now, have determined whether finite model find is on/off
1776 //apply finite model finding options
1777 if( options::finiteModelFind() ){
1778 //apply conservative quantifiers splitting
1779 if( !options::quantDynamicSplit
.wasSetByUser() ){
1780 options::quantDynamicSplit
.set( quantifiers::QUANT_DSPLIT_MODE_DEFAULT
);
1782 //do not eliminate extended arithmetic symbols from quantified formulas
1783 if( !options::elimExtArithQuant
.wasSetByUser() ){
1784 options::elimExtArithQuant
.set( false );
1786 if( !options::eMatching
.wasSetByUser() ){
1787 options::eMatching
.set( options::fmfInstEngine() );
1789 if( !options::instWhenMode
.wasSetByUser() ){
1790 //instantiate only on last call
1791 if( options::eMatching() ){
1792 options::instWhenMode
.set( quantifiers::INST_WHEN_LAST_CALL
);
1795 if( options::mbqiMode()==quantifiers::MBQI_ABS
){
1796 if( !options::preSkolemQuant
.wasSetByUser() ){
1797 options::preSkolemQuant
.set( true );
1799 if( !options::preSkolemQuantNested
.wasSetByUser() ){
1800 options::preSkolemQuantNested
.set( true );
1802 if( !options::fmfOneInstPerRound
.wasSetByUser() ){
1803 options::fmfOneInstPerRound
.set( true );
1808 //apply counterexample guided instantiation options
1809 // if we are attempting to rewrite everything to SyGuS, use ceGuidedInst
1810 if (options::sygusInference())
1812 if (!options::ceGuidedInst
.wasSetByUser())
1814 options::ceGuidedInst
.set(true);
1816 // optimization: apply preskolemization, makes it succeed more often
1817 if (!options::preSkolemQuant
.wasSetByUser())
1819 options::preSkolemQuant
.set(true);
1821 if (!options::preSkolemQuantNested
.wasSetByUser())
1823 options::preSkolemQuantNested
.set(true);
1826 if( options::cegqiSingleInvMode()!=quantifiers::CEGQI_SI_MODE_NONE
){
1827 if( !options::ceGuidedInst
.wasSetByUser() ){
1828 options::ceGuidedInst
.set( true );
1831 // if sygus is enabled, set the defaults for sygus
1832 if( options::ceGuidedInst() ){
1833 //counterexample-guided instantiation for sygus
1834 if( !options::cegqiSingleInvMode
.wasSetByUser() ){
1835 options::cegqiSingleInvMode
.set( quantifiers::CEGQI_SI_MODE_USE
);
1837 if( !options::quantConflictFind
.wasSetByUser() ){
1838 options::quantConflictFind
.set( false );
1840 if( !options::instNoEntail
.wasSetByUser() ){
1841 options::instNoEntail
.set( false );
1843 if (!options::cbqiFullEffort
.wasSetByUser())
1845 // should use full effort cbqi for single invocation and repair const
1846 options::cbqiFullEffort
.set(true);
1848 if (options::sygusRew())
1850 options::sygusRewSynth
.set(true);
1851 options::sygusRewVerify
.set(true);
1853 if (options::sygusRewSynth() || options::sygusRewVerify())
1855 // rewrite rule synthesis implies that sygus stream must be true
1856 options::sygusStream
.set(true);
1858 if (options::sygusStream())
1860 // PBE and streaming modes are incompatible
1861 if (!options::sygusSymBreakPbe
.wasSetByUser())
1863 options::sygusSymBreakPbe
.set(false);
1865 if (!options::sygusUnifPbe
.wasSetByUser())
1867 options::sygusUnifPbe
.set(false);
1870 //do not allow partial functions
1871 if( !options::bitvectorDivByZeroConst
.wasSetByUser() ){
1872 options::bitvectorDivByZeroConst
.set( true );
1874 if( !options::dtRewriteErrorSel
.wasSetByUser() ){
1875 options::dtRewriteErrorSel
.set( true );
1878 if( !options::miniscopeQuant
.wasSetByUser() ){
1879 options::miniscopeQuant
.set( false );
1881 if( !options::miniscopeQuantFreeVar
.wasSetByUser() ){
1882 options::miniscopeQuantFreeVar
.set( false );
1884 if (!options::quantSplit
.wasSetByUser())
1886 options::quantSplit
.set(false);
1889 if( !options::rewriteDivk
.wasSetByUser()) {
1890 options::rewriteDivk
.set( true );
1893 if( !options::macrosQuant
.wasSetByUser()) {
1894 options::macrosQuant
.set( false );
1896 if( !options::cbqiPreRegInst
.wasSetByUser()) {
1897 options::cbqiPreRegInst
.set( true );
1900 //counterexample-guided instantiation for non-sygus
1901 // enable if any possible quantifiers with arithmetic, datatypes or bitvectors
1902 if ((d_logic
.isQuantified()
1903 && (d_logic
.isTheoryEnabled(THEORY_ARITH
)
1904 || d_logic
.isTheoryEnabled(THEORY_DATATYPES
)
1905 || d_logic
.isTheoryEnabled(THEORY_BV
)
1906 || d_logic
.isTheoryEnabled(THEORY_FP
)))
1907 || options::cbqiAll())
1909 if( !options::cbqi
.wasSetByUser() ){
1910 options::cbqi
.set( true );
1912 // check whether we should apply full cbqi
1913 if (d_logic
.isPure(THEORY_BV
))
1915 if (!options::cbqiFullEffort
.wasSetByUser())
1917 options::cbqiFullEffort
.set(true);
1921 if( options::cbqi() ){
1923 if( !options::rewriteDivk
.wasSetByUser()) {
1924 options::rewriteDivk
.set( true );
1926 if (options::incrementalSolving())
1928 // cannot do nested quantifier elimination in incremental mode
1929 options::cbqiNestedQE
.set(false);
1931 if (d_logic
.isPure(THEORY_ARITH
) || d_logic
.isPure(THEORY_BV
))
1933 if( !options::quantConflictFind
.wasSetByUser() ){
1934 options::quantConflictFind
.set( false );
1936 if( !options::instNoEntail
.wasSetByUser() ){
1937 options::instNoEntail
.set( false );
1939 if( !options::instWhenMode
.wasSetByUser() && options::cbqiModel() ){
1940 //only instantiation should happen at last call when model is avaiable
1941 options::instWhenMode
.set( quantifiers::INST_WHEN_LAST_CALL
);
1944 // only supported in pure arithmetic or pure BV
1945 options::cbqiNestedQE
.set(false);
1948 if (options::cbqiNestedQE())
1950 // only complete with prenex = disj_normal or normal
1951 if (options::prenexQuant() <= quantifiers::PRENEX_QUANT_DISJ_NORMAL
)
1953 options::prenexQuant
.set(quantifiers::PRENEX_QUANT_DISJ_NORMAL
);
1956 else if (options::globalNegate())
1958 if (!options::prenexQuant
.wasSetByUser())
1960 options::prenexQuant
.set(quantifiers::PRENEX_QUANT_NONE
);
1964 //implied options...
1965 if( options::strictTriggers() ){
1966 if( !options::userPatternsQuant
.wasSetByUser() ){
1967 options::userPatternsQuant
.set( quantifiers::USER_PAT_MODE_TRUST
);
1970 if( options::qcfMode
.wasSetByUser() || options::qcfTConstraint() ){
1971 options::quantConflictFind
.set( true );
1973 if( options::cbqiNestedQE() ){
1974 options::prenexQuantUser
.set( true );
1975 if( !options::preSkolemQuant
.wasSetByUser() ){
1976 options::preSkolemQuant
.set( true );
1979 //for induction techniques
1980 if( options::quantInduction() ){
1981 if( !options::dtStcInduction
.wasSetByUser() ){
1982 options::dtStcInduction
.set( true );
1984 if( !options::intWfInduction
.wasSetByUser() ){
1985 options::intWfInduction
.set( true );
1988 if( options::dtStcInduction() ){
1989 //try to remove ITEs from quantified formulas
1990 if( !options::iteDtTesterSplitQuant
.wasSetByUser() ){
1991 options::iteDtTesterSplitQuant
.set( true );
1993 if( !options::iteLiftQuant
.wasSetByUser() ){
1994 options::iteLiftQuant
.set( quantifiers::ITE_LIFT_QUANT_MODE_ALL
);
1997 if( options::intWfInduction() ){
1998 if( !options::purifyTriggers
.wasSetByUser() ){
1999 options::purifyTriggers
.set( true );
2002 if( options::conjectureNoFilter() ){
2003 if( !options::conjectureFilterActiveTerms
.wasSetByUser() ){
2004 options::conjectureFilterActiveTerms
.set( false );
2006 if( !options::conjectureFilterCanonical
.wasSetByUser() ){
2007 options::conjectureFilterCanonical
.set( false );
2009 if( !options::conjectureFilterModel
.wasSetByUser() ){
2010 options::conjectureFilterModel
.set( false );
2013 if( options::conjectureGenPerRound
.wasSetByUser() ){
2014 if( options::conjectureGenPerRound()>0 ){
2015 options::conjectureGen
.set( true );
2017 options::conjectureGen
.set( false );
2020 //can't pre-skolemize nested quantifiers without UF theory
2021 if( !d_logic
.isTheoryEnabled(THEORY_UF
) && options::preSkolemQuant() ){
2022 if( !options::preSkolemQuantNested
.wasSetByUser() ){
2023 options::preSkolemQuantNested
.set( false );
2026 if( !d_logic
.isTheoryEnabled(THEORY_DATATYPES
) ){
2027 options::quantDynamicSplit
.set( quantifiers::QUANT_DSPLIT_MODE_NONE
);
2030 //until bugs 371,431 are fixed
2031 if( ! options::minisatUseElim
.wasSetByUser()){
2032 // cannot use minisat elimination for logics where a theory solver
2033 // introduces new literals into the search. This includes quantifiers
2034 // (quantifier instantiation), and the lemma schemas used in non-linear
2035 // and sets. We also can't use it if models are enabled.
2036 if (d_logic
.isTheoryEnabled(THEORY_SETS
) || d_logic
.isQuantified()
2037 || options::produceModels() || options::produceAssignments()
2038 || options::checkModels()
2039 || (d_logic
.isTheoryEnabled(THEORY_ARITH
) && !d_logic
.isLinear()))
2041 options::minisatUseElim
.set( false );
2044 else if (options::minisatUseElim()) {
2045 if (options::produceModels()) {
2046 Notice() << "SmtEngine: turning off produce-models to support minisatUseElim" << endl
;
2047 setOption("produce-models", SExpr("false"));
2049 if (options::produceAssignments()) {
2050 Notice() << "SmtEngine: turning off produce-assignments to support minisatUseElim" << endl
;
2051 setOption("produce-assignments", SExpr("false"));
2053 if (options::checkModels()) {
2054 Notice() << "SmtEngine: turning off check-models to support minisatUseElim" << endl
;
2055 setOption("check-models", SExpr("false"));
2059 // For now, these array theory optimizations do not support model-building
2060 if (options::produceModels() || options::produceAssignments() || options::checkModels()) {
2061 options::arraysOptimizeLinear
.set(false);
2062 options::arraysLazyRIntro1
.set(false);
2065 // Non-linear arithmetic does not support models unless nlExt is enabled
2066 if ((d_logic
.isTheoryEnabled(THEORY_ARITH
) && !d_logic
.isLinear()
2067 && !options::nlExt())
2068 || options::globalNegate())
2070 std::string reason
=
2071 options::globalNegate() ? "--global-negate" : "nonlinear arithmetic";
2072 if (options::produceModels()) {
2073 if(options::produceModels
.wasSetByUser()) {
2074 throw OptionException(
2075 std::string("produce-model not supported with " + reason
));
2078 << "SmtEngine: turning off produce-models because unsupported for "
2080 setOption("produce-models", SExpr("false"));
2082 if (options::produceAssignments()) {
2083 if(options::produceAssignments
.wasSetByUser()) {
2084 throw OptionException(
2085 std::string("produce-assignments not supported with " + reason
));
2087 Warning() << "SmtEngine: turning off produce-assignments because "
2090 setOption("produce-assignments", SExpr("false"));
2092 if (options::checkModels()) {
2093 if(options::checkModels
.wasSetByUser()) {
2094 throw OptionException(
2095 std::string("check-models not supported with " + reason
));
2098 << "SmtEngine: turning off check-models because unsupported for "
2100 setOption("check-models", SExpr("false"));
2104 if(options::incrementalSolving() && options::proof()) {
2105 Warning() << "SmtEngine: turning off incremental solving mode (not yet supported with --proof, try --tear-down-incremental instead)" << endl
;
2106 setOption("incremental", SExpr("false"));
2109 if (options::proof())
2111 if (options::bitvectorAlgebraicSolver())
2113 if (options::bitvectorAlgebraicSolver
.wasSetByUser())
2115 throw OptionException(
2116 "--bv-algebraic-solver is not supported with proofs");
2118 Notice() << "SmtEngine: turning off bv algebraic solver to support proofs"
2120 options::bitvectorAlgebraicSolver
.set(false);
2122 if (options::bitvectorEqualitySolver())
2124 if (options::bitvectorEqualitySolver
.wasSetByUser())
2126 throw OptionException("--bv-eq-solver is not supported with proofs");
2128 Notice() << "SmtEngine: turning off bv eq solver to support proofs"
2130 options::bitvectorEqualitySolver
.set(false);
2132 if (options::bitvectorInequalitySolver())
2134 if (options::bitvectorInequalitySolver
.wasSetByUser())
2136 throw OptionException(
2137 "--bv-inequality-solver is not supported with proofs");
2139 Notice() << "SmtEngine: turning off bv ineq solver to support proofs"
2141 options::bitvectorInequalitySolver
.set(false);
2145 if (!options::bitvectorEqualitySolver())
2147 if (options::bvLazyRewriteExtf())
2149 if (options::bvLazyRewriteExtf
.wasSetByUser())
2151 throw OptionException(
2152 "--bv-lazy-rewrite-extf requires --bv-eq-solver to be set");
2156 << "disabling bvLazyRewriteExtf since equality solver is disabled"
2158 options::bvLazyRewriteExtf
.set(false);
2162 void SmtEngine::setProblemExtended(bool value
)
2164 d_problemExtended
= value
;
2165 if (value
) { d_assumptions
.clear(); }
2168 void SmtEngine::setInfo(const std::string
& key
, const CVC4::SExpr
& value
)
2170 SmtScope
smts(this);
2172 Trace("smt") << "SMT setInfo(" << key
<< ", " << value
<< ")" << endl
;
2174 if(Dump
.isOn("benchmark")) {
2175 if(key
== "status") {
2176 string s
= value
.getValue();
2177 BenchmarkStatus status
=
2178 (s
== "sat") ? SMT_SATISFIABLE
:
2179 ((s
== "unsat") ? SMT_UNSATISFIABLE
: SMT_UNKNOWN
);
2180 Dump("benchmark") << SetBenchmarkStatusCommand(status
);
2182 Dump("benchmark") << SetInfoCommand(key
, value
);
2186 // Check for CVC4-specific info keys (prefixed with "cvc4-" or "cvc4_")
2187 if(key
.length() > 5) {
2188 string prefix
= key
.substr(0, 5);
2189 if(prefix
== "cvc4-" || prefix
== "cvc4_") {
2190 string cvc4key
= key
.substr(5);
2191 if(cvc4key
== "logic") {
2192 if(! value
.isAtom()) {
2193 throw OptionException("argument to (set-info :cvc4-logic ..) must be a string");
2195 SmtScope
smts(this);
2196 d_logic
= value
.getValue();
2200 throw UnrecognizedOptionException();
2205 // Check for standard info keys (SMT-LIB v1, SMT-LIB v2, ...)
2206 if (key
== "source" || key
== "category" || key
== "difficulty"
2207 || key
== "notes" || key
== "name" || key
== "license")
2212 else if (key
== "filename")
2214 d_filename
= value
.getValue();
2217 else if (key
== "smt-lib-version" && !options::inputLanguage
.wasSetByUser())
2219 language::input::Language ilang
= language::input::LANG_AUTO
;
2220 if( (value
.isInteger() && value
.getIntegerValue() == Integer(2)) ||
2221 (value
.isRational() && value
.getRationalValue() == Rational(2)) ||
2222 value
.getValue() == "2" ||
2223 value
.getValue() == "2.0" ) {
2224 ilang
= language::input::LANG_SMTLIB_V2_0
;
2225 } else if( (value
.isRational() && value
.getRationalValue() == Rational(5, 2)) ||
2226 value
.getValue() == "2.5" ) {
2227 ilang
= language::input::LANG_SMTLIB_V2_5
;
2228 } else if( (value
.isRational() && value
.getRationalValue() == Rational(13, 5)) ||
2229 value
.getValue() == "2.6" ) {
2230 ilang
= language::input::LANG_SMTLIB_V2_6
;
2232 else if (value
.getValue() == "2.6.1")
2234 ilang
= language::input::LANG_SMTLIB_V2_6_1
;
2238 Warning() << "Warning: unsupported smt-lib-version: " << value
<< endl
;
2239 throw UnrecognizedOptionException();
2241 options::inputLanguage
.set(ilang
);
2242 // also update the output language
2243 if (!options::outputLanguage
.wasSetByUser())
2245 language::output::Language olang
= language::toOutputLanguage(ilang
);
2246 if (options::outputLanguage() != olang
)
2248 options::outputLanguage
.set(olang
);
2249 *options::out() << language::SetLanguage(olang
);
2253 } else if(key
== "status") {
2255 if(value
.isAtom()) {
2256 s
= value
.getValue();
2258 if(s
!= "sat" && s
!= "unsat" && s
!= "unknown") {
2259 throw OptionException("argument to (set-info :status ..) must be "
2260 "`sat' or `unsat' or `unknown'");
2262 d_status
= Result(s
, d_filename
);
2265 throw UnrecognizedOptionException();
2268 CVC4::SExpr
SmtEngine::getInfo(const std::string
& key
) const {
2270 SmtScope
smts(this);
2272 Trace("smt") << "SMT getInfo(" << key
<< ")" << endl
;
2273 if(key
== "all-statistics") {
2274 vector
<SExpr
> stats
;
2275 for(StatisticsRegistry::const_iterator i
= NodeManager::fromExprManager(d_exprManager
)->getStatisticsRegistry()->begin();
2276 i
!= NodeManager::fromExprManager(d_exprManager
)->getStatisticsRegistry()->end();
2279 v
.push_back((*i
).first
);
2280 v
.push_back((*i
).second
);
2283 for(StatisticsRegistry::const_iterator i
= d_statisticsRegistry
->begin();
2284 i
!= d_statisticsRegistry
->end();
2287 v
.push_back((*i
).first
);
2288 v
.push_back((*i
).second
);
2291 return SExpr(stats
);
2292 } else if(key
== "error-behavior") {
2293 // immediate-exit | continued-execution
2294 if( options::continuedExecution() || options::interactive() ) {
2295 return SExpr(SExpr::Keyword("continued-execution"));
2297 return SExpr(SExpr::Keyword("immediate-exit"));
2299 } else if(key
== "name") {
2300 return SExpr(Configuration::getName());
2301 } else if(key
== "version") {
2302 return SExpr(Configuration::getVersionString());
2303 } else if(key
== "authors") {
2304 return SExpr(Configuration::about());
2305 } else if(key
== "status") {
2306 // sat | unsat | unknown
2307 switch(d_status
.asSatisfiabilityResult().isSat()) {
2309 return SExpr(SExpr::Keyword("sat"));
2311 return SExpr(SExpr::Keyword("unsat"));
2313 return SExpr(SExpr::Keyword("unknown"));
2315 } else if(key
== "reason-unknown") {
2316 if(!d_status
.isNull() && d_status
.isUnknown()) {
2318 ss
<< d_status
.whyUnknown();
2319 string s
= ss
.str();
2320 transform(s
.begin(), s
.end(), s
.begin(), ::tolower
);
2321 return SExpr(SExpr::Keyword(s
));
2323 throw ModalException("Can't get-info :reason-unknown when the "
2324 "last result wasn't unknown!");
2326 } else if(key
== "assertion-stack-levels") {
2327 AlwaysAssert(d_userLevels
.size() <=
2328 std::numeric_limits
<unsigned long int>::max());
2329 return SExpr(static_cast<unsigned long int>(d_userLevels
.size()));
2330 } else if(key
== "all-options") {
2331 // get the options, like all-statistics
2332 std::vector
< std::vector
<std::string
> > current_options
=
2333 Options::current()->getOptions();
2334 return SExpr::parseListOfListOfAtoms(current_options
);
2336 throw UnrecognizedOptionException();
2340 void SmtEngine::debugCheckFormals(const std::vector
<Expr
>& formals
, Expr func
)
2342 for(std::vector
<Expr
>::const_iterator i
= formals
.begin(); i
!= formals
.end(); ++i
) {
2343 if((*i
).getKind() != kind::BOUND_VARIABLE
) {
2345 ss
<< "All formal arguments to defined functions must be BOUND_VARIABLEs, but in the\n"
2346 << "definition of function " << func
<< ", formal\n"
2347 << " " << *i
<< "\n"
2348 << "has kind " << (*i
).getKind();
2349 throw TypeCheckingException(func
, ss
.str());
2354 void SmtEngine::debugCheckFunctionBody(Expr formula
,
2355 const std::vector
<Expr
>& formals
,
2358 Type formulaType
= formula
.getType(options::typeChecking());
2359 Type funcType
= func
.getType();
2360 // We distinguish here between definitions of constants and functions,
2361 // because the type checking for them is subtly different. Perhaps we
2362 // should instead have SmtEngine::defineFunction() and
2363 // SmtEngine::defineConstant() for better clarity, although then that
2364 // doesn't match the SMT-LIBv2 standard...
2365 if(formals
.size() > 0) {
2366 Type rangeType
= FunctionType(funcType
).getRangeType();
2367 if(! formulaType
.isComparableTo(rangeType
)) {
2369 ss
<< "Type of defined function does not match its declaration\n"
2370 << "The function : " << func
<< "\n"
2371 << "Declared type : " << rangeType
<< "\n"
2372 << "The body : " << formula
<< "\n"
2373 << "Body type : " << formulaType
;
2374 throw TypeCheckingException(func
, ss
.str());
2377 if(! formulaType
.isComparableTo(funcType
)) {
2379 ss
<< "Declared type of defined constant does not match its definition\n"
2380 << "The constant : " << func
<< "\n"
2381 << "Declared type : " << funcType
<< " " << Type::getTypeNode(funcType
)->getId() << "\n"
2382 << "The definition : " << formula
<< "\n"
2383 << "Definition type: " << formulaType
<< " " << Type::getTypeNode(formulaType
)->getId();
2384 throw TypeCheckingException(func
, ss
.str());
2389 void SmtEngine::defineFunction(Expr func
,
2390 const std::vector
<Expr
>& formals
,
2393 SmtScope
smts(this);
2395 Trace("smt") << "SMT defineFunction(" << func
<< ")" << endl
;
2396 debugCheckFormals(formals
, func
);
2399 ss
<< language::SetLanguage(
2400 language::SetLanguage::getLanguage(Dump
.getStream()))
2402 DefineFunctionCommand
c(ss
.str(), func
, formals
, formula
);
2403 addToModelCommandAndDump(
2404 c
, ExprManager::VAR_FLAG_DEFINED
, true, "declarations");
2406 PROOF(if (options::checkUnsatCores()) {
2407 d_defineCommands
.push_back(c
.clone());
2411 debugCheckFunctionBody(formula
, formals
, func
);
2413 // Substitute out any abstract values in formula
2415 d_private
->substituteAbstractValues(Node::fromExpr(formula
)).toExpr();
2417 TNode funcNode
= func
.getTNode();
2418 vector
<Node
> formalsNodes
;
2419 for(vector
<Expr
>::const_iterator i
= formals
.begin(),
2420 iend
= formals
.end();
2423 formalsNodes
.push_back((*i
).getNode());
2425 TNode formNode
= form
.getTNode();
2426 DefinedFunction
def(funcNode
, formalsNodes
, formNode
);
2427 // Permit (check-sat) (define-fun ...) (get-value ...) sequences.
2428 // Otherwise, (check-sat) (get-value ((! foo :named bar))) breaks
2429 // d_haveAdditions = true;
2430 Debug("smt") << "definedFunctions insert " << funcNode
<< " " << formNode
<< endl
;
2431 d_definedFunctions
->insert(funcNode
, def
);
2434 void SmtEngine::defineFunctionsRec(
2435 const std::vector
<Expr
>& funcs
,
2436 const std::vector
<std::vector
<Expr
> >& formals
,
2437 const std::vector
<Expr
>& formulas
)
2439 SmtScope
smts(this);
2440 finalOptionsAreSet();
2442 Trace("smt") << "SMT defineFunctionsRec(...)" << endl
;
2444 if (funcs
.size() != formals
.size() && funcs
.size() != formulas
.size())
2447 ss
<< "Number of functions, formals, and function bodies passed to "
2448 "defineFunctionsRec do not match:"
2450 << " #functions : " << funcs
.size() << "\n"
2451 << " #arg lists : " << formals
.size() << "\n"
2452 << " #function bodies : " << formulas
.size() << "\n";
2453 throw ModalException(ss
.str());
2455 for (unsigned i
= 0, size
= funcs
.size(); i
< size
; i
++)
2457 // check formal argument list
2458 debugCheckFormals(formals
[i
], funcs
[i
]);
2460 debugCheckFunctionBody(formulas
[i
], formals
[i
], funcs
[i
]);
2463 if (Dump
.isOn("raw-benchmark"))
2465 Dump("raw-benchmark") << DefineFunctionRecCommand(funcs
, formals
, formulas
);
2468 ExprManager
* em
= getExprManager();
2469 for (unsigned i
= 0, size
= funcs
.size(); i
< size
; i
++)
2471 // we assert a quantified formula
2473 // make the function application
2474 if (formals
[i
].empty())
2476 // it has no arguments
2477 func_app
= funcs
[i
];
2481 std::vector
<Expr
> children
;
2482 children
.push_back(funcs
[i
]);
2483 children
.insert(children
.end(), formals
[i
].begin(), formals
[i
].end());
2484 func_app
= em
->mkExpr(kind::APPLY_UF
, children
);
2486 Expr lem
= em
->mkExpr(kind::EQUAL
, func_app
, formulas
[i
]);
2487 if (!formals
[i
].empty())
2489 // set the attribute to denote this is a function definition
2490 std::string
attr_name("fun-def");
2491 Expr aexpr
= em
->mkExpr(kind::INST_ATTRIBUTE
, func_app
);
2492 aexpr
= em
->mkExpr(kind::INST_PATTERN_LIST
, aexpr
);
2493 std::vector
<Expr
> expr_values
;
2494 std::string str_value
;
2495 setUserAttribute(attr_name
, func_app
, expr_values
, str_value
);
2496 // make the quantified formula
2497 Expr boundVars
= em
->mkExpr(kind::BOUND_VAR_LIST
, formals
[i
]);
2498 lem
= em
->mkExpr(kind::FORALL
, boundVars
, lem
, aexpr
);
2500 // assert the quantified formula
2501 // notice we don't call assertFormula directly, since this would
2502 // duplicate the output on raw-benchmark.
2503 Expr e
= d_private
->substituteAbstractValues(Node::fromExpr(lem
)).toExpr();
2504 if (d_assertionList
!= NULL
)
2506 d_assertionList
->push_back(e
);
2508 d_private
->addFormula(e
.getNode(), false);
2512 void SmtEngine::defineFunctionRec(Expr func
,
2513 const std::vector
<Expr
>& formals
,
2516 std::vector
<Expr
> funcs
;
2517 funcs
.push_back(func
);
2518 std::vector
<std::vector
<Expr
> > formals_multi
;
2519 formals_multi
.push_back(formals
);
2520 std::vector
<Expr
> formulas
;
2521 formulas
.push_back(formula
);
2522 defineFunctionsRec(funcs
, formals_multi
, formulas
);
2525 bool SmtEngine::isDefinedFunction( Expr func
){
2526 Node nf
= Node::fromExpr( func
);
2527 Debug("smt") << "isDefined function " << nf
<< "?" << std::endl
;
2528 return d_definedFunctions
->find(nf
) != d_definedFunctions
->end();
2531 void SmtEnginePrivate::finishInit()
2533 PreprocessingPassRegistry
& ppReg
= PreprocessingPassRegistry::getInstance();
2534 d_preprocessingPassContext
.reset(new PreprocessingPassContext(
2535 &d_smt
, d_resourceManager
, &d_iteRemover
, &d_propagator
));
2537 // TODO: this will likely change when we add support for actually assembling
2538 // preprocessing pipelines. For now, we just create an instance of each
2539 // available preprocessing pass.
2540 std::vector
<std::string
> passNames
= ppReg
.getAvailablePasses();
2541 for (const std::string
& passName
: passNames
)
2543 d_passes
[passName
].reset(
2544 ppReg
.createPass(d_preprocessingPassContext
.get(), passName
));
2548 Node
SmtEnginePrivate::expandDefinitions(TNode n
, unordered_map
<Node
, Node
, NodeHashFunction
>& cache
, bool expandOnly
)
2550 stack
<std::tuple
<Node
, Node
, bool>> worklist
;
2552 worklist
.push(std::make_tuple(Node(n
), Node(n
), false));
2553 // The worklist is made of triples, each is input / original node then the output / rewritten node
2554 // and finally a flag tracking whether the children have been explored (i.e. if this is a downward
2558 spendResource(options::preprocessStep());
2560 // n is the input / original
2561 // node is the output / result
2563 bool childrenPushed
;
2564 std::tie(n
, node
, childrenPushed
) = worklist
.top();
2567 // Working downwards
2568 if(!childrenPushed
) {
2569 Kind k
= n
.getKind();
2571 // we can short circuit (variable) leaves
2573 SmtEngine::DefinedFunctionMap::const_iterator i
= d_smt
.d_definedFunctions
->find(n
);
2574 if(i
!= d_smt
.d_definedFunctions
->end()) {
2575 // replacement must be closed
2576 if((*i
).second
.getFormals().size() > 0) {
2577 result
.push(d_smt
.d_nodeManager
->mkNode(kind::LAMBDA
, d_smt
.d_nodeManager
->mkNode(kind::BOUND_VAR_LIST
, (*i
).second
.getFormals()), (*i
).second
.getFormula()));
2580 // don't bother putting in the cache
2581 result
.push((*i
).second
.getFormula());
2584 // don't bother putting in the cache
2589 // maybe it's in the cache
2590 unordered_map
<Node
, Node
, NodeHashFunction
>::iterator cacheHit
= cache
.find(n
);
2591 if(cacheHit
!= cache
.end()) {
2592 TNode ret
= (*cacheHit
).second
;
2593 result
.push(ret
.isNull() ? n
: ret
);
2597 // otherwise expand it
2598 bool doExpand
= false;
2599 if (k
== kind::APPLY
)
2603 else if (k
== kind::APPLY_UF
)
2605 // Always do beta-reduction here. The reason is that there may be
2606 // operators such as INTS_MODULUS in the body of the lambda that would
2607 // otherwise be introduced by beta-reduction via the rewriter, but are
2608 // not expanded here since the traversal in this function does not
2609 // traverse the operators of nodes. Hence, we beta-reduce here to
2610 // ensure terms in the body of the lambda are expanded during this
2612 if (n
.getOperator().getKind() == kind::LAMBDA
)
2616 else if (options::macrosQuant() || options::sygusInference())
2618 // The above options assign substitutions to APPLY_UF, thus we check
2619 // here and expand if this operator corresponds to a defined function.
2620 doExpand
= d_smt
.isDefinedFunction(n
.getOperator().toExpr());
2624 vector
<Node
> formals
;
2626 if( n
.getOperator().getKind() == kind::LAMBDA
){
2627 TNode op
= n
.getOperator();
2629 for( unsigned i
=0; i
<op
[0].getNumChildren(); i
++ ){
2630 formals
.push_back( op
[0][i
] );
2634 // application of a user-defined symbol
2635 TNode func
= n
.getOperator();
2636 SmtEngine::DefinedFunctionMap::const_iterator i
= d_smt
.d_definedFunctions
->find(func
);
2637 if(i
== d_smt
.d_definedFunctions
->end()) {
2638 throw TypeCheckingException(n
.toExpr(), string("Undefined function: `") + func
.toString() + "'");
2640 DefinedFunction def
= (*i
).second
;
2641 formals
= def
.getFormals();
2643 if(Debug
.isOn("expand")) {
2644 Debug("expand") << "found: " << n
<< endl
;
2645 Debug("expand") << " func: " << func
<< endl
;
2646 string name
= func
.getAttribute(expr::VarNameAttr());
2647 Debug("expand") << " : \"" << name
<< "\"" << endl
;
2649 if(Debug
.isOn("expand")) {
2650 Debug("expand") << " defn: " << def
.getFunction() << endl
2652 if(formals
.size() > 0) {
2653 copy( formals
.begin(), formals
.end() - 1,
2654 ostream_iterator
<Node
>(Debug("expand"), ", ") );
2655 Debug("expand") << formals
.back();
2657 Debug("expand") << "]" << endl
2658 << " " << def
.getFunction().getType() << endl
2659 << " " << def
.getFormula() << endl
;
2662 fm
= def
.getFormula();
2665 Node instance
= fm
.substitute(formals
.begin(),
2668 n
.begin() + formals
.size());
2669 Debug("expand") << "made : " << instance
<< endl
;
2671 Node expanded
= expandDefinitions(instance
, cache
, expandOnly
);
2672 cache
[n
] = (n
== expanded
? Node::null() : expanded
);
2673 result
.push(expanded
);
2676 } else if(! expandOnly
) {
2677 // do not do any theory stuff if expandOnly is true
2679 theory::Theory
* t
= d_smt
.d_theoryEngine
->theoryOf(node
);
2682 LogicRequest
req(d_smt
);
2683 node
= t
->expandDefinition(req
, n
);
2686 // the partial functions can fall through, in which case we still
2687 // consider their children
2688 worklist
.push(std::make_tuple(
2689 Node(n
), node
, true)); // Original and rewritten result
2691 for(size_t i
= 0; i
< node
.getNumChildren(); ++i
) {
2693 std::make_tuple(node
[i
],
2695 false)); // Rewrite the children of the result only
2700 // Reconstruct the node from it's (now rewritten) children on the stack
2702 Debug("expand") << "cons : " << node
<< endl
;
2703 if(node
.getNumChildren()>0) {
2704 //cout << "cons : " << node << endl;
2705 NodeBuilder
<> nb(node
.getKind());
2706 if(node
.getMetaKind() == kind::metakind::PARAMETERIZED
) {
2707 Debug("expand") << "op : " << node
.getOperator() << endl
;
2708 //cout << "op : " << node.getOperator() << endl;
2709 nb
<< node
.getOperator();
2711 for(size_t i
= 0; i
< node
.getNumChildren(); ++i
) {
2712 Assert(!result
.empty());
2713 Node expanded
= result
.top();
2715 //cout << "exchld : " << expanded << endl;
2716 Debug("expand") << "exchld : " << expanded
<< endl
;
2721 cache
[n
] = n
== node
? Node::null() : node
; // Only cache once all subterms are expanded
2724 } while(!worklist
.empty());
2726 AlwaysAssert(result
.size() == 1);
2728 return result
.top();
2731 // do dumping (before/after any preprocessing pass)
2732 static void dumpAssertions(const char* key
,
2733 const AssertionPipeline
& assertionList
) {
2734 if( Dump
.isOn("assertions") &&
2735 Dump
.isOn(string("assertions:") + key
) ) {
2736 // Push the simplified assertions to the dump output stream
2737 for(unsigned i
= 0; i
< assertionList
.size(); ++ i
) {
2738 TNode n
= assertionList
[i
];
2739 Dump("assertions") << AssertCommand(Expr(n
.toExpr()));
2744 // returns false if simplification led to "false"
2745 bool SmtEnginePrivate::simplifyAssertions()
2747 spendResource(options::preprocessStep());
2748 Assert(d_smt
.d_pendingPops
== 0);
2750 ScopeCounter
depth(d_simplifyAssertionsDepth
);
2752 Trace("simplify") << "SmtEnginePrivate::simplify()" << endl
;
2754 if (options::simplificationMode() != SIMPLIFICATION_MODE_NONE
)
2756 if (!options::unsatCores() && !options::fewerPreprocessingHoles())
2758 // Perform non-clausal simplification
2759 PreprocessingPassResult res
=
2760 d_passes
["non-clausal-simp"]->apply(&d_assertions
);
2761 if (res
== PreprocessingPassResult::CONFLICT
)
2767 // We piggy-back off of the BackEdgesMap in the CircuitPropagator to
2768 // do the miplib trick.
2769 if ( // check that option is on
2770 options::arithMLTrick() &&
2771 // miplib rewrites aren't safe in incremental mode
2772 !options::incrementalSolving() &&
2773 // only useful in arith
2774 d_smt
.d_logic
.isTheoryEnabled(THEORY_ARITH
) &&
2775 // we add new assertions and need this (in practice, this
2776 // restriction only disables miplib processing during
2777 // re-simplification, which we don't expect to be useful anyway)
2778 d_assertions
.getRealAssertionsEnd() == d_assertions
.size())
2780 d_passes
["miplib-trick"]->apply(&d_assertions
);
2782 Trace("simplify") << "SmtEnginePrivate::simplify(): "
2783 << "skipping miplib pseudobooleans pass (either incrementalSolving is on, or miplib pbs are turned off)..." << endl
;
2787 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
2789 // before ppRewrite check if only core theory for BV theory
2790 d_smt
.d_theoryEngine
->staticInitializeBVOptions(d_assertions
.ref());
2792 // Theory preprocessing
2793 if (d_smt
.d_earlyTheoryPP
)
2795 d_passes
["theory-preprocess"]->apply(&d_assertions
);
2798 // ITE simplification
2799 if (options::doITESimp()
2800 && (d_simplifyAssertionsDepth
<= 1 || options::doITESimpOnRepeat()))
2802 PreprocessingPassResult res
= d_passes
["ite-simp"]->apply(&d_assertions
);
2803 if (res
== PreprocessingPassResult::CONFLICT
)
2805 Chat() << "...ITE simplification found unsat..." << endl
;
2810 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
2812 // Unconstrained simplification
2813 if(options::unconstrainedSimp()) {
2814 d_passes
["unconstrained-simplifier"]->apply(&d_assertions
);
2817 if (options::repeatSimp()
2818 && options::simplificationMode() != SIMPLIFICATION_MODE_NONE
2819 && !options::unsatCores() && !options::fewerPreprocessingHoles())
2821 PreprocessingPassResult res
=
2822 d_passes
["non-clausal-simp"]->apply(&d_assertions
);
2823 if (res
== PreprocessingPassResult::CONFLICT
)
2829 dumpAssertions("post-repeatsimp", d_assertions
);
2830 Trace("smt") << "POST repeatSimp" << endl
;
2831 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
2833 } catch(TypeCheckingExceptionPrivate
& tcep
) {
2834 // Calls to this function should have already weeded out any
2835 // typechecking exceptions via (e.g.) ensureBoolean(). But a
2836 // theory could still create a new expression that isn't
2837 // well-typed, and we don't want the C++ runtime to abort our
2838 // process without any error notice.
2840 ss
<< "A bad expression was produced. Original exception follows:\n"
2842 InternalError(ss
.str().c_str());
2847 Result
SmtEngine::check() {
2848 Assert(d_fullyInited
);
2849 Assert(d_pendingPops
== 0);
2851 Trace("smt") << "SmtEngine::check()" << endl
;
2853 ResourceManager
* resourceManager
= d_private
->getResourceManager();
2855 resourceManager
->beginCall();
2857 // Only way we can be out of resource is if cumulative budget is on
2858 if (resourceManager
->cumulativeLimitOn() &&
2859 resourceManager
->out()) {
2860 Result::UnknownExplanation why
= resourceManager
->outOfResources() ?
2861 Result::RESOURCEOUT
: Result::TIMEOUT
;
2862 return Result(Result::VALIDITY_UNKNOWN
, why
, d_filename
);
2865 // Make sure the prop layer has all of the assertions
2866 Trace("smt") << "SmtEngine::check(): processing assertions" << endl
;
2867 d_private
->processAssertions();
2868 Trace("smt") << "SmtEngine::check(): done processing assertions" << endl
;
2870 // Turn off stop only for QF_LRA
2871 // TODO: Bring up in a meeting where to put this
2872 if(options::decisionStopOnly() && !options::decisionMode
.wasSetByUser() ){
2874 (not d_logic
.isQuantified() &&
2875 d_logic
.isPure(THEORY_ARITH
) && d_logic
.isLinear() && !d_logic
.isDifferenceLogic() && !d_logic
.areIntegersUsed()
2877 if (d_private
->getIteSkolemMap().empty())
2879 options::decisionStopOnly
.set(false);
2880 d_decisionEngine
->clearStrategies();
2881 Trace("smt") << "SmtEngine::check(): turning off stop only" << endl
;
2886 TimerStat::CodeTimer
solveTimer(d_stats
->d_solveTime
);
2888 Chat() << "solving..." << endl
;
2889 Trace("smt") << "SmtEngine::check(): running check" << endl
;
2890 Result result
= d_propEngine
->checkSat();
2892 resourceManager
->endCall();
2893 Trace("limit") << "SmtEngine::check(): cumulative millis " << resourceManager
->getTimeUsage()
2894 << ", resources " << resourceManager
->getResourceUsage() << endl
;
2897 return Result(result
, d_filename
);
2900 Result
SmtEngine::quickCheck() {
2901 Assert(d_fullyInited
);
2902 Trace("smt") << "SMT quickCheck()" << endl
;
2903 return Result(Result::VALIDITY_UNKNOWN
, Result::REQUIRES_FULL_CHECK
, d_filename
);
2907 void SmtEnginePrivate::collectSkolems(TNode n
, set
<TNode
>& skolemSet
, unordered_map
<Node
, bool, NodeHashFunction
>& cache
)
2909 unordered_map
<Node
, bool, NodeHashFunction
>::iterator it
;
2911 if (it
!= cache
.end()) {
2915 size_t sz
= n
.getNumChildren();
2917 IteSkolemMap::iterator it
= getIteSkolemMap().find(n
);
2918 if (it
!= getIteSkolemMap().end())
2920 skolemSet
.insert(n
);
2927 for (; k
< sz
; ++k
) {
2928 collectSkolems(n
[k
], skolemSet
, cache
);
2933 bool SmtEnginePrivate::checkForBadSkolems(TNode n
, TNode skolem
, unordered_map
<Node
, bool, NodeHashFunction
>& cache
)
2935 unordered_map
<Node
, bool, NodeHashFunction
>::iterator it
;
2937 if (it
!= cache
.end()) {
2938 return (*it
).second
;
2941 size_t sz
= n
.getNumChildren();
2943 IteSkolemMap::iterator it
= getIteSkolemMap().find(n
);
2945 if (it
!= getIteSkolemMap().end())
2947 if (!((*it
).first
< n
)) {
2956 for (; k
< sz
; ++k
) {
2957 if (checkForBadSkolems(n
[k
], skolem
, cache
)) {
2967 void SmtEnginePrivate::processAssertions() {
2968 TimerStat::CodeTimer
paTimer(d_smt
.d_stats
->d_processAssertionsTime
);
2969 spendResource(options::preprocessStep());
2970 Assert(d_smt
.d_fullyInited
);
2971 Assert(d_smt
.d_pendingPops
== 0);
2972 SubstitutionMap
& top_level_substs
=
2973 d_preprocessingPassContext
->getTopLevelSubstitutions();
2975 // Dump the assertions
2976 dumpAssertions("pre-everything", d_assertions
);
2978 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() begin" << endl
;
2979 Trace("smt") << "SmtEnginePrivate::processAssertions()" << endl
;
2981 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
2983 if (d_assertions
.size() == 0) {
2988 if (options::bvGaussElim())
2990 d_passes
["bv-gauss"]->apply(&d_assertions
);
2993 if (d_assertionsProcessed
&& options::incrementalSolving()) {
2994 // TODO(b/1255): Substitutions in incremental mode should be managed with a
2995 // proper data structure.
2997 // Placeholder for storing substitutions
2998 d_preprocessingPassContext
->setSubstitutionsIndex(d_assertions
.size());
2999 d_assertions
.push_back(NodeManager::currentNM()->mkConst
<bool>(true));
3002 // Add dummy assertion in last position - to be used as a
3003 // placeholder for any new assertions to get added
3004 d_assertions
.push_back(NodeManager::currentNM()->mkConst
<bool>(true));
3005 // any assertions added beyond realAssertionsEnd must NOT affect the
3006 // equisatisfiability
3007 d_assertions
.updateRealAssertionsEnd();
3009 // Assertions are NOT guaranteed to be rewritten by this point
3011 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-definition-expansion" << endl
;
3012 dumpAssertions("pre-definition-expansion", d_assertions
);
3014 Chat() << "expanding definitions..." << endl
;
3015 Trace("simplify") << "SmtEnginePrivate::simplify(): expanding definitions" << endl
;
3016 TimerStat::CodeTimer
codeTimer(d_smt
.d_stats
->d_definitionExpansionTime
);
3017 unordered_map
<Node
, Node
, NodeHashFunction
> cache
;
3018 for(unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
3019 d_assertions
.replace(i
, expandDefinitions(d_assertions
[i
], cache
));
3022 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-definition-expansion" << endl
;
3023 dumpAssertions("post-definition-expansion", d_assertions
);
3025 // save the assertions now
3028 for (unsigned i
= 0; i
< d_assertions
.size(); ++i
) {
3029 ProofManager::currentPM()->addAssertion(d_assertions
[i
].toExpr());
3033 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
3035 if (options::globalNegate())
3037 // global negation of the formula
3038 d_passes
["global-negate"]->apply(&d_assertions
);
3039 d_smt
.d_globalNegation
= !d_smt
.d_globalNegation
;
3042 if( options::nlExtPurify() ){
3043 d_passes
["nl-ext-purify"]->apply(&d_assertions
);
3046 if( options::ceGuidedInst() ){
3047 //register sygus conjecture pre-rewrite (motivated by solution reconstruction)
3048 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
3049 d_smt
.d_theoryEngine
->getQuantifiersEngine()
3051 ->preregisterAssertion(d_assertions
[i
]);
3055 if (options::solveRealAsInt()) {
3056 d_passes
["real-to-int"]->apply(&d_assertions
);
3059 if (options::solveIntAsBV() > 0)
3061 d_passes
["int-to-bv"]->apply(&d_assertions
);
3064 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER
&&
3065 !d_smt
.d_logic
.isPure(THEORY_BV
) &&
3066 d_smt
.d_logic
.getLogicString() != "QF_UFBV" &&
3067 d_smt
.d_logic
.getLogicString() != "QF_ABV") {
3068 throw ModalException("Eager bit-blasting does not currently support theory combination. "
3069 "Note that in a QF_BV problem UF symbols can be introduced for division. "
3070 "Try --bv-div-zero-const to interpret division by zero as a constant.");
3073 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER
3074 && !options::incrementalSolving())
3076 d_passes
["bv-ackermann"]->apply(&d_assertions
);
3079 if (options::bvAbstraction() && !options::incrementalSolving())
3081 d_passes
["bv-abstraction"]->apply(&d_assertions
);
3084 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
3086 bool noConflict
= true;
3088 if (options::extRewPrep())
3090 d_passes
["ext-rew-pre"]->apply(&d_assertions
);
3093 // Unconstrained simplification
3094 if(options::unconstrainedSimp()) {
3095 d_passes
["rewrite"]->apply(&d_assertions
);
3096 d_passes
["unconstrained-simplifier"]->apply(&d_assertions
);
3099 if(options::bvIntroducePow2())
3101 d_passes
["bv-intro-pow2"]->apply(&d_assertions
);
3104 if (options::unsatCores())
3106 // special rewriting pass for unsat cores, since many of the passes below
3108 d_passes
["rewrite"]->apply(&d_assertions
);
3112 d_passes
["apply-substs"]->apply(&d_assertions
);
3115 // Assertions ARE guaranteed to be rewritten by this point
3116 #ifdef CVC4_ASSERTIONS
3117 for (unsigned i
= 0; i
< d_assertions
.size(); ++i
)
3119 Assert(Rewriter::rewrite(d_assertions
[i
]) == d_assertions
[i
]);
3123 // Lift bit-vectors of size 1 to bool
3124 if (options::bitvectorToBool())
3126 d_passes
["bv-to-bool"]->apply(&d_assertions
);
3128 // Convert non-top-level Booleans to bit-vectors of size 1
3129 if (options::boolToBitvector())
3131 d_passes
["bool-to-bv"]->apply(&d_assertions
);
3133 if(options::sepPreSkolemEmp()) {
3134 d_passes
["sep-skolem-emp"]->apply(&d_assertions
);
3137 if( d_smt
.d_logic
.isQuantified() ){
3138 //remove rewrite rules, apply pre-skolemization to existential quantifiers
3139 d_passes
["quantifiers-preprocess"]->apply(&d_assertions
);
3140 if( options::macrosQuant() ){
3141 //quantifiers macro expansion
3142 d_passes
["quantifier-macros"]->apply(&d_assertions
);
3145 //fmf-fun : assume admissible functions, applying preprocessing reduction to FMF
3146 if( options::fmfFunWellDefined() ){
3147 quantifiers::FunDefFmf fdf
;
3148 Assert( d_smt
.d_fmfRecFunctionsDefined
!=NULL
);
3149 //must carry over current definitions (for incremental)
3150 for( context::CDList
<Node
>::const_iterator fit
= d_smt
.d_fmfRecFunctionsDefined
->begin();
3151 fit
!= d_smt
.d_fmfRecFunctionsDefined
->end(); ++fit
) {
3153 Assert( d_smt
.d_fmfRecFunctionsAbs
.find( f
)!=d_smt
.d_fmfRecFunctionsAbs
.end() );
3154 TypeNode ft
= d_smt
.d_fmfRecFunctionsAbs
[f
];
3155 fdf
.d_sorts
[f
] = ft
;
3156 std::map
< Node
, std::vector
< Node
> >::iterator fcit
= d_smt
.d_fmfRecFunctionsConcrete
.find( f
);
3157 Assert( fcit
!=d_smt
.d_fmfRecFunctionsConcrete
.end() );
3158 for( unsigned j
=0; j
<fcit
->second
.size(); j
++ ){
3159 fdf
.d_input_arg_inj
[f
].push_back( fcit
->second
[j
] );
3162 fdf
.simplify( d_assertions
.ref() );
3163 //must store new definitions (for incremental)
3164 for( unsigned i
=0; i
<fdf
.d_funcs
.size(); i
++ ){
3165 Node f
= fdf
.d_funcs
[i
];
3166 d_smt
.d_fmfRecFunctionsAbs
[f
] = fdf
.d_sorts
[f
];
3167 d_smt
.d_fmfRecFunctionsConcrete
[f
].clear();
3168 for( unsigned j
=0; j
<fdf
.d_input_arg_inj
[f
].size(); j
++ ){
3169 d_smt
.d_fmfRecFunctionsConcrete
[f
].push_back( fdf
.d_input_arg_inj
[f
][j
] );
3171 d_smt
.d_fmfRecFunctionsDefined
->push_back( f
);
3174 if (options::sygusInference())
3176 d_passes
["sygus-infer"]->apply(&d_assertions
);
3180 if( options::sortInference() || options::ufssFairnessMonotone() ){
3181 d_passes
["sort-inference"]->apply(&d_assertions
);
3184 if( options::pbRewrites() ){
3185 d_passes
["pseudo-boolean-processor"]->apply(&d_assertions
);
3188 if (options::synthRrPrep())
3190 // do candidate rewrite rule synthesis
3191 d_passes
["synth-rr"]->apply(&d_assertions
);
3194 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-simplify" << endl
;
3195 dumpAssertions("pre-simplify", d_assertions
);
3196 Chat() << "simplifying assertions..." << endl
;
3197 noConflict
= simplifyAssertions();
3199 ++(d_smt
.d_stats
->d_simplifiedToFalse
);
3201 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-simplify" << endl
;
3202 dumpAssertions("post-simplify", d_assertions
);
3204 if (options::symmetryBreakerExp() && !options::incrementalSolving())
3206 // apply symmetry breaking if not in incremental mode
3207 d_passes
["sym-break"]->apply(&d_assertions
);
3210 if(options::doStaticLearning()) {
3211 d_passes
["static-learning"]->apply(&d_assertions
);
3213 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
3216 d_smt
.d_stats
->d_numAssertionsPre
+= d_assertions
.size();
3217 d_passes
["ite-removal"]->apply(&d_assertions
);
3218 // This is needed because when solving incrementally, removeITEs may introduce
3219 // skolems that were solved for earlier and thus appear in the substitution
3221 d_passes
["apply-substs"]->apply(&d_assertions
);
3222 d_smt
.d_stats
->d_numAssertionsPost
+= d_assertions
.size();
3225 dumpAssertions("pre-repeat-simplify", d_assertions
);
3226 if(options::repeatSimp()) {
3227 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-repeat-simplify" << endl
;
3228 Chat() << "re-simplifying assertions..." << endl
;
3229 ScopeCounter
depth(d_simplifyAssertionsDepth
);
3230 noConflict
&= simplifyAssertions();
3232 // Need to fix up assertion list to maintain invariants:
3233 // Let Sk be the set of Skolem variables introduced by ITE's. Let <_sk be the order in which these variables were introduced
3234 // during ite removal.
3235 // For each skolem variable sk, let iteExpr = iteMap(sk) be the ite expr mapped to by sk.
3237 // cache for expression traversal
3238 unordered_map
<Node
, bool, NodeHashFunction
> cache
;
3240 // First, find all skolems that appear in the substitution map - their associated iteExpr will need
3241 // to be moved to the main assertion set
3242 set
<TNode
> skolemSet
;
3243 SubstitutionMap::iterator pos
= top_level_substs
.begin();
3244 for (; pos
!= top_level_substs
.end(); ++pos
)
3246 collectSkolems((*pos
).first
, skolemSet
, cache
);
3247 collectSkolems((*pos
).second
, skolemSet
, cache
);
3250 // We need to ensure:
3251 // 1. iteExpr has the form (ite cond (sk = t) (sk = e))
3252 // 2. if some sk' in Sk appears in cond, t, or e, then sk' <_sk sk
3253 // If either of these is violated, we must add iteExpr as a proper assertion
3254 IteSkolemMap::iterator it
= getIteSkolemMap().begin();
3255 IteSkolemMap::iterator iend
= getIteSkolemMap().end();
3256 NodeBuilder
<> builder(kind::AND
);
3257 builder
<< d_assertions
[d_assertions
.getRealAssertionsEnd() - 1];
3258 vector
<TNode
> toErase
;
3259 for (; it
!= iend
; ++it
) {
3260 if (skolemSet
.find((*it
).first
) == skolemSet
.end()) {
3261 TNode iteExpr
= d_assertions
[(*it
).second
];
3262 if (iteExpr
.getKind() == kind::ITE
&&
3263 iteExpr
[1].getKind() == kind::EQUAL
&&
3264 iteExpr
[1][0] == (*it
).first
&&
3265 iteExpr
[2].getKind() == kind::EQUAL
&&
3266 iteExpr
[2][0] == (*it
).first
) {
3268 bool bad
= checkForBadSkolems(iteExpr
[0], (*it
).first
, cache
);
3269 bad
= bad
|| checkForBadSkolems(iteExpr
[1][1], (*it
).first
, cache
);
3270 bad
= bad
|| checkForBadSkolems(iteExpr
[2][1], (*it
).first
, cache
);
3276 // Move this iteExpr into the main assertions
3277 builder
<< d_assertions
[(*it
).second
];
3278 d_assertions
[(*it
).second
] = NodeManager::currentNM()->mkConst
<bool>(true);
3279 toErase
.push_back((*it
).first
);
3281 if(builder
.getNumChildren() > 1) {
3282 while (!toErase
.empty()) {
3283 getIteSkolemMap().erase(toErase
.back());
3286 d_assertions
[d_assertions
.getRealAssertionsEnd() - 1] =
3287 Rewriter::rewrite(Node(builder
));
3289 // TODO(b/1256): For some reason this is needed for some benchmarks, such as
3290 // QF_AUFBV/dwp_formulas/try5_small_difret_functions_dwp_tac.re_node_set_remove_at.il.dwp.smt2
3291 d_passes
["ite-removal"]->apply(&d_assertions
);
3292 d_passes
["apply-substs"]->apply(&d_assertions
);
3293 // Assert(iteRewriteAssertionsEnd == d_assertions.size());
3295 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-repeat-simplify" << endl
;
3297 dumpAssertions("post-repeat-simplify", d_assertions
);
3299 if (options::rewriteApplyToConst())
3301 d_passes
["apply-to-const"]->apply(&d_assertions
);
3304 // begin: INVARIANT to maintain: no reordering of assertions or
3305 // introducing new ones
3306 #ifdef CVC4_ASSERTIONS
3307 unsigned iteRewriteAssertionsEnd
= d_assertions
.size();
3310 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
3312 Debug("smt") << "SmtEnginePrivate::processAssertions() POST SIMPLIFICATION" << endl
;
3313 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
3315 d_passes
["theory-preprocess"]->apply(&d_assertions
);
3317 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER
)
3319 d_passes
["bv-eager-atoms"]->apply(&d_assertions
);
3322 //notify theory engine new preprocessed assertions
3323 d_smt
.d_theoryEngine
->notifyPreprocessedAssertions( d_assertions
.ref() );
3325 // Push the formula to decision engine
3327 Chat() << "pushing to decision engine..." << endl
;
3328 Assert(iteRewriteAssertionsEnd
== d_assertions
.size());
3329 d_smt
.d_decisionEngine
->addAssertions(d_assertions
);
3332 // end: INVARIANT to maintain: no reordering of assertions or
3333 // introducing new ones
3335 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() end" << endl
;
3336 dumpAssertions("post-everything", d_assertions
);
3338 // if incremental, compute which variables are assigned
3339 if (options::incrementalSolving())
3341 d_preprocessingPassContext
->recordSymbolsInAssertions(d_assertions
.ref());
3344 // Push the formula to SAT
3346 Chat() << "converting to CNF..." << endl
;
3347 TimerStat::CodeTimer
codeTimer(d_smt
.d_stats
->d_cnfConversionTime
);
3348 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
3349 Chat() << "+ " << d_assertions
[i
] << std::endl
;
3350 d_smt
.d_propEngine
->assertFormula(d_assertions
[i
]);
3354 d_assertionsProcessed
= true;
3356 d_assertions
.clear();
3357 getIteSkolemMap().clear();
3360 void SmtEnginePrivate::addFormula(TNode n
, bool inUnsatCore
, bool inInput
)
3367 Trace("smt") << "SmtEnginePrivate::addFormula(" << n
<< "), inUnsatCore = " << inUnsatCore
<< ", inInput = " << inInput
<< endl
;
3369 // Give it to proof manager
3372 // n is an input assertion
3373 if (inUnsatCore
|| options::unsatCores() || options::dumpUnsatCores() || options::checkUnsatCores() || options::fewerPreprocessingHoles()) {
3375 ProofManager::currentPM()->addCoreAssertion(n
.toExpr());
3378 // n is the result of an unknown preprocessing step, add it to dependency map to null
3379 ProofManager::currentPM()->addDependence(n
, Node::null());
3381 // rewrite rules are by default in the unsat core because
3382 // they need to be applied until saturation
3383 if(options::unsatCores() &&
3384 n
.getKind() == kind::REWRITE_RULE
){
3385 ProofManager::currentPM()->addUnsatCore(n
.toExpr());
3389 // Add the normalized formula to the queue
3390 d_assertions
.push_back(n
);
3391 //d_assertions.push_back(Rewriter::rewrite(n));
3394 void SmtEngine::ensureBoolean(const Expr
& e
)
3396 Type type
= e
.getType(options::typeChecking());
3397 Type boolType
= d_exprManager
->booleanType();
3398 if(type
!= boolType
) {
3400 ss
<< "Expected " << boolType
<< "\n"
3401 << "The assertion : " << e
<< "\n"
3402 << "Its type : " << type
;
3403 throw TypeCheckingException(e
, ss
.str());
3407 Result
SmtEngine::checkSat(const Expr
& assumption
, bool inUnsatCore
)
3409 return checkSatisfiability(assumption
, inUnsatCore
, false);
3412 Result
SmtEngine::checkSat(const vector
<Expr
>& assumptions
, bool inUnsatCore
)
3414 return checkSatisfiability(assumptions
, inUnsatCore
, false);
3417 Result
SmtEngine::query(const Expr
& assumption
, bool inUnsatCore
)
3419 Assert(!assumption
.isNull());
3420 return checkSatisfiability(assumption
, inUnsatCore
, true);
3423 Result
SmtEngine::query(const vector
<Expr
>& assumptions
, bool inUnsatCore
)
3425 return checkSatisfiability(assumptions
, inUnsatCore
, true);
3428 Result
SmtEngine::checkSatisfiability(const Expr
& expr
,
3432 return checkSatisfiability(
3433 expr
.isNull() ? vector
<Expr
>() : vector
<Expr
>{expr
},
3438 Result
SmtEngine::checkSatisfiability(const vector
<Expr
>& assumptions
,
3444 SmtScope
smts(this);
3445 finalOptionsAreSet();
3448 Trace("smt") << "SmtEngine::" << (isQuery
? "query" : "checkSat") << "("
3449 << assumptions
<< ")" << endl
;
3451 if(d_queryMade
&& !options::incrementalSolving()) {
3452 throw ModalException("Cannot make multiple queries unless "
3453 "incremental solving is enabled "
3454 "(try --incremental)");
3457 // check to see if a postsolve() is pending
3458 if(d_needPostsolve
) {
3459 d_theoryEngine
->postsolve();
3460 d_needPostsolve
= false;
3462 // Note that a query has been made
3464 // reset global negation
3465 d_globalNegation
= false;
3467 bool didInternalPush
= false;
3469 setProblemExtended(true);
3473 size_t size
= assumptions
.size();
3476 /* Assume: not (BIGAND assumptions) */
3477 d_assumptions
.push_back(
3478 d_exprManager
->mkExpr(kind::AND
, assumptions
).notExpr());
3482 /* Assume: not expr */
3483 d_assumptions
.push_back(assumptions
[0].notExpr());
3488 /* Assume: BIGAND assumptions */
3489 d_assumptions
= assumptions
;
3492 if (!d_assumptions
.empty())
3495 didInternalPush
= true;
3498 Result
r(Result::SAT_UNKNOWN
, Result::UNKNOWN_REASON
);
3499 for (Expr e
: d_assumptions
)
3501 // Substitute out any abstract values in ex.
3502 e
= d_private
->substituteAbstractValues(Node::fromExpr(e
)).toExpr();
3503 Assert(e
.getExprManager() == d_exprManager
);
3504 // Ensure expr is type-checked at this point.
3507 /* Add assumption */
3508 if (d_assertionList
!= NULL
)
3510 d_assertionList
->push_back(e
);
3512 d_private
->addFormula(e
.getNode(), inUnsatCore
);
3515 r
= isQuery
? check().asValidityResult() : check().asSatisfiabilityResult();
3517 if ((options::solveRealAsInt() || options::solveIntAsBV() > 0)
3518 && r
.asSatisfiabilityResult().isSat() == Result::UNSAT
)
3520 r
= Result(Result::SAT_UNKNOWN
, Result::UNKNOWN_REASON
);
3522 // flipped if we did a global negation
3523 if (d_globalNegation
)
3525 Trace("smt") << "SmtEngine::process global negate " << r
<< std::endl
;
3526 if (r
.asSatisfiabilityResult().isSat() == Result::UNSAT
)
3528 r
= Result(Result::SAT
);
3530 else if (r
.asSatisfiabilityResult().isSat() == Result::SAT
)
3532 // only if satisfaction complete
3533 if (d_logic
.isPure(THEORY_ARITH
) || d_logic
.isPure(THEORY_BV
))
3535 r
= Result(Result::UNSAT
);
3539 r
= Result(Result::SAT_UNKNOWN
, Result::UNKNOWN_REASON
);
3542 Trace("smt") << "SmtEngine::global negate returned " << r
<< std::endl
;
3545 d_needPostsolve
= true;
3547 // Dump the query if requested
3548 if (Dump
.isOn("benchmark"))
3550 size_t size
= assumptions
.size();
3551 // the expr already got dumped out if assertion-dumping is on
3552 if (isQuery
&& size
== 1)
3554 Dump("benchmark") << QueryCommand(assumptions
[0]);
3558 Dump("benchmark") << CheckSatCommand();
3562 Dump("benchmark") << CheckSatAssumingCommand(d_assumptions
);
3566 d_propEngine
->resetTrail();
3569 if (didInternalPush
)
3574 // Remember the status
3577 setProblemExtended(false);
3579 Trace("smt") << "SmtEngine::" << (isQuery
? "query" : "checkSat") << "("
3580 << assumptions
<< ") => " << r
<< endl
;
3582 // Check that SAT results generate a model correctly.
3583 if(options::checkModels()) {
3584 // TODO (#1693) check model when unknown result?
3585 if (r
.asSatisfiabilityResult().isSat() == Result::SAT
)
3590 // Check that UNSAT results generate a proof correctly.
3591 if(options::checkProofs()) {
3592 if(r
.asSatisfiabilityResult().isSat() == Result::UNSAT
) {
3593 TimerStat::CodeTimer
checkProofTimer(d_stats
->d_checkProofTime
);
3597 // Check that UNSAT results generate an unsat core correctly.
3598 if(options::checkUnsatCores()) {
3599 if(r
.asSatisfiabilityResult().isSat() == Result::UNSAT
) {
3600 TimerStat::CodeTimer
checkUnsatCoreTimer(d_stats
->d_checkUnsatCoreTime
);
3604 // Check that synthesis solutions satisfy the conjecture
3605 if (options::checkSynthSol()
3606 && r
.asSatisfiabilityResult().isSat() == Result::UNSAT
)
3608 checkSynthSolution();
3612 } catch (UnsafeInterruptException
& e
) {
3613 AlwaysAssert(d_private
->getResourceManager()->out());
3614 Result::UnknownExplanation why
= d_private
->getResourceManager()->outOfResources() ?
3615 Result::RESOURCEOUT
: Result::TIMEOUT
;
3616 return Result(Result::SAT_UNKNOWN
, why
, d_filename
);
3620 vector
<Expr
> SmtEngine::getUnsatAssumptions(void)
3622 Trace("smt") << "SMT getUnsatAssumptions()" << endl
;
3623 SmtScope
smts(this);
3624 if (!options::unsatAssumptions())
3626 throw ModalException(
3627 "Cannot get unsat assumptions when produce-unsat-assumptions option "
3630 if (d_status
.isNull()
3631 || d_status
.asSatisfiabilityResult() != Result::UNSAT
3632 || d_problemExtended
)
3634 throw RecoverableModalException(
3635 "Cannot get unsat assumptions unless immediately preceded by "
3636 "UNSAT/VALID response.");
3638 finalOptionsAreSet();
3639 if (Dump
.isOn("benchmark"))
3641 Dump("benchmark") << GetUnsatAssumptionsCommand();
3643 UnsatCore core
= getUnsatCoreInternal();
3645 for (const Expr
& e
: d_assumptions
)
3647 if (find(core
.begin(), core
.end(), e
) != core
.end()) { res
.push_back(e
); }
3652 Result
SmtEngine::checkSynth(const Expr
& e
)
3654 SmtScope
smts(this);
3655 Trace("smt") << "Check synth: " << e
<< std::endl
;
3656 Trace("smt-synth") << "Check synthesis conjecture: " << e
<< std::endl
;
3657 return checkSatisfiability(e
, true, false);
3660 Result
SmtEngine::assertFormula(const Expr
& ex
, bool inUnsatCore
)
3662 Assert(ex
.getExprManager() == d_exprManager
);
3663 SmtScope
smts(this);
3664 finalOptionsAreSet();
3667 Trace("smt") << "SmtEngine::assertFormula(" << ex
<< ")" << endl
;
3669 if (Dump
.isOn("raw-benchmark")) {
3670 Dump("raw-benchmark") << AssertCommand(ex
);
3673 // Substitute out any abstract values in ex
3674 Expr e
= d_private
->substituteAbstractValues(Node::fromExpr(ex
)).toExpr();
3677 if(d_assertionList
!= NULL
) {
3678 d_assertionList
->push_back(e
);
3680 d_private
->addFormula(e
.getNode(), inUnsatCore
);
3681 return quickCheck().asValidityResult();
3682 }/* SmtEngine::assertFormula() */
3684 Node
SmtEngine::postprocess(TNode node
, TypeNode expectedType
) const {
3688 Expr
SmtEngine::simplify(const Expr
& ex
)
3690 Assert(ex
.getExprManager() == d_exprManager
);
3691 SmtScope
smts(this);
3692 finalOptionsAreSet();
3694 Trace("smt") << "SMT simplify(" << ex
<< ")" << endl
;
3696 if(Dump
.isOn("benchmark")) {
3697 Dump("benchmark") << SimplifyCommand(ex
);
3700 Expr e
= d_private
->substituteAbstractValues(Node::fromExpr(ex
)).toExpr();
3701 if( options::typeChecking() ) {
3702 e
.getType(true); // ensure expr is type-checked at this point
3705 // Make sure all preprocessing is done
3706 d_private
->processAssertions();
3707 Node n
= d_private
->simplify(Node::fromExpr(e
));
3708 n
= postprocess(n
, TypeNode::fromType(e
.getType()));
3712 Expr
SmtEngine::expandDefinitions(const Expr
& ex
)
3714 d_private
->spendResource(options::preprocessStep());
3716 Assert(ex
.getExprManager() == d_exprManager
);
3717 SmtScope
smts(this);
3718 finalOptionsAreSet();
3720 Trace("smt") << "SMT expandDefinitions(" << ex
<< ")" << endl
;
3722 // Substitute out any abstract values in ex.
3723 Expr e
= d_private
->substituteAbstractValues(Node::fromExpr(ex
)).toExpr();
3724 if(options::typeChecking()) {
3725 // Ensure expr is type-checked at this point.
3728 if(Dump
.isOn("benchmark")) {
3729 Dump("benchmark") << ExpandDefinitionsCommand(e
);
3731 unordered_map
<Node
, Node
, NodeHashFunction
> cache
;
3732 Node n
= d_private
->expandDefinitions(Node::fromExpr(e
), cache
, /* expandOnly = */ true);
3733 n
= postprocess(n
, TypeNode::fromType(e
.getType()));
3738 // TODO(#1108): Simplify the error reporting of this method.
3739 Expr
SmtEngine::getValue(const Expr
& ex
) const
3741 Assert(ex
.getExprManager() == d_exprManager
);
3742 SmtScope
smts(this);
3744 Trace("smt") << "SMT getValue(" << ex
<< ")" << endl
;
3745 if(Dump
.isOn("benchmark")) {
3746 Dump("benchmark") << GetValueCommand(ex
);
3749 if(!options::produceModels()) {
3751 "Cannot get value when produce-models options is off.";
3752 throw ModalException(msg
);
3754 if(d_status
.isNull() ||
3755 d_status
.asSatisfiabilityResult() == Result::UNSAT
||
3756 d_problemExtended
) {
3758 "Cannot get value unless immediately preceded by SAT/INVALID or UNKNOWN response.";
3759 throw RecoverableModalException(msg
);
3762 // Substitute out any abstract values in ex.
3763 Expr e
= d_private
->substituteAbstractValues(Node::fromExpr(ex
)).toExpr();
3765 // Ensure expr is type-checked at this point.
3766 e
.getType(options::typeChecking());
3768 // do not need to apply preprocessing substitutions (should be recorded
3769 // in model already)
3771 Node n
= Node::fromExpr(e
);
3772 Trace("smt") << "--- getting value of " << n
<< endl
;
3773 TypeNode expectedType
= n
.getType();
3775 // Expand, then normalize
3776 unordered_map
<Node
, Node
, NodeHashFunction
> cache
;
3777 n
= d_private
->expandDefinitions(n
, cache
);
3778 // There are two ways model values for terms are computed (for historical
3779 // reasons). One way is that used in check-model; the other is that
3780 // used by the Model classes. It's not clear to me exactly how these
3781 // two are different, but they need to be unified. This ugly hack here
3782 // is to fix bug 554 until we can revamp boolean-terms and models [MGD]
3785 if(!n
.getType().isFunction()) {
3786 n
= Rewriter::rewrite(n
);
3789 Trace("smt") << "--- getting value of " << n
<< endl
;
3790 TheoryModel
* m
= d_theoryEngine
->getModel();
3793 resultNode
= m
->getValue(n
);
3795 Trace("smt") << "--- got value " << n
<< " = " << resultNode
<< endl
;
3796 resultNode
= postprocess(resultNode
, expectedType
);
3797 Trace("smt") << "--- model-post returned " << resultNode
<< endl
;
3798 Trace("smt") << "--- model-post returned " << resultNode
.getType() << endl
;
3799 Trace("smt") << "--- model-post expected " << expectedType
<< endl
;
3801 // type-check the result we got
3802 Assert(resultNode
.isNull() || resultNode
.getType().isSubtypeOf(expectedType
),
3803 "Run with -t smt for details.");
3805 // ensure it's a constant
3806 Assert(resultNode
.getKind() == kind::LAMBDA
|| resultNode
.isConst());
3808 if(options::abstractValues() && resultNode
.getType().isArray()) {
3809 resultNode
= d_private
->mkAbstractValue(resultNode
);
3810 Trace("smt") << "--- abstract value >> " << resultNode
<< endl
;
3813 return resultNode
.toExpr();
3816 bool SmtEngine::addToAssignment(const Expr
& ex
) {
3817 SmtScope
smts(this);
3818 finalOptionsAreSet();
3820 // Substitute out any abstract values in ex
3821 Expr e
= d_private
->substituteAbstractValues(Node::fromExpr(ex
)).toExpr();
3822 Type type
= e
.getType(options::typeChecking());
3824 PrettyCheckArgument(
3825 type
.isBoolean(), e
,
3826 "expected Boolean-typed variable or function application "
3827 "in addToAssignment()" );
3828 Node n
= e
.getNode();
3829 // must be an APPLY of a zero-ary defined function, or a variable
3830 PrettyCheckArgument(
3831 ( ( n
.getKind() == kind::APPLY
&&
3832 ( d_definedFunctions
->find(n
.getOperator()) !=
3833 d_definedFunctions
->end() ) &&
3834 n
.getNumChildren() == 0 ) ||
3836 "expected variable or defined-function application "
3837 "in addToAssignment(),\ngot %s", e
.toString().c_str() );
3838 if(!options::produceAssignments()) {
3841 if(d_assignments
== NULL
) {
3842 d_assignments
= new(true) AssignmentSet(d_context
);
3844 d_assignments
->insert(n
);
3849 // TODO(#1108): Simplify the error reporting of this method.
3850 vector
<pair
<Expr
, Expr
>> SmtEngine::getAssignment()
3852 Trace("smt") << "SMT getAssignment()" << endl
;
3853 SmtScope
smts(this);
3854 finalOptionsAreSet();
3855 if(Dump
.isOn("benchmark")) {
3856 Dump("benchmark") << GetAssignmentCommand();
3858 if(!options::produceAssignments()) {
3860 "Cannot get the current assignment when "
3861 "produce-assignments option is off.";
3862 throw ModalException(msg
);
3864 if(d_status
.isNull() ||
3865 d_status
.asSatisfiabilityResult() == Result::UNSAT
||
3866 d_problemExtended
) {
3868 "Cannot get the current assignment unless immediately "
3869 "preceded by SAT/INVALID or UNKNOWN response.";
3870 throw RecoverableModalException(msg
);
3873 vector
<pair
<Expr
,Expr
>> res
;
3874 if (d_assignments
!= nullptr)
3876 TypeNode boolType
= d_nodeManager
->booleanType();
3877 TheoryModel
* m
= d_theoryEngine
->getModel();
3878 for (AssignmentSet::key_iterator i
= d_assignments
->key_begin(),
3879 iend
= d_assignments
->key_end();
3884 Assert(as
.getType() == boolType
);
3886 Trace("smt") << "--- getting value of " << as
<< endl
;
3888 // Expand, then normalize
3889 unordered_map
<Node
, Node
, NodeHashFunction
> cache
;
3890 Node n
= d_private
->expandDefinitions(as
, cache
);
3891 n
= Rewriter::rewrite(n
);
3893 Trace("smt") << "--- getting value of " << n
<< endl
;
3897 resultNode
= m
->getValue(n
);
3900 // type-check the result we got
3901 Assert(resultNode
.isNull() || resultNode
.getType() == boolType
);
3903 // ensure it's a constant
3904 Assert(resultNode
.isConst());
3906 Assert(as
.getKind() == kind::APPLY
|| as
.isVar());
3907 Assert(as
.getKind() != kind::APPLY
|| as
.getNumChildren() == 0);
3908 res
.emplace_back(as
.toExpr(), resultNode
.toExpr());
3914 void SmtEngine::addToModelCommandAndDump(const Command
& c
, uint32_t flags
, bool userVisible
, const char* dumpTag
) {
3915 Trace("smt") << "SMT addToModelCommandAndDump(" << c
<< ")" << endl
;
3916 SmtScope
smts(this);
3917 // If we aren't yet fully inited, the user might still turn on
3918 // produce-models. So let's keep any commands around just in
3919 // case. This is useful in two cases: (1) SMT-LIBv1 auto-declares
3920 // sort "U" in QF_UF before setLogic() is run and we still want to
3921 // support finding card(U) with --finite-model-find, and (2) to
3922 // decouple SmtEngine and ExprManager if the user does a few
3923 // ExprManager::mkSort() before SmtEngine::setOption("produce-models")
3924 // and expects to find their cardinalities in the model.
3925 if(/* userVisible && */
3926 (!d_fullyInited
|| options::produceModels()) &&
3927 (flags
& ExprManager::VAR_FLAG_DEFINED
) == 0) {
3929 if(flags
& ExprManager::VAR_FLAG_GLOBAL
) {
3930 d_modelGlobalCommands
.push_back(c
.clone());
3932 d_modelCommands
->push_back(c
.clone());
3935 if(Dump
.isOn(dumpTag
)) {
3939 d_dumpCommands
.push_back(c
.clone());
3944 // TODO(#1108): Simplify the error reporting of this method.
3945 Model
* SmtEngine::getModel() {
3946 Trace("smt") << "SMT getModel()" << endl
;
3947 SmtScope
smts(this);
3949 finalOptionsAreSet();
3951 if(Dump
.isOn("benchmark")) {
3952 Dump("benchmark") << GetModelCommand();
3955 if (!options::assignFunctionValues())
3958 "Cannot get the model when --assign-function-values is false.";
3959 throw RecoverableModalException(msg
);
3962 if(d_status
.isNull() ||
3963 d_status
.asSatisfiabilityResult() == Result::UNSAT
||
3964 d_problemExtended
) {
3966 "Cannot get the current model unless immediately "
3967 "preceded by SAT/INVALID or UNKNOWN response.";
3968 throw RecoverableModalException(msg
);
3970 if(!options::produceModels()) {
3972 "Cannot get model when produce-models options is off.";
3973 throw ModalException(msg
);
3975 TheoryModel
* m
= d_theoryEngine
->getModel();
3977 if (options::produceModelCores())
3979 // If we enabled model cores, we compute a model core for m based on our
3980 // assertions using the model core builder utility
3981 std::vector
<Expr
> easserts
= getAssertions();
3982 ModelCoreBuilder::setModelCore(easserts
, m
);
3984 m
->d_inputName
= d_filename
;
3988 std::pair
<Expr
, Expr
> SmtEngine::getSepHeapAndNilExpr(void)
3990 if (!d_logic
.isTheoryEnabled(THEORY_SEP
))
3993 "Cannot obtain separation logic expressions if not using the "
3994 "separation logic theory.";
3995 throw RecoverableModalException(msg
);
3997 NodeManagerScope
nms(d_nodeManager
);
4000 Model
* m
= getModel();
4001 if (m
->getHeapModel(heap
, nil
))
4003 return std::make_pair(heap
, nil
);
4006 "SmtEngine::getSepHeapAndNilExpr(): failed to obtain heap/nil "
4007 "expressions from theory model.");
4010 Expr
SmtEngine::getSepHeapExpr() { return getSepHeapAndNilExpr().first
; }
4012 Expr
SmtEngine::getSepNilExpr() { return getSepHeapAndNilExpr().second
; }
4014 UnsatCore
SmtEngine::getUnsatCoreInternal()
4017 if (!options::unsatCores())
4019 throw ModalException(
4020 "Cannot get an unsat core when produce-unsat-cores option is off.");
4022 if (d_status
.isNull() || d_status
.asSatisfiabilityResult() != Result::UNSAT
4023 || d_problemExtended
)
4025 throw RecoverableModalException(
4026 "Cannot get an unsat core unless immediately preceded by UNSAT/VALID "
4030 d_proofManager
->traceUnsatCore(); // just to trigger core creation
4031 return UnsatCore(this, d_proofManager
->extractUnsatCore());
4032 #else /* IS_PROOFS_BUILD */
4033 throw ModalException(
4034 "This build of CVC4 doesn't have proof support (required for unsat "
4036 #endif /* IS_PROOFS_BUILD */
4039 void SmtEngine::checkUnsatCore() {
4040 Assert(options::unsatCores(), "cannot check unsat core if unsat cores are turned off");
4042 Notice() << "SmtEngine::checkUnsatCore(): generating unsat core" << endl
;
4043 UnsatCore core
= getUnsatCore();
4045 SmtEngine
coreChecker(d_exprManager
);
4046 coreChecker
.setLogic(getLogicInfo());
4049 std::vector
<Command
*>::const_iterator itg
= d_defineCommands
.begin();
4050 for (; itg
!= d_defineCommands
.end(); ++itg
) {
4051 (*itg
)->invoke(&coreChecker
);
4055 Notice() << "SmtEngine::checkUnsatCore(): pushing core assertions (size == " << core
.size() << ")" << endl
;
4056 for(UnsatCore::iterator i
= core
.begin(); i
!= core
.end(); ++i
) {
4057 Notice() << "SmtEngine::checkUnsatCore(): pushing core member " << *i
<< endl
;
4058 coreChecker
.assertFormula(*i
);
4060 const bool checkUnsatCores
= options::checkUnsatCores();
4063 options::checkUnsatCores
.set(false);
4064 options::checkProofs
.set(false);
4065 r
= coreChecker
.checkSat();
4067 options::checkUnsatCores
.set(checkUnsatCores
);
4070 Notice() << "SmtEngine::checkUnsatCore(): result is " << r
<< endl
;
4071 if(r
.asSatisfiabilityResult().isUnknown()) {
4072 InternalError("SmtEngine::checkUnsatCore(): could not check core result unknown.");
4075 if(r
.asSatisfiabilityResult().isSat()) {
4076 InternalError("SmtEngine::checkUnsatCore(): produced core was satisfiable.");
4080 void SmtEngine::checkModel(bool hardFailure
) {
4081 // --check-model implies --produce-assertions, which enables the
4082 // assertion list, so we should be ok.
4083 Assert(d_assertionList
!= NULL
, "don't have an assertion list to check in SmtEngine::checkModel()");
4085 TimerStat::CodeTimer
checkModelTimer(d_stats
->d_checkModelTime
);
4087 // Throughout, we use Notice() to give diagnostic output.
4089 // If this function is running, the user gave --check-model (or equivalent),
4090 // and if Notice() is on, the user gave --verbose (or equivalent).
4092 Notice() << "SmtEngine::checkModel(): generating model" << endl
;
4093 TheoryModel
* m
= d_theoryEngine
->getModel();
4095 // check-model is not guaranteed to succeed if approximate values were used
4096 if (m
->hasApproximations())
4099 << "WARNING: running check-model on a model with approximate values..."
4103 // Check individual theory assertions
4104 d_theoryEngine
->checkTheoryAssertionsWithModel(hardFailure
);
4109 // We have a "fake context" for the substitution map (we don't need it
4110 // to be context-dependent)
4111 context::Context fakeContext
;
4112 SubstitutionMap
substitutions(&fakeContext
, /* substituteUnderQuantifiers = */ false);
4114 for(size_t k
= 0; k
< m
->getNumCommands(); ++k
) {
4115 const DeclareFunctionCommand
* c
= dynamic_cast<const DeclareFunctionCommand
*>(m
->getCommand(k
));
4116 Notice() << "SmtEngine::checkModel(): model command " << k
<< " : " << m
->getCommand(k
) << endl
;
4118 // we don't care about DECLARE-DATATYPES, DECLARE-SORT, ...
4119 Notice() << "SmtEngine::checkModel(): skipping..." << endl
;
4121 // We have a DECLARE-FUN:
4123 // We'll first do some checks, then add to our substitution map
4124 // the mapping: function symbol |-> value
4126 Expr func
= c
->getFunction();
4127 Node val
= m
->getValue(func
);
4129 Notice() << "SmtEngine::checkModel(): adding substitution: " << func
<< " |-> " << val
<< endl
;
4131 // (1) if the value is a lambda, ensure the lambda doesn't contain the
4132 // function symbol (since then the definition is recursive)
4133 if (val
.getKind() == kind::LAMBDA
) {
4134 // first apply the model substitutions we have so far
4135 Debug("boolean-terms") << "applying subses to " << val
[1] << endl
;
4136 Node n
= substitutions
.apply(val
[1]);
4137 Debug("boolean-terms") << "++ got " << n
<< endl
;
4138 // now check if n contains func by doing a substitution
4139 // [func->func2] and checking equality of the Nodes.
4140 // (this just a way to check if func is in n.)
4141 SubstitutionMap
subs(&fakeContext
);
4142 Node func2
= NodeManager::currentNM()->mkSkolem("", TypeNode::fromType(func
.getType()), "", NodeManager::SKOLEM_NO_NOTIFY
);
4143 subs
.addSubstitution(func
, func2
);
4144 if(subs
.apply(n
) != n
) {
4145 Notice() << "SmtEngine::checkModel(): *** PROBLEM: MODEL VALUE DEFINED IN TERMS OF ITSELF ***" << endl
;
4147 ss
<< "SmtEngine::checkModel(): ERRORS SATISFYING ASSERTIONS WITH MODEL:" << endl
4148 << "considering model value for " << func
<< endl
4149 << "body of lambda is: " << val
<< endl
;
4151 ss
<< "body substitutes to: " << n
<< endl
;
4153 ss
<< "so " << func
<< " is defined in terms of itself." << endl
4154 << "Run with `--check-models -v' for additional diagnostics.";
4155 InternalError(ss
.str());
4159 // (2) check that the value is actually a value
4160 else if (!val
.isConst()) {
4161 Notice() << "SmtEngine::checkModel(): *** PROBLEM: MODEL VALUE NOT A CONSTANT ***" << endl
;
4163 ss
<< "SmtEngine::checkModel(): ERRORS SATISFYING ASSERTIONS WITH MODEL:" << endl
4164 << "model value for " << func
<< endl
4165 << " is " << val
<< endl
4166 << "and that is not a constant (.isConst() == false)." << endl
4167 << "Run with `--check-models -v' for additional diagnostics.";
4168 InternalError(ss
.str());
4171 // (3) check that it's the correct (sub)type
4172 // This was intended to be a more general check, but for now we can't do that because
4173 // e.g. "1" is an INT, which isn't a subrange type [1..10] (etc.).
4174 else if(func
.getType().isInteger() && !val
.getType().isInteger()) {
4175 Notice() << "SmtEngine::checkModel(): *** PROBLEM: MODEL VALUE NOT CORRECT TYPE ***" << endl
;
4177 ss
<< "SmtEngine::checkModel(): ERRORS SATISFYING ASSERTIONS WITH MODEL:" << endl
4178 << "model value for " << func
<< endl
4179 << " is " << val
<< endl
4180 << "value type is " << val
.getType() << endl
4181 << "should be of type " << func
.getType() << endl
4182 << "Run with `--check-models -v' for additional diagnostics.";
4183 InternalError(ss
.str());
4186 // (4) checks complete, add the substitution
4187 Debug("boolean-terms") << "cm: adding subs " << func
<< " :=> " << val
<< endl
;
4188 substitutions
.addSubstitution(func
, val
);
4192 // Now go through all our user assertions checking if they're satisfied.
4193 for(AssertionList::const_iterator i
= d_assertionList
->begin(); i
!= d_assertionList
->end(); ++i
) {
4194 Notice() << "SmtEngine::checkModel(): checking assertion " << *i
<< endl
;
4195 Node n
= Node::fromExpr(*i
);
4197 // Apply any define-funs from the problem.
4199 unordered_map
<Node
, Node
, NodeHashFunction
> cache
;
4200 n
= d_private
->expandDefinitions(n
, cache
);
4202 Notice() << "SmtEngine::checkModel(): -- expands to " << n
<< endl
;
4204 // Apply our model value substitutions.
4205 Debug("boolean-terms") << "applying subses to " << n
<< endl
;
4206 n
= substitutions
.apply(n
);
4207 Debug("boolean-terms") << "++ got " << n
<< endl
;
4208 Notice() << "SmtEngine::checkModel(): -- substitutes to " << n
<< endl
;
4210 if( n
.getKind() != kind::REWRITE_RULE
){
4211 // In case it's a quantifier (or contains one), look up its value before
4212 // simplifying, or the quantifier might be irreparably altered.
4214 Notice() << "SmtEngine::checkModel(): -- get value : " << n
<< std::endl
;
4216 // Note this "skip" is done here, rather than above. This is
4217 // because (1) the quantifier could in principle simplify to false,
4218 // which should be reported, and (2) checking for the quantifier
4219 // above, before simplification, doesn't catch buried quantifiers
4220 // anyway (those not at the top-level).
4221 Notice() << "SmtEngine::checkModel(): -- skipping rewrite-rules assertion"
4226 // Simplify the result.
4227 n
= d_private
->simplify(n
);
4228 Notice() << "SmtEngine::checkModel(): -- simplifies to " << n
<< endl
;
4230 // Replace the already-known ITEs (this is important for ground ITEs under quantifiers).
4231 n
= d_private
->d_iteRemover
.replace(n
);
4232 Notice() << "SmtEngine::checkModel(): -- ite replacement gives " << n
<< endl
;
4234 // Apply our model value substitutions (again), as things may have been simplified.
4235 Debug("boolean-terms") << "applying subses to " << n
<< endl
;
4236 n
= substitutions
.apply(n
);
4237 Debug("boolean-terms") << "++ got " << n
<< endl
;
4238 Notice() << "SmtEngine::checkModel(): -- re-substitutes to " << n
<< endl
;
4240 // As a last-ditch effort, ask model to simplify it.
4241 // Presently, this is only an issue for quantifiers, which can have a value
4242 // but don't show up in our substitution map above.
4244 Notice() << "SmtEngine::checkModel(): -- model-substitutes to " << n
<< endl
;
4246 if( d_logic
.isQuantified() ){
4247 // AJR: since quantified formulas are not checkable, we assign them to true/false based on the satisfying assignment.
4248 // however, quantified formulas can be modified during preprocess, so they may not correspond to those in the satisfying assignment.
4249 // hence we use a relaxed version of check model here.
4250 // this is necessary until preprocessing passes explicitly record how they rewrite quantified formulas
4251 if( hardFailure
&& !n
.isConst() && n
.getKind() != kind::LAMBDA
){
4252 Notice() << "SmtEngine::checkModel(): -- relax check model wrt quantified formulas..." << endl
;
4253 AlwaysAssert( quantifiers::QuantifiersRewriter::containsQuantifiers( n
) );
4254 Warning() << "Warning : SmtEngine::checkModel(): cannot check simplified assertion : " << n
<< endl
;
4258 AlwaysAssert(!hardFailure
|| n
.isConst() || n
.getKind() == kind::LAMBDA
);
4260 // The result should be == true.
4261 if(n
!= NodeManager::currentNM()->mkConst(true)) {
4262 Notice() << "SmtEngine::checkModel(): *** PROBLEM: EXPECTED `TRUE' ***"
4265 ss
<< "SmtEngine::checkModel(): "
4266 << "ERRORS SATISFYING ASSERTIONS WITH MODEL:" << endl
4267 << "assertion: " << *i
<< endl
4268 << "simplifies to: " << n
<< endl
4269 << "expected `true'." << endl
4270 << "Run with `--check-models -v' for additional diagnostics.";
4272 InternalError(ss
.str());
4274 Warning() << ss
.str() << endl
;
4278 Notice() << "SmtEngine::checkModel(): all assertions checked out OK !" << endl
;
4281 void SmtEngine::checkSynthSolution()
4283 NodeManager
* nm
= NodeManager::currentNM();
4284 Notice() << "SmtEngine::checkSynthSolution(): checking synthesis solution" << endl
;
4285 map
<Node
, Node
> sol_map
;
4286 /* Get solutions and build auxiliary vectors for substituting */
4287 d_theoryEngine
->getSynthSolutions(sol_map
);
4288 if (sol_map
.empty())
4290 Trace("check-synth-sol") << "No solution to check!\n";
4293 Trace("check-synth-sol") << "Got solution map:\n";
4294 std::vector
<Node
> function_vars
, function_sols
;
4295 for (const auto& pair
: sol_map
)
4297 Trace("check-synth-sol") << pair
.first
<< " --> " << pair
.second
<< "\n";
4298 function_vars
.push_back(pair
.first
);
4299 function_sols
.push_back(pair
.second
);
4301 Trace("check-synth-sol") << "Starting new SMT Engine\n";
4302 /* Start new SMT engine to check solutions */
4303 SmtEngine
solChecker(d_exprManager
);
4304 solChecker
.setLogic(getLogicInfo());
4305 setOption("check-synth-sol", SExpr("false"));
4307 Trace("check-synth-sol") << "Retrieving assertions\n";
4308 // Build conjecture from original assertions
4309 if (d_assertionList
== NULL
)
4311 Trace("check-synth-sol") << "No assertions to check\n";
4314 for (AssertionList::const_iterator i
= d_assertionList
->begin();
4315 i
!= d_assertionList
->end();
4318 Notice() << "SmtEngine::checkSynthSolution(): checking assertion " << *i
<< endl
;
4319 Trace("check-synth-sol") << "Retrieving assertion " << *i
<< "\n";
4320 Node conj
= Node::fromExpr(*i
);
4321 // Apply any define-funs from the problem.
4323 unordered_map
<Node
, Node
, NodeHashFunction
> cache
;
4324 conj
= d_private
->expandDefinitions(conj
, cache
);
4326 Notice() << "SmtEngine::checkSynthSolution(): -- expands to " << conj
<< endl
;
4327 Trace("check-synth-sol") << "Expanded assertion " << conj
<< "\n";
4328 if (conj
.getKind() != kind::FORALL
)
4330 Trace("check-synth-sol") << "Not a checkable assertion.\n";
4334 // Apply solution map to conjecture body
4336 /* Whether property is quantifier free */
4337 if (conj
[1].getKind() != kind::EXISTS
)
4339 conjBody
= conj
[1].substitute(function_vars
.begin(),
4340 function_vars
.end(),
4341 function_sols
.begin(),
4342 function_sols
.end());
4346 conjBody
= conj
[1][1].substitute(function_vars
.begin(),
4347 function_vars
.end(),
4348 function_sols
.begin(),
4349 function_sols
.end());
4351 /* Skolemize property */
4352 std::vector
<Node
> vars
, skos
;
4353 for (unsigned j
= 0, size
= conj
[1][0].getNumChildren(); j
< size
; ++j
)
4355 vars
.push_back(conj
[1][0][j
]);
4356 std::stringstream ss
;
4358 skos
.push_back(nm
->mkSkolem(ss
.str(), conj
[1][0][j
].getType()));
4359 Trace("check-synth-sol") << "\tSkolemizing " << conj
[1][0][j
] << " to "
4360 << skos
.back() << "\n";
4362 conjBody
= conjBody
.substitute(
4363 vars
.begin(), vars
.end(), skos
.begin(), skos
.end());
4365 Notice() << "SmtEngine::checkSynthSolution(): -- body substitutes to "
4366 << conjBody
<< endl
;
4367 Trace("check-synth-sol") << "Substituted body of assertion to " << conjBody
4369 solChecker
.assertFormula(conjBody
.toExpr());
4370 Result r
= solChecker
.checkSat();
4371 Notice() << "SmtEngine::checkSynthSolution(): result is " << r
<< endl
;
4372 Trace("check-synth-sol") << "Satsifiability check: " << r
<< "\n";
4373 if (r
.asSatisfiabilityResult().isUnknown())
4376 "SmtEngine::checkSynthSolution(): could not check solution, result "
4379 else if (r
.asSatisfiabilityResult().isSat())
4382 "SmtEngine::checkSynthSolution(): produced solution leads to "
4383 "satisfiable negated conjecture.");
4385 solChecker
.resetAssertions();
4389 // TODO(#1108): Simplify the error reporting of this method.
4390 UnsatCore
SmtEngine::getUnsatCore() {
4391 Trace("smt") << "SMT getUnsatCore()" << endl
;
4392 SmtScope
smts(this);
4393 finalOptionsAreSet();
4394 if(Dump
.isOn("benchmark")) {
4395 Dump("benchmark") << GetUnsatCoreCommand();
4397 return getUnsatCoreInternal();
4400 // TODO(#1108): Simplify the error reporting of this method.
4401 const Proof
& SmtEngine::getProof()
4403 Trace("smt") << "SMT getProof()" << endl
;
4404 SmtScope
smts(this);
4405 finalOptionsAreSet();
4406 if(Dump
.isOn("benchmark")) {
4407 Dump("benchmark") << GetProofCommand();
4410 if(!options::proof()) {
4411 throw ModalException("Cannot get a proof when produce-proofs option is off.");
4413 if(d_status
.isNull() ||
4414 d_status
.asSatisfiabilityResult() != Result::UNSAT
||
4415 d_problemExtended
) {
4416 throw RecoverableModalException(
4417 "Cannot get a proof unless immediately preceded by UNSAT/VALID "
4421 return ProofManager::getProof(this);
4422 #else /* IS_PROOFS_BUILD */
4423 throw ModalException("This build of CVC4 doesn't have proof support.");
4424 #endif /* IS_PROOFS_BUILD */
4427 void SmtEngine::printInstantiations( std::ostream
& out
) {
4428 SmtScope
smts(this);
4429 if( options::instFormatMode()==INST_FORMAT_MODE_SZS
){
4430 out
<< "% SZS output start Proof for " << d_filename
.c_str() << std::endl
;
4432 if( d_theoryEngine
){
4433 d_theoryEngine
->printInstantiations( out
);
4437 if( options::instFormatMode()==INST_FORMAT_MODE_SZS
){
4438 out
<< "% SZS output end Proof for " << d_filename
.c_str() << std::endl
;
4442 void SmtEngine::printSynthSolution( std::ostream
& out
) {
4443 SmtScope
smts(this);
4444 if( d_theoryEngine
){
4445 d_theoryEngine
->printSynthSolution( out
);
4451 void SmtEngine::getSynthSolutions(std::map
<Expr
, Expr
>& sol_map
)
4453 SmtScope
smts(this);
4454 map
<Node
, Node
> sol_mapn
;
4455 Assert(d_theoryEngine
!= nullptr);
4456 d_theoryEngine
->getSynthSolutions(sol_mapn
);
4457 for (std::pair
<const Node
, Node
>& s
: sol_mapn
)
4459 sol_map
[s
.first
.toExpr()] = s
.second
.toExpr();
4463 Expr
SmtEngine::doQuantifierElimination(const Expr
& e
, bool doFull
, bool strict
)
4465 SmtScope
smts(this);
4466 if(!d_logic
.isPure(THEORY_ARITH
) && strict
){
4467 Warning() << "Unexpected logic for quantifier elimination " << d_logic
<< endl
;
4469 Trace("smt-qe") << "Do quantifier elimination " << e
<< std::endl
;
4470 Node n_e
= Node::fromExpr( e
);
4471 if (n_e
.getKind() != kind::EXISTS
&& n_e
.getKind() != kind::FORALL
)
4473 throw ModalException(
4474 "Expecting a quantified formula as argument to get-qe.");
4476 //tag the quantified formula with the quant-elim attribute
4477 TypeNode t
= NodeManager::currentNM()->booleanType();
4478 Node n_attr
= NodeManager::currentNM()->mkSkolem("qe", t
, "Auxiliary variable for qe attr.");
4479 std::vector
< Node
> node_values
;
4480 d_theoryEngine
->setUserAttribute( doFull
? "quant-elim" : "quant-elim-partial", n_attr
, node_values
, "");
4481 n_attr
= NodeManager::currentNM()->mkNode(kind::INST_ATTRIBUTE
, n_attr
);
4482 n_attr
= NodeManager::currentNM()->mkNode(kind::INST_PATTERN_LIST
, n_attr
);
4483 std::vector
< Node
> e_children
;
4484 e_children
.push_back( n_e
[0] );
4485 e_children
.push_back(n_e
.getKind() == kind::EXISTS
? n_e
[1]
4487 e_children
.push_back( n_attr
);
4488 Node nn_e
= NodeManager::currentNM()->mkNode( kind::EXISTS
, e_children
);
4489 Trace("smt-qe-debug") << "Query for quantifier elimination : " << nn_e
<< std::endl
;
4490 Assert( nn_e
.getNumChildren()==3 );
4491 Result r
= checkSatisfiability(nn_e
.toExpr(), true, true);
4492 Trace("smt-qe") << "Query returned " << r
<< std::endl
;
4493 if(r
.asSatisfiabilityResult().isSat() != Result::UNSAT
) {
4494 if( r
.asSatisfiabilityResult().isSat() != Result::SAT
&& doFull
){
4496 ss
<< "While performing quantifier elimination, unexpected result : " << r
<< " for query.";
4497 InternalError(ss
.str().c_str());
4499 std::vector
< Node
> inst_qs
;
4500 d_theoryEngine
->getInstantiatedQuantifiedFormulas( inst_qs
);
4501 Assert( inst_qs
.size()<=1 );
4503 if( inst_qs
.size()==1 ){
4504 Node top_q
= inst_qs
[0];
4505 //Node top_q = Rewriter::rewrite( nn_e ).negate();
4506 Assert( top_q
.getKind()==kind::FORALL
);
4507 Trace("smt-qe") << "Get qe for " << top_q
<< std::endl
;
4508 ret_n
= d_theoryEngine
->getInstantiatedConjunction( top_q
);
4509 Trace("smt-qe") << "Returned : " << ret_n
<< std::endl
;
4510 if (n_e
.getKind() == kind::EXISTS
)
4512 ret_n
= Rewriter::rewrite(ret_n
.negate());
4515 ret_n
= NodeManager::currentNM()->mkConst(n_e
.getKind() != kind::EXISTS
);
4517 // do extended rewrite to minimize the size of the formula aggressively
4518 theory::quantifiers::ExtendedRewriter
extr(true);
4519 ret_n
= extr
.extendedRewrite(ret_n
);
4520 return ret_n
.toExpr();
4522 return NodeManager::currentNM()
4523 ->mkConst(n_e
.getKind() == kind::EXISTS
)
4528 void SmtEngine::getInstantiatedQuantifiedFormulas( std::vector
< Expr
>& qs
) {
4529 SmtScope
smts(this);
4530 if( d_theoryEngine
){
4531 std::vector
< Node
> qs_n
;
4532 d_theoryEngine
->getInstantiatedQuantifiedFormulas( qs_n
);
4533 for( unsigned i
=0; i
<qs_n
.size(); i
++ ){
4534 qs
.push_back( qs_n
[i
].toExpr() );
4541 void SmtEngine::getInstantiations( Expr q
, std::vector
< Expr
>& insts
) {
4542 SmtScope
smts(this);
4543 if( d_theoryEngine
){
4544 std::vector
< Node
> insts_n
;
4545 d_theoryEngine
->getInstantiations( Node::fromExpr( q
), insts_n
);
4546 for( unsigned i
=0; i
<insts_n
.size(); i
++ ){
4547 insts
.push_back( insts_n
[i
].toExpr() );
4554 void SmtEngine::getInstantiationTermVectors( Expr q
, std::vector
< std::vector
< Expr
> >& tvecs
) {
4555 SmtScope
smts(this);
4556 Assert(options::trackInstLemmas());
4557 if( d_theoryEngine
){
4558 std::vector
< std::vector
< Node
> > tvecs_n
;
4559 d_theoryEngine
->getInstantiationTermVectors( Node::fromExpr( q
), tvecs_n
);
4560 for( unsigned i
=0; i
<tvecs_n
.size(); i
++ ){
4561 std::vector
< Expr
> tvec
;
4562 for( unsigned j
=0; j
<tvecs_n
[i
].size(); j
++ ){
4563 tvec
.push_back( tvecs_n
[i
][j
].toExpr() );
4565 tvecs
.push_back( tvec
);
4572 vector
<Expr
> SmtEngine::getAssertions() {
4573 SmtScope
smts(this);
4574 finalOptionsAreSet();
4576 if(Dump
.isOn("benchmark")) {
4577 Dump("benchmark") << GetAssertionsCommand();
4579 Trace("smt") << "SMT getAssertions()" << endl
;
4580 if(!options::produceAssertions()) {
4582 "Cannot query the current assertion list when not in produce-assertions mode.";
4583 throw ModalException(msg
);
4585 Assert(d_assertionList
!= NULL
);
4586 // copy the result out
4587 return vector
<Expr
>(d_assertionList
->begin(), d_assertionList
->end());
4590 void SmtEngine::push()
4592 SmtScope
smts(this);
4593 finalOptionsAreSet();
4595 Trace("smt") << "SMT push()" << endl
;
4596 d_private
->notifyPush();
4597 d_private
->processAssertions();
4598 if(Dump
.isOn("benchmark")) {
4599 Dump("benchmark") << PushCommand();
4601 if(!options::incrementalSolving()) {
4602 throw ModalException("Cannot push when not solving incrementally (use --incremental)");
4605 // check to see if a postsolve() is pending
4606 if(d_needPostsolve
) {
4607 d_theoryEngine
->postsolve();
4608 d_needPostsolve
= false;
4611 // The problem isn't really "extended" yet, but this disallows
4612 // get-model after a push, simplifying our lives somewhat and
4613 // staying symmtric with pop.
4614 setProblemExtended(true);
4616 d_userLevels
.push_back(d_userContext
->getLevel());
4618 Trace("userpushpop") << "SmtEngine: pushed to level "
4619 << d_userContext
->getLevel() << endl
;
4622 void SmtEngine::pop() {
4623 SmtScope
smts(this);
4624 finalOptionsAreSet();
4625 Trace("smt") << "SMT pop()" << endl
;
4626 if(Dump
.isOn("benchmark")) {
4627 Dump("benchmark") << PopCommand();
4629 if(!options::incrementalSolving()) {
4630 throw ModalException("Cannot pop when not solving incrementally (use --incremental)");
4632 if(d_userLevels
.size() == 0) {
4633 throw ModalException("Cannot pop beyond the first user frame");
4636 // check to see if a postsolve() is pending
4637 if(d_needPostsolve
) {
4638 d_theoryEngine
->postsolve();
4639 d_needPostsolve
= false;
4642 // The problem isn't really "extended" yet, but this disallows
4643 // get-model after a pop, simplifying our lives somewhat. It might
4644 // not be strictly necessary to do so, since the pops occur lazily,
4645 // but also it would be weird to have a legally-executed (get-model)
4646 // that only returns a subset of the assignment (because the rest
4647 // is no longer in scope!).
4648 setProblemExtended(true);
4650 AlwaysAssert(d_userContext
->getLevel() > 0);
4651 AlwaysAssert(d_userLevels
.back() < d_userContext
->getLevel());
4652 while (d_userLevels
.back() < d_userContext
->getLevel()) {
4655 d_userLevels
.pop_back();
4657 // Clear out assertion queues etc., in case anything is still in there
4658 d_private
->notifyPop();
4660 Trace("userpushpop") << "SmtEngine: popped to level "
4661 << d_userContext
->getLevel() << endl
;
4662 // FIXME: should we reset d_status here?
4663 // SMT-LIBv2 spec seems to imply no, but it would make sense to..
4666 void SmtEngine::internalPush() {
4667 Assert(d_fullyInited
);
4668 Trace("smt") << "SmtEngine::internalPush()" << endl
;
4670 if(options::incrementalSolving()) {
4671 d_private
->processAssertions();
4672 TimerStat::CodeTimer
pushPopTimer(d_stats
->d_pushPopTime
);
4673 d_userContext
->push();
4674 // the d_context push is done inside of the SAT solver
4675 d_propEngine
->push();
4679 void SmtEngine::internalPop(bool immediate
) {
4680 Assert(d_fullyInited
);
4681 Trace("smt") << "SmtEngine::internalPop()" << endl
;
4682 if(options::incrementalSolving()) {
4690 void SmtEngine::doPendingPops() {
4691 Assert(d_pendingPops
== 0 || options::incrementalSolving());
4692 while(d_pendingPops
> 0) {
4693 TimerStat::CodeTimer
pushPopTimer(d_stats
->d_pushPopTime
);
4694 d_propEngine
->pop();
4695 // the d_context pop is done inside of the SAT solver
4696 d_userContext
->pop();
4701 void SmtEngine::reset()
4703 SmtScope
smts(this);
4704 ExprManager
*em
= d_exprManager
;
4705 Trace("smt") << "SMT reset()" << endl
;
4706 if(Dump
.isOn("benchmark")) {
4707 Dump("benchmark") << ResetCommand();
4710 opts
.copyValues(d_originalOptions
);
4712 NodeManager::fromExprManager(em
)->getOptions().copyValues(opts
);
4713 new(this) SmtEngine(em
);
4716 void SmtEngine::resetAssertions()
4718 SmtScope
smts(this);
4721 Trace("smt") << "SMT resetAssertions()" << endl
;
4722 if(Dump
.isOn("benchmark")) {
4723 Dump("benchmark") << ResetAssertionsCommand();
4726 while(!d_userLevels
.empty()) {
4730 // Also remember the global push/pop around everything.
4731 Assert(d_userLevels
.size() == 0 && d_userContext
->getLevel() == 1);
4732 d_context
->popto(0);
4733 d_userContext
->popto(0);
4734 DeleteAndClearCommandVector(d_modelGlobalCommands
);
4735 d_userContext
->push();
4739 void SmtEngine::interrupt()
4741 if(!d_fullyInited
) {
4744 d_propEngine
->interrupt();
4745 d_theoryEngine
->interrupt();
4748 void SmtEngine::setResourceLimit(unsigned long units
, bool cumulative
) {
4749 d_private
->getResourceManager()->setResourceLimit(units
, cumulative
);
4751 void SmtEngine::setTimeLimit(unsigned long milis
, bool cumulative
) {
4752 d_private
->getResourceManager()->setTimeLimit(milis
, cumulative
);
4755 unsigned long SmtEngine::getResourceUsage() const {
4756 return d_private
->getResourceManager()->getResourceUsage();
4759 unsigned long SmtEngine::getTimeUsage() const {
4760 return d_private
->getResourceManager()->getTimeUsage();
4763 unsigned long SmtEngine::getResourceRemaining() const
4765 return d_private
->getResourceManager()->getResourceRemaining();
4768 unsigned long SmtEngine::getTimeRemaining() const
4770 return d_private
->getResourceManager()->getTimeRemaining();
4773 Statistics
SmtEngine::getStatistics() const
4775 return Statistics(*d_statisticsRegistry
);
4778 SExpr
SmtEngine::getStatistic(std::string name
) const
4780 return d_statisticsRegistry
->getStatistic(name
);
4783 void SmtEngine::safeFlushStatistics(int fd
) const {
4784 d_statisticsRegistry
->safeFlushInformation(fd
);
4787 void SmtEngine::setUserAttribute(const std::string
& attr
,
4789 const std::vector
<Expr
>& expr_values
,
4790 const std::string
& str_value
)
4792 SmtScope
smts(this);
4793 std::vector
<Node
> node_values
;
4794 for( unsigned i
=0; i
<expr_values
.size(); i
++ ){
4795 node_values
.push_back( expr_values
[i
].getNode() );
4797 d_theoryEngine
->setUserAttribute(attr
, expr
.getNode(), node_values
, str_value
);
4800 void SmtEngine::setPrintFuncInModel(Expr f
, bool p
) {
4801 Trace("setp-model") << "Set printInModel " << f
<< " to " << p
<< std::endl
;
4802 for( unsigned i
=0; i
<d_modelGlobalCommands
.size(); i
++ ){
4803 Command
* c
= d_modelGlobalCommands
[i
];
4804 DeclareFunctionCommand
* dfc
= dynamic_cast<DeclareFunctionCommand
*>(c
);
4806 if( dfc
->getFunction()==f
){
4807 dfc
->setPrintInModel( p
);
4811 for( unsigned i
=0; i
<d_modelCommands
->size(); i
++ ){
4812 Command
* c
= (*d_modelCommands
)[i
];
4813 DeclareFunctionCommand
* dfc
= dynamic_cast<DeclareFunctionCommand
*>(c
);
4815 if( dfc
->getFunction()==f
){
4816 dfc
->setPrintInModel( p
);
4822 void SmtEngine::beforeSearch()
4825 throw ModalException(
4826 "SmtEngine::beforeSearch called after initialization.");
4831 void SmtEngine::setOption(const std::string
& key
, const CVC4::SExpr
& value
)
4833 NodeManagerScope
nms(d_nodeManager
);
4834 Trace("smt") << "SMT setOption(" << key
<< ", " << value
<< ")" << endl
;
4836 if(Dump
.isOn("benchmark")) {
4837 Dump("benchmark") << SetOptionCommand(key
, value
);
4840 if(key
== "command-verbosity") {
4841 if(!value
.isAtom()) {
4842 const vector
<SExpr
>& cs
= value
.getChildren();
4843 if(cs
.size() == 2 &&
4844 (cs
[0].isKeyword() || cs
[0].isString()) &&
4845 cs
[1].isInteger()) {
4846 string c
= cs
[0].getValue();
4847 const Integer
& v
= cs
[1].getIntegerValue();
4848 if(v
< 0 || v
> 2) {
4849 throw OptionException("command-verbosity must be 0, 1, or 2");
4851 d_commandVerbosity
[c
] = v
;
4855 throw OptionException("command-verbosity value must be a tuple (command-name, integer)");
4858 if(!value
.isAtom()) {
4859 throw OptionException("bad value for :" + key
);
4862 string optionarg
= value
.getValue();
4863 Options
& nodeManagerOptions
= NodeManager::currentNM()->getOptions();
4864 nodeManagerOptions
.setOption(key
, optionarg
);
4867 CVC4::SExpr
SmtEngine::getOption(const std::string
& key
) const
4869 NodeManagerScope
nms(d_nodeManager
);
4871 Trace("smt") << "SMT getOption(" << key
<< ")" << endl
;
4873 if(key
.length() >= 18 &&
4874 key
.compare(0, 18, "command-verbosity:") == 0) {
4875 map
<string
, Integer
>::const_iterator i
= d_commandVerbosity
.find(key
.c_str() + 18);
4876 if(i
!= d_commandVerbosity
.end()) {
4877 return SExpr((*i
).second
);
4879 i
= d_commandVerbosity
.find("*");
4880 if(i
!= d_commandVerbosity
.end()) {
4881 return SExpr((*i
).second
);
4883 return SExpr(Integer(2));
4886 if(Dump
.isOn("benchmark")) {
4887 Dump("benchmark") << GetOptionCommand(key
);
4890 if(key
== "command-verbosity") {
4891 vector
<SExpr
> result
;
4892 SExpr defaultVerbosity
;
4893 for(map
<string
, Integer
>::const_iterator i
= d_commandVerbosity
.begin();
4894 i
!= d_commandVerbosity
.end();
4897 v
.push_back(SExpr((*i
).first
));
4898 v
.push_back(SExpr((*i
).second
));
4899 if((*i
).first
== "*") {
4900 // put the default at the end of the SExpr
4901 defaultVerbosity
= SExpr(v
);
4903 result
.push_back(SExpr(v
));
4906 // put the default at the end of the SExpr
4907 if(!defaultVerbosity
.isAtom()) {
4908 result
.push_back(defaultVerbosity
);
4910 // ensure the default is always listed
4912 v
.push_back(SExpr("*"));
4913 v
.push_back(SExpr(Integer(2)));
4914 result
.push_back(SExpr(v
));
4916 return SExpr(result
);
4919 Options
& nodeManagerOptions
= NodeManager::currentNM()->getOptions();
4920 return SExpr::parseAtom(nodeManagerOptions
.getOption(key
));
4923 void SmtEngine::setReplayStream(ExprStream
* replayStream
) {
4924 AlwaysAssert(!d_fullyInited
,
4925 "Cannot set replay stream once fully initialized");
4926 d_replayStream
= replayStream
;
4929 bool SmtEngine::getExpressionName(Expr e
, std::string
& name
) const {
4930 return d_private
->getExpressionName(e
, name
);
4933 void SmtEngine::setExpressionName(Expr e
, const std::string
& name
) {
4934 Trace("smt-debug") << "Set expression name " << e
<< " to " << name
<< std::endl
;
4935 d_private
->setExpressionName(e
,name
);
4938 }/* CVC4 namespace */