1 /********************* */
2 /*! \file smt_engine.cpp
4 ** Top contributors (to current version):
5 ** Morgan Deters, Andrew Reynolds, Tim King
6 ** This file is part of the CVC4 project.
7 ** Copyright (c) 2009-2018 by the authors listed in the file AUTHORS
8 ** in the top-level source directory) and their institutional affiliations.
9 ** All rights reserved. See the file COPYING in the top-level source
10 ** directory for licensing information.\endverbatim
12 ** \brief The main entry point into the CVC4 library's SMT interface
14 ** The main entry point into the CVC4 library's SMT interface.
17 #include "smt/smt_engine.h"
26 #include <unordered_map>
27 #include <unordered_set>
31 #include "base/configuration.h"
32 #include "base/configuration_private.h"
33 #include "base/exception.h"
34 #include "base/listener.h"
35 #include "base/modal_exception.h"
36 #include "base/output.h"
37 #include "context/cdhashmap.h"
38 #include "context/cdhashset.h"
39 #include "context/cdlist.h"
40 #include "context/context.h"
41 #include "decision/decision_engine.h"
42 #include "expr/attribute.h"
43 #include "expr/expr.h"
44 #include "expr/kind.h"
45 #include "expr/metakind.h"
46 #include "expr/node.h"
47 #include "expr/node_builder.h"
48 #include "expr/node_self_iterator.h"
49 #include "options/arith_options.h"
50 #include "options/arrays_options.h"
51 #include "options/base_options.h"
52 #include "options/booleans_options.h"
53 #include "options/bv_options.h"
54 #include "options/datatypes_options.h"
55 #include "options/decision_mode.h"
56 #include "options/decision_options.h"
57 #include "options/language.h"
58 #include "options/main_options.h"
59 #include "options/open_ostream.h"
60 #include "options/option_exception.h"
61 #include "options/printer_options.h"
62 #include "options/proof_options.h"
63 #include "options/prop_options.h"
64 #include "options/quantifiers_options.h"
65 #include "options/sep_options.h"
66 #include "options/set_language.h"
67 #include "options/smt_options.h"
68 #include "options/strings_options.h"
69 #include "options/theory_options.h"
70 #include "options/uf_options.h"
71 #include "preprocessing/passes/bv_gauss.h"
72 #include "preprocessing/passes/int_to_bv.h"
73 #include "preprocessing/passes/pseudo_boolean_processor.h"
74 #include "preprocessing/passes/symmetry_detect.h"
75 #include "preprocessing/preprocessing_pass.h"
76 #include "preprocessing/preprocessing_pass_context.h"
77 #include "preprocessing/preprocessing_pass_registry.h"
78 #include "printer/printer.h"
79 #include "proof/proof.h"
80 #include "proof/proof_manager.h"
81 #include "proof/theory_proof.h"
82 #include "proof/unsat_core.h"
83 #include "prop/prop_engine.h"
84 #include "smt/command.h"
85 #include "smt/command_list.h"
86 #include "smt/logic_request.h"
87 #include "smt/managed_ostreams.h"
88 #include "smt/smt_engine_scope.h"
89 #include "smt/term_formula_removal.h"
90 #include "smt/update_ostream.h"
91 #include "smt_util/boolean_simplification.h"
92 #include "smt_util/nary_builder.h"
93 #include "smt_util/node_visitor.h"
94 #include "theory/arith/arith_msum.h"
95 #include "theory/booleans/circuit_propagator.h"
96 #include "theory/bv/bvintropow2.h"
97 #include "theory/bv/theory_bv_rewriter.h"
98 #include "theory/logic_info.h"
99 #include "theory/quantifiers/fun_def_process.h"
100 #include "theory/quantifiers/global_negate.h"
101 #include "theory/quantifiers/macros.h"
102 #include "theory/quantifiers/quantifiers_rewriter.h"
103 #include "theory/quantifiers/single_inv_partition.h"
104 #include "theory/quantifiers/sygus/ce_guided_instantiation.h"
105 #include "theory/quantifiers/sygus_inference.h"
106 #include "theory/quantifiers/term_util.h"
107 #include "theory/sort_inference.h"
108 #include "theory/strings/theory_strings.h"
109 #include "theory/substitutions.h"
110 #include "theory/theory_engine.h"
111 #include "theory/theory_model.h"
112 #include "theory/theory_traits.h"
113 #include "util/hash.h"
114 #include "util/proof.h"
115 #include "util/random.h"
116 #include "util/resource_manager.h"
119 using namespace CVC4
;
120 using namespace CVC4::smt
;
121 using namespace CVC4::preprocessing
;
122 using namespace CVC4::preprocessing::passes
;
123 using namespace CVC4::prop
;
124 using namespace CVC4::context
;
125 using namespace CVC4::theory
;
130 struct DeleteCommandFunction
: public std::unary_function
<const Command
*, void>
132 void operator()(const Command
* command
) { delete command
; }
135 void DeleteAndClearCommandVector(std::vector
<Command
*>& commands
) {
136 std::for_each(commands
.begin(), commands
.end(), DeleteCommandFunction());
140 /** Useful for counting the number of recursive calls. */
145 ScopeCounter(unsigned& d
) : d_depth(d
) {
154 * Representation of a defined function. We keep these around in
155 * SmtEngine to permit expanding definitions late (and lazily), to
156 * support getValue() over defined functions, to support user output
157 * in terms of defined functions, etc.
159 class DefinedFunction
{
161 vector
<Node
> d_formals
;
165 DefinedFunction(Node func
, vector
<Node
> formals
, Node formula
) :
170 Node
getFunction() const { return d_func
; }
171 vector
<Node
> getFormals() const { return d_formals
; }
172 Node
getFormula() const { return d_formula
; }
173 };/* class DefinedFunction */
175 struct SmtEngineStatistics
{
176 /** time spent in gaussian elimination */
177 TimerStat d_gaussElimTime
;
178 /** time spent in definition-expansion */
179 TimerStat d_definitionExpansionTime
;
180 /** time spent in non-clausal simplification */
181 TimerStat d_nonclausalSimplificationTime
;
182 /** time spent in miplib pass */
183 TimerStat d_miplibPassTime
;
184 /** number of assertions removed by miplib pass */
185 IntStat d_numMiplibAssertionsRemoved
;
186 /** number of constant propagations found during nonclausal simp */
187 IntStat d_numConstantProps
;
188 /** time spent in static learning */
189 TimerStat d_staticLearningTime
;
190 /** time spent in simplifying ITEs */
191 TimerStat d_simpITETime
;
192 /** time spent in simplifying ITEs */
193 TimerStat d_unconstrainedSimpTime
;
194 /** time spent removing ITEs */
195 TimerStat d_iteRemovalTime
;
196 /** time spent in theory preprocessing */
197 TimerStat d_theoryPreprocessTime
;
198 /** time spent in theory preprocessing */
199 TimerStat d_rewriteApplyToConstTime
;
200 /** time spent converting to CNF */
201 TimerStat d_cnfConversionTime
;
202 /** Num of assertions before ite removal */
203 IntStat d_numAssertionsPre
;
204 /** Num of assertions after ite removal */
205 IntStat d_numAssertionsPost
;
206 /** time spent in checkModel() */
207 TimerStat d_checkModelTime
;
208 /** time spent in checkProof() */
209 TimerStat d_checkProofTime
;
210 /** time spent in checkUnsatCore() */
211 TimerStat d_checkUnsatCoreTime
;
212 /** time spent in PropEngine::checkSat() */
213 TimerStat d_solveTime
;
214 /** time spent in pushing/popping */
215 TimerStat d_pushPopTime
;
216 /** time spent in processAssertions() */
217 TimerStat d_processAssertionsTime
;
219 /** Has something simplified to false? */
220 IntStat d_simplifiedToFalse
;
221 /** Number of resource units spent. */
222 ReferenceStat
<uint64_t> d_resourceUnitsUsed
;
224 SmtEngineStatistics() :
225 d_gaussElimTime("smt::SmtEngine::gaussElimTime"),
226 d_definitionExpansionTime("smt::SmtEngine::definitionExpansionTime"),
227 d_nonclausalSimplificationTime("smt::SmtEngine::nonclausalSimplificationTime"),
228 d_miplibPassTime("smt::SmtEngine::miplibPassTime"),
229 d_numMiplibAssertionsRemoved("smt::SmtEngine::numMiplibAssertionsRemoved", 0),
230 d_numConstantProps("smt::SmtEngine::numConstantProps", 0),
231 d_staticLearningTime("smt::SmtEngine::staticLearningTime"),
232 d_simpITETime("smt::SmtEngine::simpITETime"),
233 d_unconstrainedSimpTime("smt::SmtEngine::unconstrainedSimpTime"),
234 d_iteRemovalTime("smt::SmtEngine::iteRemovalTime"),
235 d_theoryPreprocessTime("smt::SmtEngine::theoryPreprocessTime"),
236 d_rewriteApplyToConstTime("smt::SmtEngine::rewriteApplyToConstTime"),
237 d_cnfConversionTime("smt::SmtEngine::cnfConversionTime"),
238 d_numAssertionsPre("smt::SmtEngine::numAssertionsPreITERemoval", 0),
239 d_numAssertionsPost("smt::SmtEngine::numAssertionsPostITERemoval", 0),
240 d_checkModelTime("smt::SmtEngine::checkModelTime"),
241 d_checkProofTime("smt::SmtEngine::checkProofTime"),
242 d_checkUnsatCoreTime("smt::SmtEngine::checkUnsatCoreTime"),
243 d_solveTime("smt::SmtEngine::solveTime"),
244 d_pushPopTime("smt::SmtEngine::pushPopTime"),
245 d_processAssertionsTime("smt::SmtEngine::processAssertionsTime"),
246 d_simplifiedToFalse("smt::SmtEngine::simplifiedToFalse", 0),
247 d_resourceUnitsUsed("smt::SmtEngine::resourceUnitsUsed")
250 smtStatisticsRegistry()->registerStat(&d_gaussElimTime
);
251 smtStatisticsRegistry()->registerStat(&d_definitionExpansionTime
);
252 smtStatisticsRegistry()->registerStat(&d_nonclausalSimplificationTime
);
253 smtStatisticsRegistry()->registerStat(&d_miplibPassTime
);
254 smtStatisticsRegistry()->registerStat(&d_numMiplibAssertionsRemoved
);
255 smtStatisticsRegistry()->registerStat(&d_numConstantProps
);
256 smtStatisticsRegistry()->registerStat(&d_staticLearningTime
);
257 smtStatisticsRegistry()->registerStat(&d_simpITETime
);
258 smtStatisticsRegistry()->registerStat(&d_unconstrainedSimpTime
);
259 smtStatisticsRegistry()->registerStat(&d_iteRemovalTime
);
260 smtStatisticsRegistry()->registerStat(&d_theoryPreprocessTime
);
261 smtStatisticsRegistry()->registerStat(&d_rewriteApplyToConstTime
);
262 smtStatisticsRegistry()->registerStat(&d_cnfConversionTime
);
263 smtStatisticsRegistry()->registerStat(&d_numAssertionsPre
);
264 smtStatisticsRegistry()->registerStat(&d_numAssertionsPost
);
265 smtStatisticsRegistry()->registerStat(&d_checkModelTime
);
266 smtStatisticsRegistry()->registerStat(&d_checkProofTime
);
267 smtStatisticsRegistry()->registerStat(&d_checkUnsatCoreTime
);
268 smtStatisticsRegistry()->registerStat(&d_solveTime
);
269 smtStatisticsRegistry()->registerStat(&d_pushPopTime
);
270 smtStatisticsRegistry()->registerStat(&d_processAssertionsTime
);
271 smtStatisticsRegistry()->registerStat(&d_simplifiedToFalse
);
272 smtStatisticsRegistry()->registerStat(&d_resourceUnitsUsed
);
275 ~SmtEngineStatistics() {
276 smtStatisticsRegistry()->unregisterStat(&d_gaussElimTime
);
277 smtStatisticsRegistry()->unregisterStat(&d_definitionExpansionTime
);
278 smtStatisticsRegistry()->unregisterStat(&d_nonclausalSimplificationTime
);
279 smtStatisticsRegistry()->unregisterStat(&d_miplibPassTime
);
280 smtStatisticsRegistry()->unregisterStat(&d_numMiplibAssertionsRemoved
);
281 smtStatisticsRegistry()->unregisterStat(&d_numConstantProps
);
282 smtStatisticsRegistry()->unregisterStat(&d_staticLearningTime
);
283 smtStatisticsRegistry()->unregisterStat(&d_simpITETime
);
284 smtStatisticsRegistry()->unregisterStat(&d_unconstrainedSimpTime
);
285 smtStatisticsRegistry()->unregisterStat(&d_iteRemovalTime
);
286 smtStatisticsRegistry()->unregisterStat(&d_theoryPreprocessTime
);
287 smtStatisticsRegistry()->unregisterStat(&d_rewriteApplyToConstTime
);
288 smtStatisticsRegistry()->unregisterStat(&d_cnfConversionTime
);
289 smtStatisticsRegistry()->unregisterStat(&d_numAssertionsPre
);
290 smtStatisticsRegistry()->unregisterStat(&d_numAssertionsPost
);
291 smtStatisticsRegistry()->unregisterStat(&d_checkModelTime
);
292 smtStatisticsRegistry()->unregisterStat(&d_checkProofTime
);
293 smtStatisticsRegistry()->unregisterStat(&d_checkUnsatCoreTime
);
294 smtStatisticsRegistry()->unregisterStat(&d_solveTime
);
295 smtStatisticsRegistry()->unregisterStat(&d_pushPopTime
);
296 smtStatisticsRegistry()->unregisterStat(&d_processAssertionsTime
);
297 smtStatisticsRegistry()->unregisterStat(&d_simplifiedToFalse
);
298 smtStatisticsRegistry()->unregisterStat(&d_resourceUnitsUsed
);
300 };/* struct SmtEngineStatistics */
303 class SoftResourceOutListener
: public Listener
{
305 SoftResourceOutListener(SmtEngine
& smt
) : d_smt(&smt
) {}
306 void notify() override
308 SmtScope
scope(d_smt
);
309 Assert(smt::smtEngineInScope());
314 }; /* class SoftResourceOutListener */
317 class HardResourceOutListener
: public Listener
{
319 HardResourceOutListener(SmtEngine
& smt
) : d_smt(&smt
) {}
320 void notify() override
322 SmtScope
scope(d_smt
);
323 theory::Rewriter::clearCaches();
327 }; /* class HardResourceOutListener */
329 class SetLogicListener
: public Listener
{
331 SetLogicListener(SmtEngine
& smt
) : d_smt(&smt
) {}
332 void notify() override
334 LogicInfo
inOptions(options::forceLogicString());
335 d_smt
->setLogic(inOptions
);
339 }; /* class SetLogicListener */
341 class BeforeSearchListener
: public Listener
{
343 BeforeSearchListener(SmtEngine
& smt
) : d_smt(&smt
) {}
344 void notify() override
{ d_smt
->beforeSearch(); }
348 }; /* class BeforeSearchListener */
350 class UseTheoryListListener
: public Listener
{
352 UseTheoryListListener(TheoryEngine
* theoryEngine
)
353 : d_theoryEngine(theoryEngine
)
356 void notify() override
358 std::stringstream
commaList(options::useTheoryList());
361 Debug("UseTheoryListListener") << "UseTheoryListListener::notify() "
362 << options::useTheoryList() << std::endl
;
364 while(std::getline(commaList
, token
, ',')){
365 if(token
== "help") {
366 puts(theory::useTheoryHelp
);
369 if(theory::useTheoryValidate(token
)) {
370 d_theoryEngine
->enableTheoryAlternative(token
);
372 throw OptionException(
373 std::string("unknown option for --use-theory : `") + token
+
374 "'. Try --use-theory=help.");
380 TheoryEngine
* d_theoryEngine
;
381 }; /* class UseTheoryListListener */
384 class SetDefaultExprDepthListener
: public Listener
{
386 void notify() override
388 int depth
= options::defaultExprDepth();
389 Debug
.getStream() << expr::ExprSetDepth(depth
);
390 Trace
.getStream() << expr::ExprSetDepth(depth
);
391 Notice
.getStream() << expr::ExprSetDepth(depth
);
392 Chat
.getStream() << expr::ExprSetDepth(depth
);
393 Message
.getStream() << expr::ExprSetDepth(depth
);
394 Warning
.getStream() << expr::ExprSetDepth(depth
);
395 // intentionally exclude Dump stream from this list
399 class SetDefaultExprDagListener
: public Listener
{
401 void notify() override
403 int dag
= options::defaultDagThresh();
404 Debug
.getStream() << expr::ExprDag(dag
);
405 Trace
.getStream() << expr::ExprDag(dag
);
406 Notice
.getStream() << expr::ExprDag(dag
);
407 Chat
.getStream() << expr::ExprDag(dag
);
408 Message
.getStream() << expr::ExprDag(dag
);
409 Warning
.getStream() << expr::ExprDag(dag
);
410 Dump
.getStream() << expr::ExprDag(dag
);
414 class SetPrintExprTypesListener
: public Listener
{
416 void notify() override
418 bool value
= options::printExprTypes();
419 Debug
.getStream() << expr::ExprPrintTypes(value
);
420 Trace
.getStream() << expr::ExprPrintTypes(value
);
421 Notice
.getStream() << expr::ExprPrintTypes(value
);
422 Chat
.getStream() << expr::ExprPrintTypes(value
);
423 Message
.getStream() << expr::ExprPrintTypes(value
);
424 Warning
.getStream() << expr::ExprPrintTypes(value
);
425 // intentionally exclude Dump stream from this list
429 class DumpModeListener
: public Listener
{
431 void notify() override
433 const std::string
& value
= options::dumpModeString();
434 Dump
.setDumpFromString(value
);
438 class PrintSuccessListener
: public Listener
{
440 void notify() override
442 bool value
= options::printSuccess();
443 Debug
.getStream() << Command::printsuccess(value
);
444 Trace
.getStream() << Command::printsuccess(value
);
445 Notice
.getStream() << Command::printsuccess(value
);
446 Chat
.getStream() << Command::printsuccess(value
);
447 Message
.getStream() << Command::printsuccess(value
);
448 Warning
.getStream() << Command::printsuccess(value
);
449 *options::out() << Command::printsuccess(value
);
456 * This is an inelegant solution, but for the present, it will work.
457 * The point of this is to separate the public and private portions of
458 * the SmtEngine class, so that smt_engine.h doesn't
459 * include "expr/node.h", which is a private CVC4 header (and can lead
460 * to linking errors due to the improper inlining of non-visible symbols
463 * The "real" solution (that which is usually implemented) is to move
464 * ALL the implementation to SmtEnginePrivate and maintain a
465 * heap-allocated instance of it in SmtEngine. SmtEngine (the public
466 * one) becomes an "interface shell" which simply acts as a forwarder
469 class SmtEnginePrivate
: public NodeManagerListener
{
472 typedef unordered_map
<Node
, Node
, NodeHashFunction
> NodeToNodeHashMap
;
473 typedef unordered_map
<Node
, bool, NodeHashFunction
> NodeToBoolHashMap
;
476 * Manager for limiting time and abstract resource usage.
478 ResourceManager
* d_resourceManager
;
480 /** Manager for the memory of regular-output-channel. */
481 ManagedRegularOutputChannel d_managedRegularChannel
;
483 /** Manager for the memory of diagnostic-output-channel. */
484 ManagedDiagnosticOutputChannel d_managedDiagnosticChannel
;
486 /** Manager for the memory of --dump-to. */
487 ManagedDumpOStream d_managedDumpChannel
;
489 /** Manager for --replay-log. */
490 ManagedReplayLogOstream d_managedReplayLog
;
493 * This list contains:
497 * beforeSearchListener
498 * UseTheoryListListener
500 * This needs to be deleted before both NodeManager's Options,
501 * SmtEngine, d_resourceManager, and TheoryEngine.
503 ListenerRegistrationList
* d_listenerRegistrations
;
505 /** Learned literals */
506 vector
<Node
> d_nonClausalLearnedLiterals
;
508 /** Size of assertions array when preprocessing starts */
509 unsigned d_realAssertionsEnd
;
511 /** A circuit propagator for non-clausal propositional deduction */
512 booleans::CircuitPropagator d_propagator
;
513 bool d_propagatorNeedsFinish
;
514 std::vector
<Node
> d_boolVars
;
516 /** Assertions in the preprocessing pipeline */
517 AssertionPipeline d_assertions
;
519 /** Whether any assertions have been processed */
520 CDO
<bool> d_assertionsProcessed
;
522 /** Index for where to store substitutions */
523 CDO
<unsigned> d_substitutionsIndex
;
529 * A context that never pushes/pops, for use by CD structures (like
530 * SubstitutionMaps) that should be "global".
532 context::Context d_fakeContext
;
535 * A map of AbsractValues to their actual constants. Only used if
536 * options::abstractValues() is on.
538 SubstitutionMap d_abstractValueMap
;
541 * A mapping of all abstract values (actual value |-> abstract) that
542 * we've handed out. This is necessary to ensure that we give the
543 * same AbstractValues for the same real constants. Only used if
544 * options::abstractValues() is on.
546 NodeToNodeHashMap d_abstractValues
;
548 /** Number of calls of simplify assertions active.
550 unsigned d_simplifyAssertionsDepth
;
552 /** TODO: whether certain preprocess steps are necessary */
553 //bool d_needsExpandDefs;
555 //------------------------------- expression names
556 /** mapping from expressions to name */
557 context::CDHashMap
< Node
, std::string
, NodeHashFunction
> d_exprNames
;
558 //------------------------------- end expression names
561 * Map from skolem variables to index in d_assertions containing
562 * corresponding introduced Boolean ite
564 IteSkolemMap d_iteSkolemMap
;
566 /** Instance of the ITE remover */
567 RemoveTermFormulas d_iteRemover
;
569 /* Finishes the initialization of the private portion of SMTEngine. */
573 std::unique_ptr
<PreprocessingPassContext
> d_preprocessingPassContext
;
574 PreprocessingPassRegistry d_preprocessingPassRegistry
;
576 /** The top level substitutions */
577 SubstitutionMap d_topLevelSubstitutions
;
579 static const bool d_doConstantProp
= true;
582 * Runs the nonclausal solver and tries to solve all the assigned
585 * Returns false if the formula simplifies to "false"
587 bool nonClausalSimplify();
590 * Performs static learning on the assertions.
592 void staticLearning();
595 * Remove ITEs from the assertions.
599 Node
realToInt(TNode n
, NodeToNodeHashMap
& cache
, std::vector
< Node
>& var_eq
);
600 Node
purifyNlTerms(TNode n
, NodeToNodeHashMap
& cache
, NodeToNodeHashMap
& bcache
, std::vector
< Node
>& var_eq
, bool beneathMult
= false);
603 * Helper function to fix up assertion list to restore invariants needed after
606 void collectSkolems(TNode n
, set
<TNode
>& skolemSet
, NodeToBoolHashMap
& cache
);
609 * Helper function to fix up assertion list to restore invariants needed after
612 bool checkForBadSkolems(TNode n
, TNode skolem
, NodeToBoolHashMap
& cache
);
614 // Lift bit-vectors of size 1 to booleans
617 // Convert booleans to bit-vectors of size 1
620 // Abstract common structure over small domains to UF
621 // return true if changes were made.
622 void bvAbstraction();
624 // Simplify ITE structure
627 // Simplify based on unconstrained values
628 void unconstrainedSimp();
631 * Ensures the assertions asserted after before now effectively come before
632 * d_realAssertionsEnd.
634 void compressBeforeRealAssertions(size_t before
);
637 * Trace nodes back to their assertions using CircuitPropagator's
640 void traceBackToAssertions(const std::vector
<Node
>& nodes
,
641 std::vector
<TNode
>& assertions
);
644 * Remove conjuncts in toRemove from conjunction n. Return # of removed
647 size_t removeFromConjunction(Node
& n
,
648 const std::unordered_set
<unsigned long>& toRemove
);
650 /** Scrub miplib encodings. */
651 void doMiplibTrick();
654 * Perform non-clausal simplification of a Node. This involves
655 * Theory implementations, but does NOT involve the SAT solver in
658 * Returns false if the formula simplifies to "false"
660 bool simplifyAssertions();
664 SmtEnginePrivate(SmtEngine
& smt
) :
666 d_managedRegularChannel(),
667 d_managedDiagnosticChannel(),
668 d_managedDumpChannel(),
669 d_managedReplayLog(),
670 d_listenerRegistrations(new ListenerRegistrationList()),
671 d_nonClausalLearnedLiterals(),
672 d_realAssertionsEnd(0),
673 d_propagator(d_nonClausalLearnedLiterals
, true, true),
674 d_propagatorNeedsFinish(false),
676 d_assertionsProcessed(smt
.d_userContext
, false),
677 d_substitutionsIndex(smt
.d_userContext
, 0),
679 d_abstractValueMap(&d_fakeContext
),
681 d_simplifyAssertionsDepth(0),
682 //d_needsExpandDefs(true), //TODO?
683 d_exprNames(smt
.d_userContext
),
685 d_iteRemover(smt
.d_userContext
),
686 d_topLevelSubstitutions(smt
.d_userContext
)
688 d_smt
.d_nodeManager
->subscribeEvents(this);
689 d_true
= NodeManager::currentNM()->mkConst(true);
690 d_resourceManager
= NodeManager::currentResourceManager();
692 d_listenerRegistrations
->add(d_resourceManager
->registerSoftListener(
693 new SoftResourceOutListener(d_smt
)));
695 d_listenerRegistrations
->add(d_resourceManager
->registerHardListener(
696 new HardResourceOutListener(d_smt
)));
698 Options
& nodeManagerOptions
= NodeManager::currentNM()->getOptions();
699 d_listenerRegistrations
->add(
700 nodeManagerOptions
.registerForceLogicListener(
701 new SetLogicListener(d_smt
), true));
703 // Multiple options reuse BeforeSearchListener so registration requires an
704 // extra bit of care.
705 // We can safely not call notify on this before search listener at
706 // registration time. This d_smt cannot be beforeSearch at construction
707 // time. Therefore the BeforeSearchListener is a no-op. Therefore it does
708 // not have to be called.
709 d_listenerRegistrations
->add(
710 nodeManagerOptions
.registerBeforeSearchListener(
711 new BeforeSearchListener(d_smt
)));
713 // These do need registration calls.
714 d_listenerRegistrations
->add(
715 nodeManagerOptions
.registerSetDefaultExprDepthListener(
716 new SetDefaultExprDepthListener(), true));
717 d_listenerRegistrations
->add(
718 nodeManagerOptions
.registerSetDefaultExprDagListener(
719 new SetDefaultExprDagListener(), true));
720 d_listenerRegistrations
->add(
721 nodeManagerOptions
.registerSetPrintExprTypesListener(
722 new SetPrintExprTypesListener(), true));
723 d_listenerRegistrations
->add(
724 nodeManagerOptions
.registerSetDumpModeListener(
725 new DumpModeListener(), true));
726 d_listenerRegistrations
->add(
727 nodeManagerOptions
.registerSetPrintSuccessListener(
728 new PrintSuccessListener(), true));
729 d_listenerRegistrations
->add(
730 nodeManagerOptions
.registerSetRegularOutputChannelListener(
731 new SetToDefaultSourceListener(&d_managedRegularChannel
), true));
732 d_listenerRegistrations
->add(
733 nodeManagerOptions
.registerSetDiagnosticOutputChannelListener(
734 new SetToDefaultSourceListener(&d_managedDiagnosticChannel
), true));
735 d_listenerRegistrations
->add(
736 nodeManagerOptions
.registerDumpToFileNameListener(
737 new SetToDefaultSourceListener(&d_managedDumpChannel
), true));
738 d_listenerRegistrations
->add(
739 nodeManagerOptions
.registerSetReplayLogFilename(
740 new SetToDefaultSourceListener(&d_managedReplayLog
), true));
745 delete d_listenerRegistrations
;
747 if(d_propagatorNeedsFinish
) {
748 d_propagator
.finish();
749 d_propagatorNeedsFinish
= false;
751 d_smt
.d_nodeManager
->unsubscribeEvents(this);
754 ResourceManager
* getResourceManager() { return d_resourceManager
; }
755 void spendResource(unsigned amount
)
757 d_resourceManager
->spendResource(amount
);
760 void nmNotifyNewSort(TypeNode tn
, uint32_t flags
) override
762 DeclareTypeCommand
c(tn
.getAttribute(expr::VarNameAttr()),
765 if((flags
& ExprManager::SORT_FLAG_PLACEHOLDER
) == 0) {
766 d_smt
.addToModelCommandAndDump(c
, flags
);
770 void nmNotifyNewSortConstructor(TypeNode tn
) override
772 DeclareTypeCommand
c(tn
.getAttribute(expr::VarNameAttr()),
773 tn
.getAttribute(expr::SortArityAttr()),
775 d_smt
.addToModelCommandAndDump(c
);
778 void nmNotifyNewDatatypes(const std::vector
<DatatypeType
>& dtts
) override
780 DatatypeDeclarationCommand
c(dtts
);
781 d_smt
.addToModelCommandAndDump(c
);
784 void nmNotifyNewVar(TNode n
, uint32_t flags
) override
786 DeclareFunctionCommand
c(n
.getAttribute(expr::VarNameAttr()),
788 n
.getType().toType());
789 if((flags
& ExprManager::VAR_FLAG_DEFINED
) == 0) {
790 d_smt
.addToModelCommandAndDump(c
, flags
);
792 if(n
.getType().isBoolean() && !options::incrementalSolving()) {
793 d_boolVars
.push_back(n
);
797 void nmNotifyNewSkolem(TNode n
,
798 const std::string
& comment
,
799 uint32_t flags
) override
801 string id
= n
.getAttribute(expr::VarNameAttr());
802 DeclareFunctionCommand
c(id
, n
.toExpr(), n
.getType().toType());
803 if(Dump
.isOn("skolems") && comment
!= "") {
804 Dump("skolems") << CommentCommand(id
+ " is " + comment
);
806 if((flags
& ExprManager::VAR_FLAG_DEFINED
) == 0) {
807 d_smt
.addToModelCommandAndDump(c
, flags
, false, "skolems");
809 if(n
.getType().isBoolean() && !options::incrementalSolving()) {
810 d_boolVars
.push_back(n
);
814 void nmNotifyDeleteNode(TNode n
) override
{}
816 Node
applySubstitutions(TNode node
) const {
817 return Rewriter::rewrite(d_topLevelSubstitutions
.apply(node
));
821 * Apply the substitutions in d_topLevelAssertions and the rewriter to each of
822 * the assertions in d_assertions, and store the result back in d_assertions.
824 void applySubstitutionsToAssertions();
827 * Process the assertions that have been asserted.
829 void processAssertions();
831 /** Process a user push.
838 * Process a user pop. Clears out the non-context-dependent stuff in this
839 * SmtEnginePrivate. Necessary to clear out our assertion vectors in case
840 * someone does a push-assert-pop without a check-sat. It also pops the
841 * last map of expression names from notifyPush.
844 d_assertions
.clear();
845 d_nonClausalLearnedLiterals
.clear();
846 d_realAssertionsEnd
= 0;
847 d_iteSkolemMap
.clear();
851 * Adds a formula to the current context. Action here depends on
852 * the SimplificationMode (in the current Options scope); the
853 * formula might be pushed out to the propositional layer
854 * immediately, or it might be simplified and kept, or it might not
855 * even be simplified.
856 * the 2nd and 3rd arguments added for bookkeeping for proofs
858 void addFormula(TNode n
, bool inUnsatCore
, bool inInput
= true);
860 /** Expand definitions in n. */
861 Node
expandDefinitions(TNode n
,
862 NodeToNodeHashMap
& cache
,
863 bool expandOnly
= false);
866 * Simplify node "in" by expanding definitions and applying any
867 * substitutions learned from preprocessing.
869 Node
simplify(TNode in
) {
870 // Substitute out any abstract values in ex.
871 // Expand definitions.
872 NodeToNodeHashMap cache
;
873 Node n
= expandDefinitions(in
, cache
).toExpr();
874 // Make sure we've done all preprocessing, etc.
875 Assert(d_assertions
.size() == 0);
876 return applySubstitutions(n
).toExpr();
880 * Substitute away all AbstractValues in a node.
882 Node
substituteAbstractValues(TNode n
) {
883 // We need to do this even if options::abstractValues() is off,
884 // since the setting might have changed after we already gave out
885 // some abstract values.
886 return d_abstractValueMap
.apply(n
);
890 * Make a new (or return an existing) abstract value for a node.
891 * Can only use this if options::abstractValues() is on.
893 Node
mkAbstractValue(TNode n
) {
894 Assert(options::abstractValues());
895 Node
& val
= d_abstractValues
[n
];
897 val
= d_smt
.d_nodeManager
->mkAbstractValue(n
.getType());
898 d_abstractValueMap
.addSubstitution(val
, n
);
900 // We are supposed to ascribe types to all abstract values that go out.
901 NodeManager
* current
= d_smt
.d_nodeManager
;
902 Node ascription
= current
->mkConst(AscriptionType(n
.getType().toType()));
903 Node retval
= current
->mkNode(kind::APPLY_TYPE_ASCRIPTION
, ascription
, val
);
907 NodeToNodeHashMap d_rewriteApplyToConstCache
;
908 Node
rewriteApplyToConst(TNode n
) {
909 Trace("rewriteApplyToConst") << "rewriteApplyToConst :: " << n
<< std::endl
;
911 if(n
.getMetaKind() == kind::metakind::CONSTANT
||
912 n
.getMetaKind() == kind::metakind::VARIABLE
||
913 n
.getMetaKind() == kind::metakind::NULLARY_OPERATOR
)
918 if(d_rewriteApplyToConstCache
.find(n
) != d_rewriteApplyToConstCache
.end()) {
919 Trace("rewriteApplyToConst") << "in cache :: "
920 << d_rewriteApplyToConstCache
[n
]
922 return d_rewriteApplyToConstCache
[n
];
925 if(n
.getKind() == kind::APPLY_UF
) {
926 if(n
.getNumChildren() == 1 && n
[0].isConst() &&
927 n
[0].getType().isInteger())
930 ss
<< n
.getOperator() << "_";
931 if(n
[0].getConst
<Rational
>() < 0) {
932 ss
<< "m" << -n
[0].getConst
<Rational
>();
936 Node newvar
= NodeManager::currentNM()->mkSkolem(
937 ss
.str(), n
.getType(), "rewriteApplyToConst skolem",
938 NodeManager::SKOLEM_EXACT_NAME
);
939 d_rewriteApplyToConstCache
[n
] = newvar
;
940 Trace("rewriteApplyToConst") << "made :: " << newvar
<< std::endl
;
944 ss
<< "The rewrite-apply-to-const preprocessor is currently limited;"
946 << "it only works if all function symbols are unary and with Integer"
948 << "domain, and all applications are to integer values." << std::endl
949 << "Found application: " << n
;
954 NodeBuilder
<> builder(n
.getKind());
955 if(n
.getMetaKind() == kind::metakind::PARAMETERIZED
) {
956 builder
<< n
.getOperator();
958 for(unsigned i
= 0; i
< n
.getNumChildren(); ++i
) {
959 builder
<< rewriteApplyToConst(n
[i
]);
962 d_rewriteApplyToConstCache
[n
] = rewr
;
963 Trace("rewriteApplyToConst") << "built :: " << rewr
<< std::endl
;
967 void addUseTheoryListListener(TheoryEngine
* theoryEngine
){
968 Options
& nodeManagerOptions
= NodeManager::currentNM()->getOptions();
969 d_listenerRegistrations
->add(
970 nodeManagerOptions
.registerUseTheoryListListener(
971 new UseTheoryListListener(theoryEngine
), true));
974 std::ostream
* getReplayLog() const {
975 return d_managedReplayLog
.getReplayLog();
978 //------------------------------- expression names
979 // implements setExpressionName, as described in smt_engine.h
980 void setExpressionName(Expr e
, std::string name
) {
981 d_exprNames
[Node::fromExpr(e
)] = name
;
984 // implements getExpressionName, as described in smt_engine.h
985 bool getExpressionName(Expr e
, std::string
& name
) const {
986 context::CDHashMap
< Node
, std::string
, NodeHashFunction
>::const_iterator it
= d_exprNames
.find(e
);
987 if(it
!=d_exprNames
.end()) {
994 //------------------------------- end expression names
996 };/* class SmtEnginePrivate */
998 }/* namespace CVC4::smt */
1000 SmtEngine::SmtEngine(ExprManager
* em
)
1001 : d_context(new Context()),
1003 d_userContext(new UserContext()),
1005 d_nodeManager(d_exprManager
->getNodeManager()),
1006 d_decisionEngine(NULL
),
1007 d_theoryEngine(NULL
),
1009 d_proofManager(NULL
),
1010 d_definedFunctions(NULL
),
1011 d_fmfRecFunctionsDefined(NULL
),
1012 d_assertionList(NULL
),
1013 d_assignments(NULL
),
1014 d_modelGlobalCommands(),
1015 d_modelCommands(NULL
),
1019 d_originalOptions(),
1021 d_fullyInited(false),
1022 d_problemExtended(false),
1024 d_needPostsolve(false),
1025 d_earlyTheoryPP(true),
1026 d_globalNegation(false),
1028 d_replayStream(NULL
),
1030 d_statisticsRegistry(NULL
),
1032 d_channels(new LemmaChannels())
1034 SmtScope
smts(this);
1035 d_originalOptions
.copyValues(em
->getOptions());
1036 d_private
= new smt::SmtEnginePrivate(*this);
1037 d_statisticsRegistry
= new StatisticsRegistry();
1038 d_stats
= new SmtEngineStatistics();
1039 d_stats
->d_resourceUnitsUsed
.setData(
1040 d_private
->getResourceManager()->getResourceUsage());
1042 // The ProofManager is constructed before any other proof objects such as
1043 // SatProof and TheoryProofs. The TheoryProofEngine and the SatProof are
1044 // initialized in TheoryEngine and PropEngine respectively.
1045 Assert(d_proofManager
== NULL
);
1047 // d_proofManager must be created before Options has been finished
1048 // being parsed from the input file. Because of this, we cannot trust
1049 // that options::proof() is set correctly yet.
1051 d_proofManager
= new ProofManager(d_userContext
);
1054 // We have mutual dependency here, so we add the prop engine to the theory
1055 // engine later (it is non-essential there)
1056 d_theoryEngine
= new TheoryEngine(d_context
, d_userContext
,
1057 d_private
->d_iteRemover
,
1058 const_cast<const LogicInfo
&>(d_logic
),
1062 for(TheoryId id
= theory::THEORY_FIRST
; id
< theory::THEORY_LAST
; ++id
) {
1063 TheoryConstructor::addTheory(d_theoryEngine
, id
);
1064 //register with proof engine if applicable
1066 ProofManager::currentPM()->getTheoryProofEngine()->registerTheory(d_theoryEngine
->theoryOf(id
));
1070 d_private
->addUseTheoryListListener(d_theoryEngine
);
1072 // global push/pop around everything, to ensure proper destruction
1073 // of context-dependent data structures
1074 d_userContext
->push();
1077 d_definedFunctions
= new(true) DefinedFunctionMap(d_userContext
);
1078 d_fmfRecFunctionsDefined
= new(true) NodeList(d_userContext
);
1079 d_modelCommands
= new(true) smt::CommandList(d_userContext
);
1082 void SmtEngine::finishInit() {
1083 Trace("smt-debug") << "SmtEngine::finishInit" << std::endl
;
1084 // ensure that our heuristics are properly set up
1087 Trace("smt-debug") << "Making decision engine..." << std::endl
;
1089 d_decisionEngine
= new DecisionEngine(d_context
, d_userContext
);
1090 d_decisionEngine
->init(); // enable appropriate strategies
1092 Trace("smt-debug") << "Making prop engine..." << std::endl
;
1093 d_propEngine
= new PropEngine(d_theoryEngine
, d_decisionEngine
, d_context
,
1094 d_userContext
, d_private
->getReplayLog(),
1095 d_replayStream
, d_channels
);
1097 Trace("smt-debug") << "Setting up theory engine..." << std::endl
;
1098 d_theoryEngine
->setPropEngine(d_propEngine
);
1099 d_theoryEngine
->setDecisionEngine(d_decisionEngine
);
1100 Trace("smt-debug") << "Finishing init for theory engine..." << std::endl
;
1101 d_theoryEngine
->finishInit();
1103 Trace("smt-debug") << "Set up assertion list..." << std::endl
;
1104 // [MGD 10/20/2011] keep around in incremental mode, due to a
1105 // cleanup ordering issue and Nodes/TNodes. If SAT is popped
1106 // first, some user-context-dependent TNodes might still exist
1108 if(options::produceAssertions() ||
1109 options::incrementalSolving()) {
1110 // In the case of incremental solving, we appear to need these to
1111 // ensure the relevant Nodes remain live.
1112 d_assertionList
= new(true) AssertionList(d_userContext
);
1115 // dump out a set-logic command
1116 if(Dump
.isOn("benchmark")) {
1117 if (Dump
.isOn("raw-benchmark")) {
1118 Dump("raw-benchmark") << SetBenchmarkLogicCommand(d_logic
.getLogicString());
1120 LogicInfo everything
;
1122 Dump("benchmark") << CommentCommand("CVC4 always dumps the most general, all-supported logic (below), as some internals might require the use of a logic more general than the input.")
1123 << SetBenchmarkLogicCommand(everything
.getLogicString());
1127 Trace("smt-debug") << "Dump declaration commands..." << std::endl
;
1128 // dump out any pending declaration commands
1129 for(unsigned i
= 0; i
< d_dumpCommands
.size(); ++i
) {
1130 Dump("declarations") << *d_dumpCommands
[i
];
1131 delete d_dumpCommands
[i
];
1133 d_dumpCommands
.clear();
1135 PROOF( ProofManager::currentPM()->setLogic(d_logic
); );
1137 for(TheoryId id
= theory::THEORY_FIRST
; id
< theory::THEORY_LAST
; ++id
) {
1138 ProofManager::currentPM()->getTheoryProofEngine()->
1139 finishRegisterTheory(d_theoryEngine
->theoryOf(id
));
1142 d_private
->finishInit();
1143 Trace("smt-debug") << "SmtEngine::finishInit done" << std::endl
;
1146 void SmtEngine::finalOptionsAreSet() {
1151 if(! d_logic
.isLocked()) {
1155 // finish initialization, create the prop engine, etc.
1158 AlwaysAssert( d_propEngine
->getAssertionLevel() == 0,
1159 "The PropEngine has pushed but the SmtEngine "
1160 "hasn't finished initializing!" );
1162 d_fullyInited
= true;
1163 Assert(d_logic
.isLocked());
1165 d_propEngine
->assertFormula(NodeManager::currentNM()->mkConst
<bool>(true));
1166 d_propEngine
->assertFormula(NodeManager::currentNM()->mkConst
<bool>(false).notNode());
1169 void SmtEngine::shutdown() {
1172 while(options::incrementalSolving() && d_userContext
->getLevel() > 1) {
1176 // check to see if a postsolve() is pending
1177 if(d_needPostsolve
) {
1178 d_theoryEngine
->postsolve();
1179 d_needPostsolve
= false;
1182 if(d_propEngine
!= NULL
) {
1183 d_propEngine
->shutdown();
1185 if(d_theoryEngine
!= NULL
) {
1186 d_theoryEngine
->shutdown();
1188 if(d_decisionEngine
!= NULL
) {
1189 d_decisionEngine
->shutdown();
1193 SmtEngine::~SmtEngine()
1195 SmtScope
smts(this);
1200 // global push/pop around everything, to ensure proper destruction
1201 // of context-dependent data structures
1202 d_context
->popto(0);
1203 d_userContext
->popto(0);
1205 if(d_assignments
!= NULL
) {
1206 d_assignments
->deleteSelf();
1209 if(d_assertionList
!= NULL
) {
1210 d_assertionList
->deleteSelf();
1213 for(unsigned i
= 0; i
< d_dumpCommands
.size(); ++i
) {
1214 delete d_dumpCommands
[i
];
1215 d_dumpCommands
[i
] = NULL
;
1217 d_dumpCommands
.clear();
1219 DeleteAndClearCommandVector(d_modelGlobalCommands
);
1221 if(d_modelCommands
!= NULL
) {
1222 d_modelCommands
->deleteSelf();
1225 d_definedFunctions
->deleteSelf();
1226 d_fmfRecFunctionsDefined
->deleteSelf();
1228 delete d_theoryEngine
;
1229 d_theoryEngine
= NULL
;
1230 delete d_propEngine
;
1231 d_propEngine
= NULL
;
1232 delete d_decisionEngine
;
1233 d_decisionEngine
= NULL
;
1236 // d_proofManager is always created when proofs are enabled at configure time.
1237 // Becuase of this, this code should not be wrapped in PROOF() which
1238 // additionally checks flags such as options::proof().
1240 delete d_proofManager
;
1241 d_proofManager
= NULL
;
1246 delete d_statisticsRegistry
;
1247 d_statisticsRegistry
= NULL
;
1252 delete d_userContext
;
1253 d_userContext
= NULL
;
1260 } catch(Exception
& e
) {
1261 Warning() << "CVC4 threw an exception during cleanup." << endl
1266 void SmtEngine::setLogic(const LogicInfo
& logic
)
1268 SmtScope
smts(this);
1270 throw ModalException("Cannot set logic in SmtEngine after the engine has "
1271 "finished initializing.");
1277 void SmtEngine::setLogic(const std::string
& s
)
1279 SmtScope
smts(this);
1281 setLogic(LogicInfo(s
));
1282 } catch(IllegalArgumentException
& e
) {
1283 throw LogicException(e
.what());
1287 void SmtEngine::setLogic(const char* logic
) { setLogic(string(logic
)); }
1288 LogicInfo
SmtEngine::getLogicInfo() const {
1291 void SmtEngine::setLogicInternal()
1293 Assert(!d_fullyInited
, "setting logic in SmtEngine but the engine has already"
1294 " finished initializing for this run");
1298 void SmtEngine::setDefaults() {
1299 Random::getRandom().setSeed(options::seed());
1300 // Language-based defaults
1301 if (!options::bitvectorDivByZeroConst
.wasSetByUser())
1303 options::bitvectorDivByZeroConst
.set(options::inputLanguage()
1304 == language::input::LANG_SMTLIB_V2_6
);
1306 if (options::inputLanguage() == language::input::LANG_SYGUS
)
1308 if (!options::ceGuidedInst
.wasSetByUser())
1310 options::ceGuidedInst
.set(true);
1312 // must use Ferrante/Rackoff for real arithmetic
1313 if (!options::cbqiMidpoint
.wasSetByUser())
1315 options::cbqiMidpoint
.set(true);
1319 if(options::forceLogicString
.wasSetByUser()) {
1320 d_logic
= LogicInfo(options::forceLogicString());
1321 }else if (options::solveIntAsBV() > 0) {
1322 d_logic
= LogicInfo("QF_BV");
1323 }else if (d_logic
.getLogicString() == "QF_NRA" && options::solveRealAsInt()) {
1324 d_logic
= LogicInfo("QF_NIA");
1325 } else if ((d_logic
.getLogicString() == "QF_UFBV" ||
1326 d_logic
.getLogicString() == "QF_ABV") &&
1327 options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER
) {
1328 d_logic
= LogicInfo("QF_BV");
1332 /* - disabled for 1.4 release [MGD 2014.06.25]
1333 if(!d_logic.hasEverything() && d_logic.isTheoryEnabled(THEORY_STRINGS) ) {
1334 if(! options::stringExp.wasSetByUser()) {
1335 options::stringExp.set( true );
1336 Trace("smt") << "turning on strings-exp, for the theory of strings" << std::endl;
1341 if(options::stringExp()) {
1342 if( !d_logic
.isQuantified() ) {
1343 d_logic
= d_logic
.getUnlockedCopy();
1344 d_logic
.enableQuantifiers();
1346 Trace("smt") << "turning on quantifier logic, for strings-exp"
1349 if(! options::fmfBound
.wasSetByUser()) {
1350 options::fmfBound
.set( true );
1351 Trace("smt") << "turning on fmf-bound-int, for strings-exp" << std::endl
;
1353 if(! options::fmfInstEngine
.wasSetByUser()) {
1354 options::fmfInstEngine
.set( true );
1355 Trace("smt") << "turning on fmf-inst-engine, for strings-exp" << std::endl
;
1358 if(! options::rewriteDivk.wasSetByUser()) {
1359 options::rewriteDivk.set( true );
1360 Trace("smt") << "turning on rewrite-divk, for strings-exp" << std::endl;
1363 if(! options::stringFMF.wasSetByUser()) {
1364 options::stringFMF.set( true );
1365 Trace("smt") << "turning on strings-fmf, for strings-exp" << std::endl;
1370 // sygus inference may require datatypes
1371 if (options::sygusInference())
1373 d_logic
= d_logic
.getUnlockedCopy();
1374 d_logic
.enableTheory(THEORY_DATATYPES
);
1378 if ((options::checkModels() || options::checkSynthSol())
1379 && !options::produceAssertions())
1381 Notice() << "SmtEngine: turning on produce-assertions to support "
1382 << "check-models or check-synth-sol." << endl
;
1383 setOption("produce-assertions", SExpr("true"));
1386 if(options::unsatCores()) {
1387 if(options::simplificationMode() != SIMPLIFICATION_MODE_NONE
) {
1388 if(options::simplificationMode
.wasSetByUser()) {
1389 throw OptionException("simplification not supported with unsat cores");
1391 Notice() << "SmtEngine: turning off simplification to support unsat-cores"
1393 options::simplificationMode
.set(SIMPLIFICATION_MODE_NONE
);
1396 if(options::unconstrainedSimp()) {
1397 if(options::unconstrainedSimp
.wasSetByUser()) {
1398 throw OptionException("unconstrained simplification not supported with unsat cores");
1400 Notice() << "SmtEngine: turning off unconstrained simplification to support unsat-cores" << endl
;
1401 options::unconstrainedSimp
.set(false);
1404 if(options::pbRewrites()) {
1405 if(options::pbRewrites
.wasSetByUser()) {
1406 throw OptionException("pseudoboolean rewrites not supported with unsat cores");
1408 Notice() << "SmtEngine: turning off pseudoboolean rewrites to support unsat-cores" << endl
;
1409 setOption("pb-rewrites", false);
1412 if(options::sortInference()) {
1413 if(options::sortInference
.wasSetByUser()) {
1414 throw OptionException("sort inference not supported with unsat cores");
1416 Notice() << "SmtEngine: turning off sort inference to support unsat-cores" << endl
;
1417 options::sortInference
.set(false);
1420 if(options::preSkolemQuant()) {
1421 if(options::preSkolemQuant
.wasSetByUser()) {
1422 throw OptionException("pre-skolemization not supported with unsat cores");
1424 Notice() << "SmtEngine: turning off pre-skolemization to support unsat-cores" << endl
;
1425 options::preSkolemQuant
.set(false);
1428 if(options::bitvectorToBool()) {
1429 if(options::bitvectorToBool
.wasSetByUser()) {
1430 throw OptionException("bv-to-bool not supported with unsat cores");
1432 Notice() << "SmtEngine: turning off bitvector-to-bool to support unsat-cores" << endl
;
1433 options::bitvectorToBool
.set(false);
1436 if(options::boolToBitvector()) {
1437 if(options::boolToBitvector
.wasSetByUser()) {
1438 throw OptionException("bool-to-bv not supported with unsat cores");
1440 Notice() << "SmtEngine: turning off bool-to-bitvector to support unsat-cores" << endl
;
1441 options::boolToBitvector
.set(false);
1444 if(options::bvIntroducePow2()) {
1445 if(options::bvIntroducePow2
.wasSetByUser()) {
1446 throw OptionException("bv-intro-pow2 not supported with unsat cores");
1448 Notice() << "SmtEngine: turning off bv-intro-pow2 to support unsat-cores" << endl
;
1449 setOption("bv-intro-pow2", false);
1452 if(options::repeatSimp()) {
1453 if(options::repeatSimp
.wasSetByUser()) {
1454 throw OptionException("repeat-simp not supported with unsat cores");
1456 Notice() << "SmtEngine: turning off repeat-simp to support unsat-cores" << endl
;
1457 setOption("repeat-simp", false);
1460 if (options::globalNegate())
1462 if (options::globalNegate
.wasSetByUser())
1464 throw OptionException("global-negate not supported with unsat cores");
1466 Notice() << "SmtEngine: turning off global-negate to support unsat-cores"
1468 setOption("global-negate", false);
1472 if (options::cbqiBv() && d_logic
.isQuantified())
1474 if(options::boolToBitvector
.wasSetByUser()) {
1475 throw OptionException(
1476 "bool-to-bv not supported with CBQI BV for quantified logics");
1478 Notice() << "SmtEngine: turning off bool-to-bitvector to support CBQI BV"
1480 options::boolToBitvector
.set(false);
1483 // cases where we need produce models
1484 if (!options::produceModels()
1485 && (options::produceAssignments() || options::sygusRewSynthCheck()))
1487 Notice() << "SmtEngine: turning on produce-models" << endl
;
1488 setOption("produce-models", SExpr("true"));
1491 // Set the options for the theoryOf
1492 if(!options::theoryOfMode
.wasSetByUser()) {
1493 if(d_logic
.isSharingEnabled() &&
1494 !d_logic
.isTheoryEnabled(THEORY_BV
) &&
1495 !d_logic
.isTheoryEnabled(THEORY_STRINGS
) &&
1496 !d_logic
.isTheoryEnabled(THEORY_SETS
) ) {
1497 Trace("smt") << "setting theoryof-mode to term-based" << endl
;
1498 options::theoryOfMode
.set(THEORY_OF_TERM_BASED
);
1502 // strings require LIA, UF; widen the logic
1503 if(d_logic
.isTheoryEnabled(THEORY_STRINGS
)) {
1504 LogicInfo
log(d_logic
.getUnlockedCopy());
1505 // Strings requires arith for length constraints, and also UF
1506 if(!d_logic
.isTheoryEnabled(THEORY_UF
)) {
1507 Trace("smt") << "because strings are enabled, also enabling UF" << endl
;
1508 log
.enableTheory(THEORY_UF
);
1510 if(!d_logic
.isTheoryEnabled(THEORY_ARITH
) || d_logic
.isDifferenceLogic() || !d_logic
.areIntegersUsed()) {
1511 Trace("smt") << "because strings are enabled, also enabling linear integer arithmetic" << endl
;
1512 log
.enableTheory(THEORY_ARITH
);
1513 log
.enableIntegers();
1514 log
.arithOnlyLinear();
1519 if(d_logic
.isTheoryEnabled(THEORY_ARRAYS
) || d_logic
.isTheoryEnabled(THEORY_DATATYPES
) || d_logic
.isTheoryEnabled(THEORY_SETS
)) {
1520 if(!d_logic
.isTheoryEnabled(THEORY_UF
)) {
1521 LogicInfo
log(d_logic
.getUnlockedCopy());
1522 Trace("smt") << "because a theory that permits Boolean terms is enabled, also enabling UF" << endl
;
1523 log
.enableTheory(THEORY_UF
);
1529 // by default, symmetry breaker is on only for QF_UF
1530 if(! options::ufSymmetryBreaker
.wasSetByUser()) {
1531 bool qf_uf
= d_logic
.isPure(THEORY_UF
) && !d_logic
.isQuantified() && !options::proof();
1532 Trace("smt") << "setting uf symmetry breaker to " << qf_uf
<< endl
;
1533 options::ufSymmetryBreaker
.set(qf_uf
);
1535 // by default, nonclausal simplification is off for QF_SAT
1536 if(! options::simplificationMode
.wasSetByUser()) {
1537 bool qf_sat
= d_logic
.isPure(THEORY_BOOL
) && !d_logic
.isQuantified();
1538 Trace("smt") << "setting simplification mode to <" << d_logic
.getLogicString() << "> " << (!qf_sat
) << endl
;
1539 //simplification=none works better for SMT LIB benchmarks with quantifiers, not others
1540 //options::simplificationMode.set(qf_sat || quantifiers ? SIMPLIFICATION_MODE_NONE : SIMPLIFICATION_MODE_BATCH);
1541 options::simplificationMode
.set(qf_sat
? SIMPLIFICATION_MODE_NONE
: SIMPLIFICATION_MODE_BATCH
);
1544 // If in arrays, set the UF handler to arrays
1545 if(d_logic
.isTheoryEnabled(THEORY_ARRAYS
) && ( !d_logic
.isQuantified() ||
1546 (d_logic
.isQuantified() && !d_logic
.isTheoryEnabled(THEORY_UF
)))) {
1547 Theory::setUninterpretedSortOwner(THEORY_ARRAYS
);
1549 Theory::setUninterpretedSortOwner(THEORY_UF
);
1552 // Turn on ite simplification for QF_LIA and QF_AUFBV
1553 // WARNING: These checks match much more than just QF_AUFBV and
1554 // QF_LIA logics. --K [2014/10/15]
1555 if(! options::doITESimp
.wasSetByUser()) {
1556 bool qf_aufbv
= !d_logic
.isQuantified() &&
1557 d_logic
.isTheoryEnabled(THEORY_ARRAYS
) &&
1558 d_logic
.isTheoryEnabled(THEORY_UF
) &&
1559 d_logic
.isTheoryEnabled(THEORY_BV
);
1560 bool qf_lia
= !d_logic
.isQuantified() &&
1561 d_logic
.isPure(THEORY_ARITH
) &&
1562 d_logic
.isLinear() &&
1563 !d_logic
.isDifferenceLogic() &&
1564 !d_logic
.areRealsUsed();
1566 bool iteSimp
= (qf_aufbv
|| qf_lia
);
1567 Trace("smt") << "setting ite simplification to " << iteSimp
<< endl
;
1568 options::doITESimp
.set(iteSimp
);
1570 if(! options::compressItes
.wasSetByUser() ){
1571 bool qf_lia
= !d_logic
.isQuantified() &&
1572 d_logic
.isPure(THEORY_ARITH
) &&
1573 d_logic
.isLinear() &&
1574 !d_logic
.isDifferenceLogic() &&
1575 !d_logic
.areRealsUsed();
1577 bool compressIte
= qf_lia
;
1578 Trace("smt") << "setting ite compression to " << compressIte
<< endl
;
1579 options::compressItes
.set(compressIte
);
1581 if(! options::simplifyWithCareEnabled
.wasSetByUser() ){
1582 bool qf_aufbv
= !d_logic
.isQuantified() &&
1583 d_logic
.isTheoryEnabled(THEORY_ARRAYS
) &&
1584 d_logic
.isTheoryEnabled(THEORY_UF
) &&
1585 d_logic
.isTheoryEnabled(THEORY_BV
);
1587 bool withCare
= qf_aufbv
;
1588 Trace("smt") << "setting ite simplify with care to " << withCare
<< endl
;
1589 options::simplifyWithCareEnabled
.set(withCare
);
1591 // Turn off array eager index splitting for QF_AUFLIA
1592 if(! options::arraysEagerIndexSplitting
.wasSetByUser()) {
1593 if (not d_logic
.isQuantified() &&
1594 d_logic
.isTheoryEnabled(THEORY_ARRAYS
) &&
1595 d_logic
.isTheoryEnabled(THEORY_UF
) &&
1596 d_logic
.isTheoryEnabled(THEORY_ARITH
)) {
1597 Trace("smt") << "setting array eager index splitting to false" << endl
;
1598 options::arraysEagerIndexSplitting
.set(false);
1601 // Turn on model-based arrays for QF_AX (unless models are enabled)
1602 // if(! options::arraysModelBased.wasSetByUser()) {
1603 // if (not d_logic.isQuantified() &&
1604 // d_logic.isTheoryEnabled(THEORY_ARRAYS) &&
1605 // d_logic.isPure(THEORY_ARRAYS) &&
1606 // !options::produceModels() &&
1607 // !options::checkModels()) {
1608 // Trace("smt") << "turning on model-based array solver" << endl;
1609 // options::arraysModelBased.set(true);
1612 // Turn on multiple-pass non-clausal simplification for QF_AUFBV
1613 if(! options::repeatSimp
.wasSetByUser()) {
1614 bool repeatSimp
= !d_logic
.isQuantified() &&
1615 (d_logic
.isTheoryEnabled(THEORY_ARRAYS
) &&
1616 d_logic
.isTheoryEnabled(THEORY_UF
) &&
1617 d_logic
.isTheoryEnabled(THEORY_BV
)) &&
1618 !options::unsatCores();
1619 Trace("smt") << "setting repeat simplification to " << repeatSimp
<< endl
;
1620 options::repeatSimp
.set(repeatSimp
);
1622 // Turn on unconstrained simplification for QF_AUFBV
1623 if(!options::unconstrainedSimp
.wasSetByUser() ||
1624 options::incrementalSolving()) {
1625 // bool qf_sat = d_logic.isPure(THEORY_BOOL) && !d_logic.isQuantified();
1626 // bool uncSimp = false && !qf_sat && !options::incrementalSolving();
1627 bool uncSimp
= !options::incrementalSolving() &&
1628 !d_logic
.isQuantified() &&
1629 !options::produceModels() &&
1630 !options::produceAssignments() &&
1631 !options::checkModels() &&
1632 !options::unsatCores() &&
1633 (d_logic
.isTheoryEnabled(THEORY_ARRAYS
) && d_logic
.isTheoryEnabled(THEORY_BV
));
1634 Trace("smt") << "setting unconstrained simplification to " << uncSimp
<< endl
;
1635 options::unconstrainedSimp
.set(uncSimp
);
1637 // Unconstrained simp currently does *not* support model generation
1638 if (options::unconstrainedSimp
.wasSetByUser() && options::unconstrainedSimp()) {
1639 if (options::produceModels()) {
1640 if (options::produceModels
.wasSetByUser()) {
1641 throw OptionException("Cannot use unconstrained-simp with model generation.");
1643 Notice() << "SmtEngine: turning off produce-models to support unconstrainedSimp" << endl
;
1644 setOption("produce-models", SExpr("false"));
1646 if (options::produceAssignments()) {
1647 if (options::produceAssignments
.wasSetByUser()) {
1648 throw OptionException("Cannot use unconstrained-simp with model generation (produce-assignments).");
1650 Notice() << "SmtEngine: turning off produce-assignments to support unconstrainedSimp" << endl
;
1651 setOption("produce-assignments", SExpr("false"));
1653 if (options::checkModels()) {
1654 if (options::checkModels
.wasSetByUser()) {
1655 throw OptionException("Cannot use unconstrained-simp with model generation (check-models).");
1657 Notice() << "SmtEngine: turning off check-models to support unconstrainedSimp" << endl
;
1658 setOption("check-models", SExpr("false"));
1663 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER
&&
1664 options::incrementalSolving()) {
1665 if (options::incrementalSolving
.wasSetByUser()) {
1666 throw OptionException(std::string("Eager bit-blasting does not currently support incremental mode. \n\
1667 Try --bitblast=lazy"));
1669 Notice() << "SmtEngine: turning off incremental to support eager bit-blasting" << endl
;
1670 setOption("incremental", SExpr("false"));
1673 if (! options::bvEagerExplanations
.wasSetByUser() &&
1674 d_logic
.isTheoryEnabled(THEORY_ARRAYS
) &&
1675 d_logic
.isTheoryEnabled(THEORY_BV
)) {
1676 Trace("smt") << "enabling eager bit-vector explanations " << endl
;
1677 options::bvEagerExplanations
.set(true);
1680 if( !options::bitvectorEqualitySolver() ){
1681 Trace("smt") << "disabling bvLazyRewriteExtf since equality solver is disabled" << endl
;
1682 options::bvLazyRewriteExtf
.set(false);
1685 // Turn on arith rewrite equalities only for pure arithmetic
1686 if(! options::arithRewriteEq
.wasSetByUser()) {
1687 bool arithRewriteEq
= d_logic
.isPure(THEORY_ARITH
) && d_logic
.isLinear() && !d_logic
.isQuantified();
1688 Trace("smt") << "setting arith rewrite equalities " << arithRewriteEq
<< endl
;
1689 options::arithRewriteEq
.set(arithRewriteEq
);
1691 if(! options::arithHeuristicPivots
.wasSetByUser()) {
1692 int16_t heuristicPivots
= 5;
1693 if(d_logic
.isPure(THEORY_ARITH
) && !d_logic
.isQuantified()) {
1694 if(d_logic
.isDifferenceLogic()) {
1695 heuristicPivots
= -1;
1696 } else if(!d_logic
.areIntegersUsed()) {
1697 heuristicPivots
= 0;
1700 Trace("smt") << "setting arithHeuristicPivots " << heuristicPivots
<< endl
;
1701 options::arithHeuristicPivots
.set(heuristicPivots
);
1703 if(! options::arithPivotThreshold
.wasSetByUser()){
1704 uint16_t pivotThreshold
= 2;
1705 if(d_logic
.isPure(THEORY_ARITH
) && !d_logic
.isQuantified()){
1706 if(d_logic
.isDifferenceLogic()){
1707 pivotThreshold
= 16;
1710 Trace("smt") << "setting arith arithPivotThreshold " << pivotThreshold
<< endl
;
1711 options::arithPivotThreshold
.set(pivotThreshold
);
1713 if(! options::arithStandardCheckVarOrderPivots
.wasSetByUser()){
1714 int16_t varOrderPivots
= -1;
1715 if(d_logic
.isPure(THEORY_ARITH
) && !d_logic
.isQuantified()){
1716 varOrderPivots
= 200;
1718 Trace("smt") << "setting arithStandardCheckVarOrderPivots " << varOrderPivots
<< endl
;
1719 options::arithStandardCheckVarOrderPivots
.set(varOrderPivots
);
1721 // Turn off early theory preprocessing if arithRewriteEq is on
1722 if (options::arithRewriteEq()) {
1723 d_earlyTheoryPP
= false;
1726 // Set decision mode based on logic (if not set by user)
1727 if(!options::decisionMode
.wasSetByUser()) {
1728 decision::DecisionMode decMode
=
1730 d_logic
.hasEverything() ? decision::DECISION_STRATEGY_JUSTIFICATION
:
1732 (not d_logic
.isQuantified() &&
1733 d_logic
.isPure(THEORY_BV
)
1735 // QF_AUFBV or QF_ABV or QF_UFBV
1736 (not d_logic
.isQuantified() &&
1737 (d_logic
.isTheoryEnabled(THEORY_ARRAYS
) ||
1738 d_logic
.isTheoryEnabled(THEORY_UF
)) &&
1739 d_logic
.isTheoryEnabled(THEORY_BV
)
1741 // QF_AUFLIA (and may be ends up enabling QF_AUFLRA?)
1742 (not d_logic
.isQuantified() &&
1743 d_logic
.isTheoryEnabled(THEORY_ARRAYS
) &&
1744 d_logic
.isTheoryEnabled(THEORY_UF
) &&
1745 d_logic
.isTheoryEnabled(THEORY_ARITH
)
1748 (not d_logic
.isQuantified() &&
1749 d_logic
.isPure(THEORY_ARITH
) && d_logic
.isLinear() && !d_logic
.isDifferenceLogic() && !d_logic
.areIntegersUsed()
1752 d_logic
.isQuantified() ||
1754 d_logic
.isTheoryEnabled(THEORY_STRINGS
)
1755 ? decision::DECISION_STRATEGY_JUSTIFICATION
1756 : decision::DECISION_STRATEGY_INTERNAL
1761 d_logic
.hasEverything() || d_logic
.isTheoryEnabled(THEORY_STRINGS
) ? false :
1763 (not d_logic
.isQuantified() &&
1764 d_logic
.isTheoryEnabled(THEORY_ARRAYS
) &&
1765 d_logic
.isTheoryEnabled(THEORY_UF
) &&
1766 d_logic
.isTheoryEnabled(THEORY_ARITH
)
1769 (not d_logic
.isQuantified() &&
1770 d_logic
.isPure(THEORY_ARITH
) && d_logic
.isLinear() && !d_logic
.isDifferenceLogic() && !d_logic
.areIntegersUsed()
1775 Trace("smt") << "setting decision mode to " << decMode
<< endl
;
1776 options::decisionMode
.set(decMode
);
1777 options::decisionStopOnly
.set(stoponly
);
1779 if( options::incrementalSolving() ){
1780 //disable modes not supported by incremental
1781 options::sortInference
.set( false );
1782 options::ufssFairnessMonotone
.set( false );
1783 options::quantEpr
.set( false );
1784 options::globalNegate
.set(false);
1786 if( d_logic
.hasCardinalityConstraints() ){
1787 //must have finite model finding on
1788 options::finiteModelFind
.set( true );
1791 //if it contains a theory with non-termination, do not strictly enforce that quantifiers and theory combination must be interleaved
1792 if( d_logic
.isTheoryEnabled(THEORY_STRINGS
) || (d_logic
.isTheoryEnabled(THEORY_ARITH
) && !d_logic
.isLinear()) ){
1793 if( !options::instWhenStrictInterleave
.wasSetByUser() ){
1794 options::instWhenStrictInterleave
.set( false );
1798 //local theory extensions
1799 if( options::localTheoryExt() ){
1800 if( !options::instMaxLevel
.wasSetByUser() ){
1801 options::instMaxLevel
.set( 0 );
1804 if( options::instMaxLevel()!=-1 ){
1805 Notice() << "SmtEngine: turning off cbqi to support instMaxLevel" << endl
;
1806 options::cbqi
.set(false);
1808 //track instantiations?
1809 if( options::cbqiNestedQE() || ( options::proof() && !options::trackInstLemmas
.wasSetByUser() ) ){
1810 options::trackInstLemmas
.set( true );
1813 if( ( options::fmfBoundLazy
.wasSetByUser() && options::fmfBoundLazy() ) ||
1814 ( options::fmfBoundInt
.wasSetByUser() && options::fmfBoundInt() ) ) {
1815 options::fmfBound
.set( true );
1817 //now have determined whether fmfBoundInt is on/off
1818 //apply fmfBoundInt options
1819 if( options::fmfBound() ){
1820 //must have finite model finding on
1821 options::finiteModelFind
.set( true );
1822 if( ! options::mbqiMode
.wasSetByUser() ||
1823 ( options::mbqiMode()!=quantifiers::MBQI_NONE
&&
1824 options::mbqiMode()!=quantifiers::MBQI_FMC
&&
1825 options::mbqiMode()!=quantifiers::MBQI_FMC_INTERVAL
) ){
1826 //if bounded integers are set, use no MBQI by default
1827 options::mbqiMode
.set( quantifiers::MBQI_NONE
);
1829 if( ! options::prenexQuant
.wasSetByUser() ){
1830 options::prenexQuant
.set( quantifiers::PRENEX_QUANT_NONE
);
1833 if( options::ufHo() ){
1834 //if higher-order, then current variants of model-based instantiation cannot be used
1835 if( options::mbqiMode()!=quantifiers::MBQI_NONE
){
1836 options::mbqiMode
.set( quantifiers::MBQI_NONE
);
1839 if( options::mbqiMode()==quantifiers::MBQI_ABS
){
1840 if( !d_logic
.isPure(THEORY_UF
) ){
1841 //MBQI_ABS is only supported in pure quantified UF
1842 options::mbqiMode
.set( quantifiers::MBQI_FMC
);
1845 if( options::ufssSymBreak() ){
1846 options::sortInference
.set( true );
1848 if( options::fmfFunWellDefinedRelevant() ){
1849 if( !options::fmfFunWellDefined
.wasSetByUser() ){
1850 options::fmfFunWellDefined
.set( true );
1853 if( options::fmfFunWellDefined() ){
1854 if( !options::finiteModelFind
.wasSetByUser() ){
1855 options::finiteModelFind
.set( true );
1859 if( options::quantEpr() ){
1860 if( !options::preSkolemQuant
.wasSetByUser() ){
1861 options::preSkolemQuant
.set( true );
1865 //now, have determined whether finite model find is on/off
1866 //apply finite model finding options
1867 if( options::finiteModelFind() ){
1868 //apply conservative quantifiers splitting
1869 if( !options::quantDynamicSplit
.wasSetByUser() ){
1870 options::quantDynamicSplit
.set( quantifiers::QUANT_DSPLIT_MODE_DEFAULT
);
1872 //do not eliminate extended arithmetic symbols from quantified formulas
1873 if( !options::elimExtArithQuant
.wasSetByUser() ){
1874 options::elimExtArithQuant
.set( false );
1876 if( !options::eMatching
.wasSetByUser() ){
1877 options::eMatching
.set( options::fmfInstEngine() );
1879 if( !options::instWhenMode
.wasSetByUser() ){
1880 //instantiate only on last call
1881 if( options::eMatching() ){
1882 options::instWhenMode
.set( quantifiers::INST_WHEN_LAST_CALL
);
1885 if( options::mbqiMode()==quantifiers::MBQI_ABS
){
1886 if( !options::preSkolemQuant
.wasSetByUser() ){
1887 options::preSkolemQuant
.set( true );
1889 if( !options::preSkolemQuantNested
.wasSetByUser() ){
1890 options::preSkolemQuantNested
.set( true );
1892 if( !options::fmfOneInstPerRound
.wasSetByUser() ){
1893 options::fmfOneInstPerRound
.set( true );
1898 //apply counterexample guided instantiation options
1899 // if we are attempting to rewrite everything to SyGuS, use ceGuidedInst
1900 if (options::sygusInference())
1902 if (!options::ceGuidedInst
.wasSetByUser())
1904 options::ceGuidedInst
.set(true);
1906 // optimization: apply preskolemization, makes it succeed more often
1907 if (!options::preSkolemQuant
.wasSetByUser())
1909 options::preSkolemQuant
.set(true);
1911 if (!options::preSkolemQuantNested
.wasSetByUser())
1913 options::preSkolemQuantNested
.set(true);
1916 if( options::cegqiSingleInvMode()!=quantifiers::CEGQI_SI_MODE_NONE
){
1917 if( !options::ceGuidedInst
.wasSetByUser() ){
1918 options::ceGuidedInst
.set( true );
1921 if( options::ceGuidedInst() ){
1922 //counterexample-guided instantiation for sygus
1923 if( !options::cegqiSingleInvMode
.wasSetByUser() ){
1924 options::cegqiSingleInvMode
.set( quantifiers::CEGQI_SI_MODE_USE
);
1926 if( !options::quantConflictFind
.wasSetByUser() ){
1927 options::quantConflictFind
.set( false );
1929 if( !options::instNoEntail
.wasSetByUser() ){
1930 options::instNoEntail
.set( false );
1932 if (options::sygusRew())
1934 options::sygusRewSynth
.set(true);
1935 options::sygusRewVerify
.set(true);
1937 if (options::sygusRewSynth() || options::sygusRewVerify())
1939 // rewrite rule synthesis implies that sygus stream must be true
1940 options::sygusStream
.set(true);
1942 if (options::sygusStream())
1944 // PBE and streaming modes are incompatible
1945 if (!options::sygusPbe
.wasSetByUser())
1947 options::sygusPbe
.set(false);
1950 //do not allow partial functions
1951 if( !options::bitvectorDivByZeroConst
.wasSetByUser() ){
1952 options::bitvectorDivByZeroConst
.set( true );
1954 if( !options::dtRewriteErrorSel
.wasSetByUser() ){
1955 options::dtRewriteErrorSel
.set( true );
1958 if( !options::miniscopeQuant
.wasSetByUser() ){
1959 options::miniscopeQuant
.set( false );
1961 if( !options::miniscopeQuantFreeVar
.wasSetByUser() ){
1962 options::miniscopeQuantFreeVar
.set( false );
1965 if( !options::rewriteDivk
.wasSetByUser()) {
1966 options::rewriteDivk
.set( true );
1969 if( !options::macrosQuant
.wasSetByUser()) {
1970 options::macrosQuant
.set( false );
1972 if( !options::cbqiPreRegInst
.wasSetByUser()) {
1973 options::cbqiPreRegInst
.set( true );
1976 //counterexample-guided instantiation for non-sygus
1977 // enable if any possible quantifiers with arithmetic, datatypes or bitvectors
1978 if( d_logic
.isQuantified() &&
1979 ( ( options::decisionMode()!=decision::DECISION_STRATEGY_INTERNAL
&&
1980 ( d_logic
.isTheoryEnabled(THEORY_ARITH
) || d_logic
.isTheoryEnabled(THEORY_DATATYPES
) || d_logic
.isTheoryEnabled(THEORY_BV
) ) ) ||
1981 d_logic
.isPure(THEORY_ARITH
) || d_logic
.isPure(THEORY_BV
) ||
1982 options::cbqiAll() ) ){
1983 if( !options::cbqi
.wasSetByUser() ){
1984 options::cbqi
.set( true );
1986 // check whether we should apply full cbqi
1987 if (d_logic
.isPure(THEORY_BV
))
1989 if (!options::cbqiFullEffort
.wasSetByUser())
1991 options::cbqiFullEffort
.set(true);
1995 if( options::cbqi() ){
1997 if( !options::rewriteDivk
.wasSetByUser()) {
1998 options::rewriteDivk
.set( true );
2000 if (d_logic
.isPure(THEORY_ARITH
) || d_logic
.isPure(THEORY_BV
))
2002 options::cbqiAll
.set( false );
2003 if( !options::quantConflictFind
.wasSetByUser() ){
2004 options::quantConflictFind
.set( false );
2006 if( !options::instNoEntail
.wasSetByUser() ){
2007 options::instNoEntail
.set( false );
2009 if( !options::instWhenMode
.wasSetByUser() && options::cbqiModel() ){
2010 //only instantiation should happen at last call when model is avaiable
2011 options::instWhenMode
.set( quantifiers::INST_WHEN_LAST_CALL
);
2014 // only supported in pure arithmetic or pure BV
2015 options::cbqiNestedQE
.set(false);
2018 if (options::cbqiNestedQE()
2019 || options::decisionMode() == decision::DECISION_STRATEGY_INTERNAL
)
2021 // only complete with prenex = disj_normal or normal
2022 if (options::prenexQuant() <= quantifiers::PRENEX_QUANT_DISJ_NORMAL
)
2024 options::prenexQuant
.set(quantifiers::PRENEX_QUANT_DISJ_NORMAL
);
2027 else if (options::globalNegate())
2029 if (!options::prenexQuant
.wasSetByUser())
2031 options::prenexQuant
.set(quantifiers::PRENEX_QUANT_NONE
);
2035 //implied options...
2036 if( options::strictTriggers() ){
2037 if( !options::userPatternsQuant
.wasSetByUser() ){
2038 options::userPatternsQuant
.set( quantifiers::USER_PAT_MODE_TRUST
);
2041 if( options::qcfMode
.wasSetByUser() || options::qcfTConstraint() ){
2042 options::quantConflictFind
.set( true );
2044 if( options::cbqiNestedQE() ){
2045 options::prenexQuantUser
.set( true );
2046 if( !options::preSkolemQuant
.wasSetByUser() ){
2047 options::preSkolemQuant
.set( true );
2050 //for induction techniques
2051 if( options::quantInduction() ){
2052 if( !options::dtStcInduction
.wasSetByUser() ){
2053 options::dtStcInduction
.set( true );
2055 if( !options::intWfInduction
.wasSetByUser() ){
2056 options::intWfInduction
.set( true );
2059 if( options::dtStcInduction() ){
2060 //try to remove ITEs from quantified formulas
2061 if( !options::iteDtTesterSplitQuant
.wasSetByUser() ){
2062 options::iteDtTesterSplitQuant
.set( true );
2064 if( !options::iteLiftQuant
.wasSetByUser() ){
2065 options::iteLiftQuant
.set( quantifiers::ITE_LIFT_QUANT_MODE_ALL
);
2068 if( options::intWfInduction() ){
2069 if( !options::purifyTriggers
.wasSetByUser() ){
2070 options::purifyTriggers
.set( true );
2073 if( options::conjectureNoFilter() ){
2074 if( !options::conjectureFilterActiveTerms
.wasSetByUser() ){
2075 options::conjectureFilterActiveTerms
.set( false );
2077 if( !options::conjectureFilterCanonical
.wasSetByUser() ){
2078 options::conjectureFilterCanonical
.set( false );
2080 if( !options::conjectureFilterModel
.wasSetByUser() ){
2081 options::conjectureFilterModel
.set( false );
2084 if( options::conjectureGenPerRound
.wasSetByUser() ){
2085 if( options::conjectureGenPerRound()>0 ){
2086 options::conjectureGen
.set( true );
2088 options::conjectureGen
.set( false );
2091 //can't pre-skolemize nested quantifiers without UF theory
2092 if( !d_logic
.isTheoryEnabled(THEORY_UF
) && options::preSkolemQuant() ){
2093 if( !options::preSkolemQuantNested
.wasSetByUser() ){
2094 options::preSkolemQuantNested
.set( false );
2097 if( !d_logic
.isTheoryEnabled(THEORY_DATATYPES
) ){
2098 options::quantDynamicSplit
.set( quantifiers::QUANT_DSPLIT_MODE_NONE
);
2101 //until bugs 371,431 are fixed
2102 if( ! options::minisatUseElim
.wasSetByUser()){
2103 //AJR: cannot use minisat elim for new implementation of sets TODO: why?
2104 if( d_logic
.isTheoryEnabled(THEORY_SETS
) || d_logic
.isQuantified() || options::produceModels() || options::produceAssignments() || options::checkModels() ){
2105 options::minisatUseElim
.set( false );
2108 else if (options::minisatUseElim()) {
2109 if (options::produceModels()) {
2110 Notice() << "SmtEngine: turning off produce-models to support minisatUseElim" << endl
;
2111 setOption("produce-models", SExpr("false"));
2113 if (options::produceAssignments()) {
2114 Notice() << "SmtEngine: turning off produce-assignments to support minisatUseElim" << endl
;
2115 setOption("produce-assignments", SExpr("false"));
2117 if (options::checkModels()) {
2118 Notice() << "SmtEngine: turning off check-models to support minisatUseElim" << endl
;
2119 setOption("check-models", SExpr("false"));
2123 // For now, these array theory optimizations do not support model-building
2124 if (options::produceModels() || options::produceAssignments() || options::checkModels()) {
2125 options::arraysOptimizeLinear
.set(false);
2126 options::arraysLazyRIntro1
.set(false);
2129 // Non-linear arithmetic does not support models unless nlExt is enabled
2130 if ((d_logic
.isTheoryEnabled(THEORY_ARITH
) && !d_logic
.isLinear()
2131 && !options::nlExt())
2132 || options::globalNegate())
2134 std::string reason
=
2135 options::globalNegate() ? "--global-negate" : "nonlinear arithmetic";
2136 if (options::produceModels()) {
2137 if(options::produceModels
.wasSetByUser()) {
2138 throw OptionException(
2139 std::string("produce-model not supported with " + reason
));
2142 << "SmtEngine: turning off produce-models because unsupported for "
2144 setOption("produce-models", SExpr("false"));
2146 if (options::produceAssignments()) {
2147 if(options::produceAssignments
.wasSetByUser()) {
2148 throw OptionException(
2149 std::string("produce-assignments not supported with " + reason
));
2151 Warning() << "SmtEngine: turning off produce-assignments because "
2154 setOption("produce-assignments", SExpr("false"));
2156 if (options::checkModels()) {
2157 if(options::checkModels
.wasSetByUser()) {
2158 throw OptionException(
2159 std::string("check-models not supported with " + reason
));
2162 << "SmtEngine: turning off check-models because unsupported for "
2164 setOption("check-models", SExpr("false"));
2168 if(options::incrementalSolving() && options::proof()) {
2169 Warning() << "SmtEngine: turning off incremental solving mode (not yet supported with --proof, try --tear-down-incremental instead)" << endl
;
2170 setOption("incremental", SExpr("false"));
2173 if (options::proof())
2175 if (options::bitvectorAlgebraicSolver())
2177 if (options::bitvectorAlgebraicSolver
.wasSetByUser())
2179 throw OptionException(
2180 "--bv-algebraic-solver is not supported with proofs");
2182 Notice() << "SmtEngine: turning off bv algebraic solver to support proofs"
2184 options::bitvectorAlgebraicSolver
.set(false);
2186 if (options::bitvectorEqualitySolver())
2188 if (options::bitvectorEqualitySolver
.wasSetByUser())
2190 throw OptionException("--bv-eq-solver is not supported with proofs");
2192 Notice() << "SmtEngine: turning off bv eq solver to support proofs"
2194 options::bitvectorEqualitySolver
.set(false);
2196 if (options::bitvectorInequalitySolver())
2198 if (options::bitvectorInequalitySolver
.wasSetByUser())
2200 throw OptionException(
2201 "--bv-inequality-solver is not supported with proofs");
2203 Notice() << "SmtEngine: turning off bv ineq solver to support proofs"
2205 options::bitvectorInequalitySolver
.set(false);
2210 void SmtEngine::setProblemExtended(bool value
)
2212 d_problemExtended
= value
;
2213 if (value
) { d_assumptions
.clear(); }
2216 void SmtEngine::setInfo(const std::string
& key
, const CVC4::SExpr
& value
)
2218 SmtScope
smts(this);
2220 Trace("smt") << "SMT setInfo(" << key
<< ", " << value
<< ")" << endl
;
2222 if(Dump
.isOn("benchmark")) {
2223 if(key
== "status") {
2224 string s
= value
.getValue();
2225 BenchmarkStatus status
=
2226 (s
== "sat") ? SMT_SATISFIABLE
:
2227 ((s
== "unsat") ? SMT_UNSATISFIABLE
: SMT_UNKNOWN
);
2228 Dump("benchmark") << SetBenchmarkStatusCommand(status
);
2230 Dump("benchmark") << SetInfoCommand(key
, value
);
2234 // Check for CVC4-specific info keys (prefixed with "cvc4-" or "cvc4_")
2235 if(key
.length() > 5) {
2236 string prefix
= key
.substr(0, 5);
2237 if(prefix
== "cvc4-" || prefix
== "cvc4_") {
2238 string cvc4key
= key
.substr(5);
2239 if(cvc4key
== "logic") {
2240 if(! value
.isAtom()) {
2241 throw OptionException("argument to (set-info :cvc4-logic ..) must be a string");
2243 SmtScope
smts(this);
2244 d_logic
= value
.getValue();
2248 throw UnrecognizedOptionException();
2253 // Check for standard info keys (SMT-LIB v1, SMT-LIB v2, ...)
2254 if(key
== "source" ||
2255 key
== "category" ||
2256 key
== "difficulty" ||
2260 } else if(key
== "name") {
2261 d_filename
= value
.getValue();
2263 } else if(key
== "smt-lib-version") {
2264 if( (value
.isInteger() && value
.getIntegerValue() == Integer(2)) ||
2265 (value
.isRational() && value
.getRationalValue() == Rational(2)) ||
2266 value
.getValue() == "2" ||
2267 value
.getValue() == "2.0" ) {
2268 options::inputLanguage
.set(language::input::LANG_SMTLIB_V2_0
);
2270 // supported SMT-LIB version
2271 if(!options::outputLanguage
.wasSetByUser() &&
2272 ( options::outputLanguage() == language::output::LANG_SMTLIB_V2_5
|| options::outputLanguage() == language::output::LANG_SMTLIB_V2_6
)) {
2273 options::outputLanguage
.set(language::output::LANG_SMTLIB_V2_0
);
2274 *options::out() << language::SetLanguage(language::output::LANG_SMTLIB_V2_0
);
2277 } else if( (value
.isRational() && value
.getRationalValue() == Rational(5, 2)) ||
2278 value
.getValue() == "2.5" ) {
2279 options::inputLanguage
.set(language::input::LANG_SMTLIB_V2_5
);
2281 // supported SMT-LIB version
2282 if(!options::outputLanguage
.wasSetByUser() &&
2283 options::outputLanguage() == language::output::LANG_SMTLIB_V2_0
) {
2284 options::outputLanguage
.set(language::output::LANG_SMTLIB_V2_5
);
2285 *options::out() << language::SetLanguage(language::output::LANG_SMTLIB_V2_5
);
2288 } else if( (value
.isRational() && value
.getRationalValue() == Rational(13, 5)) ||
2289 value
.getValue() == "2.6" ) {
2290 options::inputLanguage
.set(language::input::LANG_SMTLIB_V2_6
);
2292 // supported SMT-LIB version
2293 if(!options::outputLanguage
.wasSetByUser() &&
2294 options::outputLanguage() == language::output::LANG_SMTLIB_V2_0
) {
2295 options::outputLanguage
.set(language::output::LANG_SMTLIB_V2_6
);
2296 *options::out() << language::SetLanguage(language::output::LANG_SMTLIB_V2_6
);
2300 Warning() << "Warning: unsupported smt-lib-version: " << value
<< endl
;
2301 throw UnrecognizedOptionException();
2302 } else if(key
== "status") {
2304 if(value
.isAtom()) {
2305 s
= value
.getValue();
2307 if(s
!= "sat" && s
!= "unsat" && s
!= "unknown") {
2308 throw OptionException("argument to (set-info :status ..) must be "
2309 "`sat' or `unsat' or `unknown'");
2311 d_status
= Result(s
, d_filename
);
2314 throw UnrecognizedOptionException();
2317 CVC4::SExpr
SmtEngine::getInfo(const std::string
& key
) const {
2319 SmtScope
smts(this);
2321 Trace("smt") << "SMT getInfo(" << key
<< ")" << endl
;
2322 if(key
== "all-statistics") {
2323 vector
<SExpr
> stats
;
2324 for(StatisticsRegistry::const_iterator i
= NodeManager::fromExprManager(d_exprManager
)->getStatisticsRegistry()->begin();
2325 i
!= NodeManager::fromExprManager(d_exprManager
)->getStatisticsRegistry()->end();
2328 v
.push_back((*i
).first
);
2329 v
.push_back((*i
).second
);
2332 for(StatisticsRegistry::const_iterator i
= d_statisticsRegistry
->begin();
2333 i
!= d_statisticsRegistry
->end();
2336 v
.push_back((*i
).first
);
2337 v
.push_back((*i
).second
);
2340 return SExpr(stats
);
2341 } else if(key
== "error-behavior") {
2342 // immediate-exit | continued-execution
2343 if( options::continuedExecution() || options::interactive() ) {
2344 return SExpr(SExpr::Keyword("continued-execution"));
2346 return SExpr(SExpr::Keyword("immediate-exit"));
2348 } else if(key
== "name") {
2349 return SExpr(Configuration::getName());
2350 } else if(key
== "version") {
2351 return SExpr(Configuration::getVersionString());
2352 } else if(key
== "authors") {
2353 return SExpr(Configuration::about());
2354 } else if(key
== "status") {
2355 // sat | unsat | unknown
2356 switch(d_status
.asSatisfiabilityResult().isSat()) {
2358 return SExpr(SExpr::Keyword("sat"));
2360 return SExpr(SExpr::Keyword("unsat"));
2362 return SExpr(SExpr::Keyword("unknown"));
2364 } else if(key
== "reason-unknown") {
2365 if(!d_status
.isNull() && d_status
.isUnknown()) {
2367 ss
<< d_status
.whyUnknown();
2368 string s
= ss
.str();
2369 transform(s
.begin(), s
.end(), s
.begin(), ::tolower
);
2370 return SExpr(SExpr::Keyword(s
));
2372 throw ModalException("Can't get-info :reason-unknown when the "
2373 "last result wasn't unknown!");
2375 } else if(key
== "assertion-stack-levels") {
2376 AlwaysAssert(d_userLevels
.size() <=
2377 std::numeric_limits
<unsigned long int>::max());
2378 return SExpr(static_cast<unsigned long int>(d_userLevels
.size()));
2379 } else if(key
== "all-options") {
2380 // get the options, like all-statistics
2381 std::vector
< std::vector
<std::string
> > current_options
=
2382 Options::current()->getOptions();
2383 return SExpr::parseListOfListOfAtoms(current_options
);
2385 throw UnrecognizedOptionException();
2389 void SmtEngine::debugCheckFormals(const std::vector
<Expr
>& formals
, Expr func
)
2391 for(std::vector
<Expr
>::const_iterator i
= formals
.begin(); i
!= formals
.end(); ++i
) {
2392 if((*i
).getKind() != kind::BOUND_VARIABLE
) {
2394 ss
<< "All formal arguments to defined functions must be BOUND_VARIABLEs, but in the\n"
2395 << "definition of function " << func
<< ", formal\n"
2396 << " " << *i
<< "\n"
2397 << "has kind " << (*i
).getKind();
2398 throw TypeCheckingException(func
, ss
.str());
2403 void SmtEngine::debugCheckFunctionBody(Expr formula
,
2404 const std::vector
<Expr
>& formals
,
2407 Type formulaType
= formula
.getType(options::typeChecking());
2408 Type funcType
= func
.getType();
2409 // We distinguish here between definitions of constants and functions,
2410 // because the type checking for them is subtly different. Perhaps we
2411 // should instead have SmtEngine::defineFunction() and
2412 // SmtEngine::defineConstant() for better clarity, although then that
2413 // doesn't match the SMT-LIBv2 standard...
2414 if(formals
.size() > 0) {
2415 Type rangeType
= FunctionType(funcType
).getRangeType();
2416 if(! formulaType
.isComparableTo(rangeType
)) {
2418 ss
<< "Type of defined function does not match its declaration\n"
2419 << "The function : " << func
<< "\n"
2420 << "Declared type : " << rangeType
<< "\n"
2421 << "The body : " << formula
<< "\n"
2422 << "Body type : " << formulaType
;
2423 throw TypeCheckingException(func
, ss
.str());
2426 if(! formulaType
.isComparableTo(funcType
)) {
2428 ss
<< "Declared type of defined constant does not match its definition\n"
2429 << "The constant : " << func
<< "\n"
2430 << "Declared type : " << funcType
<< " " << Type::getTypeNode(funcType
)->getId() << "\n"
2431 << "The definition : " << formula
<< "\n"
2432 << "Definition type: " << formulaType
<< " " << Type::getTypeNode(formulaType
)->getId();
2433 throw TypeCheckingException(func
, ss
.str());
2438 void SmtEngine::defineFunction(Expr func
,
2439 const std::vector
<Expr
>& formals
,
2442 SmtScope
smts(this);
2444 Trace("smt") << "SMT defineFunction(" << func
<< ")" << endl
;
2445 debugCheckFormals(formals
, func
);
2448 ss
<< language::SetLanguage(
2449 language::SetLanguage::getLanguage(Dump
.getStream()))
2451 DefineFunctionCommand
c(ss
.str(), func
, formals
, formula
);
2452 addToModelCommandAndDump(
2453 c
, ExprManager::VAR_FLAG_DEFINED
, true, "declarations");
2455 PROOF(if (options::checkUnsatCores()) {
2456 d_defineCommands
.push_back(c
.clone());
2460 debugCheckFunctionBody(formula
, formals
, func
);
2462 // Substitute out any abstract values in formula
2464 d_private
->substituteAbstractValues(Node::fromExpr(formula
)).toExpr();
2466 TNode funcNode
= func
.getTNode();
2467 vector
<Node
> formalsNodes
;
2468 for(vector
<Expr
>::const_iterator i
= formals
.begin(),
2469 iend
= formals
.end();
2472 formalsNodes
.push_back((*i
).getNode());
2474 TNode formNode
= form
.getTNode();
2475 DefinedFunction
def(funcNode
, formalsNodes
, formNode
);
2476 // Permit (check-sat) (define-fun ...) (get-value ...) sequences.
2477 // Otherwise, (check-sat) (get-value ((! foo :named bar))) breaks
2478 // d_haveAdditions = true;
2479 Debug("smt") << "definedFunctions insert " << funcNode
<< " " << formNode
<< endl
;
2480 d_definedFunctions
->insert(funcNode
, def
);
2483 void SmtEngine::defineFunctionsRec(
2484 const std::vector
<Expr
>& funcs
,
2485 const std::vector
<std::vector
<Expr
> >& formals
,
2486 const std::vector
<Expr
>& formulas
)
2488 SmtScope
smts(this);
2489 finalOptionsAreSet();
2491 Trace("smt") << "SMT defineFunctionsRec(...)" << endl
;
2493 if (funcs
.size() != formals
.size() && funcs
.size() != formulas
.size())
2496 ss
<< "Number of functions, formals, and function bodies passed to "
2497 "defineFunctionsRec do not match:"
2499 << " #functions : " << funcs
.size() << "\n"
2500 << " #arg lists : " << formals
.size() << "\n"
2501 << " #function bodies : " << formulas
.size() << "\n";
2502 throw ModalException(ss
.str());
2504 for (unsigned i
= 0, size
= funcs
.size(); i
< size
; i
++)
2506 // check formal argument list
2507 debugCheckFormals(formals
[i
], funcs
[i
]);
2509 debugCheckFunctionBody(formulas
[i
], formals
[i
], funcs
[i
]);
2512 if (Dump
.isOn("raw-benchmark"))
2514 Dump("raw-benchmark") << DefineFunctionRecCommand(funcs
, formals
, formulas
);
2517 ExprManager
* em
= getExprManager();
2518 for (unsigned i
= 0, size
= funcs
.size(); i
< size
; i
++)
2520 // we assert a quantified formula
2522 // make the function application
2523 if (formals
[i
].empty())
2525 // it has no arguments
2526 func_app
= funcs
[i
];
2530 std::vector
<Expr
> children
;
2531 children
.push_back(funcs
[i
]);
2532 children
.insert(children
.end(), formals
[i
].begin(), formals
[i
].end());
2533 func_app
= em
->mkExpr(kind::APPLY_UF
, children
);
2535 Expr lem
= em
->mkExpr(kind::EQUAL
, func_app
, formulas
[i
]);
2536 if (!formals
[i
].empty())
2538 // set the attribute to denote this is a function definition
2539 std::string
attr_name("fun-def");
2540 Expr aexpr
= em
->mkExpr(kind::INST_ATTRIBUTE
, func_app
);
2541 aexpr
= em
->mkExpr(kind::INST_PATTERN_LIST
, aexpr
);
2542 std::vector
<Expr
> expr_values
;
2543 std::string str_value
;
2544 setUserAttribute(attr_name
, func_app
, expr_values
, str_value
);
2545 // make the quantified formula
2546 Expr boundVars
= em
->mkExpr(kind::BOUND_VAR_LIST
, formals
[i
]);
2547 lem
= em
->mkExpr(kind::FORALL
, boundVars
, lem
, aexpr
);
2549 // assert the quantified formula
2550 // notice we don't call assertFormula directly, since this would
2551 // duplicate the output on raw-benchmark.
2552 Expr e
= d_private
->substituteAbstractValues(Node::fromExpr(lem
)).toExpr();
2553 if (d_assertionList
!= NULL
)
2555 d_assertionList
->push_back(e
);
2557 d_private
->addFormula(e
.getNode(), false);
2561 void SmtEngine::defineFunctionRec(Expr func
,
2562 const std::vector
<Expr
>& formals
,
2565 std::vector
<Expr
> funcs
;
2566 funcs
.push_back(func
);
2567 std::vector
<std::vector
<Expr
> > formals_multi
;
2568 formals_multi
.push_back(formals
);
2569 std::vector
<Expr
> formulas
;
2570 formulas
.push_back(formula
);
2571 defineFunctionsRec(funcs
, formals_multi
, formulas
);
2574 bool SmtEngine::isDefinedFunction( Expr func
){
2575 Node nf
= Node::fromExpr( func
);
2576 Debug("smt") << "isDefined function " << nf
<< "?" << std::endl
;
2577 return d_definedFunctions
->find(nf
) != d_definedFunctions
->end();
2580 void SmtEnginePrivate::finishInit() {
2581 d_preprocessingPassContext
.reset(new PreprocessingPassContext(&d_smt
));
2582 // TODO: register passes here (this will likely change when we add support for
2583 // actually assembling preprocessing pipelines).
2584 std::unique_ptr
<BVGauss
> bvGauss(new BVGauss(d_preprocessingPassContext
.get()));
2585 std::unique_ptr
<IntToBV
> intToBV(new IntToBV(d_preprocessingPassContext
.get()));
2586 std::unique_ptr
<PseudoBooleanProcessor
> pbProc(
2587 new PseudoBooleanProcessor(d_preprocessingPassContext
.get()));
2589 d_preprocessingPassRegistry
.registerPass("bv-gauss", std::move(bvGauss
));
2590 d_preprocessingPassRegistry
.registerPass("int-to-bv", std::move(intToBV
));
2591 d_preprocessingPassRegistry
.registerPass("pseudo-boolean-processor",
2595 Node
SmtEnginePrivate::expandDefinitions(TNode n
, unordered_map
<Node
, Node
, NodeHashFunction
>& cache
, bool expandOnly
)
2597 stack
< triple
<Node
, Node
, bool> > worklist
;
2599 worklist
.push(make_triple(Node(n
), Node(n
), false));
2600 // The worklist is made of triples, each is input / original node then the output / rewritten node
2601 // and finally a flag tracking whether the children have been explored (i.e. if this is a downward
2605 spendResource(options::preprocessStep());
2606 n
= worklist
.top().first
; // n is the input / original
2607 Node node
= worklist
.top().second
; // node is the output / result
2608 bool childrenPushed
= worklist
.top().third
;
2611 // Working downwards
2612 if(!childrenPushed
) {
2613 Kind k
= n
.getKind();
2615 // we can short circuit (variable) leaves
2617 SmtEngine::DefinedFunctionMap::const_iterator i
= d_smt
.d_definedFunctions
->find(n
);
2618 if(i
!= d_smt
.d_definedFunctions
->end()) {
2619 // replacement must be closed
2620 if((*i
).second
.getFormals().size() > 0) {
2621 result
.push(d_smt
.d_nodeManager
->mkNode(kind::LAMBDA
, d_smt
.d_nodeManager
->mkNode(kind::BOUND_VAR_LIST
, (*i
).second
.getFormals()), (*i
).second
.getFormula()));
2624 // don't bother putting in the cache
2625 result
.push((*i
).second
.getFormula());
2628 // don't bother putting in the cache
2633 // maybe it's in the cache
2634 unordered_map
<Node
, Node
, NodeHashFunction
>::iterator cacheHit
= cache
.find(n
);
2635 if(cacheHit
!= cache
.end()) {
2636 TNode ret
= (*cacheHit
).second
;
2637 result
.push(ret
.isNull() ? n
: ret
);
2641 // otherwise expand it
2642 bool doExpand
= k
== kind::APPLY
;
2644 if( options::macrosQuant() ){
2645 //expand if we have inferred an operator corresponds to a defined function
2646 doExpand
= k
==kind::APPLY_UF
&& d_smt
.isDefinedFunction( n
.getOperator().toExpr() );
2650 vector
<Node
> formals
;
2652 if( n
.getOperator().getKind() == kind::LAMBDA
){
2653 TNode op
= n
.getOperator();
2655 for( unsigned i
=0; i
<op
[0].getNumChildren(); i
++ ){
2656 formals
.push_back( op
[0][i
] );
2660 // application of a user-defined symbol
2661 TNode func
= n
.getOperator();
2662 SmtEngine::DefinedFunctionMap::const_iterator i
= d_smt
.d_definedFunctions
->find(func
);
2663 if(i
== d_smt
.d_definedFunctions
->end()) {
2664 throw TypeCheckingException(n
.toExpr(), string("Undefined function: `") + func
.toString() + "'");
2666 DefinedFunction def
= (*i
).second
;
2667 formals
= def
.getFormals();
2669 if(Debug
.isOn("expand")) {
2670 Debug("expand") << "found: " << n
<< endl
;
2671 Debug("expand") << " func: " << func
<< endl
;
2672 string name
= func
.getAttribute(expr::VarNameAttr());
2673 Debug("expand") << " : \"" << name
<< "\"" << endl
;
2675 if(Debug
.isOn("expand")) {
2676 Debug("expand") << " defn: " << def
.getFunction() << endl
2678 if(formals
.size() > 0) {
2679 copy( formals
.begin(), formals
.end() - 1,
2680 ostream_iterator
<Node
>(Debug("expand"), ", ") );
2681 Debug("expand") << formals
.back();
2683 Debug("expand") << "]" << endl
2684 << " " << def
.getFunction().getType() << endl
2685 << " " << def
.getFormula() << endl
;
2688 fm
= def
.getFormula();
2691 Node instance
= fm
.substitute(formals
.begin(),
2694 n
.begin() + formals
.size());
2695 Debug("expand") << "made : " << instance
<< endl
;
2697 Node expanded
= expandDefinitions(instance
, cache
, expandOnly
);
2698 cache
[n
] = (n
== expanded
? Node::null() : expanded
);
2699 result
.push(expanded
);
2702 } else if(! expandOnly
) {
2703 // do not do any theory stuff if expandOnly is true
2705 theory::Theory
* t
= d_smt
.d_theoryEngine
->theoryOf(node
);
2708 LogicRequest
req(d_smt
);
2709 node
= t
->expandDefinition(req
, n
);
2712 // the partial functions can fall through, in which case we still
2713 // consider their children
2714 worklist
.push(make_triple(Node(n
), node
, true)); // Original and rewritten result
2716 for(size_t i
= 0; i
< node
.getNumChildren(); ++i
) {
2717 worklist
.push(make_triple(node
[i
], node
[i
], false)); // Rewrite the children of the result only
2722 // Reconstruct the node from it's (now rewritten) children on the stack
2724 Debug("expand") << "cons : " << node
<< endl
;
2725 if(node
.getNumChildren()>0) {
2726 //cout << "cons : " << node << endl;
2727 NodeBuilder
<> nb(node
.getKind());
2728 if(node
.getMetaKind() == kind::metakind::PARAMETERIZED
) {
2729 Debug("expand") << "op : " << node
.getOperator() << endl
;
2730 //cout << "op : " << node.getOperator() << endl;
2731 nb
<< node
.getOperator();
2733 for(size_t i
= 0; i
< node
.getNumChildren(); ++i
) {
2734 Assert(!result
.empty());
2735 Node expanded
= result
.top();
2737 //cout << "exchld : " << expanded << endl;
2738 Debug("expand") << "exchld : " << expanded
<< endl
;
2743 cache
[n
] = n
== node
? Node::null() : node
; // Only cache once all subterms are expanded
2746 } while(!worklist
.empty());
2748 AlwaysAssert(result
.size() == 1);
2750 return result
.top();
2753 typedef std::unordered_map
<Node
, Node
, NodeHashFunction
> NodeMap
;
2755 Node
SmtEnginePrivate::realToInt(TNode n
, NodeMap
& cache
, std::vector
< Node
>& var_eq
) {
2756 Trace("real-as-int-debug") << "Convert : " << n
<< std::endl
;
2757 NodeMap::iterator find
= cache
.find(n
);
2758 if (find
!= cache
.end()) {
2759 return (*find
).second
;
2762 if( n
.getNumChildren()>0 ){
2763 if( n
.getKind()==kind::EQUAL
|| n
.getKind()==kind::GEQ
|| n
.getKind()==kind::LT
|| n
.getKind()==kind::GT
|| n
.getKind()==kind::LEQ
){
2764 ret
= Rewriter::rewrite( n
);
2765 Trace("real-as-int-debug") << "Now looking at : " << ret
<< std::endl
;
2766 if( !ret
.isConst() ){
2767 Node ret_lit
= ret
.getKind()==kind::NOT
? ret
[0] : ret
;
2768 bool ret_pol
= ret
.getKind()!=kind::NOT
;
2769 std::map
< Node
, Node
> msum
;
2770 if (ArithMSum::getMonomialSumLit(ret_lit
, msum
))
2772 //get common coefficient
2773 std::vector
< Node
> coeffs
;
2774 for( std::map
< Node
, Node
>::iterator itm
= msum
.begin(); itm
!= msum
.end(); ++itm
){
2775 Node v
= itm
->first
;
2776 Node c
= itm
->second
;
2778 Assert( c
.isConst() );
2779 coeffs
.push_back( NodeManager::currentNM()->mkConst( Rational( c
.getConst
<Rational
>().getDenominator() ) ) );
2782 Node cc
= coeffs
.empty() ? Node::null() : ( coeffs
.size()==1 ? coeffs
[0] : Rewriter::rewrite( NodeManager::currentNM()->mkNode( kind::MULT
, coeffs
) ) );
2783 std::vector
< Node
> sum
;
2784 for( std::map
< Node
, Node
>::iterator itm
= msum
.begin(); itm
!= msum
.end(); ++itm
){
2785 Node v
= itm
->first
;
2786 Node c
= itm
->second
;
2789 c
= cc
.isNull() ? NodeManager::currentNM()->mkConst( Rational( 1 ) ) : cc
;
2792 c
= Rewriter::rewrite( NodeManager::currentNM()->mkNode( kind::MULT
, c
, cc
) );
2795 Assert( c
.getType().isInteger() );
2799 Node vv
= realToInt( v
, cache
, var_eq
);
2800 if( vv
.getType().isInteger() ){
2801 sum
.push_back( NodeManager::currentNM()->mkNode( kind::MULT
, c
, vv
) );
2803 throw TypeCheckingException(v
.toExpr(), string("Cannot translate to Int: ") + v
.toString());
2807 Node sumt
= sum
.empty() ? NodeManager::currentNM()->mkConst( Rational( 0 ) ) : ( sum
.size()==1 ? sum
[0] : NodeManager::currentNM()->mkNode( kind::PLUS
, sum
) );
2808 ret
= NodeManager::currentNM()->mkNode( ret_lit
.getKind(), sumt
, NodeManager::currentNM()->mkConst( Rational( 0 ) ) );
2812 Trace("real-as-int") << "Convert : " << std::endl
;
2813 Trace("real-as-int") << " " << n
<< std::endl
;
2814 Trace("real-as-int") << " " << ret
<< std::endl
;
2816 throw TypeCheckingException(n
.toExpr(), string("Cannot translate to Int: ") + n
.toString());
2820 bool childChanged
= false;
2821 std::vector
< Node
> children
;
2822 for( unsigned i
=0; i
<n
.getNumChildren(); i
++ ){
2823 Node nc
= realToInt( n
[i
], cache
, var_eq
);
2824 childChanged
= childChanged
|| nc
!=n
[i
];
2825 children
.push_back( nc
);
2828 ret
= NodeManager::currentNM()->mkNode( n
.getKind(), children
);
2833 if( !n
.getType().isInteger() ){
2834 ret
= NodeManager::currentNM()->mkSkolem("__realToInt_var", NodeManager::currentNM()->integerType(), "Variable introduced in realToInt pass");
2835 var_eq
.push_back( n
.eqNode( ret
) );
2836 TheoryModel
* m
= d_smt
.d_theoryEngine
->getModel();
2837 m
->addSubstitution(n
,ret
);
2846 Node
SmtEnginePrivate::purifyNlTerms(TNode n
, NodeMap
& cache
, NodeMap
& bcache
, std::vector
< Node
>& var_eq
, bool beneathMult
) {
2848 NodeMap::iterator find
= bcache
.find(n
);
2849 if (find
!= bcache
.end()) {
2850 return (*find
).second
;
2853 NodeMap::iterator find
= cache
.find(n
);
2854 if (find
!= cache
.end()) {
2855 return (*find
).second
;
2859 if( n
.getNumChildren()>0 ){
2860 if( beneathMult
&& n
.getKind()!=kind::MULT
){
2862 ret
= NodeManager::currentNM()->mkSkolem("__purifyNl_var", n
.getType(), "Variable introduced in purifyNl pass");
2863 Node np
= purifyNlTerms( n
, cache
, bcache
, var_eq
, false );
2864 var_eq
.push_back( np
.eqNode( ret
) );
2866 bool beneathMultNew
= beneathMult
|| n
.getKind()==kind::MULT
;
2867 bool childChanged
= false;
2868 std::vector
< Node
> children
;
2869 for( unsigned i
=0; i
<n
.getNumChildren(); i
++ ){
2870 Node nc
= purifyNlTerms( n
[i
], cache
, bcache
, var_eq
, beneathMultNew
);
2871 childChanged
= childChanged
|| nc
!=n
[i
];
2872 children
.push_back( nc
);
2875 ret
= NodeManager::currentNM()->mkNode( n
.getKind(), children
);
2887 void SmtEnginePrivate::removeITEs() {
2888 d_smt
.finalOptionsAreSet();
2889 spendResource(options::preprocessStep());
2890 Trace("simplify") << "SmtEnginePrivate::removeITEs()" << endl
;
2892 // Remove all of the ITE occurrences and normalize
2893 d_iteRemover
.run(d_assertions
.ref(), d_iteSkolemMap
, true);
2894 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
2895 d_assertions
.replace(i
, Rewriter::rewrite(d_assertions
[i
]));
2899 void SmtEnginePrivate::staticLearning() {
2900 d_smt
.finalOptionsAreSet();
2901 spendResource(options::preprocessStep());
2903 TimerStat::CodeTimer
staticLearningTimer(d_smt
.d_stats
->d_staticLearningTime
);
2905 Trace("simplify") << "SmtEnginePrivate::staticLearning()" << endl
;
2907 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
2909 NodeBuilder
<> learned(kind::AND
);
2910 learned
<< d_assertions
[i
];
2911 d_smt
.d_theoryEngine
->ppStaticLearn(d_assertions
[i
], learned
);
2912 if(learned
.getNumChildren() == 1) {
2915 d_assertions
.replace(i
, learned
);
2920 // do dumping (before/after any preprocessing pass)
2921 static void dumpAssertions(const char* key
,
2922 const AssertionPipeline
& assertionList
) {
2923 if( Dump
.isOn("assertions") &&
2924 Dump
.isOn(string("assertions:") + key
) ) {
2925 // Push the simplified assertions to the dump output stream
2926 for(unsigned i
= 0; i
< assertionList
.size(); ++ i
) {
2927 TNode n
= assertionList
[i
];
2928 Dump("assertions") << AssertCommand(Expr(n
.toExpr()));
2933 // returns false if it learns a conflict
2934 bool SmtEnginePrivate::nonClausalSimplify() {
2935 spendResource(options::preprocessStep());
2936 d_smt
.finalOptionsAreSet();
2938 if(options::unsatCores() || options::fewerPreprocessingHoles()) {
2942 TimerStat::CodeTimer
nonclausalTimer(d_smt
.d_stats
->d_nonclausalSimplificationTime
);
2944 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify()" << endl
;
2945 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
2946 Trace("simplify") << "Assertion #" << i
<< " : " << d_assertions
[i
] << std::endl
;
2949 if(d_propagatorNeedsFinish
) {
2950 d_propagator
.finish();
2951 d_propagatorNeedsFinish
= false;
2953 d_propagator
.initialize();
2955 // Assert all the assertions to the propagator
2956 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
2957 << "asserting to propagator" << endl
;
2958 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
2959 Assert(Rewriter::rewrite(d_assertions
[i
]) == d_assertions
[i
]);
2960 // Don't reprocess substitutions
2961 if (d_substitutionsIndex
> 0 && i
== d_substitutionsIndex
) {
2964 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): asserting " << d_assertions
[i
] << endl
;
2965 Debug("cores") << "d_propagator assertTrue: " << d_assertions
[i
] << std::endl
;
2966 d_propagator
.assertTrue(d_assertions
[i
]);
2969 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
2970 << "propagating" << endl
;
2971 if (d_propagator
.propagate()) {
2972 // If in conflict, just return false
2973 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
2974 << "conflict in non-clausal propagation" << endl
;
2975 Node falseNode
= NodeManager::currentNM()->mkConst
<bool>(false);
2976 Assert(!options::unsatCores() && !options::fewerPreprocessingHoles());
2977 d_assertions
.clear();
2978 addFormula(falseNode
, false, false);
2979 d_propagatorNeedsFinish
= true;
2984 Trace("simplify") << "Iterate through " << d_nonClausalLearnedLiterals
.size() << " learned literals." << std::endl
;
2985 // No conflict, go through the literals and solve them
2986 SubstitutionMap
constantPropagations(d_smt
.d_context
);
2987 SubstitutionMap
newSubstitutions(d_smt
.d_context
);
2988 SubstitutionMap::iterator pos
;
2990 for(unsigned i
= 0, i_end
= d_nonClausalLearnedLiterals
.size(); i
< i_end
; ++ i
) {
2991 // Simplify the literal we learned wrt previous substitutions
2992 Node learnedLiteral
= d_nonClausalLearnedLiterals
[i
];
2993 Assert(Rewriter::rewrite(learnedLiteral
) == learnedLiteral
);
2994 Assert(d_topLevelSubstitutions
.apply(learnedLiteral
) == learnedLiteral
);
2995 Trace("simplify") << "Process learnedLiteral : " << learnedLiteral
<< std::endl
;
2996 Node learnedLiteralNew
= newSubstitutions
.apply(learnedLiteral
);
2997 if (learnedLiteral
!= learnedLiteralNew
) {
2998 learnedLiteral
= Rewriter::rewrite(learnedLiteralNew
);
3000 Trace("simplify") << "Process learnedLiteral, after newSubs : " << learnedLiteral
<< std::endl
;
3002 learnedLiteralNew
= constantPropagations
.apply(learnedLiteral
);
3003 if (learnedLiteralNew
== learnedLiteral
) {
3006 ++d_smt
.d_stats
->d_numConstantProps
;
3007 learnedLiteral
= Rewriter::rewrite(learnedLiteralNew
);
3009 Trace("simplify") << "Process learnedLiteral, after constProp : " << learnedLiteral
<< std::endl
;
3010 // It might just simplify to a constant
3011 if (learnedLiteral
.isConst()) {
3012 if (learnedLiteral
.getConst
<bool>()) {
3013 // If the learned literal simplifies to true, it's redundant
3016 // If the learned literal simplifies to false, we're in conflict
3017 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
3019 << d_nonClausalLearnedLiterals
[i
] << endl
;
3020 Assert(!options::unsatCores());
3021 d_assertions
.clear();
3022 addFormula(NodeManager::currentNM()->mkConst
<bool>(false), false, false);
3023 d_propagatorNeedsFinish
= true;
3028 // Solve it with the corresponding theory, possibly adding new
3029 // substitutions to newSubstitutions
3030 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
3031 << "solving " << learnedLiteral
<< endl
;
3033 Theory::PPAssertStatus solveStatus
=
3034 d_smt
.d_theoryEngine
->solve(learnedLiteral
, newSubstitutions
);
3036 switch (solveStatus
) {
3037 case Theory::PP_ASSERT_STATUS_SOLVED
: {
3038 // The literal should rewrite to true
3039 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
3040 << "solved " << learnedLiteral
<< endl
;
3041 Assert(Rewriter::rewrite(newSubstitutions
.apply(learnedLiteral
)).isConst());
3042 // vector<pair<Node, Node> > equations;
3043 // constantPropagations.simplifyLHS(d_topLevelSubstitutions, equations, true);
3044 // if (equations.empty()) {
3047 // Assert(equations[0].first.isConst() && equations[0].second.isConst() && equations[0].first != equations[0].second);
3048 // else fall through
3051 case Theory::PP_ASSERT_STATUS_CONFLICT
:
3052 // If in conflict, we return false
3053 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
3054 << "conflict while solving "
3055 << learnedLiteral
<< endl
;
3056 Assert(!options::unsatCores());
3057 d_assertions
.clear();
3058 addFormula(NodeManager::currentNM()->mkConst
<bool>(false), false, false);
3059 d_propagatorNeedsFinish
= true;
3062 if (d_doConstantProp
&& learnedLiteral
.getKind() == kind::EQUAL
&& (learnedLiteral
[0].isConst() || learnedLiteral
[1].isConst())) {
3063 // constant propagation
3066 if (learnedLiteral
[0].isConst()) {
3067 t
= learnedLiteral
[1];
3068 c
= learnedLiteral
[0];
3071 t
= learnedLiteral
[0];
3072 c
= learnedLiteral
[1];
3074 Assert(!t
.isConst());
3075 Assert(constantPropagations
.apply(t
) == t
);
3076 Assert(d_topLevelSubstitutions
.apply(t
) == t
);
3077 Assert(newSubstitutions
.apply(t
) == t
);
3078 constantPropagations
.addSubstitution(t
, c
);
3079 // vector<pair<Node,Node> > equations;
3080 // constantPropagations.simplifyLHS(t, c, equations, true);
3081 // if (!equations.empty()) {
3082 // Assert(equations[0].first.isConst() && equations[0].second.isConst() && equations[0].first != equations[0].second);
3083 // d_assertions.clear();
3084 // addFormula(NodeManager::currentNM()->mkConst<bool>(false), false, false);
3087 // d_topLevelSubstitutions.simplifyRHS(constantPropagations);
3091 d_nonClausalLearnedLiterals
[j
++] = d_nonClausalLearnedLiterals
[i
];
3097 #ifdef CVC4_ASSERTIONS
3098 // NOTE: When debugging this code, consider moving this check inside of the
3099 // loop over d_nonClausalLearnedLiterals. This check has been moved outside
3100 // because it is costly for certain inputs (see bug 508).
3102 // Check data structure invariants:
3103 // 1. for each lhs of d_topLevelSubstitutions, does not appear anywhere in rhs of d_topLevelSubstitutions or anywhere in constantPropagations
3104 // 2. each lhs of constantPropagations rewrites to itself
3105 // 3. if l -> r is a constant propagation and l is a subterm of l' with l' -> r' another constant propagation, then l'[l/r] -> r' should be a
3106 // constant propagation too
3107 // 4. each lhs of constantPropagations is different from each rhs
3108 for (pos
= newSubstitutions
.begin(); pos
!= newSubstitutions
.end(); ++pos
) {
3109 Assert((*pos
).first
.isVar());
3110 Assert(d_topLevelSubstitutions
.apply((*pos
).first
) == (*pos
).first
);
3111 Assert(d_topLevelSubstitutions
.apply((*pos
).second
) == (*pos
).second
);
3112 Assert(newSubstitutions
.apply(newSubstitutions
.apply((*pos
).second
)) == newSubstitutions
.apply((*pos
).second
));
3114 for (pos
= constantPropagations
.begin(); pos
!= constantPropagations
.end(); ++pos
) {
3115 Assert((*pos
).second
.isConst());
3116 Assert(Rewriter::rewrite((*pos
).first
) == (*pos
).first
);
3117 // Node newLeft = d_topLevelSubstitutions.apply((*pos).first);
3118 // if (newLeft != (*pos).first) {
3119 // newLeft = Rewriter::rewrite(newLeft);
3120 // Assert(newLeft == (*pos).second ||
3121 // (constantPropagations.hasSubstitution(newLeft) && constantPropagations.apply(newLeft) == (*pos).second));
3123 // newLeft = constantPropagations.apply((*pos).first);
3124 // if (newLeft != (*pos).first) {
3125 // newLeft = Rewriter::rewrite(newLeft);
3126 // Assert(newLeft == (*pos).second ||
3127 // (constantPropagations.hasSubstitution(newLeft) && constantPropagations.apply(newLeft) == (*pos).second));
3129 Assert(constantPropagations
.apply((*pos
).second
) == (*pos
).second
);
3131 #endif /* CVC4_ASSERTIONS */
3133 // Resize the learnt
3134 Trace("simplify") << "Resize non-clausal learned literals to " << j
<< std::endl
;
3135 d_nonClausalLearnedLiterals
.resize(j
);
3137 unordered_set
<TNode
, TNodeHashFunction
> s
;
3138 Trace("debugging") << "NonClausal simplify pre-preprocess\n";
3139 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
3140 Node assertion
= d_assertions
[i
];
3141 Node assertionNew
= newSubstitutions
.apply(assertion
);
3142 Trace("debugging") << "assertion = " << assertion
<< endl
;
3143 Trace("debugging") << "assertionNew = " << assertionNew
<< endl
;
3144 if (assertion
!= assertionNew
) {
3145 assertion
= Rewriter::rewrite(assertionNew
);
3146 Trace("debugging") << "rewrite(assertion) = " << assertion
<< endl
;
3148 Assert(Rewriter::rewrite(assertion
) == assertion
);
3150 assertionNew
= constantPropagations
.apply(assertion
);
3151 if (assertionNew
== assertion
) {
3154 ++d_smt
.d_stats
->d_numConstantProps
;
3155 Trace("debugging") << "assertionNew = " << assertionNew
<< endl
;
3156 assertion
= Rewriter::rewrite(assertionNew
);
3157 Trace("debugging") << "assertionNew = " << assertionNew
<< endl
;
3159 Trace("debugging") << "\n";
3160 s
.insert(assertion
);
3161 d_assertions
.replace(i
, assertion
);
3162 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
3163 << "non-clausal preprocessed: "
3164 << assertion
<< endl
;
3167 // If in incremental mode, add substitutions to the list of assertions
3168 if (d_substitutionsIndex
> 0) {
3169 NodeBuilder
<> substitutionsBuilder(kind::AND
);
3170 substitutionsBuilder
<< d_assertions
[d_substitutionsIndex
];
3171 pos
= newSubstitutions
.begin();
3172 for (; pos
!= newSubstitutions
.end(); ++pos
) {
3173 // Add back this substitution as an assertion
3174 TNode lhs
= (*pos
).first
, rhs
= newSubstitutions
.apply((*pos
).second
);
3175 Node n
= NodeManager::currentNM()->mkNode(kind::EQUAL
, lhs
, rhs
);
3176 substitutionsBuilder
<< n
;
3177 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): will notify SAT layer of substitution: " << n
<< endl
;
3179 if (substitutionsBuilder
.getNumChildren() > 1) {
3180 d_assertions
.replace(d_substitutionsIndex
,
3181 Rewriter::rewrite(Node(substitutionsBuilder
)));
3184 // If not in incremental mode, must add substitutions to model
3185 TheoryModel
* m
= d_smt
.d_theoryEngine
->getModel();
3187 for(pos
= newSubstitutions
.begin(); pos
!= newSubstitutions
.end(); ++pos
) {
3188 Node n
= (*pos
).first
;
3189 Node v
= newSubstitutions
.apply((*pos
).second
);
3190 Trace("model") << "Add substitution : " << n
<< " " << v
<< endl
;
3191 m
->addSubstitution( n
, v
);
3196 NodeBuilder
<> learnedBuilder(kind::AND
);
3197 Assert(d_realAssertionsEnd
<= d_assertions
.size());
3198 learnedBuilder
<< d_assertions
[d_realAssertionsEnd
- 1];
3200 for (unsigned i
= 0; i
< d_nonClausalLearnedLiterals
.size(); ++ i
) {
3201 Node learned
= d_nonClausalLearnedLiterals
[i
];
3202 Assert(d_topLevelSubstitutions
.apply(learned
) == learned
);
3203 Node learnedNew
= newSubstitutions
.apply(learned
);
3204 if (learned
!= learnedNew
) {
3205 learned
= Rewriter::rewrite(learnedNew
);
3207 Assert(Rewriter::rewrite(learned
) == learned
);
3209 learnedNew
= constantPropagations
.apply(learned
);
3210 if (learnedNew
== learned
) {
3213 ++d_smt
.d_stats
->d_numConstantProps
;
3214 learned
= Rewriter::rewrite(learnedNew
);
3216 if (s
.find(learned
) != s
.end()) {
3220 learnedBuilder
<< learned
;
3221 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
3222 << "non-clausal learned : "
3225 d_nonClausalLearnedLiterals
.clear();
3227 for (pos
= constantPropagations
.begin(); pos
!= constantPropagations
.end(); ++pos
) {
3228 Node cProp
= (*pos
).first
.eqNode((*pos
).second
);
3229 Assert(d_topLevelSubstitutions
.apply(cProp
) == cProp
);
3230 Node cPropNew
= newSubstitutions
.apply(cProp
);
3231 if (cProp
!= cPropNew
) {
3232 cProp
= Rewriter::rewrite(cPropNew
);
3233 Assert(Rewriter::rewrite(cProp
) == cProp
);
3235 if (s
.find(cProp
) != s
.end()) {
3239 learnedBuilder
<< cProp
;
3240 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
3241 << "non-clausal constant propagation : "
3245 // Add new substitutions to topLevelSubstitutions
3246 // Note that we don't have to keep rhs's in full solved form
3247 // because SubstitutionMap::apply does a fixed-point iteration when substituting
3248 d_topLevelSubstitutions
.addSubstitutions(newSubstitutions
);
3250 if(learnedBuilder
.getNumChildren() > 1) {
3251 d_assertions
.replace(d_realAssertionsEnd
- 1,
3252 Rewriter::rewrite(Node(learnedBuilder
)));
3255 d_propagatorNeedsFinish
= true;
3259 void SmtEnginePrivate::bvAbstraction() {
3260 Trace("bv-abstraction") << "SmtEnginePrivate::bvAbstraction()" << endl
;
3261 std::vector
<Node
> new_assertions
;
3262 bool changed
= d_smt
.d_theoryEngine
->ppBvAbstraction(d_assertions
.ref(), new_assertions
);
3263 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
3264 d_assertions
.replace(i
, Rewriter::rewrite(new_assertions
[i
]));
3266 // if we are using the lazy solver and the abstraction
3267 // applies, then UF symbols were introduced
3268 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_LAZY
&&
3270 LogicRequest
req(d_smt
);
3271 req
.widenLogic(THEORY_UF
);
3276 void SmtEnginePrivate::bvToBool() {
3277 Trace("bv-to-bool") << "SmtEnginePrivate::bvToBool()" << endl
;
3278 spendResource(options::preprocessStep());
3279 std::vector
<Node
> new_assertions
;
3280 d_smt
.d_theoryEngine
->ppBvToBool(d_assertions
.ref(), new_assertions
);
3281 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
3282 d_assertions
.replace(i
, Rewriter::rewrite(new_assertions
[i
]));
3286 void SmtEnginePrivate::boolToBv() {
3287 Trace("bool-to-bv") << "SmtEnginePrivate::boolToBv()" << endl
;
3288 spendResource(options::preprocessStep());
3289 std::vector
<Node
> new_assertions
;
3290 d_smt
.d_theoryEngine
->ppBoolToBv(d_assertions
.ref(), new_assertions
);
3291 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
3292 d_assertions
.replace(i
, Rewriter::rewrite(new_assertions
[i
]));
3296 bool SmtEnginePrivate::simpITE() {
3297 TimerStat::CodeTimer
simpITETimer(d_smt
.d_stats
->d_simpITETime
);
3299 spendResource(options::preprocessStep());
3301 Trace("simplify") << "SmtEnginePrivate::simpITE()" << endl
;
3303 unsigned numAssertionOnEntry
= d_assertions
.size();
3304 for (unsigned i
= 0; i
< d_assertions
.size(); ++i
) {
3305 spendResource(options::preprocessStep());
3306 Node result
= d_smt
.d_theoryEngine
->ppSimpITE(d_assertions
[i
]);
3307 d_assertions
.replace(i
, result
);
3308 if(result
.isConst() && !result
.getConst
<bool>()){
3312 bool result
= d_smt
.d_theoryEngine
->donePPSimpITE(d_assertions
.ref());
3313 if(numAssertionOnEntry
< d_assertions
.size()){
3314 compressBeforeRealAssertions(numAssertionOnEntry
);
3319 void SmtEnginePrivate::compressBeforeRealAssertions(size_t before
){
3320 size_t curr
= d_assertions
.size();
3321 if(before
>= curr
||
3322 d_realAssertionsEnd
<= 0 ||
3323 d_realAssertionsEnd
>= curr
){
3328 // original: [0 ... d_realAssertionsEnd)
3330 // ites skolems [d_realAssertionsEnd, before)
3332 // added [before, curr)
3334 Assert(0 < d_realAssertionsEnd
);
3335 Assert(d_realAssertionsEnd
<= before
);
3336 Assert(before
< curr
);
3338 std::vector
<Node
> intoConjunction
;
3339 for(size_t i
= before
; i
<curr
; ++i
){
3340 intoConjunction
.push_back(d_assertions
[i
]);
3342 d_assertions
.resize(before
);
3343 size_t lastBeforeItes
= d_realAssertionsEnd
- 1;
3344 intoConjunction
.push_back(d_assertions
[lastBeforeItes
]);
3345 Node newLast
= util::NaryBuilder::mkAssoc(kind::AND
, intoConjunction
);
3346 d_assertions
.replace(lastBeforeItes
, newLast
);
3347 Assert(d_assertions
.size() == before
);
3350 void SmtEnginePrivate::unconstrainedSimp() {
3351 TimerStat::CodeTimer
unconstrainedSimpTimer(d_smt
.d_stats
->d_unconstrainedSimpTime
);
3352 spendResource(options::preprocessStep());
3353 Trace("simplify") << "SmtEnginePrivate::unconstrainedSimp()" << endl
;
3354 d_smt
.d_theoryEngine
->ppUnconstrainedSimp(d_assertions
.ref());
3357 void SmtEnginePrivate::traceBackToAssertions(const std::vector
<Node
>& nodes
, std::vector
<TNode
>& assertions
) {
3358 const booleans::CircuitPropagator::BackEdgesMap
& backEdges
= d_propagator
.getBackEdges();
3359 for(vector
<Node
>::const_iterator i
= nodes
.begin(); i
!= nodes
.end(); ++i
) {
3360 booleans::CircuitPropagator::BackEdgesMap::const_iterator j
= backEdges
.find(*i
);
3361 // term must appear in map, otherwise how did we get here?!
3362 Assert(j
!= backEdges
.end());
3363 // if term maps to empty, that means it's a top-level assertion
3364 if(!(*j
).second
.empty()) {
3365 traceBackToAssertions((*j
).second
, assertions
);
3367 assertions
.push_back(*i
);
3372 size_t SmtEnginePrivate::removeFromConjunction(Node
& n
, const std::unordered_set
<unsigned long>& toRemove
) {
3373 Assert(n
.getKind() == kind::AND
);
3374 size_t removals
= 0;
3375 for(Node::iterator j
= n
.begin(); j
!= n
.end(); ++j
) {
3376 size_t subremovals
= 0;
3378 if(toRemove
.find(sub
.getId()) != toRemove
.end() ||
3379 (sub
.getKind() == kind::AND
&& (subremovals
= removeFromConjunction(sub
, toRemove
)) > 0)) {
3380 NodeBuilder
<> b(kind::AND
);
3381 b
.append(n
.begin(), j
);
3382 if(subremovals
> 0) {
3383 removals
+= subremovals
;
3388 for(++j
; j
!= n
.end(); ++j
) {
3389 if(toRemove
.find((*j
).getId()) != toRemove
.end()) {
3391 } else if((*j
).getKind() == kind::AND
) {
3393 if((subremovals
= removeFromConjunction(sub
, toRemove
)) > 0) {
3394 removals
+= subremovals
;
3403 if(b
.getNumChildren() == 0) {
3406 } else if(b
.getNumChildren() == 1) {
3412 n
= Rewriter::rewrite(n
);
3417 Assert(removals
== 0);
3421 void SmtEnginePrivate::doMiplibTrick() {
3422 Assert(d_realAssertionsEnd
== d_assertions
.size());
3423 Assert(!options::incrementalSolving());
3425 const booleans::CircuitPropagator::BackEdgesMap
& backEdges
= d_propagator
.getBackEdges();
3426 unordered_set
<unsigned long> removeAssertions
;
3428 NodeManager
* nm
= NodeManager::currentNM();
3429 Node zero
= nm
->mkConst(Rational(0)), one
= nm
->mkConst(Rational(1));
3431 unordered_map
<TNode
, Node
, TNodeHashFunction
> intVars
;
3432 for(vector
<Node
>::const_iterator i
= d_boolVars
.begin(); i
!= d_boolVars
.end(); ++i
) {
3433 if(d_propagator
.isAssigned(*i
)) {
3434 Debug("miplib") << "ineligible: " << *i
<< " because assigned " << d_propagator
.getAssignment(*i
) << endl
;
3438 vector
<TNode
> assertions
;
3439 booleans::CircuitPropagator::BackEdgesMap::const_iterator j
= backEdges
.find(*i
);
3440 // if not in back edges map, the bool var is unconstrained, showing up in no assertions.
3441 // if maps to an empty vector, that means the bool var was asserted itself.
3442 if(j
!= backEdges
.end()) {
3443 if(!(*j
).second
.empty()) {
3444 traceBackToAssertions((*j
).second
, assertions
);
3446 assertions
.push_back(*i
);
3449 Debug("miplib") << "for " << *i
<< endl
;
3450 bool eligible
= true;
3451 map
<pair
<Node
, Node
>, uint64_t> marks
;
3452 map
<pair
<Node
, Node
>, vector
<Rational
> > coef
;
3453 map
<pair
<Node
, Node
>, vector
<Rational
> > checks
;
3454 map
<pair
<Node
, Node
>, vector
<TNode
> > asserts
;
3455 for(vector
<TNode
>::const_iterator j
= assertions
.begin(); j
!= assertions
.end(); ++j
) {
3456 Debug("miplib") << " found: " << *j
<< endl
;
3457 if((*j
).getKind() != kind::IMPLIES
) {
3459 Debug("miplib") << " -- INELIGIBLE -- (not =>)" << endl
;
3462 Node conj
= BooleanSimplification::simplify((*j
)[0]);
3463 if(conj
.getKind() == kind::AND
&& conj
.getNumChildren() > 6) {
3465 Debug("miplib") << " -- INELIGIBLE -- (N-ary /\\ too big)" << endl
;
3468 if(conj
.getKind() != kind::AND
&& !conj
.isVar() && !(conj
.getKind() == kind::NOT
&& conj
[0].isVar())) {
3470 Debug("miplib") << " -- INELIGIBLE -- (not /\\ or literal)" << endl
;
3473 if((*j
)[1].getKind() != kind::EQUAL
||
3474 !( ( (*j
)[1][0].isVar() &&
3475 (*j
)[1][1].getKind() == kind::CONST_RATIONAL
) ||
3476 ( (*j
)[1][0].getKind() == kind::CONST_RATIONAL
&&
3477 (*j
)[1][1].isVar() ) )) {
3479 Debug("miplib") << " -- INELIGIBLE -- (=> (and X X) X)" << endl
;
3482 if(conj
.getKind() == kind::AND
) {
3484 bool found_x
= false;
3485 map
<TNode
, bool> neg
;
3486 for(Node::iterator ii
= conj
.begin(); ii
!= conj
.end(); ++ii
) {
3488 posv
.push_back(*ii
);
3490 found_x
= found_x
|| *i
== *ii
;
3491 } else if((*ii
).getKind() == kind::NOT
&& (*ii
)[0].isVar()) {
3492 posv
.push_back((*ii
)[0]);
3493 neg
[(*ii
)[0]] = true;
3494 found_x
= found_x
|| *i
== (*ii
)[0];
3497 Debug("miplib") << " -- INELIGIBLE -- (non-var: " << *ii
<< ")" << endl
;
3500 if(d_propagator
.isAssigned(posv
.back())) {
3502 Debug("miplib") << " -- INELIGIBLE -- (" << posv
.back() << " asserted)" << endl
;
3511 Debug("miplib") << " --INELIGIBLE -- (couldn't find " << *i
<< " in conjunction)" << endl
;
3514 sort(posv
.begin(), posv
.end());
3515 const Node pos
= NodeManager::currentNM()->mkNode(kind::AND
, posv
);
3516 const TNode var
= ((*j
)[1][0].getKind() == kind::CONST_RATIONAL
) ? (*j
)[1][1] : (*j
)[1][0];
3517 const pair
<Node
, Node
> pos_var(pos
, var
);
3518 const Rational
& constant
= ((*j
)[1][0].getKind() == kind::CONST_RATIONAL
) ? (*j
)[1][0].getConst
<Rational
>() : (*j
)[1][1].getConst
<Rational
>();
3520 unsigned countneg
= 0, thepos
= 0;
3521 for(unsigned ii
= 0; ii
< pos
.getNumChildren(); ++ii
) {
3526 mark
|= (0x1 << ii
);
3529 if((marks
[pos_var
] & (1lu << mark
)) != 0) {
3531 Debug("miplib") << " -- INELIGIBLE -- (remarked)" << endl
;
3534 Debug("miplib") << "mark is " << mark
<< " -- " << (1lu << mark
) << endl
;
3535 marks
[pos_var
] |= (1lu << mark
);
3536 Debug("miplib") << "marks[" << pos
<< "," << var
<< "] now " << marks
[pos_var
] << endl
;
3537 if(countneg
== pos
.getNumChildren()) {
3540 Debug("miplib") << " -- INELIGIBLE -- (nonzero constant)" << endl
;
3543 } else if(countneg
== pos
.getNumChildren() - 1) {
3544 Assert(coef
[pos_var
].size() <= 6 && thepos
< 6);
3545 if(coef
[pos_var
].size() <= thepos
) {
3546 coef
[pos_var
].resize(thepos
+ 1);
3548 coef
[pos_var
][thepos
] = constant
;
3550 if(checks
[pos_var
].size() <= mark
) {
3551 checks
[pos_var
].resize(mark
+ 1);
3553 checks
[pos_var
][mark
] = constant
;
3555 asserts
[pos_var
].push_back(*j
);
3558 if(x
!= *i
&& x
!= (*i
).notNode()) {
3560 Debug("miplib") << " -- INELIGIBLE -- (x not present where I expect it)" << endl
;
3563 const bool xneg
= (x
.getKind() == kind::NOT
);
3564 x
= xneg
? x
[0] : x
;
3565 Debug("miplib") << " x:" << x
<< " " << xneg
<< endl
;
3566 const TNode var
= ((*j
)[1][0].getKind() == kind::CONST_RATIONAL
) ? (*j
)[1][1] : (*j
)[1][0];
3567 const pair
<Node
, Node
> x_var(x
, var
);
3568 const Rational
& constant
= ((*j
)[1][0].getKind() == kind::CONST_RATIONAL
) ? (*j
)[1][0].getConst
<Rational
>() : (*j
)[1][1].getConst
<Rational
>();
3569 unsigned mark
= (xneg
? 0 : 1);
3570 if((marks
[x_var
] & (1u << mark
)) != 0) {
3572 Debug("miplib") << " -- INELIGIBLE -- (remarked)" << endl
;
3575 marks
[x_var
] |= (1u << mark
);
3579 Debug("miplib") << " -- INELIGIBLE -- (nonzero constant)" << endl
;
3583 Assert(coef
[x_var
].size() <= 6);
3584 coef
[x_var
].resize(6);
3585 coef
[x_var
][0] = constant
;
3587 asserts
[x_var
].push_back(*j
);
3591 for(map
<pair
<Node
, Node
>, uint64_t>::const_iterator j
= marks
.begin(); j
!= marks
.end(); ++j
) {
3592 const TNode pos
= (*j
).first
.first
;
3593 const TNode var
= (*j
).first
.second
;
3594 const pair
<Node
, Node
>& pos_var
= (*j
).first
;
3595 const uint64_t mark
= (*j
).second
;
3596 const unsigned numVars
= pos
.getKind() == kind::AND
? pos
.getNumChildren() : 1;
3597 uint64_t expected
= (uint64_t(1) << (1 << numVars
)) - 1;
3598 expected
= (expected
== 0) ? -1 : expected
; // fix for overflow
3599 Debug("miplib") << "[" << pos
<< "] => " << hex
<< mark
<< " expect " << expected
<< dec
<< endl
;
3600 Assert(pos
.getKind() == kind::AND
|| pos
.isVar());
3601 if(mark
!= expected
) {
3602 Debug("miplib") << " -- INELIGIBLE " << pos
<< " -- (insufficiently marked, got " << mark
<< " for " << numVars
<< " vars, expected " << expected
<< endl
;
3604 if(mark
!= 3) { // exclude single-var case; nothing to check there
3605 uint64_t sz
= (uint64_t(1) << checks
[pos_var
].size()) - 1;
3606 sz
= (sz
== 0) ? -1 : sz
; // fix for overflow
3607 Assert(sz
== mark
, "expected size %u == mark %u", sz
, mark
);
3608 for(size_t k
= 0; k
< checks
[pos_var
].size(); ++k
) {
3609 if((k
& (k
- 1)) != 0) {
3611 Debug("miplib") << k
<< " => " << checks
[pos_var
][k
] << endl
;
3612 for(size_t v
= 1, kk
= k
; kk
!= 0; ++v
, kk
>>= 1) {
3613 if((kk
& 0x1) == 1) {
3614 Assert(pos
.getKind() == kind::AND
);
3615 Debug("miplib") << "var " << v
<< " : " << pos
[v
- 1] << " coef:" << coef
[pos_var
][v
- 1] << endl
;
3616 sum
+= coef
[pos_var
][v
- 1];
3619 Debug("miplib") << "checkSum is " << sum
<< " input says " << checks
[pos_var
][k
] << endl
;
3620 if(sum
!= checks
[pos_var
][k
]) {
3622 Debug("miplib") << " -- INELIGIBLE " << pos
<< " -- (nonlinear combination)" << endl
;
3626 Assert(checks
[pos_var
][k
] == 0, "checks[(%s,%s)][%u] should be 0, but it's %s", pos
.toString().c_str(), var
.toString().c_str(), k
, checks
[pos_var
][k
].toString().c_str()); // we never set for single-positive-var
3631 eligible
= true; // next is still eligible
3635 Debug("miplib") << " -- ELIGIBLE " << *i
<< " , " << pos
<< " --" << endl
;
3636 vector
<Node
> newVars
;
3637 expr::NodeSelfIterator ii
, iiend
;
3638 if(pos
.getKind() == kind::AND
) {
3642 ii
= expr::NodeSelfIterator::self(pos
);
3643 iiend
= expr::NodeSelfIterator::selfEnd(pos
);
3645 for(; ii
!= iiend
; ++ii
) {
3646 Node
& varRef
= intVars
[*ii
];
3647 if(varRef
.isNull()) {
3649 ss
<< "mipvar_" << *ii
;
3650 Node newVar
= nm
->mkSkolem(ss
.str(), nm
->integerType(), "a variable introduced due to scrubbing a miplib encoding", NodeManager::SKOLEM_EXACT_NAME
);
3651 Node geq
= Rewriter::rewrite(nm
->mkNode(kind::GEQ
, newVar
, zero
));
3652 Node leq
= Rewriter::rewrite(nm
->mkNode(kind::LEQ
, newVar
, one
));
3653 addFormula(Rewriter::rewrite(geq
.andNode(leq
)), false, false);
3654 SubstitutionMap
nullMap(&d_fakeContext
);
3655 Theory::PPAssertStatus status CVC4_UNUSED
; // just for assertions
3656 status
= d_smt
.d_theoryEngine
->solve(geq
, nullMap
);
3657 Assert(status
== Theory::PP_ASSERT_STATUS_UNSOLVED
,
3658 "unexpected solution from arith's ppAssert()");
3659 Assert(nullMap
.empty(),
3660 "unexpected substitution from arith's ppAssert()");
3661 status
= d_smt
.d_theoryEngine
->solve(leq
, nullMap
);
3662 Assert(status
== Theory::PP_ASSERT_STATUS_UNSOLVED
,
3663 "unexpected solution from arith's ppAssert()");
3664 Assert(nullMap
.empty(),
3665 "unexpected substitution from arith's ppAssert()");
3666 d_smt
.d_theoryEngine
->getModel()->addSubstitution(*ii
, newVar
.eqNode(one
));
3667 newVars
.push_back(newVar
);
3670 newVars
.push_back(varRef
);
3672 if(!d_smt
.d_logic
.areIntegersUsed()) {
3673 d_smt
.d_logic
= d_smt
.d_logic
.getUnlockedCopy();
3674 d_smt
.d_logic
.enableIntegers();
3675 d_smt
.d_logic
.lock();
3679 if(pos
.getKind() == kind::AND
) {
3680 NodeBuilder
<> sumb(kind::PLUS
);
3681 for(size_t ii
= 0; ii
< pos
.getNumChildren(); ++ii
) {
3682 sumb
<< nm
->mkNode(kind::MULT
, nm
->mkConst(coef
[pos_var
][ii
]), newVars
[ii
]);
3686 sum
= nm
->mkNode(kind::MULT
, nm
->mkConst(coef
[pos_var
][0]), newVars
[0]);
3688 Debug("miplib") << "vars[] " << var
<< endl
3689 << " eq " << Rewriter::rewrite(sum
) << endl
;
3690 Node newAssertion
= var
.eqNode(Rewriter::rewrite(sum
));
3691 if(d_topLevelSubstitutions
.hasSubstitution(newAssertion
[0])) {
3692 //Warning() << "RE-SUBSTITUTION " << newAssertion[0] << endl;
3693 //Warning() << "REPLACE " << newAssertion[1] << endl;
3694 //Warning() << "ORIG " << d_topLevelSubstitutions.getSubstitution(newAssertion[0]) << endl;
3695 Assert(d_topLevelSubstitutions
.getSubstitution(newAssertion
[0]) == newAssertion
[1]);
3696 } else if(pos
.getNumChildren() <= options::arithMLTrickSubstitutions()) {
3697 d_topLevelSubstitutions
.addSubstitution(newAssertion
[0], newAssertion
[1]);
3698 Debug("miplib") << "addSubs: " << newAssertion
[0] << " to " << newAssertion
[1] << endl
;
3700 Debug("miplib") << "skipSubs: " << newAssertion
[0] << " to " << newAssertion
[1] << " (threshold is " << options::arithMLTrickSubstitutions() << ")" << endl
;
3702 newAssertion
= Rewriter::rewrite(newAssertion
);
3703 Debug("miplib") << " " << newAssertion
<< endl
;
3704 addFormula(newAssertion
, false, false);
3705 Debug("miplib") << " assertions to remove: " << endl
;
3706 for(vector
<TNode
>::const_iterator k
= asserts
[pos_var
].begin(), k_end
= asserts
[pos_var
].end(); k
!= k_end
; ++k
) {
3707 Debug("miplib") << " " << *k
<< endl
;
3708 removeAssertions
.insert((*k
).getId());
3714 if(!removeAssertions
.empty()) {
3715 Debug("miplib") << "SmtEnginePrivate::simplify(): scrubbing miplib encoding..." << endl
;
3716 for(size_t i
= 0; i
< d_realAssertionsEnd
; ++i
) {
3717 if(removeAssertions
.find(d_assertions
[i
].getId()) != removeAssertions
.end()) {
3718 Debug("miplib") << "SmtEnginePrivate::simplify(): - removing " << d_assertions
[i
] << endl
;
3719 d_assertions
[i
] = d_true
;
3720 ++d_smt
.d_stats
->d_numMiplibAssertionsRemoved
;
3721 } else if(d_assertions
[i
].getKind() == kind::AND
) {
3722 size_t removals
= removeFromConjunction(d_assertions
[i
], removeAssertions
);
3724 Debug("miplib") << "SmtEnginePrivate::simplify(): - reduced " << d_assertions
[i
] << endl
;
3725 Debug("miplib") << "SmtEnginePrivate::simplify(): - by " << removals
<< " conjuncts" << endl
;
3726 d_smt
.d_stats
->d_numMiplibAssertionsRemoved
+= removals
;
3729 Debug("miplib") << "had: " << d_assertions
[i
] << endl
;
3730 d_assertions
[i
] = Rewriter::rewrite(d_topLevelSubstitutions
.apply(d_assertions
[i
]));
3731 Debug("miplib") << "now: " << d_assertions
[i
] << endl
;
3734 Debug("miplib") << "SmtEnginePrivate::simplify(): miplib pass found nothing." << endl
;
3736 d_realAssertionsEnd
= d_assertions
.size();
3740 // returns false if simplification led to "false"
3741 bool SmtEnginePrivate::simplifyAssertions()
3743 spendResource(options::preprocessStep());
3744 Assert(d_smt
.d_pendingPops
== 0);
3746 ScopeCounter
depth(d_simplifyAssertionsDepth
);
3748 Trace("simplify") << "SmtEnginePrivate::simplify()" << endl
;
3750 dumpAssertions("pre-nonclausal", d_assertions
);
3752 if(options::simplificationMode() != SIMPLIFICATION_MODE_NONE
) {
3753 // Perform non-clausal simplification
3754 Chat() << "...performing nonclausal simplification..." << endl
;
3755 Trace("simplify") << "SmtEnginePrivate::simplify(): "
3756 << "performing non-clausal simplification" << endl
;
3757 bool noConflict
= nonClausalSimplify();
3762 // We piggy-back off of the BackEdgesMap in the CircuitPropagator to
3763 // do the miplib trick.
3764 if( // check that option is on
3765 options::arithMLTrick() &&
3766 // miplib rewrites aren't safe in incremental mode
3767 ! options::incrementalSolving() &&
3768 // only useful in arith
3769 d_smt
.d_logic
.isTheoryEnabled(THEORY_ARITH
) &&
3770 // we add new assertions and need this (in practice, this
3771 // restriction only disables miplib processing during
3772 // re-simplification, which we don't expect to be useful anyway)
3773 d_realAssertionsEnd
== d_assertions
.size() ) {
3774 Chat() << "...fixing miplib encodings..." << endl
;
3775 Trace("simplify") << "SmtEnginePrivate::simplify(): "
3776 << "looking for miplib pseudobooleans..." << endl
;
3778 TimerStat::CodeTimer
miplibTimer(d_smt
.d_stats
->d_miplibPassTime
);
3782 Trace("simplify") << "SmtEnginePrivate::simplify(): "
3783 << "skipping miplib pseudobooleans pass (either incrementalSolving is on, or miplib pbs are turned off)..." << endl
;
3787 dumpAssertions("post-nonclausal", d_assertions
);
3788 Trace("smt") << "POST nonClausalSimplify" << endl
;
3789 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
3791 // before ppRewrite check if only core theory for BV theory
3792 d_smt
.d_theoryEngine
->staticInitializeBVOptions(d_assertions
.ref());
3794 dumpAssertions("pre-theorypp", d_assertions
);
3796 // Theory preprocessing
3797 if (d_smt
.d_earlyTheoryPP
) {
3798 Chat() << "...doing early theory preprocessing..." << endl
;
3799 TimerStat::CodeTimer
codeTimer(d_smt
.d_stats
->d_theoryPreprocessTime
);
3800 // Call the theory preprocessors
3801 d_smt
.d_theoryEngine
->preprocessStart();
3802 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
3803 Assert(Rewriter::rewrite(d_assertions
[i
]) == d_assertions
[i
]);
3804 d_assertions
.replace(i
, d_smt
.d_theoryEngine
->preprocess(d_assertions
[i
]));
3805 Assert(Rewriter::rewrite(d_assertions
[i
]) == d_assertions
[i
]);
3809 dumpAssertions("post-theorypp", d_assertions
);
3810 Trace("smt") << "POST theoryPP" << endl
;
3811 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
3813 // ITE simplification
3814 if(options::doITESimp() &&
3815 (d_simplifyAssertionsDepth
<= 1 || options::doITESimpOnRepeat())) {
3816 Chat() << "...doing ITE simplification..." << endl
;
3817 bool noConflict
= simpITE();
3819 Chat() << "...ITE simplification found unsat..." << endl
;
3824 dumpAssertions("post-itesimp", d_assertions
);
3825 Trace("smt") << "POST iteSimp" << endl
;
3826 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
3828 // Unconstrained simplification
3829 if(options::unconstrainedSimp()) {
3830 Chat() << "...doing unconstrained simplification..." << endl
;
3831 unconstrainedSimp();
3834 dumpAssertions("post-unconstrained", d_assertions
);
3835 Trace("smt") << "POST unconstrainedSimp" << endl
;
3836 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
3838 if(options::repeatSimp() && options::simplificationMode() != SIMPLIFICATION_MODE_NONE
) {
3839 Chat() << "...doing another round of nonclausal simplification..." << endl
;
3840 Trace("simplify") << "SmtEnginePrivate::simplify(): "
3841 << " doing repeated simplification" << endl
;
3842 bool noConflict
= nonClausalSimplify();
3848 dumpAssertions("post-repeatsimp", d_assertions
);
3849 Trace("smt") << "POST repeatSimp" << endl
;
3850 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
3852 } catch(TypeCheckingExceptionPrivate
& tcep
) {
3853 // Calls to this function should have already weeded out any
3854 // typechecking exceptions via (e.g.) ensureBoolean(). But a
3855 // theory could still create a new expression that isn't
3856 // well-typed, and we don't want the C++ runtime to abort our
3857 // process without any error notice.
3859 ss
<< "A bad expression was produced. Original exception follows:\n"
3861 InternalError(ss
.str().c_str());
3866 Result
SmtEngine::check() {
3867 Assert(d_fullyInited
);
3868 Assert(d_pendingPops
== 0);
3870 Trace("smt") << "SmtEngine::check()" << endl
;
3872 ResourceManager
* resourceManager
= d_private
->getResourceManager();
3874 resourceManager
->beginCall();
3876 // Only way we can be out of resource is if cumulative budget is on
3877 if (resourceManager
->cumulativeLimitOn() &&
3878 resourceManager
->out()) {
3879 Result::UnknownExplanation why
= resourceManager
->outOfResources() ?
3880 Result::RESOURCEOUT
: Result::TIMEOUT
;
3881 return Result(Result::VALIDITY_UNKNOWN
, why
, d_filename
);
3884 // Make sure the prop layer has all of the assertions
3885 Trace("smt") << "SmtEngine::check(): processing assertions" << endl
;
3886 d_private
->processAssertions();
3887 Trace("smt") << "SmtEngine::check(): done processing assertions" << endl
;
3889 // Turn off stop only for QF_LRA
3890 // TODO: Bring up in a meeting where to put this
3891 if(options::decisionStopOnly() && !options::decisionMode
.wasSetByUser() ){
3893 (not d_logic
.isQuantified() &&
3894 d_logic
.isPure(THEORY_ARITH
) && d_logic
.isLinear() && !d_logic
.isDifferenceLogic() && !d_logic
.areIntegersUsed()
3896 if(d_private
->d_iteSkolemMap
.empty()){
3897 options::decisionStopOnly
.set(false);
3898 d_decisionEngine
->clearStrategies();
3899 Trace("smt") << "SmtEngine::check(): turning off stop only" << endl
;
3904 TimerStat::CodeTimer
solveTimer(d_stats
->d_solveTime
);
3906 Chat() << "solving..." << endl
;
3907 Trace("smt") << "SmtEngine::check(): running check" << endl
;
3908 Result result
= d_propEngine
->checkSat();
3910 resourceManager
->endCall();
3911 Trace("limit") << "SmtEngine::check(): cumulative millis " << resourceManager
->getTimeUsage()
3912 << ", resources " << resourceManager
->getResourceUsage() << endl
;
3915 return Result(result
, d_filename
);
3918 Result
SmtEngine::quickCheck() {
3919 Assert(d_fullyInited
);
3920 Trace("smt") << "SMT quickCheck()" << endl
;
3921 return Result(Result::VALIDITY_UNKNOWN
, Result::REQUIRES_FULL_CHECK
, d_filename
);
3925 void SmtEnginePrivate::collectSkolems(TNode n
, set
<TNode
>& skolemSet
, unordered_map
<Node
, bool, NodeHashFunction
>& cache
)
3927 unordered_map
<Node
, bool, NodeHashFunction
>::iterator it
;
3929 if (it
!= cache
.end()) {
3933 size_t sz
= n
.getNumChildren();
3935 IteSkolemMap::iterator it
= d_iteSkolemMap
.find(n
);
3936 if (it
!= d_iteSkolemMap
.end()) {
3937 skolemSet
.insert(n
);
3944 for (; k
< sz
; ++k
) {
3945 collectSkolems(n
[k
], skolemSet
, cache
);
3951 bool SmtEnginePrivate::checkForBadSkolems(TNode n
, TNode skolem
, unordered_map
<Node
, bool, NodeHashFunction
>& cache
)
3953 unordered_map
<Node
, bool, NodeHashFunction
>::iterator it
;
3955 if (it
!= cache
.end()) {
3956 return (*it
).second
;
3959 size_t sz
= n
.getNumChildren();
3961 IteSkolemMap::iterator it
= d_iteSkolemMap
.find(n
);
3963 if (it
!= d_iteSkolemMap
.end()) {
3964 if (!((*it
).first
< n
)) {
3973 for (; k
< sz
; ++k
) {
3974 if (checkForBadSkolems(n
[k
], skolem
, cache
)) {
3984 void SmtEnginePrivate::applySubstitutionsToAssertions() {
3985 if(!options::unsatCores()) {
3986 Chat() << "applying substitutions..." << endl
;
3987 Trace("simplify") << "SmtEnginePrivate::processAssertions(): "
3988 << "applying substitutions" << endl
;
3989 // TODO(b/1255): Substitutions in incremental mode should be managed with a
3990 // proper data structure.
3992 // When solving incrementally, all substitutions are piled into the
3993 // assertion at d_substitutionsIndex: we don't want to apply substitutions
3994 // to this assertion or information will be lost.
3995 unsigned substitutionAssertion
= d_substitutionsIndex
> 0 ? d_substitutionsIndex
: d_assertions
.size();
3996 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
3997 if (i
== substitutionAssertion
) {
4000 Trace("simplify") << "applying to " << d_assertions
[i
] << endl
;
4001 spendResource(options::preprocessStep());
4002 d_assertions
.replace(i
, Rewriter::rewrite(d_topLevelSubstitutions
.apply(d_assertions
[i
])));
4003 Trace("simplify") << " got " << d_assertions
[i
] << endl
;
4008 void SmtEnginePrivate::processAssertions() {
4009 TimerStat::CodeTimer
paTimer(d_smt
.d_stats
->d_processAssertionsTime
);
4010 spendResource(options::preprocessStep());
4011 Assert(d_smt
.d_fullyInited
);
4012 Assert(d_smt
.d_pendingPops
== 0);
4014 // Dump the assertions
4015 dumpAssertions("pre-everything", d_assertions
);
4017 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() begin" << endl
;
4018 Trace("smt") << "SmtEnginePrivate::processAssertions()" << endl
;
4020 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
4022 if (d_assertions
.size() == 0) {
4027 if (options::bvGaussElim())
4029 TimerStat::CodeTimer
gaussElimTimer(d_smt
.d_stats
->d_gaussElimTime
);
4030 d_preprocessingPassRegistry
.getPass("bv-gauss")->apply(&d_assertions
);
4033 if (d_assertionsProcessed
&& options::incrementalSolving()) {
4034 // TODO(b/1255): Substitutions in incremental mode should be managed with a
4035 // proper data structure.
4037 // Placeholder for storing substitutions
4038 d_substitutionsIndex
= d_assertions
.size();
4039 d_assertions
.push_back(NodeManager::currentNM()->mkConst
<bool>(true));
4042 // Add dummy assertion in last position - to be used as a
4043 // placeholder for any new assertions to get added
4044 d_assertions
.push_back(NodeManager::currentNM()->mkConst
<bool>(true));
4045 // any assertions added beyond realAssertionsEnd must NOT affect the
4046 // equisatisfiability
4047 d_realAssertionsEnd
= d_assertions
.size();
4049 // Assertions are NOT guaranteed to be rewritten by this point
4051 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-definition-expansion" << endl
;
4052 dumpAssertions("pre-definition-expansion", d_assertions
);
4054 Chat() << "expanding definitions..." << endl
;
4055 Trace("simplify") << "SmtEnginePrivate::simplify(): expanding definitions" << endl
;
4056 TimerStat::CodeTimer
codeTimer(d_smt
.d_stats
->d_definitionExpansionTime
);
4057 unordered_map
<Node
, Node
, NodeHashFunction
> cache
;
4058 for(unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
4059 d_assertions
.replace(i
, expandDefinitions(d_assertions
[i
], cache
));
4062 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-definition-expansion" << endl
;
4063 dumpAssertions("post-definition-expansion", d_assertions
);
4065 // save the assertions now
4068 for (unsigned i
= 0; i
< d_assertions
.size(); ++i
) {
4069 ProofManager::currentPM()->addAssertion(d_assertions
[i
].toExpr());
4073 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
4075 if (options::sygusInference())
4077 // try recast as sygus
4078 quantifiers::SygusInference si
;
4079 if (si
.simplify(d_assertions
.ref()))
4081 Trace("smt-proc") << "...converted to sygus conjecture." << std::endl
;
4082 d_smt
.d_globalNegation
= !d_smt
.d_globalNegation
;
4085 else if (options::globalNegate())
4087 // global negation of the formula
4088 quantifiers::GlobalNegate gn
;
4089 gn
.simplify(d_assertions
.ref());
4090 d_smt
.d_globalNegation
= !d_smt
.d_globalNegation
;
4093 if( options::nlExtPurify() ){
4094 unordered_map
<Node
, Node
, NodeHashFunction
> cache
;
4095 unordered_map
<Node
, Node
, NodeHashFunction
> bcache
;
4096 std::vector
< Node
> var_eq
;
4097 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
4098 d_assertions
.replace(i
, purifyNlTerms(d_assertions
[i
], cache
, bcache
, var_eq
));
4100 if( !var_eq
.empty() ){
4101 unsigned lastIndex
= d_assertions
.size()-1;
4102 var_eq
.insert( var_eq
.begin(), d_assertions
[lastIndex
] );
4103 d_assertions
.replace(lastIndex
, NodeManager::currentNM()->mkNode( kind::AND
, var_eq
) );
4107 if( options::ceGuidedInst() ){
4108 //register sygus conjecture pre-rewrite (motivated by solution reconstruction)
4109 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
4110 d_smt
.d_theoryEngine
->getQuantifiersEngine()->getCegInstantiation()->preregisterAssertion( d_assertions
[i
] );
4114 if (options::solveRealAsInt()) {
4115 Chat() << "converting reals to ints..." << endl
;
4116 unordered_map
<Node
, Node
, NodeHashFunction
> cache
;
4117 std::vector
< Node
> var_eq
;
4118 for(unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
4119 d_assertions
.replace(i
, realToInt(d_assertions
[i
], cache
, var_eq
));
4122 if( !var_eq.empty() ){
4123 unsigned lastIndex = d_assertions.size()-1;
4124 var_eq.insert( var_eq.begin(), d_assertions[lastIndex] );
4125 d_assertions.replace(last_index, NodeManager::currentNM()->mkNode( kind::AND, var_eq ) );
4130 if (options::solveIntAsBV() > 0)
4132 d_preprocessingPassRegistry
.getPass("int-to-bv")->apply(&d_assertions
);
4135 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER
&&
4136 !d_smt
.d_logic
.isPure(THEORY_BV
) &&
4137 d_smt
.d_logic
.getLogicString() != "QF_UFBV" &&
4138 d_smt
.d_logic
.getLogicString() != "QF_ABV") {
4139 throw ModalException("Eager bit-blasting does not currently support theory combination. "
4140 "Note that in a QF_BV problem UF symbols can be introduced for division. "
4141 "Try --bv-div-zero-const to interpret division by zero as a constant.");
4144 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER
) {
4145 d_smt
.d_theoryEngine
->mkAckermanizationAssertions(d_assertions
.ref());
4148 if ( options::bvAbstraction() &&
4149 !options::incrementalSolving()) {
4150 dumpAssertions("pre-bv-abstraction", d_assertions
);
4152 dumpAssertions("post-bv-abstraction", d_assertions
);
4155 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
4157 bool noConflict
= true;
4159 if (options::extRewPrep())
4161 theory::quantifiers::ExtendedRewriter
extr(options::extRewPrepAgg());
4162 for (unsigned i
= 0; i
< d_assertions
.size(); ++i
)
4164 Node a
= d_assertions
[i
];
4165 d_assertions
.replace(i
, extr
.extendedRewrite(a
));
4169 // Unconstrained simplification
4170 if(options::unconstrainedSimp()) {
4171 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-unconstrained-simp" << endl
;
4172 dumpAssertions("pre-unconstrained-simp", d_assertions
);
4173 Chat() << "...doing unconstrained simplification..." << endl
;
4174 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
4175 d_assertions
.replace(i
, Rewriter::rewrite(d_assertions
[i
]));
4177 unconstrainedSimp();
4178 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-unconstrained-simp" << endl
;
4179 dumpAssertions("post-unconstrained-simp", d_assertions
);
4182 if(options::bvIntroducePow2()){
4183 theory::bv::BVIntroducePow2::pow2Rewrite(d_assertions
.ref());
4186 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-substitution" << endl
;
4187 dumpAssertions("pre-substitution", d_assertions
);
4189 if(options::unsatCores()) {
4190 // special rewriting pass for unsat cores, since many of the passes below are skipped
4191 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
4192 d_assertions
.replace(i
, Rewriter::rewrite(d_assertions
[i
]));
4195 applySubstitutionsToAssertions();
4197 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-substitution" << endl
;
4198 dumpAssertions("post-substitution", d_assertions
);
4200 // Assertions ARE guaranteed to be rewritten by this point
4201 #ifdef CVC4_ASSERTIONS
4202 for (unsigned i
= 0; i
< d_assertions
.size(); ++i
)
4204 Assert(Rewriter::rewrite(d_assertions
[i
]) == d_assertions
[i
]);
4208 // Lift bit-vectors of size 1 to bool
4209 if(options::bitvectorToBool()) {
4210 dumpAssertions("pre-bv-to-bool", d_assertions
);
4211 Chat() << "...doing bvToBool..." << endl
;
4213 dumpAssertions("post-bv-to-bool", d_assertions
);
4214 Trace("smt") << "POST bvToBool" << endl
;
4216 // Convert non-top-level Booleans to bit-vectors of size 1
4217 if(options::boolToBitvector()) {
4218 dumpAssertions("pre-bool-to-bv", d_assertions
);
4219 Chat() << "...doing boolToBv..." << endl
;
4221 dumpAssertions("post-bool-to-bv", d_assertions
);
4222 Trace("smt") << "POST boolToBv" << endl
;
4224 if(options::sepPreSkolemEmp()) {
4225 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
4226 Node prev
= d_assertions
[i
];
4227 Node next
= sep::TheorySepRewriter::preprocess( prev
);
4229 d_assertions
.replace( i
, Rewriter::rewrite( next
) );
4230 Trace("sep-preprocess") << "*** Preprocess sep " << prev
<< endl
;
4231 Trace("sep-preprocess") << " ...got " << d_assertions
[i
] << endl
;
4236 if( d_smt
.d_logic
.isQuantified() ){
4237 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-quant-preprocess" << endl
;
4239 dumpAssertions("pre-skolem-quant", d_assertions
);
4240 //remove rewrite rules, apply pre-skolemization to existential quantifiers
4241 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
4242 Node prev
= d_assertions
[i
];
4243 Node next
= quantifiers::QuantifiersRewriter::preprocess( prev
);
4245 d_assertions
.replace( i
, Rewriter::rewrite( next
) );
4246 Trace("quantifiers-preprocess") << "*** Pre-skolemize " << prev
<< endl
;
4247 Trace("quantifiers-preprocess") << " ...got " << d_assertions
[i
] << endl
;
4250 dumpAssertions("post-skolem-quant", d_assertions
);
4251 if( options::macrosQuant() ){
4252 //quantifiers macro expansion
4253 quantifiers::QuantifierMacros
qm( d_smt
.d_theoryEngine
->getQuantifiersEngine() );
4256 success
= qm
.simplify( d_assertions
.ref(), true );
4258 //finalize the definitions
4259 qm
.finalizeDefinitions();
4262 //fmf-fun : assume admissible functions, applying preprocessing reduction to FMF
4263 if( options::fmfFunWellDefined() ){
4264 quantifiers::FunDefFmf fdf
;
4265 Assert( d_smt
.d_fmfRecFunctionsDefined
!=NULL
);
4266 //must carry over current definitions (for incremental)
4267 for( context::CDList
<Node
>::const_iterator fit
= d_smt
.d_fmfRecFunctionsDefined
->begin();
4268 fit
!= d_smt
.d_fmfRecFunctionsDefined
->end(); ++fit
) {
4270 Assert( d_smt
.d_fmfRecFunctionsAbs
.find( f
)!=d_smt
.d_fmfRecFunctionsAbs
.end() );
4271 TypeNode ft
= d_smt
.d_fmfRecFunctionsAbs
[f
];
4272 fdf
.d_sorts
[f
] = ft
;
4273 std::map
< Node
, std::vector
< Node
> >::iterator fcit
= d_smt
.d_fmfRecFunctionsConcrete
.find( f
);
4274 Assert( fcit
!=d_smt
.d_fmfRecFunctionsConcrete
.end() );
4275 for( unsigned j
=0; j
<fcit
->second
.size(); j
++ ){
4276 fdf
.d_input_arg_inj
[f
].push_back( fcit
->second
[j
] );
4279 fdf
.simplify( d_assertions
.ref() );
4280 //must store new definitions (for incremental)
4281 for( unsigned i
=0; i
<fdf
.d_funcs
.size(); i
++ ){
4282 Node f
= fdf
.d_funcs
[i
];
4283 d_smt
.d_fmfRecFunctionsAbs
[f
] = fdf
.d_sorts
[f
];
4284 d_smt
.d_fmfRecFunctionsConcrete
[f
].clear();
4285 for( unsigned j
=0; j
<fdf
.d_input_arg_inj
[f
].size(); j
++ ){
4286 d_smt
.d_fmfRecFunctionsConcrete
[f
].push_back( fdf
.d_input_arg_inj
[f
][j
] );
4288 d_smt
.d_fmfRecFunctionsDefined
->push_back( f
);
4291 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-quant-preprocess" << endl
;
4294 if( options::sortInference() || options::ufssFairnessMonotone() ){
4295 //sort inference technique
4296 SortInference
* si
= d_smt
.d_theoryEngine
->getSortInference();
4297 si
->simplify( d_assertions
.ref(), options::sortInference(), options::ufssFairnessMonotone() );
4298 for( std::map
< Node
, Node
>::iterator it
= si
->d_model_replace_f
.begin(); it
!= si
->d_model_replace_f
.end(); ++it
){
4299 d_smt
.setPrintFuncInModel( it
->first
.toExpr(), false );
4300 d_smt
.setPrintFuncInModel( it
->second
.toExpr(), true );
4304 if( options::pbRewrites() ){
4305 d_preprocessingPassRegistry
.getPass("pseudo-boolean-processor")
4306 ->apply(&d_assertions
);
4309 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-simplify" << endl
;
4310 dumpAssertions("pre-simplify", d_assertions
);
4311 Chat() << "simplifying assertions..." << endl
;
4312 noConflict
= simplifyAssertions();
4314 ++(d_smt
.d_stats
->d_simplifiedToFalse
);
4316 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-simplify" << endl
;
4317 dumpAssertions("post-simplify", d_assertions
);
4319 if (options::symmetryDetect())
4321 SymmetryDetect symd
;
4322 vector
<vector
<Node
>> part
;
4323 symd
.getPartition(part
, d_assertions
.ref());
4326 dumpAssertions("pre-static-learning", d_assertions
);
4327 if(options::doStaticLearning()) {
4328 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-static-learning" << endl
;
4329 // Perform static learning
4330 Chat() << "doing static learning..." << endl
;
4331 Trace("simplify") << "SmtEnginePrivate::simplify(): "
4332 << "performing static learning" << endl
;
4334 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-static-learning" << endl
;
4336 dumpAssertions("post-static-learning", d_assertions
);
4338 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
4341 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-ite-removal" << endl
;
4342 dumpAssertions("pre-ite-removal", d_assertions
);
4344 Chat() << "removing term ITEs..." << endl
;
4345 TimerStat::CodeTimer
codeTimer(d_smt
.d_stats
->d_iteRemovalTime
);
4346 // Remove ITEs, updating d_iteSkolemMap
4347 d_smt
.d_stats
->d_numAssertionsPre
+= d_assertions
.size();
4349 // This is needed because when solving incrementally, removeITEs may introduce
4350 // skolems that were solved for earlier and thus appear in the substitution
4352 applySubstitutionsToAssertions();
4353 d_smt
.d_stats
->d_numAssertionsPost
+= d_assertions
.size();
4355 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-ite-removal" << endl
;
4356 dumpAssertions("post-ite-removal", d_assertions
);
4358 dumpAssertions("pre-repeat-simplify", d_assertions
);
4359 if(options::repeatSimp()) {
4360 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-repeat-simplify" << endl
;
4361 Chat() << "re-simplifying assertions..." << endl
;
4362 ScopeCounter
depth(d_simplifyAssertionsDepth
);
4363 noConflict
&= simplifyAssertions();
4365 // Need to fix up assertion list to maintain invariants:
4366 // Let Sk be the set of Skolem variables introduced by ITE's. Let <_sk be the order in which these variables were introduced
4367 // during ite removal.
4368 // For each skolem variable sk, let iteExpr = iteMap(sk) be the ite expr mapped to by sk.
4370 // cache for expression traversal
4371 unordered_map
<Node
, bool, NodeHashFunction
> cache
;
4373 // First, find all skolems that appear in the substitution map - their associated iteExpr will need
4374 // to be moved to the main assertion set
4375 set
<TNode
> skolemSet
;
4376 SubstitutionMap::iterator pos
= d_topLevelSubstitutions
.begin();
4377 for (; pos
!= d_topLevelSubstitutions
.end(); ++pos
) {
4378 collectSkolems((*pos
).first
, skolemSet
, cache
);
4379 collectSkolems((*pos
).second
, skolemSet
, cache
);
4382 // We need to ensure:
4383 // 1. iteExpr has the form (ite cond (sk = t) (sk = e))
4384 // 2. if some sk' in Sk appears in cond, t, or e, then sk' <_sk sk
4385 // If either of these is violated, we must add iteExpr as a proper assertion
4386 IteSkolemMap::iterator it
= d_iteSkolemMap
.begin();
4387 IteSkolemMap::iterator iend
= d_iteSkolemMap
.end();
4388 NodeBuilder
<> builder(kind::AND
);
4389 builder
<< d_assertions
[d_realAssertionsEnd
- 1];
4390 vector
<TNode
> toErase
;
4391 for (; it
!= iend
; ++it
) {
4392 if (skolemSet
.find((*it
).first
) == skolemSet
.end()) {
4393 TNode iteExpr
= d_assertions
[(*it
).second
];
4394 if (iteExpr
.getKind() == kind::ITE
&&
4395 iteExpr
[1].getKind() == kind::EQUAL
&&
4396 iteExpr
[1][0] == (*it
).first
&&
4397 iteExpr
[2].getKind() == kind::EQUAL
&&
4398 iteExpr
[2][0] == (*it
).first
) {
4400 bool bad
= checkForBadSkolems(iteExpr
[0], (*it
).first
, cache
);
4401 bad
= bad
|| checkForBadSkolems(iteExpr
[1][1], (*it
).first
, cache
);
4402 bad
= bad
|| checkForBadSkolems(iteExpr
[2][1], (*it
).first
, cache
);
4408 // Move this iteExpr into the main assertions
4409 builder
<< d_assertions
[(*it
).second
];
4410 d_assertions
[(*it
).second
] = NodeManager::currentNM()->mkConst
<bool>(true);
4411 toErase
.push_back((*it
).first
);
4413 if(builder
.getNumChildren() > 1) {
4414 while (!toErase
.empty()) {
4415 d_iteSkolemMap
.erase(toErase
.back());
4418 d_assertions
[d_realAssertionsEnd
- 1] = Rewriter::rewrite(Node(builder
));
4420 // TODO(b/1256): For some reason this is needed for some benchmarks, such as
4421 // QF_AUFBV/dwp_formulas/try5_small_difret_functions_dwp_tac.re_node_set_remove_at.il.dwp.smt2
4423 applySubstitutionsToAssertions();
4424 // Assert(iteRewriteAssertionsEnd == d_assertions.size());
4426 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-repeat-simplify" << endl
;
4428 dumpAssertions("post-repeat-simplify", d_assertions
);
4430 dumpAssertions("pre-rewrite-apply-to-const", d_assertions
);
4431 if(options::rewriteApplyToConst()) {
4432 Chat() << "Rewriting applies to constants..." << endl
;
4433 TimerStat::CodeTimer
codeTimer(d_smt
.d_stats
->d_rewriteApplyToConstTime
);
4434 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
4435 d_assertions
[i
] = Rewriter::rewrite(rewriteApplyToConst(d_assertions
[i
]));
4438 dumpAssertions("post-rewrite-apply-to-const", d_assertions
);
4440 // begin: INVARIANT to maintain: no reordering of assertions or
4441 // introducing new ones
4442 #ifdef CVC4_ASSERTIONS
4443 unsigned iteRewriteAssertionsEnd
= d_assertions
.size();
4446 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
4448 Debug("smt") << "SmtEnginePrivate::processAssertions() POST SIMPLIFICATION" << endl
;
4449 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
4451 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-theory-preprocessing" << endl
;
4452 dumpAssertions("pre-theory-preprocessing", d_assertions
);
4454 Chat() << "theory preprocessing..." << endl
;
4455 TimerStat::CodeTimer
codeTimer(d_smt
.d_stats
->d_theoryPreprocessTime
);
4456 // Call the theory preprocessors
4457 d_smt
.d_theoryEngine
->preprocessStart();
4458 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
4459 d_assertions
.replace(i
, d_smt
.d_theoryEngine
->preprocess(d_assertions
[i
]));
4462 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-theory-preprocessing" << endl
;
4463 dumpAssertions("post-theory-preprocessing", d_assertions
);
4465 // If we are using eager bit-blasting wrap assertions in fake atom so that
4466 // everything gets bit-blasted to internal SAT solver
4467 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER
) {
4468 for (unsigned i
= 0; i
< d_assertions
.size(); ++i
) {
4469 TNode atom
= d_assertions
[i
];
4470 Node eager_atom
= NodeManager::currentNM()->mkNode(kind::BITVECTOR_EAGER_ATOM
, atom
);
4471 d_assertions
.replace(i
, eager_atom
);
4472 TheoryModel
* m
= d_smt
.d_theoryEngine
->getModel();
4473 m
->addSubstitution(eager_atom
, atom
);
4477 //notify theory engine new preprocessed assertions
4478 d_smt
.d_theoryEngine
->notifyPreprocessedAssertions( d_assertions
.ref() );
4480 // Push the formula to decision engine
4482 Chat() << "pushing to decision engine..." << endl
;
4483 Assert(iteRewriteAssertionsEnd
== d_assertions
.size());
4484 d_smt
.d_decisionEngine
->addAssertions
4485 (d_assertions
.ref(), d_realAssertionsEnd
, d_iteSkolemMap
);
4488 // end: INVARIANT to maintain: no reordering of assertions or
4489 // introducing new ones
4491 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() end" << endl
;
4492 dumpAssertions("post-everything", d_assertions
);
4494 // Push the formula to SAT
4496 Chat() << "converting to CNF..." << endl
;
4497 TimerStat::CodeTimer
codeTimer(d_smt
.d_stats
->d_cnfConversionTime
);
4498 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
4499 Chat() << "+ " << d_assertions
[i
] << std::endl
;
4500 d_smt
.d_propEngine
->assertFormula(d_assertions
[i
]);
4504 d_assertionsProcessed
= true;
4506 d_assertions
.clear();
4507 d_iteSkolemMap
.clear();
4510 void SmtEnginePrivate::addFormula(TNode n
, bool inUnsatCore
, bool inInput
)
4517 Trace("smt") << "SmtEnginePrivate::addFormula(" << n
<< "), inUnsatCore = " << inUnsatCore
<< ", inInput = " << inInput
<< endl
;
4519 // Give it to proof manager
4522 // n is an input assertion
4523 if (inUnsatCore
|| options::unsatCores() || options::dumpUnsatCores() || options::checkUnsatCores() || options::fewerPreprocessingHoles()) {
4525 ProofManager::currentPM()->addCoreAssertion(n
.toExpr());
4528 // n is the result of an unknown preprocessing step, add it to dependency map to null
4529 ProofManager::currentPM()->addDependence(n
, Node::null());
4531 // rewrite rules are by default in the unsat core because
4532 // they need to be applied until saturation
4533 if(options::unsatCores() &&
4534 n
.getKind() == kind::REWRITE_RULE
){
4535 ProofManager::currentPM()->addUnsatCore(n
.toExpr());
4539 // Add the normalized formula to the queue
4540 d_assertions
.push_back(n
);
4541 //d_assertions.push_back(Rewriter::rewrite(n));
4544 void SmtEngine::ensureBoolean(const Expr
& e
)
4546 Type type
= e
.getType(options::typeChecking());
4547 Type boolType
= d_exprManager
->booleanType();
4548 if(type
!= boolType
) {
4550 ss
<< "Expected " << boolType
<< "\n"
4551 << "The assertion : " << e
<< "\n"
4552 << "Its type : " << type
;
4553 throw TypeCheckingException(e
, ss
.str());
4557 Result
SmtEngine::checkSat(const Expr
& assumption
, bool inUnsatCore
)
4559 return checkSatisfiability(assumption
, inUnsatCore
, false);
4562 Result
SmtEngine::checkSat(const vector
<Expr
>& assumptions
, bool inUnsatCore
)
4564 return checkSatisfiability(assumptions
, inUnsatCore
, false);
4567 Result
SmtEngine::query(const Expr
& assumption
, bool inUnsatCore
)
4569 Assert(!assumption
.isNull());
4570 return checkSatisfiability(assumption
, inUnsatCore
, true);
4573 Result
SmtEngine::query(const vector
<Expr
>& assumptions
, bool inUnsatCore
)
4575 return checkSatisfiability(assumptions
, inUnsatCore
, true);
4578 Result
SmtEngine::checkSatisfiability(const Expr
& expr
,
4582 return checkSatisfiability(
4583 expr
.isNull() ? vector
<Expr
>() : vector
<Expr
>{expr
},
4588 Result
SmtEngine::checkSatisfiability(const vector
<Expr
>& assumptions
,
4594 SmtScope
smts(this);
4595 finalOptionsAreSet();
4598 Trace("smt") << "SmtEngine::" << (isQuery
? "query" : "checkSat") << "("
4599 << assumptions
<< ")" << endl
;
4601 if(d_queryMade
&& !options::incrementalSolving()) {
4602 throw ModalException("Cannot make multiple queries unless "
4603 "incremental solving is enabled "
4604 "(try --incremental)");
4607 // check to see if a postsolve() is pending
4608 if(d_needPostsolve
) {
4609 d_theoryEngine
->postsolve();
4610 d_needPostsolve
= false;
4612 // Note that a query has been made
4614 // reset global negation
4615 d_globalNegation
= false;
4617 bool didInternalPush
= false;
4619 setProblemExtended(true);
4623 size_t size
= assumptions
.size();
4626 /* Assume: not (BIGAND assumptions) */
4627 d_assumptions
.push_back(
4628 d_exprManager
->mkExpr(kind::AND
, assumptions
).notExpr());
4632 /* Assume: not expr */
4633 d_assumptions
.push_back(assumptions
[0].notExpr());
4638 /* Assume: BIGAND assumptions */
4639 d_assumptions
= assumptions
;
4642 Result
r(Result::SAT_UNKNOWN
, Result::UNKNOWN_REASON
);
4643 for (Expr e
: d_assumptions
)
4645 // Substitute out any abstract values in ex.
4646 e
= d_private
->substituteAbstractValues(Node::fromExpr(e
)).toExpr();
4647 Assert(e
.getExprManager() == d_exprManager
);
4648 // Ensure expr is type-checked at this point.
4651 /* Add assumption */
4653 didInternalPush
= true;
4654 if (d_assertionList
!= NULL
)
4656 d_assertionList
->push_back(e
);
4658 d_private
->addFormula(e
.getNode(), inUnsatCore
);
4661 r
= isQuery
? check().asValidityResult() : check().asSatisfiabilityResult();
4663 if ((options::solveRealAsInt() || options::solveIntAsBV() > 0)
4664 && r
.asSatisfiabilityResult().isSat() == Result::UNSAT
)
4666 r
= Result(Result::SAT_UNKNOWN
, Result::UNKNOWN_REASON
);
4668 // flipped if we did a global negation
4669 if (d_globalNegation
)
4671 Trace("smt") << "SmtEngine::process global negate " << r
<< std::endl
;
4672 if (r
.asSatisfiabilityResult().isSat() == Result::UNSAT
)
4674 r
= Result(Result::SAT
);
4676 else if (r
.asSatisfiabilityResult().isSat() == Result::SAT
)
4678 // only if satisfaction complete
4679 if (d_logic
.isPure(THEORY_ARITH
) || d_logic
.isPure(THEORY_BV
))
4681 r
= Result(Result::UNSAT
);
4685 r
= Result(Result::SAT_UNKNOWN
, Result::UNKNOWN_REASON
);
4688 Trace("smt") << "SmtEngine::global negate returned " << r
<< std::endl
;
4691 d_needPostsolve
= true;
4693 // Dump the query if requested
4694 if (Dump
.isOn("benchmark"))
4696 size_t size
= assumptions
.size();
4697 // the expr already got dumped out if assertion-dumping is on
4698 if (isQuery
&& size
== 1)
4700 Dump("benchmark") << QueryCommand(assumptions
[0]);
4704 Dump("benchmark") << CheckSatCommand();
4708 Dump("benchmark") << CheckSatAssumingCommand(d_assumptions
,
4714 if (didInternalPush
)
4719 // Remember the status
4722 setProblemExtended(false);
4724 Trace("smt") << "SmtEngine::" << (isQuery
? "query" : "checkSat") << "("
4725 << assumptions
<< ") => " << r
<< endl
;
4727 // Check that SAT results generate a model correctly.
4728 if(options::checkModels()) {
4729 // TODO (#1693) check model when unknown result?
4730 if (r
.asSatisfiabilityResult().isSat() == Result::SAT
)
4735 // Check that UNSAT results generate a proof correctly.
4736 if(options::checkProofs()) {
4737 if(r
.asSatisfiabilityResult().isSat() == Result::UNSAT
) {
4738 TimerStat::CodeTimer
checkProofTimer(d_stats
->d_checkProofTime
);
4742 // Check that UNSAT results generate an unsat core correctly.
4743 if(options::checkUnsatCores()) {
4744 if(r
.asSatisfiabilityResult().isSat() == Result::UNSAT
) {
4745 TimerStat::CodeTimer
checkUnsatCoreTimer(d_stats
->d_checkUnsatCoreTime
);
4749 // Check that synthesis solutions satisfy the conjecture
4750 if (options::checkSynthSol()
4751 && r
.asSatisfiabilityResult().isSat() == Result::UNSAT
)
4753 checkSynthSolution();
4757 } catch (UnsafeInterruptException
& e
) {
4758 AlwaysAssert(d_private
->getResourceManager()->out());
4759 Result::UnknownExplanation why
= d_private
->getResourceManager()->outOfResources() ?
4760 Result::RESOURCEOUT
: Result::TIMEOUT
;
4761 return Result(Result::SAT_UNKNOWN
, why
, d_filename
);
4765 vector
<Expr
> SmtEngine::getUnsatAssumptions(void)
4767 Trace("smt") << "SMT getUnsatAssumptions()" << endl
;
4768 SmtScope
smts(this);
4769 if (!options::unsatAssumptions())
4771 throw ModalException(
4772 "Cannot get unsat assumptions when produce-unsat-assumptions option "
4775 if (d_status
.isNull()
4776 || d_status
.asSatisfiabilityResult() != Result::UNSAT
4777 || d_problemExtended
)
4779 throw RecoverableModalException(
4780 "Cannot get unsat assumptions unless immediately preceded by "
4781 "UNSAT/VALID response.");
4783 finalOptionsAreSet();
4784 if (Dump
.isOn("benchmark"))
4786 Dump("benchmark") << GetUnsatCoreCommand();
4788 UnsatCore core
= getUnsatCore();
4790 for (const Expr
& e
: d_assumptions
)
4792 if (find(core
.begin(), core
.end(), e
) != core
.end()) { res
.push_back(e
); }
4797 Result
SmtEngine::checkSynth(const Expr
& e
)
4799 SmtScope
smts(this);
4800 Trace("smt") << "Check synth: " << e
<< std::endl
;
4801 Trace("smt-synth") << "Check synthesis conjecture: " << e
<< std::endl
;
4803 if (options::sygusQePreproc())
4805 // the following does quantifier elimination as a preprocess step
4806 // for "non-ground single invocation synthesis conjectures":
4807 // exists f. forall xy. P[ f(x), x, y ]
4808 // We run quantifier elimination:
4809 // exists y. P[ z, x, y ] ----> Q[ z, x ]
4810 // Where we replace the original conjecture with:
4811 // exists f. forall x. Q[ f(x), x ]
4812 // For more details, see Example 6 of Reynolds et al. SYNT 2017.
4813 Node conj
= Node::fromExpr(e
);
4814 if (conj
.getKind() == kind::FORALL
&& conj
[1].getKind() == kind::EXISTS
)
4816 Node conj_se
= Node::fromExpr(expandDefinitions(conj
[1][1].toExpr()));
4818 Trace("smt-synth") << "Compute single invocation for " << conj_se
<< "..."
4820 quantifiers::SingleInvocationPartition sip
;
4821 std::vector
<Node
> funcs
;
4822 funcs
.insert(funcs
.end(), conj
[0].begin(), conj
[0].end());
4823 sip
.init(funcs
, conj_se
.negate());
4824 Trace("smt-synth") << "...finished, got:" << std::endl
;
4825 sip
.debugPrint("smt-synth");
4827 if (!sip
.isPurelySingleInvocation() && sip
.isNonGroundSingleInvocation())
4829 // create new smt engine to do quantifier elimination
4830 SmtEngine
smt_qe(d_exprManager
);
4831 smt_qe
.setLogic(getLogicInfo());
4832 Trace("smt-synth") << "Property is non-ground single invocation, run "
4833 "QE to obtain single invocation."
4835 NodeManager
* nm
= NodeManager::currentNM();
4836 // partition variables
4837 std::vector
<Node
> all_vars
;
4838 sip
.getAllVariables(all_vars
);
4839 std::vector
<Node
> si_vars
;
4840 sip
.getSingleInvocationVariables(si_vars
);
4841 std::vector
<Node
> qe_vars
;
4842 std::vector
<Node
> nqe_vars
;
4843 for (unsigned i
= 0, size
= all_vars
.size(); i
< size
; i
++)
4845 Node v
= all_vars
[i
];
4846 if (std::find(si_vars
.begin(), si_vars
.end(), v
) == si_vars
.end())
4848 qe_vars
.push_back(v
);
4852 nqe_vars
.push_back(v
);
4855 std::vector
<Node
> orig
;
4856 std::vector
<Node
> subs
;
4857 // skolemize non-qe variables
4858 for (unsigned i
= 0; i
< nqe_vars
.size(); i
++)
4860 Node k
= nm
->mkSkolem("k",
4861 nqe_vars
[i
].getType(),
4862 "qe for non-ground single invocation");
4863 orig
.push_back(nqe_vars
[i
]);
4865 Trace("smt-synth") << " subs : " << nqe_vars
[i
] << " -> " << k
4868 std::vector
<Node
> funcs
;
4869 sip
.getFunctions(funcs
);
4870 for (unsigned i
= 0, size
= funcs
.size(); i
< size
; i
++)
4873 Node fi
= sip
.getFunctionInvocationFor(f
);
4874 Node fv
= sip
.getFirstOrderVariableForFunction(f
);
4875 Assert(!fi
.isNull());
4880 "qe for function in non-ground single invocation");
4882 Trace("smt-synth") << " subs : " << fi
<< " -> " << k
<< std::endl
;
4884 Node conj_se_ngsi
= sip
.getFullSpecification();
4885 Trace("smt-synth") << "Full specification is " << conj_se_ngsi
4887 Node conj_se_ngsi_subs
= conj_se_ngsi
.substitute(
4888 orig
.begin(), orig
.end(), subs
.begin(), subs
.end());
4889 Assert(!qe_vars
.empty());
4891 nm
->mkNode(kind::EXISTS
,
4892 nm
->mkNode(kind::BOUND_VAR_LIST
, qe_vars
),
4893 conj_se_ngsi_subs
.negate());
4895 Trace("smt-synth") << "Run quantifier elimination on "
4896 << conj_se_ngsi_subs
<< std::endl
;
4897 Expr qe_res
= smt_qe
.doQuantifierElimination(
4898 conj_se_ngsi_subs
.toExpr(), true, false);
4899 Trace("smt-synth") << "Result : " << qe_res
<< std::endl
;
4901 // create single invocation conjecture
4902 Node qe_res_n
= Node::fromExpr(qe_res
);
4903 qe_res_n
= qe_res_n
.substitute(
4904 subs
.begin(), subs
.end(), orig
.begin(), orig
.end());
4905 if (!nqe_vars
.empty())
4907 qe_res_n
= nm
->mkNode(kind::EXISTS
,
4908 nm
->mkNode(kind::BOUND_VAR_LIST
, nqe_vars
),
4911 Assert(conj
.getNumChildren() == 3);
4912 qe_res_n
= nm
->mkNode(kind::FORALL
, conj
[0], qe_res_n
, conj
[2]);
4913 Trace("smt-synth") << "Converted conjecture after QE : " << qe_res_n
4915 e_check
= qe_res_n
.toExpr();
4920 return checkSatisfiability( e_check
, true, false );
4923 Result
SmtEngine::assertFormula(const Expr
& ex
, bool inUnsatCore
)
4925 Assert(ex
.getExprManager() == d_exprManager
);
4926 SmtScope
smts(this);
4927 finalOptionsAreSet();
4930 Trace("smt") << "SmtEngine::assertFormula(" << ex
<< ")" << endl
;
4932 if (Dump
.isOn("raw-benchmark")) {
4933 Dump("raw-benchmark") << AssertCommand(ex
);
4936 // Substitute out any abstract values in ex
4937 Expr e
= d_private
->substituteAbstractValues(Node::fromExpr(ex
)).toExpr();
4940 if(d_assertionList
!= NULL
) {
4941 d_assertionList
->push_back(e
);
4943 d_private
->addFormula(e
.getNode(), inUnsatCore
);
4944 return quickCheck().asValidityResult();
4945 }/* SmtEngine::assertFormula() */
4947 Node
SmtEngine::postprocess(TNode node
, TypeNode expectedType
) const {
4951 Expr
SmtEngine::simplify(const Expr
& ex
)
4953 Assert(ex
.getExprManager() == d_exprManager
);
4954 SmtScope
smts(this);
4955 finalOptionsAreSet();
4957 Trace("smt") << "SMT simplify(" << ex
<< ")" << endl
;
4959 if(Dump
.isOn("benchmark")) {
4960 Dump("benchmark") << SimplifyCommand(ex
);
4963 Expr e
= d_private
->substituteAbstractValues(Node::fromExpr(ex
)).toExpr();
4964 if( options::typeChecking() ) {
4965 e
.getType(true); // ensure expr is type-checked at this point
4968 // Make sure all preprocessing is done
4969 d_private
->processAssertions();
4970 Node n
= d_private
->simplify(Node::fromExpr(e
));
4971 n
= postprocess(n
, TypeNode::fromType(e
.getType()));
4975 Expr
SmtEngine::expandDefinitions(const Expr
& ex
)
4977 d_private
->spendResource(options::preprocessStep());
4979 Assert(ex
.getExprManager() == d_exprManager
);
4980 SmtScope
smts(this);
4981 finalOptionsAreSet();
4983 Trace("smt") << "SMT expandDefinitions(" << ex
<< ")" << endl
;
4985 // Substitute out any abstract values in ex.
4986 Expr e
= d_private
->substituteAbstractValues(Node::fromExpr(ex
)).toExpr();
4987 if(options::typeChecking()) {
4988 // Ensure expr is type-checked at this point.
4991 if(Dump
.isOn("benchmark")) {
4992 Dump("benchmark") << ExpandDefinitionsCommand(e
);
4994 unordered_map
<Node
, Node
, NodeHashFunction
> cache
;
4995 Node n
= d_private
->expandDefinitions(Node::fromExpr(e
), cache
, /* expandOnly = */ true);
4996 n
= postprocess(n
, TypeNode::fromType(e
.getType()));
5001 // TODO(#1108): Simplify the error reporting of this method.
5002 Expr
SmtEngine::getValue(const Expr
& ex
) const
5004 Assert(ex
.getExprManager() == d_exprManager
);
5005 SmtScope
smts(this);
5007 Trace("smt") << "SMT getValue(" << ex
<< ")" << endl
;
5008 if(Dump
.isOn("benchmark")) {
5009 Dump("benchmark") << GetValueCommand(ex
);
5012 if(!options::produceModels()) {
5014 "Cannot get value when produce-models options is off.";
5015 throw ModalException(msg
);
5017 if(d_status
.isNull() ||
5018 d_status
.asSatisfiabilityResult() == Result::UNSAT
||
5019 d_problemExtended
) {
5021 "Cannot get value unless immediately preceded by SAT/INVALID or UNKNOWN response.";
5022 throw RecoverableModalException(msg
);
5025 // Substitute out any abstract values in ex.
5026 Expr e
= d_private
->substituteAbstractValues(Node::fromExpr(ex
)).toExpr();
5028 // Ensure expr is type-checked at this point.
5029 e
.getType(options::typeChecking());
5031 // do not need to apply preprocessing substitutions (should be recorded
5032 // in model already)
5034 Node n
= Node::fromExpr(e
);
5035 Trace("smt") << "--- getting value of " << n
<< endl
;
5036 TypeNode expectedType
= n
.getType();
5038 // Expand, then normalize
5039 unordered_map
<Node
, Node
, NodeHashFunction
> cache
;
5040 n
= d_private
->expandDefinitions(n
, cache
);
5041 // There are two ways model values for terms are computed (for historical
5042 // reasons). One way is that used in check-model; the other is that
5043 // used by the Model classes. It's not clear to me exactly how these
5044 // two are different, but they need to be unified. This ugly hack here
5045 // is to fix bug 554 until we can revamp boolean-terms and models [MGD]
5048 if(!n
.getType().isFunction()) {
5049 n
= Rewriter::rewrite(n
);
5052 Trace("smt") << "--- getting value of " << n
<< endl
;
5053 TheoryModel
* m
= d_theoryEngine
->getModel();
5056 resultNode
= m
->getValue(n
);
5058 Trace("smt") << "--- got value " << n
<< " = " << resultNode
<< endl
;
5059 resultNode
= postprocess(resultNode
, expectedType
);
5060 Trace("smt") << "--- model-post returned " << resultNode
<< endl
;
5061 Trace("smt") << "--- model-post returned " << resultNode
.getType() << endl
;
5062 Trace("smt") << "--- model-post expected " << expectedType
<< endl
;
5064 // type-check the result we got
5065 Assert(resultNode
.isNull() || resultNode
.getType().isSubtypeOf(expectedType
),
5066 "Run with -t smt for details.");
5068 // ensure it's a constant
5069 Assert(resultNode
.getKind() == kind::LAMBDA
|| resultNode
.isConst());
5071 if(options::abstractValues() && resultNode
.getType().isArray()) {
5072 resultNode
= d_private
->mkAbstractValue(resultNode
);
5073 Trace("smt") << "--- abstract value >> " << resultNode
<< endl
;
5076 return resultNode
.toExpr();
5079 bool SmtEngine::addToAssignment(const Expr
& ex
) {
5080 SmtScope
smts(this);
5081 finalOptionsAreSet();
5083 // Substitute out any abstract values in ex
5084 Expr e
= d_private
->substituteAbstractValues(Node::fromExpr(ex
)).toExpr();
5085 Type type
= e
.getType(options::typeChecking());
5087 PrettyCheckArgument(
5088 type
.isBoolean(), e
,
5089 "expected Boolean-typed variable or function application "
5090 "in addToAssignment()" );
5091 Node n
= e
.getNode();
5092 // must be an APPLY of a zero-ary defined function, or a variable
5093 PrettyCheckArgument(
5094 ( ( n
.getKind() == kind::APPLY
&&
5095 ( d_definedFunctions
->find(n
.getOperator()) !=
5096 d_definedFunctions
->end() ) &&
5097 n
.getNumChildren() == 0 ) ||
5099 "expected variable or defined-function application "
5100 "in addToAssignment(),\ngot %s", e
.toString().c_str() );
5101 if(!options::produceAssignments()) {
5104 if(d_assignments
== NULL
) {
5105 d_assignments
= new(true) AssignmentSet(d_context
);
5107 d_assignments
->insert(n
);
5112 // TODO(#1108): Simplify the error reporting of this method.
5113 vector
<pair
<Expr
, Expr
>> SmtEngine::getAssignment()
5115 Trace("smt") << "SMT getAssignment()" << endl
;
5116 SmtScope
smts(this);
5117 finalOptionsAreSet();
5118 if(Dump
.isOn("benchmark")) {
5119 Dump("benchmark") << GetAssignmentCommand();
5121 if(!options::produceAssignments()) {
5123 "Cannot get the current assignment when "
5124 "produce-assignments option is off.";
5125 throw ModalException(msg
);
5127 if(d_status
.isNull() ||
5128 d_status
.asSatisfiabilityResult() == Result::UNSAT
||
5129 d_problemExtended
) {
5131 "Cannot get the current assignment unless immediately "
5132 "preceded by SAT/INVALID or UNKNOWN response.";
5133 throw RecoverableModalException(msg
);
5136 vector
<pair
<Expr
,Expr
>> res
;
5137 if (d_assignments
!= nullptr)
5139 TypeNode boolType
= d_nodeManager
->booleanType();
5140 TheoryModel
* m
= d_theoryEngine
->getModel();
5141 for (AssignmentSet::key_iterator i
= d_assignments
->key_begin(),
5142 iend
= d_assignments
->key_end();
5147 Assert(as
.getType() == boolType
);
5149 Trace("smt") << "--- getting value of " << as
<< endl
;
5151 // Expand, then normalize
5152 unordered_map
<Node
, Node
, NodeHashFunction
> cache
;
5153 Node n
= d_private
->expandDefinitions(as
, cache
);
5154 n
= Rewriter::rewrite(n
);
5156 Trace("smt") << "--- getting value of " << n
<< endl
;
5160 resultNode
= m
->getValue(n
);
5163 // type-check the result we got
5164 Assert(resultNode
.isNull() || resultNode
.getType() == boolType
);
5166 // ensure it's a constant
5167 Assert(resultNode
.isConst());
5169 Assert(as
.getKind() == kind::APPLY
|| as
.isVar());
5170 Assert(as
.getKind() != kind::APPLY
|| as
.getNumChildren() == 0);
5171 res
.emplace_back(as
.toExpr(), resultNode
.toExpr());
5177 void SmtEngine::addToModelCommandAndDump(const Command
& c
, uint32_t flags
, bool userVisible
, const char* dumpTag
) {
5178 Trace("smt") << "SMT addToModelCommandAndDump(" << c
<< ")" << endl
;
5179 SmtScope
smts(this);
5180 // If we aren't yet fully inited, the user might still turn on
5181 // produce-models. So let's keep any commands around just in
5182 // case. This is useful in two cases: (1) SMT-LIBv1 auto-declares
5183 // sort "U" in QF_UF before setLogic() is run and we still want to
5184 // support finding card(U) with --finite-model-find, and (2) to
5185 // decouple SmtEngine and ExprManager if the user does a few
5186 // ExprManager::mkSort() before SmtEngine::setOption("produce-models")
5187 // and expects to find their cardinalities in the model.
5188 if(/* userVisible && */
5189 (!d_fullyInited
|| options::produceModels()) &&
5190 (flags
& ExprManager::VAR_FLAG_DEFINED
) == 0) {
5192 if(flags
& ExprManager::VAR_FLAG_GLOBAL
) {
5193 d_modelGlobalCommands
.push_back(c
.clone());
5195 d_modelCommands
->push_back(c
.clone());
5198 if(Dump
.isOn(dumpTag
)) {
5202 d_dumpCommands
.push_back(c
.clone());
5207 // TODO(#1108): Simplify the error reporting of this method.
5208 Model
* SmtEngine::getModel() {
5209 Trace("smt") << "SMT getModel()" << endl
;
5210 SmtScope
smts(this);
5212 finalOptionsAreSet();
5214 if(Dump
.isOn("benchmark")) {
5215 Dump("benchmark") << GetModelCommand();
5218 if(d_status
.isNull() ||
5219 d_status
.asSatisfiabilityResult() == Result::UNSAT
||
5220 d_problemExtended
) {
5222 "Cannot get the current model unless immediately "
5223 "preceded by SAT/INVALID or UNKNOWN response.";
5224 throw RecoverableModalException(msg
);
5226 if(!options::produceModels()) {
5228 "Cannot get model when produce-models options is off.";
5229 throw ModalException(msg
);
5231 TheoryModel
* m
= d_theoryEngine
->getModel();
5232 m
->d_inputName
= d_filename
;
5236 void SmtEngine::checkUnsatCore() {
5237 Assert(options::unsatCores(), "cannot check unsat core if unsat cores are turned off");
5239 Notice() << "SmtEngine::checkUnsatCore(): generating unsat core" << endl
;
5240 UnsatCore core
= getUnsatCore();
5242 SmtEngine
coreChecker(d_exprManager
);
5243 coreChecker
.setLogic(getLogicInfo());
5246 std::vector
<Command
*>::const_iterator itg
= d_defineCommands
.begin();
5247 for (; itg
!= d_defineCommands
.end(); ++itg
) {
5248 (*itg
)->invoke(&coreChecker
);
5252 Notice() << "SmtEngine::checkUnsatCore(): pushing core assertions (size == " << core
.size() << ")" << endl
;
5253 for(UnsatCore::iterator i
= core
.begin(); i
!= core
.end(); ++i
) {
5254 Notice() << "SmtEngine::checkUnsatCore(): pushing core member " << *i
<< endl
;
5255 coreChecker
.assertFormula(*i
);
5257 const bool checkUnsatCores
= options::checkUnsatCores();
5260 options::checkUnsatCores
.set(false);
5261 options::checkProofs
.set(false);
5262 r
= coreChecker
.checkSat();
5264 options::checkUnsatCores
.set(checkUnsatCores
);
5267 Notice() << "SmtEngine::checkUnsatCore(): result is " << r
<< endl
;
5268 if(r
.asSatisfiabilityResult().isUnknown()) {
5269 InternalError("SmtEngine::checkUnsatCore(): could not check core result unknown.");
5272 if(r
.asSatisfiabilityResult().isSat()) {
5273 InternalError("SmtEngine::checkUnsatCore(): produced core was satisfiable.");
5277 void SmtEngine::checkModel(bool hardFailure
) {
5278 // --check-model implies --produce-assertions, which enables the
5279 // assertion list, so we should be ok.
5280 Assert(d_assertionList
!= NULL
, "don't have an assertion list to check in SmtEngine::checkModel()");
5282 TimerStat::CodeTimer
checkModelTimer(d_stats
->d_checkModelTime
);
5284 // Throughout, we use Notice() to give diagnostic output.
5286 // If this function is running, the user gave --check-model (or equivalent),
5287 // and if Notice() is on, the user gave --verbose (or equivalent).
5289 Notice() << "SmtEngine::checkModel(): generating model" << endl
;
5290 TheoryModel
* m
= d_theoryEngine
->getModel();
5292 // Check individual theory assertions
5293 d_theoryEngine
->checkTheoryAssertionsWithModel(hardFailure
);
5298 // We have a "fake context" for the substitution map (we don't need it
5299 // to be context-dependent)
5300 context::Context fakeContext
;
5301 SubstitutionMap
substitutions(&fakeContext
, /* substituteUnderQuantifiers = */ false);
5303 for(size_t k
= 0; k
< m
->getNumCommands(); ++k
) {
5304 const DeclareFunctionCommand
* c
= dynamic_cast<const DeclareFunctionCommand
*>(m
->getCommand(k
));
5305 Notice() << "SmtEngine::checkModel(): model command " << k
<< " : " << m
->getCommand(k
) << endl
;
5307 // we don't care about DECLARE-DATATYPES, DECLARE-SORT, ...
5308 Notice() << "SmtEngine::checkModel(): skipping..." << endl
;
5310 // We have a DECLARE-FUN:
5312 // We'll first do some checks, then add to our substitution map
5313 // the mapping: function symbol |-> value
5315 Expr func
= c
->getFunction();
5316 Node val
= m
->getValue(func
);
5318 Notice() << "SmtEngine::checkModel(): adding substitution: " << func
<< " |-> " << val
<< endl
;
5320 // (1) if the value is a lambda, ensure the lambda doesn't contain the
5321 // function symbol (since then the definition is recursive)
5322 if (val
.getKind() == kind::LAMBDA
) {
5323 // first apply the model substitutions we have so far
5324 Debug("boolean-terms") << "applying subses to " << val
[1] << endl
;
5325 Node n
= substitutions
.apply(val
[1]);
5326 Debug("boolean-terms") << "++ got " << n
<< endl
;
5327 // now check if n contains func by doing a substitution
5328 // [func->func2] and checking equality of the Nodes.
5329 // (this just a way to check if func is in n.)
5330 SubstitutionMap
subs(&fakeContext
);
5331 Node func2
= NodeManager::currentNM()->mkSkolem("", TypeNode::fromType(func
.getType()), "", NodeManager::SKOLEM_NO_NOTIFY
);
5332 subs
.addSubstitution(func
, func2
);
5333 if(subs
.apply(n
) != n
) {
5334 Notice() << "SmtEngine::checkModel(): *** PROBLEM: MODEL VALUE DEFINED IN TERMS OF ITSELF ***" << endl
;
5336 ss
<< "SmtEngine::checkModel(): ERRORS SATISFYING ASSERTIONS WITH MODEL:" << endl
5337 << "considering model value for " << func
<< endl
5338 << "body of lambda is: " << val
<< endl
;
5340 ss
<< "body substitutes to: " << n
<< endl
;
5342 ss
<< "so " << func
<< " is defined in terms of itself." << endl
5343 << "Run with `--check-models -v' for additional diagnostics.";
5344 InternalError(ss
.str());
5348 // (2) check that the value is actually a value
5349 else if (!val
.isConst()) {
5350 Notice() << "SmtEngine::checkModel(): *** PROBLEM: MODEL VALUE NOT A CONSTANT ***" << endl
;
5352 ss
<< "SmtEngine::checkModel(): ERRORS SATISFYING ASSERTIONS WITH MODEL:" << endl
5353 << "model value for " << func
<< endl
5354 << " is " << val
<< endl
5355 << "and that is not a constant (.isConst() == false)." << endl
5356 << "Run with `--check-models -v' for additional diagnostics.";
5357 InternalError(ss
.str());
5360 // (3) check that it's the correct (sub)type
5361 // This was intended to be a more general check, but for now we can't do that because
5362 // e.g. "1" is an INT, which isn't a subrange type [1..10] (etc.).
5363 else if(func
.getType().isInteger() && !val
.getType().isInteger()) {
5364 Notice() << "SmtEngine::checkModel(): *** PROBLEM: MODEL VALUE NOT CORRECT TYPE ***" << endl
;
5366 ss
<< "SmtEngine::checkModel(): ERRORS SATISFYING ASSERTIONS WITH MODEL:" << endl
5367 << "model value for " << func
<< endl
5368 << " is " << val
<< endl
5369 << "value type is " << val
.getType() << endl
5370 << "should be of type " << func
.getType() << endl
5371 << "Run with `--check-models -v' for additional diagnostics.";
5372 InternalError(ss
.str());
5375 // (4) checks complete, add the substitution
5376 Debug("boolean-terms") << "cm: adding subs " << func
<< " :=> " << val
<< endl
;
5377 substitutions
.addSubstitution(func
, val
);
5381 // Now go through all our user assertions checking if they're satisfied.
5382 for(AssertionList::const_iterator i
= d_assertionList
->begin(); i
!= d_assertionList
->end(); ++i
) {
5383 Notice() << "SmtEngine::checkModel(): checking assertion " << *i
<< endl
;
5384 Node n
= Node::fromExpr(*i
);
5386 // Apply any define-funs from the problem.
5388 unordered_map
<Node
, Node
, NodeHashFunction
> cache
;
5389 n
= d_private
->expandDefinitions(n
, cache
);
5391 Notice() << "SmtEngine::checkModel(): -- expands to " << n
<< endl
;
5393 // Apply our model value substitutions.
5394 Debug("boolean-terms") << "applying subses to " << n
<< endl
;
5395 n
= substitutions
.apply(n
);
5396 Debug("boolean-terms") << "++ got " << n
<< endl
;
5397 Notice() << "SmtEngine::checkModel(): -- substitutes to " << n
<< endl
;
5399 if( n
.getKind() != kind::REWRITE_RULE
){
5400 // In case it's a quantifier (or contains one), look up its value before
5401 // simplifying, or the quantifier might be irreparably altered.
5403 Notice() << "SmtEngine::checkModel(): -- get value : " << n
<< std::endl
;
5405 // Note this "skip" is done here, rather than above. This is
5406 // because (1) the quantifier could in principle simplify to false,
5407 // which should be reported, and (2) checking for the quantifier
5408 // above, before simplification, doesn't catch buried quantifiers
5409 // anyway (those not at the top-level).
5410 Notice() << "SmtEngine::checkModel(): -- skipping rewrite-rules assertion"
5415 // Simplify the result.
5416 n
= d_private
->simplify(n
);
5417 Notice() << "SmtEngine::checkModel(): -- simplifies to " << n
<< endl
;
5419 // Replace the already-known ITEs (this is important for ground ITEs under quantifiers).
5420 n
= d_private
->d_iteRemover
.replace(n
);
5421 Notice() << "SmtEngine::checkModel(): -- ite replacement gives " << n
<< endl
;
5423 // Apply our model value substitutions (again), as things may have been simplified.
5424 Debug("boolean-terms") << "applying subses to " << n
<< endl
;
5425 n
= substitutions
.apply(n
);
5426 Debug("boolean-terms") << "++ got " << n
<< endl
;
5427 Notice() << "SmtEngine::checkModel(): -- re-substitutes to " << n
<< endl
;
5429 // As a last-ditch effort, ask model to simplify it.
5430 // Presently, this is only an issue for quantifiers, which can have a value
5431 // but don't show up in our substitution map above.
5433 Notice() << "SmtEngine::checkModel(): -- model-substitutes to " << n
<< endl
;
5435 if( d_logic
.isQuantified() ){
5436 // AJR: since quantified formulas are not checkable, we assign them to true/false based on the satisfying assignment.
5437 // however, quantified formulas can be modified during preprocess, so they may not correspond to those in the satisfying assignment.
5438 // hence we use a relaxed version of check model here.
5439 // this is necessary until preprocessing passes explicitly record how they rewrite quantified formulas
5440 if( hardFailure
&& !n
.isConst() && n
.getKind() != kind::LAMBDA
){
5441 Notice() << "SmtEngine::checkModel(): -- relax check model wrt quantified formulas..." << endl
;
5442 AlwaysAssert( quantifiers::QuantifiersRewriter::containsQuantifiers( n
) );
5443 Warning() << "Warning : SmtEngine::checkModel(): cannot check simplified assertion : " << n
<< endl
;
5447 AlwaysAssert(!hardFailure
|| n
.isConst() || n
.getKind() == kind::LAMBDA
);
5449 // The result should be == true.
5450 if(n
!= NodeManager::currentNM()->mkConst(true)) {
5451 Notice() << "SmtEngine::checkModel(): *** PROBLEM: EXPECTED `TRUE' ***"
5454 ss
<< "SmtEngine::checkModel(): "
5455 << "ERRORS SATISFYING ASSERTIONS WITH MODEL:" << endl
5456 << "assertion: " << *i
<< endl
5457 << "simplifies to: " << n
<< endl
5458 << "expected `true'." << endl
5459 << "Run with `--check-models -v' for additional diagnostics.";
5461 InternalError(ss
.str());
5463 Warning() << ss
.str() << endl
;
5467 Notice() << "SmtEngine::checkModel(): all assertions checked out OK !" << endl
;
5470 void SmtEngine::checkSynthSolution()
5472 NodeManager
* nm
= NodeManager::currentNM();
5473 Notice() << "SmtEngine::checkSynthSolution(): checking synthesis solution" << endl
;
5474 map
<Node
, Node
> sol_map
;
5475 /* Get solutions and build auxiliary vectors for substituting */
5476 d_theoryEngine
->getSynthSolutions(sol_map
);
5477 Trace("check-synth-sol") << "Got solution map:\n";
5478 std::vector
<Node
> function_vars
, function_sols
;
5479 for (const auto& pair
: sol_map
)
5481 Trace("check-synth-sol") << pair
.first
<< " --> " << pair
.second
<< "\n";
5482 function_vars
.push_back(pair
.first
);
5483 function_sols
.push_back(pair
.second
);
5485 Trace("check-synth-sol") << "Starting new SMT Engine\n";
5486 /* Start new SMT engine to check solutions */
5487 SmtEngine
solChecker(d_exprManager
);
5488 solChecker
.setLogic(getLogicInfo());
5489 setOption("check-synth-sol", SExpr("false"));
5491 Trace("check-synth-sol") << "Retrieving assertions\n";
5492 // Build conjecture from original assertions
5493 if (d_assertionList
== NULL
)
5495 Trace("check-synth-sol") << "No assertions to check\n";
5498 for (AssertionList::const_iterator i
= d_assertionList
->begin();
5499 i
!= d_assertionList
->end();
5502 Notice() << "SmtEngine::checkSynthSolution(): checking assertion " << *i
<< endl
;
5503 Trace("check-synth-sol") << "Retrieving assertion " << *i
<< "\n";
5504 Node conj
= Node::fromExpr(*i
);
5505 // Apply any define-funs from the problem.
5507 unordered_map
<Node
, Node
, NodeHashFunction
> cache
;
5508 conj
= d_private
->expandDefinitions(conj
, cache
);
5510 Notice() << "SmtEngine::checkSynthSolution(): -- expands to " << conj
<< endl
;
5511 Trace("check-synth-sol") << "Expanded assertion " << conj
<< "\n";
5513 // Apply solution map to conjecture body
5515 /* Whether property is quantifier free */
5516 if (conj
[1].getKind() != kind::EXISTS
)
5518 conjBody
= conj
[1].substitute(function_vars
.begin(),
5519 function_vars
.end(),
5520 function_sols
.begin(),
5521 function_sols
.end());
5525 conjBody
= conj
[1][1].substitute(function_vars
.begin(),
5526 function_vars
.end(),
5527 function_sols
.begin(),
5528 function_sols
.end());
5530 /* Skolemize property */
5531 std::vector
<Node
> vars
, skos
;
5532 for (unsigned j
= 0, size
= conj
[1][0].getNumChildren(); j
< size
; ++j
)
5534 vars
.push_back(conj
[1][0][j
]);
5535 std::stringstream ss
;
5537 skos
.push_back(nm
->mkSkolem(ss
.str(), conj
[1][0][j
].getType()));
5538 Trace("check-synth-sol") << "\tSkolemizing " << conj
[1][0][j
] << " to "
5539 << skos
.back() << "\n";
5541 conjBody
= conjBody
.substitute(
5542 vars
.begin(), vars
.end(), skos
.begin(), skos
.end());
5544 Notice() << "SmtEngine::checkSynthSolution(): -- body substitutes to "
5545 << conjBody
<< endl
;
5546 Trace("check-synth-sol") << "Substituted body of assertion to " << conjBody
5548 solChecker
.assertFormula(conjBody
.toExpr());
5549 Result r
= solChecker
.checkSat();
5550 Notice() << "SmtEngine::checkSynthSolution(): result is " << r
<< endl
;
5551 Trace("check-synth-sol") << "Satsifiability check: " << r
<< "\n";
5552 if (r
.asSatisfiabilityResult().isUnknown())
5555 "SmtEngine::checkSynthSolution(): could not check solution, result "
5558 else if (r
.asSatisfiabilityResult().isSat())
5561 "SmtEngine::checkSynhtSol(): produced solution allows satisfiable "
5562 "negated conjecture.");
5564 solChecker
.resetAssertions();
5568 // TODO(#1108): Simplify the error reporting of this method.
5569 UnsatCore
SmtEngine::getUnsatCore() {
5570 Trace("smt") << "SMT getUnsatCore()" << endl
;
5571 SmtScope
smts(this);
5572 finalOptionsAreSet();
5573 if(Dump
.isOn("benchmark")) {
5574 Dump("benchmark") << GetUnsatCoreCommand();
5577 if(!options::unsatCores()) {
5578 throw ModalException("Cannot get an unsat core when produce-unsat-cores option is off.");
5580 if(d_status
.isNull() ||
5581 d_status
.asSatisfiabilityResult() != Result::UNSAT
||
5582 d_problemExtended
) {
5583 throw RecoverableModalException(
5584 "Cannot get an unsat core unless immediately preceded by UNSAT/VALID "
5588 d_proofManager
->traceUnsatCore();// just to trigger core creation
5589 return UnsatCore(this, d_proofManager
->extractUnsatCore());
5590 #else /* IS_PROOFS_BUILD */
5591 throw ModalException("This build of CVC4 doesn't have proof support (required for unsat cores).");
5592 #endif /* IS_PROOFS_BUILD */
5595 // TODO(#1108): Simplify the error reporting of this method.
5596 const Proof
& SmtEngine::getProof()
5598 Trace("smt") << "SMT getProof()" << endl
;
5599 SmtScope
smts(this);
5600 finalOptionsAreSet();
5601 if(Dump
.isOn("benchmark")) {
5602 Dump("benchmark") << GetProofCommand();
5605 if(!options::proof()) {
5606 throw ModalException("Cannot get a proof when produce-proofs option is off.");
5608 if(d_status
.isNull() ||
5609 d_status
.asSatisfiabilityResult() != Result::UNSAT
||
5610 d_problemExtended
) {
5611 throw RecoverableModalException(
5612 "Cannot get a proof unless immediately preceded by UNSAT/VALID "
5616 return ProofManager::getProof(this);
5617 #else /* IS_PROOFS_BUILD */
5618 throw ModalException("This build of CVC4 doesn't have proof support.");
5619 #endif /* IS_PROOFS_BUILD */
5622 void SmtEngine::printInstantiations( std::ostream
& out
) {
5623 SmtScope
smts(this);
5624 if( options::instFormatMode()==INST_FORMAT_MODE_SZS
){
5625 out
<< "% SZS output start Proof for " << d_filename
.c_str() << std::endl
;
5627 if( d_theoryEngine
){
5628 d_theoryEngine
->printInstantiations( out
);
5632 if( options::instFormatMode()==INST_FORMAT_MODE_SZS
){
5633 out
<< "% SZS output end Proof for " << d_filename
.c_str() << std::endl
;
5637 void SmtEngine::printSynthSolution( std::ostream
& out
) {
5638 SmtScope
smts(this);
5639 if( d_theoryEngine
){
5640 d_theoryEngine
->printSynthSolution( out
);
5646 Expr
SmtEngine::doQuantifierElimination(const Expr
& e
, bool doFull
, bool strict
)
5648 SmtScope
smts(this);
5649 if(!d_logic
.isPure(THEORY_ARITH
) && strict
){
5650 Warning() << "Unexpected logic for quantifier elimination " << d_logic
<< endl
;
5652 Trace("smt-qe") << "Do quantifier elimination " << e
<< std::endl
;
5653 Node n_e
= Node::fromExpr( e
);
5654 if (n_e
.getKind() != kind::EXISTS
&& n_e
.getKind() != kind::FORALL
)
5656 throw ModalException(
5657 "Expecting a quantified formula as argument to get-qe.");
5659 //tag the quantified formula with the quant-elim attribute
5660 TypeNode t
= NodeManager::currentNM()->booleanType();
5661 Node n_attr
= NodeManager::currentNM()->mkSkolem("qe", t
, "Auxiliary variable for qe attr.");
5662 std::vector
< Node
> node_values
;
5663 d_theoryEngine
->setUserAttribute( doFull
? "quant-elim" : "quant-elim-partial", n_attr
, node_values
, "");
5664 n_attr
= NodeManager::currentNM()->mkNode(kind::INST_ATTRIBUTE
, n_attr
);
5665 n_attr
= NodeManager::currentNM()->mkNode(kind::INST_PATTERN_LIST
, n_attr
);
5666 std::vector
< Node
> e_children
;
5667 e_children
.push_back( n_e
[0] );
5668 e_children
.push_back(n_e
.getKind() == kind::EXISTS
? n_e
[1]
5670 e_children
.push_back( n_attr
);
5671 Node nn_e
= NodeManager::currentNM()->mkNode( kind::EXISTS
, e_children
);
5672 Trace("smt-qe-debug") << "Query for quantifier elimination : " << nn_e
<< std::endl
;
5673 Assert( nn_e
.getNumChildren()==3 );
5674 Result r
= checkSatisfiability(nn_e
.toExpr(), true, true);
5675 Trace("smt-qe") << "Query returned " << r
<< std::endl
;
5676 if(r
.asSatisfiabilityResult().isSat() != Result::UNSAT
) {
5677 if( r
.asSatisfiabilityResult().isSat() != Result::SAT
&& doFull
){
5679 ss
<< "While performing quantifier elimination, unexpected result : " << r
<< " for query.";
5680 InternalError(ss
.str().c_str());
5682 std::vector
< Node
> inst_qs
;
5683 d_theoryEngine
->getInstantiatedQuantifiedFormulas( inst_qs
);
5684 Assert( inst_qs
.size()<=1 );
5686 if( inst_qs
.size()==1 ){
5687 Node top_q
= inst_qs
[0];
5688 //Node top_q = Rewriter::rewrite( nn_e ).negate();
5689 Assert( top_q
.getKind()==kind::FORALL
);
5690 Trace("smt-qe") << "Get qe for " << top_q
<< std::endl
;
5691 ret_n
= d_theoryEngine
->getInstantiatedConjunction( top_q
);
5692 Trace("smt-qe") << "Returned : " << ret_n
<< std::endl
;
5693 if (n_e
.getKind() == kind::EXISTS
)
5695 ret_n
= Rewriter::rewrite(ret_n
.negate());
5698 ret_n
= NodeManager::currentNM()->mkConst(n_e
.getKind() != kind::EXISTS
);
5700 return ret_n
.toExpr();
5702 return NodeManager::currentNM()
5703 ->mkConst(n_e
.getKind() == kind::EXISTS
)
5708 void SmtEngine::getInstantiatedQuantifiedFormulas( std::vector
< Expr
>& qs
) {
5709 SmtScope
smts(this);
5710 if( d_theoryEngine
){
5711 std::vector
< Node
> qs_n
;
5712 d_theoryEngine
->getInstantiatedQuantifiedFormulas( qs_n
);
5713 for( unsigned i
=0; i
<qs_n
.size(); i
++ ){
5714 qs
.push_back( qs_n
[i
].toExpr() );
5721 void SmtEngine::getInstantiations( Expr q
, std::vector
< Expr
>& insts
) {
5722 SmtScope
smts(this);
5723 if( d_theoryEngine
){
5724 std::vector
< Node
> insts_n
;
5725 d_theoryEngine
->getInstantiations( Node::fromExpr( q
), insts_n
);
5726 for( unsigned i
=0; i
<insts_n
.size(); i
++ ){
5727 insts
.push_back( insts_n
[i
].toExpr() );
5734 void SmtEngine::getInstantiationTermVectors( Expr q
, std::vector
< std::vector
< Expr
> >& tvecs
) {
5735 SmtScope
smts(this);
5736 Assert(options::trackInstLemmas());
5737 if( d_theoryEngine
){
5738 std::vector
< std::vector
< Node
> > tvecs_n
;
5739 d_theoryEngine
->getInstantiationTermVectors( Node::fromExpr( q
), tvecs_n
);
5740 for( unsigned i
=0; i
<tvecs_n
.size(); i
++ ){
5741 std::vector
< Expr
> tvec
;
5742 for( unsigned j
=0; j
<tvecs_n
[i
].size(); j
++ ){
5743 tvec
.push_back( tvecs_n
[i
][j
].toExpr() );
5745 tvecs
.push_back( tvec
);
5752 vector
<Expr
> SmtEngine::getAssertions() {
5753 SmtScope
smts(this);
5754 finalOptionsAreSet();
5756 if(Dump
.isOn("benchmark")) {
5757 Dump("benchmark") << GetAssertionsCommand();
5759 Trace("smt") << "SMT getAssertions()" << endl
;
5760 if(!options::produceAssertions()) {
5762 "Cannot query the current assertion list when not in produce-assertions mode.";
5763 throw ModalException(msg
);
5765 Assert(d_assertionList
!= NULL
);
5766 // copy the result out
5767 return vector
<Expr
>(d_assertionList
->begin(), d_assertionList
->end());
5770 void SmtEngine::push()
5772 SmtScope
smts(this);
5773 finalOptionsAreSet();
5775 Trace("smt") << "SMT push()" << endl
;
5776 d_private
->notifyPush();
5777 d_private
->processAssertions();
5778 if(Dump
.isOn("benchmark")) {
5779 Dump("benchmark") << PushCommand();
5781 if(!options::incrementalSolving()) {
5782 throw ModalException("Cannot push when not solving incrementally (use --incremental)");
5785 // check to see if a postsolve() is pending
5786 if(d_needPostsolve
) {
5787 d_theoryEngine
->postsolve();
5788 d_needPostsolve
= false;
5791 // The problem isn't really "extended" yet, but this disallows
5792 // get-model after a push, simplifying our lives somewhat and
5793 // staying symmtric with pop.
5794 setProblemExtended(true);
5796 d_userLevels
.push_back(d_userContext
->getLevel());
5798 Trace("userpushpop") << "SmtEngine: pushed to level "
5799 << d_userContext
->getLevel() << endl
;
5802 void SmtEngine::pop() {
5803 SmtScope
smts(this);
5804 finalOptionsAreSet();
5805 Trace("smt") << "SMT pop()" << endl
;
5806 if(Dump
.isOn("benchmark")) {
5807 Dump("benchmark") << PopCommand();
5809 if(!options::incrementalSolving()) {
5810 throw ModalException("Cannot pop when not solving incrementally (use --incremental)");
5812 if(d_userLevels
.size() == 0) {
5813 throw ModalException("Cannot pop beyond the first user frame");
5816 // check to see if a postsolve() is pending
5817 if(d_needPostsolve
) {
5818 d_theoryEngine
->postsolve();
5819 d_needPostsolve
= false;
5822 // The problem isn't really "extended" yet, but this disallows
5823 // get-model after a pop, simplifying our lives somewhat. It might
5824 // not be strictly necessary to do so, since the pops occur lazily,
5825 // but also it would be weird to have a legally-executed (get-model)
5826 // that only returns a subset of the assignment (because the rest
5827 // is no longer in scope!).
5828 setProblemExtended(true);
5830 AlwaysAssert(d_userContext
->getLevel() > 0);
5831 AlwaysAssert(d_userLevels
.back() < d_userContext
->getLevel());
5832 while (d_userLevels
.back() < d_userContext
->getLevel()) {
5835 d_userLevels
.pop_back();
5837 // Clear out assertion queues etc., in case anything is still in there
5838 d_private
->notifyPop();
5840 Trace("userpushpop") << "SmtEngine: popped to level "
5841 << d_userContext
->getLevel() << endl
;
5842 // FIXME: should we reset d_status here?
5843 // SMT-LIBv2 spec seems to imply no, but it would make sense to..
5846 void SmtEngine::internalPush() {
5847 Assert(d_fullyInited
);
5848 Trace("smt") << "SmtEngine::internalPush()" << endl
;
5850 if(options::incrementalSolving()) {
5851 d_private
->processAssertions();
5852 TimerStat::CodeTimer
pushPopTimer(d_stats
->d_pushPopTime
);
5853 d_userContext
->push();
5854 // the d_context push is done inside of the SAT solver
5855 d_propEngine
->push();
5859 void SmtEngine::internalPop(bool immediate
) {
5860 Assert(d_fullyInited
);
5861 Trace("smt") << "SmtEngine::internalPop()" << endl
;
5862 if(options::incrementalSolving()) {
5870 void SmtEngine::doPendingPops() {
5871 Assert(d_pendingPops
== 0 || options::incrementalSolving());
5872 while(d_pendingPops
> 0) {
5873 TimerStat::CodeTimer
pushPopTimer(d_stats
->d_pushPopTime
);
5874 d_propEngine
->pop();
5875 // the d_context pop is done inside of the SAT solver
5876 d_userContext
->pop();
5881 void SmtEngine::reset()
5883 SmtScope
smts(this);
5884 ExprManager
*em
= d_exprManager
;
5885 Trace("smt") << "SMT reset()" << endl
;
5886 if(Dump
.isOn("benchmark")) {
5887 Dump("benchmark") << ResetCommand();
5890 opts
.copyValues(d_originalOptions
);
5892 NodeManager::fromExprManager(em
)->getOptions().copyValues(opts
);
5893 new(this) SmtEngine(em
);
5896 void SmtEngine::resetAssertions()
5898 SmtScope
smts(this);
5901 Trace("smt") << "SMT resetAssertions()" << endl
;
5902 if(Dump
.isOn("benchmark")) {
5903 Dump("benchmark") << ResetAssertionsCommand();
5906 while(!d_userLevels
.empty()) {
5910 // Also remember the global push/pop around everything.
5911 Assert(d_userLevels
.size() == 0 && d_userContext
->getLevel() == 1);
5912 d_context
->popto(0);
5913 d_userContext
->popto(0);
5914 DeleteAndClearCommandVector(d_modelGlobalCommands
);
5915 d_userContext
->push();
5919 void SmtEngine::interrupt()
5921 if(!d_fullyInited
) {
5924 d_propEngine
->interrupt();
5925 d_theoryEngine
->interrupt();
5928 void SmtEngine::setResourceLimit(unsigned long units
, bool cumulative
) {
5929 d_private
->getResourceManager()->setResourceLimit(units
, cumulative
);
5931 void SmtEngine::setTimeLimit(unsigned long milis
, bool cumulative
) {
5932 d_private
->getResourceManager()->setTimeLimit(milis
, cumulative
);
5935 unsigned long SmtEngine::getResourceUsage() const {
5936 return d_private
->getResourceManager()->getResourceUsage();
5939 unsigned long SmtEngine::getTimeUsage() const {
5940 return d_private
->getResourceManager()->getTimeUsage();
5943 unsigned long SmtEngine::getResourceRemaining() const
5945 return d_private
->getResourceManager()->getResourceRemaining();
5948 unsigned long SmtEngine::getTimeRemaining() const
5950 return d_private
->getResourceManager()->getTimeRemaining();
5953 Statistics
SmtEngine::getStatistics() const
5955 return Statistics(*d_statisticsRegistry
);
5958 SExpr
SmtEngine::getStatistic(std::string name
) const
5960 return d_statisticsRegistry
->getStatistic(name
);
5963 void SmtEngine::safeFlushStatistics(int fd
) const {
5964 d_statisticsRegistry
->safeFlushInformation(fd
);
5967 void SmtEngine::setUserAttribute(const std::string
& attr
,
5969 const std::vector
<Expr
>& expr_values
,
5970 const std::string
& str_value
)
5972 SmtScope
smts(this);
5973 std::vector
<Node
> node_values
;
5974 for( unsigned i
=0; i
<expr_values
.size(); i
++ ){
5975 node_values
.push_back( expr_values
[i
].getNode() );
5977 d_theoryEngine
->setUserAttribute(attr
, expr
.getNode(), node_values
, str_value
);
5980 void SmtEngine::setPrintFuncInModel(Expr f
, bool p
) {
5981 Trace("setp-model") << "Set printInModel " << f
<< " to " << p
<< std::endl
;
5982 for( unsigned i
=0; i
<d_modelGlobalCommands
.size(); i
++ ){
5983 Command
* c
= d_modelGlobalCommands
[i
];
5984 DeclareFunctionCommand
* dfc
= dynamic_cast<DeclareFunctionCommand
*>(c
);
5986 if( dfc
->getFunction()==f
){
5987 dfc
->setPrintInModel( p
);
5991 for( unsigned i
=0; i
<d_modelCommands
->size(); i
++ ){
5992 Command
* c
= (*d_modelCommands
)[i
];
5993 DeclareFunctionCommand
* dfc
= dynamic_cast<DeclareFunctionCommand
*>(c
);
5995 if( dfc
->getFunction()==f
){
5996 dfc
->setPrintInModel( p
);
6002 void SmtEngine::beforeSearch()
6005 throw ModalException(
6006 "SmtEngine::beforeSearch called after initialization.");
6011 void SmtEngine::setOption(const std::string
& key
, const CVC4::SExpr
& value
)
6013 NodeManagerScope
nms(d_nodeManager
);
6014 Trace("smt") << "SMT setOption(" << key
<< ", " << value
<< ")" << endl
;
6016 if(Dump
.isOn("benchmark")) {
6017 Dump("benchmark") << SetOptionCommand(key
, value
);
6020 if(key
== "command-verbosity") {
6021 if(!value
.isAtom()) {
6022 const vector
<SExpr
>& cs
= value
.getChildren();
6023 if(cs
.size() == 2 &&
6024 (cs
[0].isKeyword() || cs
[0].isString()) &&
6025 cs
[1].isInteger()) {
6026 string c
= cs
[0].getValue();
6027 const Integer
& v
= cs
[1].getIntegerValue();
6028 if(v
< 0 || v
> 2) {
6029 throw OptionException("command-verbosity must be 0, 1, or 2");
6031 d_commandVerbosity
[c
] = v
;
6035 throw OptionException("command-verbosity value must be a tuple (command-name, integer)");
6038 if(!value
.isAtom()) {
6039 throw OptionException("bad value for :" + key
);
6042 string optionarg
= value
.getValue();
6043 Options
& nodeManagerOptions
= NodeManager::currentNM()->getOptions();
6044 nodeManagerOptions
.setOption(key
, optionarg
);
6047 CVC4::SExpr
SmtEngine::getOption(const std::string
& key
) const
6049 NodeManagerScope
nms(d_nodeManager
);
6051 Trace("smt") << "SMT getOption(" << key
<< ")" << endl
;
6053 if(key
.length() >= 18 &&
6054 key
.compare(0, 18, "command-verbosity:") == 0) {
6055 map
<string
, Integer
>::const_iterator i
= d_commandVerbosity
.find(key
.c_str() + 18);
6056 if(i
!= d_commandVerbosity
.end()) {
6057 return SExpr((*i
).second
);
6059 i
= d_commandVerbosity
.find("*");
6060 if(i
!= d_commandVerbosity
.end()) {
6061 return SExpr((*i
).second
);
6063 return SExpr(Integer(2));
6066 if(Dump
.isOn("benchmark")) {
6067 Dump("benchmark") << GetOptionCommand(key
);
6070 if(key
== "command-verbosity") {
6071 vector
<SExpr
> result
;
6072 SExpr defaultVerbosity
;
6073 for(map
<string
, Integer
>::const_iterator i
= d_commandVerbosity
.begin();
6074 i
!= d_commandVerbosity
.end();
6077 v
.push_back(SExpr((*i
).first
));
6078 v
.push_back(SExpr((*i
).second
));
6079 if((*i
).first
== "*") {
6080 // put the default at the end of the SExpr
6081 defaultVerbosity
= SExpr(v
);
6083 result
.push_back(SExpr(v
));
6086 // put the default at the end of the SExpr
6087 if(!defaultVerbosity
.isAtom()) {
6088 result
.push_back(defaultVerbosity
);
6090 // ensure the default is always listed
6092 v
.push_back(SExpr("*"));
6093 v
.push_back(SExpr(Integer(2)));
6094 result
.push_back(SExpr(v
));
6096 return SExpr(result
);
6099 Options
& nodeManagerOptions
= NodeManager::currentNM()->getOptions();
6100 return SExpr::parseAtom(nodeManagerOptions
.getOption(key
));
6103 void SmtEngine::setReplayStream(ExprStream
* replayStream
) {
6104 AlwaysAssert(!d_fullyInited
,
6105 "Cannot set replay stream once fully initialized");
6106 d_replayStream
= replayStream
;
6109 bool SmtEngine::getExpressionName(Expr e
, std::string
& name
) const {
6110 return d_private
->getExpressionName(e
, name
);
6113 void SmtEngine::setExpressionName(Expr e
, const std::string
& name
) {
6114 Trace("smt-debug") << "Set expression name " << e
<< " to " << name
<< std::endl
;
6115 d_private
->setExpressionName(e
,name
);
6118 }/* CVC4 namespace */