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/bool_to_bv.h"
72 #include "preprocessing/passes/bv_abstraction.h"
73 #include "preprocessing/passes/bv_ackermann.h"
74 #include "preprocessing/passes/bv_gauss.h"
75 #include "preprocessing/passes/bv_intro_pow2.h"
76 #include "preprocessing/passes/bv_to_bool.h"
77 #include "preprocessing/passes/int_to_bv.h"
78 #include "preprocessing/passes/pseudo_boolean_processor.h"
79 #include "preprocessing/passes/real_to_int.h"
80 #include "preprocessing/passes/symmetry_breaker.h"
81 #include "preprocessing/passes/symmetry_detect.h"
82 #include "preprocessing/preprocessing_pass.h"
83 #include "preprocessing/preprocessing_pass_context.h"
84 #include "preprocessing/preprocessing_pass_registry.h"
85 #include "printer/printer.h"
86 #include "proof/proof.h"
87 #include "proof/proof_manager.h"
88 #include "proof/theory_proof.h"
89 #include "proof/unsat_core.h"
90 #include "prop/prop_engine.h"
91 #include "smt/command.h"
92 #include "smt/command_list.h"
93 #include "smt/logic_request.h"
94 #include "smt/managed_ostreams.h"
95 #include "smt/smt_engine_scope.h"
96 #include "smt/term_formula_removal.h"
97 #include "smt/update_ostream.h"
98 #include "smt_util/boolean_simplification.h"
99 #include "smt_util/nary_builder.h"
100 #include "smt_util/node_visitor.h"
101 #include "theory/booleans/circuit_propagator.h"
102 #include "theory/bv/theory_bv_rewriter.h"
103 #include "theory/logic_info.h"
104 #include "theory/quantifiers/fun_def_process.h"
105 #include "theory/quantifiers/global_negate.h"
106 #include "theory/quantifiers/macros.h"
107 #include "theory/quantifiers/quantifiers_rewriter.h"
108 #include "theory/quantifiers/single_inv_partition.h"
109 #include "theory/quantifiers/sygus/ce_guided_instantiation.h"
110 #include "theory/quantifiers/sygus_inference.h"
111 #include "theory/quantifiers/term_util.h"
112 #include "theory/sort_inference.h"
113 #include "theory/strings/theory_strings.h"
114 #include "theory/substitutions.h"
115 #include "theory/theory_engine.h"
116 #include "theory/theory_model.h"
117 #include "theory/theory_traits.h"
118 #include "util/hash.h"
119 #include "util/proof.h"
120 #include "util/random.h"
121 #include "util/resource_manager.h"
124 using namespace CVC4
;
125 using namespace CVC4::smt
;
126 using namespace CVC4::preprocessing
;
127 using namespace CVC4::preprocessing::passes
;
128 using namespace CVC4::prop
;
129 using namespace CVC4::context
;
130 using namespace CVC4::theory
;
135 struct DeleteCommandFunction
: public std::unary_function
<const Command
*, void>
137 void operator()(const Command
* command
) { delete command
; }
140 void DeleteAndClearCommandVector(std::vector
<Command
*>& commands
) {
141 std::for_each(commands
.begin(), commands
.end(), DeleteCommandFunction());
145 /** Useful for counting the number of recursive calls. */
150 ScopeCounter(unsigned& d
) : d_depth(d
) {
159 * Representation of a defined function. We keep these around in
160 * SmtEngine to permit expanding definitions late (and lazily), to
161 * support getValue() over defined functions, to support user output
162 * in terms of defined functions, etc.
164 class DefinedFunction
{
166 vector
<Node
> d_formals
;
170 DefinedFunction(Node func
, vector
<Node
> formals
, Node formula
) :
175 Node
getFunction() const { return d_func
; }
176 vector
<Node
> getFormals() const { return d_formals
; }
177 Node
getFormula() const { return d_formula
; }
178 };/* class DefinedFunction */
180 struct SmtEngineStatistics
{
181 /** time spent in gaussian elimination */
182 TimerStat d_gaussElimTime
;
183 /** time spent in definition-expansion */
184 TimerStat d_definitionExpansionTime
;
185 /** time spent in non-clausal simplification */
186 TimerStat d_nonclausalSimplificationTime
;
187 /** time spent in miplib pass */
188 TimerStat d_miplibPassTime
;
189 /** number of assertions removed by miplib pass */
190 IntStat d_numMiplibAssertionsRemoved
;
191 /** number of constant propagations found during nonclausal simp */
192 IntStat d_numConstantProps
;
193 /** time spent in static learning */
194 TimerStat d_staticLearningTime
;
195 /** time spent in simplifying ITEs */
196 TimerStat d_simpITETime
;
197 /** time spent in simplifying ITEs */
198 TimerStat d_unconstrainedSimpTime
;
199 /** time spent removing ITEs */
200 TimerStat d_iteRemovalTime
;
201 /** time spent in theory preprocessing */
202 TimerStat d_theoryPreprocessTime
;
203 /** time spent in theory preprocessing */
204 TimerStat d_rewriteApplyToConstTime
;
205 /** time spent converting to CNF */
206 TimerStat d_cnfConversionTime
;
207 /** Num of assertions before ite removal */
208 IntStat d_numAssertionsPre
;
209 /** Num of assertions after ite removal */
210 IntStat d_numAssertionsPost
;
211 /** time spent in checkModel() */
212 TimerStat d_checkModelTime
;
213 /** time spent in checkProof() */
214 TimerStat d_checkProofTime
;
215 /** time spent in checkUnsatCore() */
216 TimerStat d_checkUnsatCoreTime
;
217 /** time spent in PropEngine::checkSat() */
218 TimerStat d_solveTime
;
219 /** time spent in pushing/popping */
220 TimerStat d_pushPopTime
;
221 /** time spent in processAssertions() */
222 TimerStat d_processAssertionsTime
;
224 /** Has something simplified to false? */
225 IntStat d_simplifiedToFalse
;
226 /** Number of resource units spent. */
227 ReferenceStat
<uint64_t> d_resourceUnitsUsed
;
229 SmtEngineStatistics() :
230 d_gaussElimTime("smt::SmtEngine::gaussElimTime"),
231 d_definitionExpansionTime("smt::SmtEngine::definitionExpansionTime"),
232 d_nonclausalSimplificationTime("smt::SmtEngine::nonclausalSimplificationTime"),
233 d_miplibPassTime("smt::SmtEngine::miplibPassTime"),
234 d_numMiplibAssertionsRemoved("smt::SmtEngine::numMiplibAssertionsRemoved", 0),
235 d_numConstantProps("smt::SmtEngine::numConstantProps", 0),
236 d_staticLearningTime("smt::SmtEngine::staticLearningTime"),
237 d_simpITETime("smt::SmtEngine::simpITETime"),
238 d_unconstrainedSimpTime("smt::SmtEngine::unconstrainedSimpTime"),
239 d_iteRemovalTime("smt::SmtEngine::iteRemovalTime"),
240 d_theoryPreprocessTime("smt::SmtEngine::theoryPreprocessTime"),
241 d_rewriteApplyToConstTime("smt::SmtEngine::rewriteApplyToConstTime"),
242 d_cnfConversionTime("smt::SmtEngine::cnfConversionTime"),
243 d_numAssertionsPre("smt::SmtEngine::numAssertionsPreITERemoval", 0),
244 d_numAssertionsPost("smt::SmtEngine::numAssertionsPostITERemoval", 0),
245 d_checkModelTime("smt::SmtEngine::checkModelTime"),
246 d_checkProofTime("smt::SmtEngine::checkProofTime"),
247 d_checkUnsatCoreTime("smt::SmtEngine::checkUnsatCoreTime"),
248 d_solveTime("smt::SmtEngine::solveTime"),
249 d_pushPopTime("smt::SmtEngine::pushPopTime"),
250 d_processAssertionsTime("smt::SmtEngine::processAssertionsTime"),
251 d_simplifiedToFalse("smt::SmtEngine::simplifiedToFalse", 0),
252 d_resourceUnitsUsed("smt::SmtEngine::resourceUnitsUsed")
255 smtStatisticsRegistry()->registerStat(&d_gaussElimTime
);
256 smtStatisticsRegistry()->registerStat(&d_definitionExpansionTime
);
257 smtStatisticsRegistry()->registerStat(&d_nonclausalSimplificationTime
);
258 smtStatisticsRegistry()->registerStat(&d_miplibPassTime
);
259 smtStatisticsRegistry()->registerStat(&d_numMiplibAssertionsRemoved
);
260 smtStatisticsRegistry()->registerStat(&d_numConstantProps
);
261 smtStatisticsRegistry()->registerStat(&d_staticLearningTime
);
262 smtStatisticsRegistry()->registerStat(&d_simpITETime
);
263 smtStatisticsRegistry()->registerStat(&d_unconstrainedSimpTime
);
264 smtStatisticsRegistry()->registerStat(&d_iteRemovalTime
);
265 smtStatisticsRegistry()->registerStat(&d_theoryPreprocessTime
);
266 smtStatisticsRegistry()->registerStat(&d_rewriteApplyToConstTime
);
267 smtStatisticsRegistry()->registerStat(&d_cnfConversionTime
);
268 smtStatisticsRegistry()->registerStat(&d_numAssertionsPre
);
269 smtStatisticsRegistry()->registerStat(&d_numAssertionsPost
);
270 smtStatisticsRegistry()->registerStat(&d_checkModelTime
);
271 smtStatisticsRegistry()->registerStat(&d_checkProofTime
);
272 smtStatisticsRegistry()->registerStat(&d_checkUnsatCoreTime
);
273 smtStatisticsRegistry()->registerStat(&d_solveTime
);
274 smtStatisticsRegistry()->registerStat(&d_pushPopTime
);
275 smtStatisticsRegistry()->registerStat(&d_processAssertionsTime
);
276 smtStatisticsRegistry()->registerStat(&d_simplifiedToFalse
);
277 smtStatisticsRegistry()->registerStat(&d_resourceUnitsUsed
);
280 ~SmtEngineStatistics() {
281 smtStatisticsRegistry()->unregisterStat(&d_gaussElimTime
);
282 smtStatisticsRegistry()->unregisterStat(&d_definitionExpansionTime
);
283 smtStatisticsRegistry()->unregisterStat(&d_nonclausalSimplificationTime
);
284 smtStatisticsRegistry()->unregisterStat(&d_miplibPassTime
);
285 smtStatisticsRegistry()->unregisterStat(&d_numMiplibAssertionsRemoved
);
286 smtStatisticsRegistry()->unregisterStat(&d_numConstantProps
);
287 smtStatisticsRegistry()->unregisterStat(&d_staticLearningTime
);
288 smtStatisticsRegistry()->unregisterStat(&d_simpITETime
);
289 smtStatisticsRegistry()->unregisterStat(&d_unconstrainedSimpTime
);
290 smtStatisticsRegistry()->unregisterStat(&d_iteRemovalTime
);
291 smtStatisticsRegistry()->unregisterStat(&d_theoryPreprocessTime
);
292 smtStatisticsRegistry()->unregisterStat(&d_rewriteApplyToConstTime
);
293 smtStatisticsRegistry()->unregisterStat(&d_cnfConversionTime
);
294 smtStatisticsRegistry()->unregisterStat(&d_numAssertionsPre
);
295 smtStatisticsRegistry()->unregisterStat(&d_numAssertionsPost
);
296 smtStatisticsRegistry()->unregisterStat(&d_checkModelTime
);
297 smtStatisticsRegistry()->unregisterStat(&d_checkProofTime
);
298 smtStatisticsRegistry()->unregisterStat(&d_checkUnsatCoreTime
);
299 smtStatisticsRegistry()->unregisterStat(&d_solveTime
);
300 smtStatisticsRegistry()->unregisterStat(&d_pushPopTime
);
301 smtStatisticsRegistry()->unregisterStat(&d_processAssertionsTime
);
302 smtStatisticsRegistry()->unregisterStat(&d_simplifiedToFalse
);
303 smtStatisticsRegistry()->unregisterStat(&d_resourceUnitsUsed
);
305 };/* struct SmtEngineStatistics */
308 class SoftResourceOutListener
: public Listener
{
310 SoftResourceOutListener(SmtEngine
& smt
) : d_smt(&smt
) {}
311 void notify() override
313 SmtScope
scope(d_smt
);
314 Assert(smt::smtEngineInScope());
319 }; /* class SoftResourceOutListener */
322 class HardResourceOutListener
: public Listener
{
324 HardResourceOutListener(SmtEngine
& smt
) : d_smt(&smt
) {}
325 void notify() override
327 SmtScope
scope(d_smt
);
328 theory::Rewriter::clearCaches();
332 }; /* class HardResourceOutListener */
334 class SetLogicListener
: public Listener
{
336 SetLogicListener(SmtEngine
& smt
) : d_smt(&smt
) {}
337 void notify() override
339 LogicInfo
inOptions(options::forceLogicString());
340 d_smt
->setLogic(inOptions
);
344 }; /* class SetLogicListener */
346 class BeforeSearchListener
: public Listener
{
348 BeforeSearchListener(SmtEngine
& smt
) : d_smt(&smt
) {}
349 void notify() override
{ d_smt
->beforeSearch(); }
353 }; /* class BeforeSearchListener */
355 class UseTheoryListListener
: public Listener
{
357 UseTheoryListListener(TheoryEngine
* theoryEngine
)
358 : d_theoryEngine(theoryEngine
)
361 void notify() override
363 std::stringstream
commaList(options::useTheoryList());
366 Debug("UseTheoryListListener") << "UseTheoryListListener::notify() "
367 << options::useTheoryList() << std::endl
;
369 while(std::getline(commaList
, token
, ',')){
370 if(token
== "help") {
371 puts(theory::useTheoryHelp
);
374 if(theory::useTheoryValidate(token
)) {
375 d_theoryEngine
->enableTheoryAlternative(token
);
377 throw OptionException(
378 std::string("unknown option for --use-theory : `") + token
+
379 "'. Try --use-theory=help.");
385 TheoryEngine
* d_theoryEngine
;
386 }; /* class UseTheoryListListener */
389 class SetDefaultExprDepthListener
: public Listener
{
391 void notify() override
393 int depth
= options::defaultExprDepth();
394 Debug
.getStream() << expr::ExprSetDepth(depth
);
395 Trace
.getStream() << expr::ExprSetDepth(depth
);
396 Notice
.getStream() << expr::ExprSetDepth(depth
);
397 Chat
.getStream() << expr::ExprSetDepth(depth
);
398 Message
.getStream() << expr::ExprSetDepth(depth
);
399 Warning
.getStream() << expr::ExprSetDepth(depth
);
400 // intentionally exclude Dump stream from this list
404 class SetDefaultExprDagListener
: public Listener
{
406 void notify() override
408 int dag
= options::defaultDagThresh();
409 Debug
.getStream() << expr::ExprDag(dag
);
410 Trace
.getStream() << expr::ExprDag(dag
);
411 Notice
.getStream() << expr::ExprDag(dag
);
412 Chat
.getStream() << expr::ExprDag(dag
);
413 Message
.getStream() << expr::ExprDag(dag
);
414 Warning
.getStream() << expr::ExprDag(dag
);
415 Dump
.getStream() << expr::ExprDag(dag
);
419 class SetPrintExprTypesListener
: public Listener
{
421 void notify() override
423 bool value
= options::printExprTypes();
424 Debug
.getStream() << expr::ExprPrintTypes(value
);
425 Trace
.getStream() << expr::ExprPrintTypes(value
);
426 Notice
.getStream() << expr::ExprPrintTypes(value
);
427 Chat
.getStream() << expr::ExprPrintTypes(value
);
428 Message
.getStream() << expr::ExprPrintTypes(value
);
429 Warning
.getStream() << expr::ExprPrintTypes(value
);
430 // intentionally exclude Dump stream from this list
434 class DumpModeListener
: public Listener
{
436 void notify() override
438 const std::string
& value
= options::dumpModeString();
439 Dump
.setDumpFromString(value
);
443 class PrintSuccessListener
: public Listener
{
445 void notify() override
447 bool value
= options::printSuccess();
448 Debug
.getStream() << Command::printsuccess(value
);
449 Trace
.getStream() << Command::printsuccess(value
);
450 Notice
.getStream() << Command::printsuccess(value
);
451 Chat
.getStream() << Command::printsuccess(value
);
452 Message
.getStream() << Command::printsuccess(value
);
453 Warning
.getStream() << Command::printsuccess(value
);
454 *options::out() << Command::printsuccess(value
);
461 * This is an inelegant solution, but for the present, it will work.
462 * The point of this is to separate the public and private portions of
463 * the SmtEngine class, so that smt_engine.h doesn't
464 * include "expr/node.h", which is a private CVC4 header (and can lead
465 * to linking errors due to the improper inlining of non-visible symbols
468 * The "real" solution (that which is usually implemented) is to move
469 * ALL the implementation to SmtEnginePrivate and maintain a
470 * heap-allocated instance of it in SmtEngine. SmtEngine (the public
471 * one) becomes an "interface shell" which simply acts as a forwarder
474 class SmtEnginePrivate
: public NodeManagerListener
{
477 typedef unordered_map
<Node
, Node
, NodeHashFunction
> NodeToNodeHashMap
;
478 typedef unordered_map
<Node
, bool, NodeHashFunction
> NodeToBoolHashMap
;
481 * Manager for limiting time and abstract resource usage.
483 ResourceManager
* d_resourceManager
;
485 /** Manager for the memory of regular-output-channel. */
486 ManagedRegularOutputChannel d_managedRegularChannel
;
488 /** Manager for the memory of diagnostic-output-channel. */
489 ManagedDiagnosticOutputChannel d_managedDiagnosticChannel
;
491 /** Manager for the memory of --dump-to. */
492 ManagedDumpOStream d_managedDumpChannel
;
494 /** Manager for --replay-log. */
495 ManagedReplayLogOstream d_managedReplayLog
;
498 * This list contains:
502 * beforeSearchListener
503 * UseTheoryListListener
505 * This needs to be deleted before both NodeManager's Options,
506 * SmtEngine, d_resourceManager, and TheoryEngine.
508 ListenerRegistrationList
* d_listenerRegistrations
;
510 /** Learned literals */
511 vector
<Node
> d_nonClausalLearnedLiterals
;
513 /** Size of assertions array when preprocessing starts */
514 unsigned d_realAssertionsEnd
;
516 /** A circuit propagator for non-clausal propositional deduction */
517 booleans::CircuitPropagator d_propagator
;
518 bool d_propagatorNeedsFinish
;
519 std::vector
<Node
> d_boolVars
;
521 /** Assertions in the preprocessing pipeline */
522 AssertionPipeline d_assertions
;
524 /** Whether any assertions have been processed */
525 CDO
<bool> d_assertionsProcessed
;
527 /** Index for where to store substitutions */
528 CDO
<unsigned> d_substitutionsIndex
;
534 * A context that never pushes/pops, for use by CD structures (like
535 * SubstitutionMaps) that should be "global".
537 context::Context d_fakeContext
;
540 * A map of AbsractValues to their actual constants. Only used if
541 * options::abstractValues() is on.
543 SubstitutionMap d_abstractValueMap
;
546 * A mapping of all abstract values (actual value |-> abstract) that
547 * we've handed out. This is necessary to ensure that we give the
548 * same AbstractValues for the same real constants. Only used if
549 * options::abstractValues() is on.
551 NodeToNodeHashMap d_abstractValues
;
553 /** Number of calls of simplify assertions active.
555 unsigned d_simplifyAssertionsDepth
;
557 /** TODO: whether certain preprocess steps are necessary */
558 //bool d_needsExpandDefs;
560 //------------------------------- expression names
561 /** mapping from expressions to name */
562 context::CDHashMap
< Node
, std::string
, NodeHashFunction
> d_exprNames
;
563 //------------------------------- end expression names
566 * Map from skolem variables to index in d_assertions containing
567 * corresponding introduced Boolean ite
569 IteSkolemMap d_iteSkolemMap
;
571 /** Instance of the ITE remover */
572 RemoveTermFormulas d_iteRemover
;
574 /* Finishes the initialization of the private portion of SMTEngine. */
578 std::unique_ptr
<PreprocessingPassContext
> d_preprocessingPassContext
;
579 PreprocessingPassRegistry d_preprocessingPassRegistry
;
581 /** The top level substitutions */
582 SubstitutionMap d_topLevelSubstitutions
;
584 static const bool d_doConstantProp
= true;
587 * Runs the nonclausal solver and tries to solve all the assigned
590 * Returns false if the formula simplifies to "false"
592 bool nonClausalSimplify();
595 * Performs static learning on the assertions.
597 void staticLearning();
600 * Remove ITEs from the assertions.
604 Node
realToInt(TNode n
, NodeToNodeHashMap
& cache
, std::vector
< Node
>& var_eq
);
605 Node
purifyNlTerms(TNode n
, NodeToNodeHashMap
& cache
, NodeToNodeHashMap
& bcache
, std::vector
< Node
>& var_eq
, bool beneathMult
= false);
608 * Helper function to fix up assertion list to restore invariants needed after
611 void collectSkolems(TNode n
, set
<TNode
>& skolemSet
, NodeToBoolHashMap
& cache
);
614 * Helper function to fix up assertion list to restore invariants needed after
617 bool checkForBadSkolems(TNode n
, TNode skolem
, NodeToBoolHashMap
& cache
);
619 // Simplify ITE structure
622 // Simplify based on unconstrained values
623 void unconstrainedSimp();
626 * Ensures the assertions asserted after before now effectively come before
627 * d_realAssertionsEnd.
629 void compressBeforeRealAssertions(size_t before
);
632 * Trace nodes back to their assertions using CircuitPropagator's
635 void traceBackToAssertions(const std::vector
<Node
>& nodes
,
636 std::vector
<TNode
>& assertions
);
639 * Remove conjuncts in toRemove from conjunction n. Return # of removed
642 size_t removeFromConjunction(Node
& n
,
643 const std::unordered_set
<unsigned long>& toRemove
);
645 /** Scrub miplib encodings. */
646 void doMiplibTrick();
649 * Perform non-clausal simplification of a Node. This involves
650 * Theory implementations, but does NOT involve the SAT solver in
653 * Returns false if the formula simplifies to "false"
655 bool simplifyAssertions();
659 SmtEnginePrivate(SmtEngine
& smt
) :
661 d_managedRegularChannel(),
662 d_managedDiagnosticChannel(),
663 d_managedDumpChannel(),
664 d_managedReplayLog(),
665 d_listenerRegistrations(new ListenerRegistrationList()),
666 d_nonClausalLearnedLiterals(),
667 d_realAssertionsEnd(0),
668 d_propagator(d_nonClausalLearnedLiterals
, true, true),
669 d_propagatorNeedsFinish(false),
671 d_assertionsProcessed(smt
.d_userContext
, false),
672 d_substitutionsIndex(smt
.d_userContext
, 0),
674 d_abstractValueMap(&d_fakeContext
),
676 d_simplifyAssertionsDepth(0),
677 //d_needsExpandDefs(true), //TODO?
678 d_exprNames(smt
.d_userContext
),
680 d_iteRemover(smt
.d_userContext
),
681 d_topLevelSubstitutions(smt
.d_userContext
)
683 d_smt
.d_nodeManager
->subscribeEvents(this);
684 d_true
= NodeManager::currentNM()->mkConst(true);
685 d_resourceManager
= NodeManager::currentResourceManager();
687 d_listenerRegistrations
->add(d_resourceManager
->registerSoftListener(
688 new SoftResourceOutListener(d_smt
)));
690 d_listenerRegistrations
->add(d_resourceManager
->registerHardListener(
691 new HardResourceOutListener(d_smt
)));
693 Options
& nodeManagerOptions
= NodeManager::currentNM()->getOptions();
694 d_listenerRegistrations
->add(
695 nodeManagerOptions
.registerForceLogicListener(
696 new SetLogicListener(d_smt
), true));
698 // Multiple options reuse BeforeSearchListener so registration requires an
699 // extra bit of care.
700 // We can safely not call notify on this before search listener at
701 // registration time. This d_smt cannot be beforeSearch at construction
702 // time. Therefore the BeforeSearchListener is a no-op. Therefore it does
703 // not have to be called.
704 d_listenerRegistrations
->add(
705 nodeManagerOptions
.registerBeforeSearchListener(
706 new BeforeSearchListener(d_smt
)));
708 // These do need registration calls.
709 d_listenerRegistrations
->add(
710 nodeManagerOptions
.registerSetDefaultExprDepthListener(
711 new SetDefaultExprDepthListener(), true));
712 d_listenerRegistrations
->add(
713 nodeManagerOptions
.registerSetDefaultExprDagListener(
714 new SetDefaultExprDagListener(), true));
715 d_listenerRegistrations
->add(
716 nodeManagerOptions
.registerSetPrintExprTypesListener(
717 new SetPrintExprTypesListener(), true));
718 d_listenerRegistrations
->add(
719 nodeManagerOptions
.registerSetDumpModeListener(
720 new DumpModeListener(), true));
721 d_listenerRegistrations
->add(
722 nodeManagerOptions
.registerSetPrintSuccessListener(
723 new PrintSuccessListener(), true));
724 d_listenerRegistrations
->add(
725 nodeManagerOptions
.registerSetRegularOutputChannelListener(
726 new SetToDefaultSourceListener(&d_managedRegularChannel
), true));
727 d_listenerRegistrations
->add(
728 nodeManagerOptions
.registerSetDiagnosticOutputChannelListener(
729 new SetToDefaultSourceListener(&d_managedDiagnosticChannel
), true));
730 d_listenerRegistrations
->add(
731 nodeManagerOptions
.registerDumpToFileNameListener(
732 new SetToDefaultSourceListener(&d_managedDumpChannel
), true));
733 d_listenerRegistrations
->add(
734 nodeManagerOptions
.registerSetReplayLogFilename(
735 new SetToDefaultSourceListener(&d_managedReplayLog
), true));
740 delete d_listenerRegistrations
;
742 if(d_propagatorNeedsFinish
) {
743 d_propagator
.finish();
744 d_propagatorNeedsFinish
= false;
746 d_smt
.d_nodeManager
->unsubscribeEvents(this);
749 void unregisterPreprocessingPasses()
751 d_preprocessingPassRegistry
.unregisterPasses();
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 //destroy all passes before destroying things that they refer to
1229 d_private
->unregisterPreprocessingPasses();
1231 delete d_theoryEngine
;
1232 d_theoryEngine
= NULL
;
1233 delete d_propEngine
;
1234 d_propEngine
= NULL
;
1235 delete d_decisionEngine
;
1236 d_decisionEngine
= NULL
;
1239 // d_proofManager is always created when proofs are enabled at configure time.
1240 // Becuase of this, this code should not be wrapped in PROOF() which
1241 // additionally checks flags such as options::proof().
1243 delete d_proofManager
;
1244 d_proofManager
= NULL
;
1249 delete d_statisticsRegistry
;
1250 d_statisticsRegistry
= NULL
;
1255 delete d_userContext
;
1256 d_userContext
= NULL
;
1263 } catch(Exception
& e
) {
1264 Warning() << "CVC4 threw an exception during cleanup." << endl
1269 void SmtEngine::setLogic(const LogicInfo
& logic
)
1271 SmtScope
smts(this);
1273 throw ModalException("Cannot set logic in SmtEngine after the engine has "
1274 "finished initializing.");
1280 void SmtEngine::setLogic(const std::string
& s
)
1282 SmtScope
smts(this);
1284 setLogic(LogicInfo(s
));
1285 } catch(IllegalArgumentException
& e
) {
1286 throw LogicException(e
.what());
1290 void SmtEngine::setLogic(const char* logic
) { setLogic(string(logic
)); }
1291 LogicInfo
SmtEngine::getLogicInfo() const {
1294 void SmtEngine::setLogicInternal()
1296 Assert(!d_fullyInited
, "setting logic in SmtEngine but the engine has already"
1297 " finished initializing for this run");
1301 void SmtEngine::setDefaults() {
1302 Random::getRandom().setSeed(options::seed());
1303 // Language-based defaults
1304 if (!options::bitvectorDivByZeroConst
.wasSetByUser())
1306 options::bitvectorDivByZeroConst
.set(
1307 language::isInputLang_smt2_6(options::inputLanguage()));
1309 if (options::inputLanguage() == language::input::LANG_SYGUS
)
1311 if (!options::ceGuidedInst
.wasSetByUser())
1313 options::ceGuidedInst
.set(true);
1315 // must use Ferrante/Rackoff for real arithmetic
1316 if (!options::cbqiMidpoint
.wasSetByUser())
1318 options::cbqiMidpoint
.set(true);
1323 // cannot use sygus repair constants
1324 options::sygusRepairConst
.set(false);
1327 if(options::forceLogicString
.wasSetByUser()) {
1328 d_logic
= LogicInfo(options::forceLogicString());
1329 }else if (options::solveIntAsBV() > 0) {
1330 d_logic
= LogicInfo("QF_BV");
1331 }else if (d_logic
.getLogicString() == "QF_NRA" && options::solveRealAsInt()) {
1332 d_logic
= LogicInfo("QF_NIA");
1333 } else if ((d_logic
.getLogicString() == "QF_UFBV" ||
1334 d_logic
.getLogicString() == "QF_ABV") &&
1335 options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER
) {
1336 d_logic
= LogicInfo("QF_BV");
1340 /* - disabled for 1.4 release [MGD 2014.06.25]
1341 if(!d_logic.hasEverything() && d_logic.isTheoryEnabled(THEORY_STRINGS) ) {
1342 if(! options::stringExp.wasSetByUser()) {
1343 options::stringExp.set( true );
1344 Trace("smt") << "turning on strings-exp, for the theory of strings" << std::endl;
1349 if(options::stringExp()) {
1350 if( !d_logic
.isQuantified() ) {
1351 d_logic
= d_logic
.getUnlockedCopy();
1352 d_logic
.enableQuantifiers();
1354 Trace("smt") << "turning on quantifier logic, for strings-exp"
1357 if(! options::fmfBound
.wasSetByUser()) {
1358 options::fmfBound
.set( true );
1359 Trace("smt") << "turning on fmf-bound-int, for strings-exp" << std::endl
;
1361 if(! options::fmfInstEngine
.wasSetByUser()) {
1362 options::fmfInstEngine
.set( true );
1363 Trace("smt") << "turning on fmf-inst-engine, for strings-exp" << std::endl
;
1366 if(! options::rewriteDivk.wasSetByUser()) {
1367 options::rewriteDivk.set( true );
1368 Trace("smt") << "turning on rewrite-divk, for strings-exp" << std::endl;
1371 if(! options::stringFMF.wasSetByUser()) {
1372 options::stringFMF.set( true );
1373 Trace("smt") << "turning on strings-fmf, for strings-exp" << std::endl;
1378 // sygus inference may require datatypes
1379 if (options::sygusInference())
1381 d_logic
= d_logic
.getUnlockedCopy();
1382 d_logic
.enableTheory(THEORY_DATATYPES
);
1386 if ((options::checkModels() || options::checkSynthSol())
1387 && !options::produceAssertions())
1389 Notice() << "SmtEngine: turning on produce-assertions to support "
1390 << "check-models or check-synth-sol." << endl
;
1391 setOption("produce-assertions", SExpr("true"));
1394 if(options::unsatCores()) {
1395 if(options::simplificationMode() != SIMPLIFICATION_MODE_NONE
) {
1396 if(options::simplificationMode
.wasSetByUser()) {
1397 throw OptionException("simplification not supported with unsat cores");
1399 Notice() << "SmtEngine: turning off simplification to support unsat-cores"
1401 options::simplificationMode
.set(SIMPLIFICATION_MODE_NONE
);
1404 if(options::unconstrainedSimp()) {
1405 if(options::unconstrainedSimp
.wasSetByUser()) {
1406 throw OptionException("unconstrained simplification not supported with unsat cores");
1408 Notice() << "SmtEngine: turning off unconstrained simplification to support unsat-cores" << endl
;
1409 options::unconstrainedSimp
.set(false);
1412 if(options::pbRewrites()) {
1413 if(options::pbRewrites
.wasSetByUser()) {
1414 throw OptionException("pseudoboolean rewrites not supported with unsat cores");
1416 Notice() << "SmtEngine: turning off pseudoboolean rewrites to support unsat-cores" << endl
;
1417 setOption("pb-rewrites", false);
1420 if(options::sortInference()) {
1421 if(options::sortInference
.wasSetByUser()) {
1422 throw OptionException("sort inference not supported with unsat cores");
1424 Notice() << "SmtEngine: turning off sort inference to support unsat-cores" << endl
;
1425 options::sortInference
.set(false);
1428 if(options::preSkolemQuant()) {
1429 if(options::preSkolemQuant
.wasSetByUser()) {
1430 throw OptionException("pre-skolemization not supported with unsat cores");
1432 Notice() << "SmtEngine: turning off pre-skolemization to support unsat-cores" << endl
;
1433 options::preSkolemQuant
.set(false);
1436 if(options::bitvectorToBool()) {
1437 if(options::bitvectorToBool
.wasSetByUser()) {
1438 throw OptionException("bv-to-bool not supported with unsat cores");
1440 Notice() << "SmtEngine: turning off bitvector-to-bool to support unsat-cores" << endl
;
1441 options::bitvectorToBool
.set(false);
1444 if(options::boolToBitvector()) {
1445 if(options::boolToBitvector
.wasSetByUser()) {
1446 throw OptionException("bool-to-bv not supported with unsat cores");
1448 Notice() << "SmtEngine: turning off bool-to-bitvector to support unsat-cores" << endl
;
1449 options::boolToBitvector
.set(false);
1452 if(options::bvIntroducePow2()) {
1453 if(options::bvIntroducePow2
.wasSetByUser()) {
1454 throw OptionException("bv-intro-pow2 not supported with unsat cores");
1456 Notice() << "SmtEngine: turning off bv-intro-pow2 to support unsat-cores" << endl
;
1457 setOption("bv-intro-pow2", false);
1460 if(options::repeatSimp()) {
1461 if(options::repeatSimp
.wasSetByUser()) {
1462 throw OptionException("repeat-simp not supported with unsat cores");
1464 Notice() << "SmtEngine: turning off repeat-simp to support unsat-cores" << endl
;
1465 setOption("repeat-simp", false);
1468 if (options::globalNegate())
1470 if (options::globalNegate
.wasSetByUser())
1472 throw OptionException("global-negate not supported with unsat cores");
1474 Notice() << "SmtEngine: turning off global-negate to support unsat-cores"
1476 setOption("global-negate", false);
1480 if (options::cbqiBv() && d_logic
.isQuantified())
1482 if(options::boolToBitvector
.wasSetByUser()) {
1483 throw OptionException(
1484 "bool-to-bv not supported with CBQI BV for quantified logics");
1486 Notice() << "SmtEngine: turning off bool-to-bitvector to support CBQI BV"
1488 options::boolToBitvector
.set(false);
1491 // cases where we need produce models
1492 if (!options::produceModels()
1493 && (options::produceAssignments() || options::sygusRewSynthCheck()
1494 || options::sygusRepairConst()))
1496 Notice() << "SmtEngine: turning on produce-models" << endl
;
1497 setOption("produce-models", SExpr("true"));
1500 // Set the options for the theoryOf
1501 if(!options::theoryOfMode
.wasSetByUser()) {
1502 if(d_logic
.isSharingEnabled() &&
1503 !d_logic
.isTheoryEnabled(THEORY_BV
) &&
1504 !d_logic
.isTheoryEnabled(THEORY_STRINGS
) &&
1505 !d_logic
.isTheoryEnabled(THEORY_SETS
) ) {
1506 Trace("smt") << "setting theoryof-mode to term-based" << endl
;
1507 options::theoryOfMode
.set(THEORY_OF_TERM_BASED
);
1511 // strings require LIA, UF; widen the logic
1512 if(d_logic
.isTheoryEnabled(THEORY_STRINGS
)) {
1513 LogicInfo
log(d_logic
.getUnlockedCopy());
1514 // Strings requires arith for length constraints, and also UF
1515 if(!d_logic
.isTheoryEnabled(THEORY_UF
)) {
1516 Trace("smt") << "because strings are enabled, also enabling UF" << endl
;
1517 log
.enableTheory(THEORY_UF
);
1519 if(!d_logic
.isTheoryEnabled(THEORY_ARITH
) || d_logic
.isDifferenceLogic() || !d_logic
.areIntegersUsed()) {
1520 Trace("smt") << "because strings are enabled, also enabling linear integer arithmetic" << endl
;
1521 log
.enableTheory(THEORY_ARITH
);
1522 log
.enableIntegers();
1523 log
.arithOnlyLinear();
1528 if(d_logic
.isTheoryEnabled(THEORY_ARRAYS
) || d_logic
.isTheoryEnabled(THEORY_DATATYPES
) || d_logic
.isTheoryEnabled(THEORY_SETS
)) {
1529 if(!d_logic
.isTheoryEnabled(THEORY_UF
)) {
1530 LogicInfo
log(d_logic
.getUnlockedCopy());
1531 Trace("smt") << "because a theory that permits Boolean terms is enabled, also enabling UF" << endl
;
1532 log
.enableTheory(THEORY_UF
);
1538 // by default, symmetry breaker is on only for QF_UF
1539 if(! options::ufSymmetryBreaker
.wasSetByUser()) {
1540 bool qf_uf
= d_logic
.isPure(THEORY_UF
) && !d_logic
.isQuantified() && !options::proof();
1541 Trace("smt") << "setting uf symmetry breaker to " << qf_uf
<< endl
;
1542 options::ufSymmetryBreaker
.set(qf_uf
);
1544 // by default, nonclausal simplification is off for QF_SAT
1545 if(! options::simplificationMode
.wasSetByUser()) {
1546 bool qf_sat
= d_logic
.isPure(THEORY_BOOL
) && !d_logic
.isQuantified();
1547 Trace("smt") << "setting simplification mode to <" << d_logic
.getLogicString() << "> " << (!qf_sat
) << endl
;
1548 //simplification=none works better for SMT LIB benchmarks with quantifiers, not others
1549 //options::simplificationMode.set(qf_sat || quantifiers ? SIMPLIFICATION_MODE_NONE : SIMPLIFICATION_MODE_BATCH);
1550 options::simplificationMode
.set(qf_sat
? SIMPLIFICATION_MODE_NONE
: SIMPLIFICATION_MODE_BATCH
);
1553 // If in arrays, set the UF handler to arrays
1554 if(d_logic
.isTheoryEnabled(THEORY_ARRAYS
) && ( !d_logic
.isQuantified() ||
1555 (d_logic
.isQuantified() && !d_logic
.isTheoryEnabled(THEORY_UF
)))) {
1556 Theory::setUninterpretedSortOwner(THEORY_ARRAYS
);
1558 Theory::setUninterpretedSortOwner(THEORY_UF
);
1561 // Turn on ite simplification for QF_LIA and QF_AUFBV
1562 // WARNING: These checks match much more than just QF_AUFBV and
1563 // QF_LIA logics. --K [2014/10/15]
1564 if(! options::doITESimp
.wasSetByUser()) {
1565 bool qf_aufbv
= !d_logic
.isQuantified() &&
1566 d_logic
.isTheoryEnabled(THEORY_ARRAYS
) &&
1567 d_logic
.isTheoryEnabled(THEORY_UF
) &&
1568 d_logic
.isTheoryEnabled(THEORY_BV
);
1569 bool qf_lia
= !d_logic
.isQuantified() &&
1570 d_logic
.isPure(THEORY_ARITH
) &&
1571 d_logic
.isLinear() &&
1572 !d_logic
.isDifferenceLogic() &&
1573 !d_logic
.areRealsUsed();
1575 bool iteSimp
= (qf_aufbv
|| qf_lia
);
1576 Trace("smt") << "setting ite simplification to " << iteSimp
<< endl
;
1577 options::doITESimp
.set(iteSimp
);
1579 if(! options::compressItes
.wasSetByUser() ){
1580 bool qf_lia
= !d_logic
.isQuantified() &&
1581 d_logic
.isPure(THEORY_ARITH
) &&
1582 d_logic
.isLinear() &&
1583 !d_logic
.isDifferenceLogic() &&
1584 !d_logic
.areRealsUsed();
1586 bool compressIte
= qf_lia
;
1587 Trace("smt") << "setting ite compression to " << compressIte
<< endl
;
1588 options::compressItes
.set(compressIte
);
1590 if(! options::simplifyWithCareEnabled
.wasSetByUser() ){
1591 bool qf_aufbv
= !d_logic
.isQuantified() &&
1592 d_logic
.isTheoryEnabled(THEORY_ARRAYS
) &&
1593 d_logic
.isTheoryEnabled(THEORY_UF
) &&
1594 d_logic
.isTheoryEnabled(THEORY_BV
);
1596 bool withCare
= qf_aufbv
;
1597 Trace("smt") << "setting ite simplify with care to " << withCare
<< endl
;
1598 options::simplifyWithCareEnabled
.set(withCare
);
1600 // Turn off array eager index splitting for QF_AUFLIA
1601 if(! options::arraysEagerIndexSplitting
.wasSetByUser()) {
1602 if (not d_logic
.isQuantified() &&
1603 d_logic
.isTheoryEnabled(THEORY_ARRAYS
) &&
1604 d_logic
.isTheoryEnabled(THEORY_UF
) &&
1605 d_logic
.isTheoryEnabled(THEORY_ARITH
)) {
1606 Trace("smt") << "setting array eager index splitting to false" << endl
;
1607 options::arraysEagerIndexSplitting
.set(false);
1610 // Turn on model-based arrays for QF_AX (unless models are enabled)
1611 // if(! options::arraysModelBased.wasSetByUser()) {
1612 // if (not d_logic.isQuantified() &&
1613 // d_logic.isTheoryEnabled(THEORY_ARRAYS) &&
1614 // d_logic.isPure(THEORY_ARRAYS) &&
1615 // !options::produceModels() &&
1616 // !options::checkModels()) {
1617 // Trace("smt") << "turning on model-based array solver" << endl;
1618 // options::arraysModelBased.set(true);
1621 // Turn on multiple-pass non-clausal simplification for QF_AUFBV
1622 if(! options::repeatSimp
.wasSetByUser()) {
1623 bool repeatSimp
= !d_logic
.isQuantified() &&
1624 (d_logic
.isTheoryEnabled(THEORY_ARRAYS
) &&
1625 d_logic
.isTheoryEnabled(THEORY_UF
) &&
1626 d_logic
.isTheoryEnabled(THEORY_BV
)) &&
1627 !options::unsatCores();
1628 Trace("smt") << "setting repeat simplification to " << repeatSimp
<< endl
;
1629 options::repeatSimp
.set(repeatSimp
);
1631 // Turn on unconstrained simplification for QF_AUFBV
1632 if(!options::unconstrainedSimp
.wasSetByUser() ||
1633 options::incrementalSolving()) {
1634 // bool qf_sat = d_logic.isPure(THEORY_BOOL) && !d_logic.isQuantified();
1635 // bool uncSimp = false && !qf_sat && !options::incrementalSolving();
1636 bool uncSimp
= !options::incrementalSolving() &&
1637 !d_logic
.isQuantified() &&
1638 !options::produceModels() &&
1639 !options::produceAssignments() &&
1640 !options::checkModels() &&
1641 !options::unsatCores() &&
1642 (d_logic
.isTheoryEnabled(THEORY_ARRAYS
) && d_logic
.isTheoryEnabled(THEORY_BV
));
1643 Trace("smt") << "setting unconstrained simplification to " << uncSimp
<< endl
;
1644 options::unconstrainedSimp
.set(uncSimp
);
1646 // Unconstrained simp currently does *not* support model generation
1647 if (options::unconstrainedSimp
.wasSetByUser() && options::unconstrainedSimp()) {
1648 if (options::produceModels()) {
1649 if (options::produceModels
.wasSetByUser()) {
1650 throw OptionException("Cannot use unconstrained-simp with model generation.");
1652 Notice() << "SmtEngine: turning off produce-models to support unconstrainedSimp" << endl
;
1653 setOption("produce-models", SExpr("false"));
1655 if (options::produceAssignments()) {
1656 if (options::produceAssignments
.wasSetByUser()) {
1657 throw OptionException("Cannot use unconstrained-simp with model generation (produce-assignments).");
1659 Notice() << "SmtEngine: turning off produce-assignments to support unconstrainedSimp" << endl
;
1660 setOption("produce-assignments", SExpr("false"));
1662 if (options::checkModels()) {
1663 if (options::checkModels
.wasSetByUser()) {
1664 throw OptionException("Cannot use unconstrained-simp with model generation (check-models).");
1666 Notice() << "SmtEngine: turning off check-models to support unconstrainedSimp" << endl
;
1667 setOption("check-models", SExpr("false"));
1672 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER
&&
1673 options::incrementalSolving()) {
1674 if (options::incrementalSolving
.wasSetByUser()) {
1675 throw OptionException(std::string("Eager bit-blasting does not currently support incremental mode. \n\
1676 Try --bitblast=lazy"));
1678 Notice() << "SmtEngine: turning off incremental to support eager bit-blasting" << endl
;
1679 setOption("incremental", SExpr("false"));
1682 if (! options::bvEagerExplanations
.wasSetByUser() &&
1683 d_logic
.isTheoryEnabled(THEORY_ARRAYS
) &&
1684 d_logic
.isTheoryEnabled(THEORY_BV
)) {
1685 Trace("smt") << "enabling eager bit-vector explanations " << endl
;
1686 options::bvEagerExplanations
.set(true);
1689 if( !options::bitvectorEqualitySolver() ){
1690 Trace("smt") << "disabling bvLazyRewriteExtf since equality solver is disabled" << endl
;
1691 options::bvLazyRewriteExtf
.set(false);
1694 // Turn on arith rewrite equalities only for pure arithmetic
1695 if(! options::arithRewriteEq
.wasSetByUser()) {
1696 bool arithRewriteEq
= d_logic
.isPure(THEORY_ARITH
) && d_logic
.isLinear() && !d_logic
.isQuantified();
1697 Trace("smt") << "setting arith rewrite equalities " << arithRewriteEq
<< endl
;
1698 options::arithRewriteEq
.set(arithRewriteEq
);
1700 if(! options::arithHeuristicPivots
.wasSetByUser()) {
1701 int16_t heuristicPivots
= 5;
1702 if(d_logic
.isPure(THEORY_ARITH
) && !d_logic
.isQuantified()) {
1703 if(d_logic
.isDifferenceLogic()) {
1704 heuristicPivots
= -1;
1705 } else if(!d_logic
.areIntegersUsed()) {
1706 heuristicPivots
= 0;
1709 Trace("smt") << "setting arithHeuristicPivots " << heuristicPivots
<< endl
;
1710 options::arithHeuristicPivots
.set(heuristicPivots
);
1712 if(! options::arithPivotThreshold
.wasSetByUser()){
1713 uint16_t pivotThreshold
= 2;
1714 if(d_logic
.isPure(THEORY_ARITH
) && !d_logic
.isQuantified()){
1715 if(d_logic
.isDifferenceLogic()){
1716 pivotThreshold
= 16;
1719 Trace("smt") << "setting arith arithPivotThreshold " << pivotThreshold
<< endl
;
1720 options::arithPivotThreshold
.set(pivotThreshold
);
1722 if(! options::arithStandardCheckVarOrderPivots
.wasSetByUser()){
1723 int16_t varOrderPivots
= -1;
1724 if(d_logic
.isPure(THEORY_ARITH
) && !d_logic
.isQuantified()){
1725 varOrderPivots
= 200;
1727 Trace("smt") << "setting arithStandardCheckVarOrderPivots " << varOrderPivots
<< endl
;
1728 options::arithStandardCheckVarOrderPivots
.set(varOrderPivots
);
1730 // Turn off early theory preprocessing if arithRewriteEq is on
1731 if (options::arithRewriteEq()) {
1732 d_earlyTheoryPP
= false;
1734 if (d_logic
.isPure(THEORY_ARITH
) && !d_logic
.areRealsUsed())
1736 if (!options::nlExtTangentPlanesInterleave
.wasSetByUser())
1738 Trace("smt") << "setting nlExtTangentPlanesInterleave to true" << endl
;
1739 options::nlExtTangentPlanesInterleave
.set(true);
1743 // Set decision mode based on logic (if not set by user)
1744 if(!options::decisionMode
.wasSetByUser()) {
1745 decision::DecisionMode decMode
=
1747 d_logic
.hasEverything() ? decision::DECISION_STRATEGY_JUSTIFICATION
:
1749 (not d_logic
.isQuantified() &&
1750 d_logic
.isPure(THEORY_BV
)
1752 // QF_AUFBV or QF_ABV or QF_UFBV
1753 (not d_logic
.isQuantified() &&
1754 (d_logic
.isTheoryEnabled(THEORY_ARRAYS
) ||
1755 d_logic
.isTheoryEnabled(THEORY_UF
)) &&
1756 d_logic
.isTheoryEnabled(THEORY_BV
)
1758 // QF_AUFLIA (and may be ends up enabling QF_AUFLRA?)
1759 (not d_logic
.isQuantified() &&
1760 d_logic
.isTheoryEnabled(THEORY_ARRAYS
) &&
1761 d_logic
.isTheoryEnabled(THEORY_UF
) &&
1762 d_logic
.isTheoryEnabled(THEORY_ARITH
)
1765 (not d_logic
.isQuantified() &&
1766 d_logic
.isPure(THEORY_ARITH
) && d_logic
.isLinear() && !d_logic
.isDifferenceLogic() && !d_logic
.areIntegersUsed()
1769 d_logic
.isQuantified() ||
1771 d_logic
.isTheoryEnabled(THEORY_STRINGS
)
1772 ? decision::DECISION_STRATEGY_JUSTIFICATION
1773 : decision::DECISION_STRATEGY_INTERNAL
1778 d_logic
.hasEverything() || d_logic
.isTheoryEnabled(THEORY_STRINGS
) ? false :
1780 (not d_logic
.isQuantified() &&
1781 d_logic
.isTheoryEnabled(THEORY_ARRAYS
) &&
1782 d_logic
.isTheoryEnabled(THEORY_UF
) &&
1783 d_logic
.isTheoryEnabled(THEORY_ARITH
)
1786 (not d_logic
.isQuantified() &&
1787 d_logic
.isPure(THEORY_ARITH
) && d_logic
.isLinear() && !d_logic
.isDifferenceLogic() && !d_logic
.areIntegersUsed()
1792 Trace("smt") << "setting decision mode to " << decMode
<< endl
;
1793 options::decisionMode
.set(decMode
);
1794 options::decisionStopOnly
.set(stoponly
);
1796 if( options::incrementalSolving() ){
1797 //disable modes not supported by incremental
1798 options::sortInference
.set( false );
1799 options::ufssFairnessMonotone
.set( false );
1800 options::quantEpr
.set( false );
1801 options::globalNegate
.set(false);
1803 if( d_logic
.hasCardinalityConstraints() ){
1804 //must have finite model finding on
1805 options::finiteModelFind
.set( true );
1808 //if it contains a theory with non-termination, do not strictly enforce that quantifiers and theory combination must be interleaved
1809 if( d_logic
.isTheoryEnabled(THEORY_STRINGS
) || (d_logic
.isTheoryEnabled(THEORY_ARITH
) && !d_logic
.isLinear()) ){
1810 if( !options::instWhenStrictInterleave
.wasSetByUser() ){
1811 options::instWhenStrictInterleave
.set( false );
1815 //local theory extensions
1816 if( options::localTheoryExt() ){
1817 if( !options::instMaxLevel
.wasSetByUser() ){
1818 options::instMaxLevel
.set( 0 );
1821 if( options::instMaxLevel()!=-1 ){
1822 Notice() << "SmtEngine: turning off cbqi to support instMaxLevel" << endl
;
1823 options::cbqi
.set(false);
1825 //track instantiations?
1826 if( options::cbqiNestedQE() || ( options::proof() && !options::trackInstLemmas
.wasSetByUser() ) ){
1827 options::trackInstLemmas
.set( true );
1830 if( ( options::fmfBoundLazy
.wasSetByUser() && options::fmfBoundLazy() ) ||
1831 ( options::fmfBoundInt
.wasSetByUser() && options::fmfBoundInt() ) ) {
1832 options::fmfBound
.set( true );
1834 //now have determined whether fmfBoundInt is on/off
1835 //apply fmfBoundInt options
1836 if( options::fmfBound() ){
1837 //must have finite model finding on
1838 options::finiteModelFind
.set( true );
1839 if( ! options::mbqiMode
.wasSetByUser() ||
1840 ( options::mbqiMode()!=quantifiers::MBQI_NONE
&&
1841 options::mbqiMode()!=quantifiers::MBQI_FMC
&&
1842 options::mbqiMode()!=quantifiers::MBQI_FMC_INTERVAL
) ){
1843 //if bounded integers are set, use no MBQI by default
1844 options::mbqiMode
.set( quantifiers::MBQI_NONE
);
1846 if( ! options::prenexQuant
.wasSetByUser() ){
1847 options::prenexQuant
.set( quantifiers::PRENEX_QUANT_NONE
);
1850 if( options::ufHo() ){
1851 //if higher-order, then current variants of model-based instantiation cannot be used
1852 if( options::mbqiMode()!=quantifiers::MBQI_NONE
){
1853 options::mbqiMode
.set( quantifiers::MBQI_NONE
);
1856 if( options::mbqiMode()==quantifiers::MBQI_ABS
){
1857 if( !d_logic
.isPure(THEORY_UF
) ){
1858 //MBQI_ABS is only supported in pure quantified UF
1859 options::mbqiMode
.set( quantifiers::MBQI_FMC
);
1862 if( options::fmfFunWellDefinedRelevant() ){
1863 if( !options::fmfFunWellDefined
.wasSetByUser() ){
1864 options::fmfFunWellDefined
.set( true );
1867 if( options::fmfFunWellDefined() ){
1868 if( !options::finiteModelFind
.wasSetByUser() ){
1869 options::finiteModelFind
.set( true );
1873 if( options::quantEpr() ){
1874 if( !options::preSkolemQuant
.wasSetByUser() ){
1875 options::preSkolemQuant
.set( true );
1879 //now, have determined whether finite model find is on/off
1880 //apply finite model finding options
1881 if( options::finiteModelFind() ){
1882 //apply conservative quantifiers splitting
1883 if( !options::quantDynamicSplit
.wasSetByUser() ){
1884 options::quantDynamicSplit
.set( quantifiers::QUANT_DSPLIT_MODE_DEFAULT
);
1886 //do not eliminate extended arithmetic symbols from quantified formulas
1887 if( !options::elimExtArithQuant
.wasSetByUser() ){
1888 options::elimExtArithQuant
.set( false );
1890 if( !options::eMatching
.wasSetByUser() ){
1891 options::eMatching
.set( options::fmfInstEngine() );
1893 if( !options::instWhenMode
.wasSetByUser() ){
1894 //instantiate only on last call
1895 if( options::eMatching() ){
1896 options::instWhenMode
.set( quantifiers::INST_WHEN_LAST_CALL
);
1899 if( options::mbqiMode()==quantifiers::MBQI_ABS
){
1900 if( !options::preSkolemQuant
.wasSetByUser() ){
1901 options::preSkolemQuant
.set( true );
1903 if( !options::preSkolemQuantNested
.wasSetByUser() ){
1904 options::preSkolemQuantNested
.set( true );
1906 if( !options::fmfOneInstPerRound
.wasSetByUser() ){
1907 options::fmfOneInstPerRound
.set( true );
1912 //apply counterexample guided instantiation options
1913 // if we are attempting to rewrite everything to SyGuS, use ceGuidedInst
1914 if (options::sygusInference())
1916 if (!options::ceGuidedInst
.wasSetByUser())
1918 options::ceGuidedInst
.set(true);
1920 // optimization: apply preskolemization, makes it succeed more often
1921 if (!options::preSkolemQuant
.wasSetByUser())
1923 options::preSkolemQuant
.set(true);
1925 if (!options::preSkolemQuantNested
.wasSetByUser())
1927 options::preSkolemQuantNested
.set(true);
1930 if( options::cegqiSingleInvMode()!=quantifiers::CEGQI_SI_MODE_NONE
){
1931 if( !options::ceGuidedInst
.wasSetByUser() ){
1932 options::ceGuidedInst
.set( true );
1935 if( options::ceGuidedInst() ){
1936 //counterexample-guided instantiation for sygus
1937 if( !options::cegqiSingleInvMode
.wasSetByUser() ){
1938 options::cegqiSingleInvMode
.set( quantifiers::CEGQI_SI_MODE_USE
);
1940 if( !options::quantConflictFind
.wasSetByUser() ){
1941 options::quantConflictFind
.set( false );
1943 if( !options::instNoEntail
.wasSetByUser() ){
1944 options::instNoEntail
.set( false );
1946 if (options::sygusRew())
1948 options::sygusRewSynth
.set(true);
1949 options::sygusRewVerify
.set(true);
1951 if (options::sygusRewSynth() || options::sygusRewVerify())
1953 // rewrite rule synthesis implies that sygus stream must be true
1954 options::sygusStream
.set(true);
1956 if (options::sygusStream())
1958 // PBE and streaming modes are incompatible
1959 if (!options::sygusSymBreakPbe
.wasSetByUser())
1961 options::sygusSymBreakPbe
.set(false);
1963 if (!options::sygusUnifPbe
.wasSetByUser())
1965 options::sygusUnifPbe
.set(false);
1968 //do not allow partial functions
1969 if( !options::bitvectorDivByZeroConst
.wasSetByUser() ){
1970 options::bitvectorDivByZeroConst
.set( true );
1972 if( !options::dtRewriteErrorSel
.wasSetByUser() ){
1973 options::dtRewriteErrorSel
.set( true );
1976 if( !options::miniscopeQuant
.wasSetByUser() ){
1977 options::miniscopeQuant
.set( false );
1979 if( !options::miniscopeQuantFreeVar
.wasSetByUser() ){
1980 options::miniscopeQuantFreeVar
.set( false );
1983 if( !options::rewriteDivk
.wasSetByUser()) {
1984 options::rewriteDivk
.set( true );
1987 if( !options::macrosQuant
.wasSetByUser()) {
1988 options::macrosQuant
.set( false );
1990 if( !options::cbqiPreRegInst
.wasSetByUser()) {
1991 options::cbqiPreRegInst
.set( true );
1994 //counterexample-guided instantiation for non-sygus
1995 // enable if any possible quantifiers with arithmetic, datatypes or bitvectors
1996 if( d_logic
.isQuantified() &&
1997 ( ( options::decisionMode()!=decision::DECISION_STRATEGY_INTERNAL
&&
1998 ( d_logic
.isTheoryEnabled(THEORY_ARITH
) || d_logic
.isTheoryEnabled(THEORY_DATATYPES
) || d_logic
.isTheoryEnabled(THEORY_BV
) ) ) ||
1999 d_logic
.isPure(THEORY_ARITH
) || d_logic
.isPure(THEORY_BV
) ||
2000 options::cbqiAll() ) ){
2001 if( !options::cbqi
.wasSetByUser() ){
2002 options::cbqi
.set( true );
2004 // check whether we should apply full cbqi
2005 if (d_logic
.isPure(THEORY_BV
))
2007 if (!options::cbqiFullEffort
.wasSetByUser())
2009 options::cbqiFullEffort
.set(true);
2013 if( options::cbqi() ){
2015 if( !options::rewriteDivk
.wasSetByUser()) {
2016 options::rewriteDivk
.set( true );
2018 if (d_logic
.isPure(THEORY_ARITH
) || d_logic
.isPure(THEORY_BV
))
2020 options::cbqiAll
.set( false );
2021 if( !options::quantConflictFind
.wasSetByUser() ){
2022 options::quantConflictFind
.set( false );
2024 if( !options::instNoEntail
.wasSetByUser() ){
2025 options::instNoEntail
.set( false );
2027 if( !options::instWhenMode
.wasSetByUser() && options::cbqiModel() ){
2028 //only instantiation should happen at last call when model is avaiable
2029 options::instWhenMode
.set( quantifiers::INST_WHEN_LAST_CALL
);
2032 // only supported in pure arithmetic or pure BV
2033 options::cbqiNestedQE
.set(false);
2036 if (options::cbqiNestedQE()
2037 || options::decisionMode() == decision::DECISION_STRATEGY_INTERNAL
)
2039 // only complete with prenex = disj_normal or normal
2040 if (options::prenexQuant() <= quantifiers::PRENEX_QUANT_DISJ_NORMAL
)
2042 options::prenexQuant
.set(quantifiers::PRENEX_QUANT_DISJ_NORMAL
);
2045 else if (options::globalNegate())
2047 if (!options::prenexQuant
.wasSetByUser())
2049 options::prenexQuant
.set(quantifiers::PRENEX_QUANT_NONE
);
2053 //implied options...
2054 if( options::strictTriggers() ){
2055 if( !options::userPatternsQuant
.wasSetByUser() ){
2056 options::userPatternsQuant
.set( quantifiers::USER_PAT_MODE_TRUST
);
2059 if( options::qcfMode
.wasSetByUser() || options::qcfTConstraint() ){
2060 options::quantConflictFind
.set( true );
2062 if( options::cbqiNestedQE() ){
2063 options::prenexQuantUser
.set( true );
2064 if( !options::preSkolemQuant
.wasSetByUser() ){
2065 options::preSkolemQuant
.set( true );
2068 //for induction techniques
2069 if( options::quantInduction() ){
2070 if( !options::dtStcInduction
.wasSetByUser() ){
2071 options::dtStcInduction
.set( true );
2073 if( !options::intWfInduction
.wasSetByUser() ){
2074 options::intWfInduction
.set( true );
2077 if( options::dtStcInduction() ){
2078 //try to remove ITEs from quantified formulas
2079 if( !options::iteDtTesterSplitQuant
.wasSetByUser() ){
2080 options::iteDtTesterSplitQuant
.set( true );
2082 if( !options::iteLiftQuant
.wasSetByUser() ){
2083 options::iteLiftQuant
.set( quantifiers::ITE_LIFT_QUANT_MODE_ALL
);
2086 if( options::intWfInduction() ){
2087 if( !options::purifyTriggers
.wasSetByUser() ){
2088 options::purifyTriggers
.set( true );
2091 if( options::conjectureNoFilter() ){
2092 if( !options::conjectureFilterActiveTerms
.wasSetByUser() ){
2093 options::conjectureFilterActiveTerms
.set( false );
2095 if( !options::conjectureFilterCanonical
.wasSetByUser() ){
2096 options::conjectureFilterCanonical
.set( false );
2098 if( !options::conjectureFilterModel
.wasSetByUser() ){
2099 options::conjectureFilterModel
.set( false );
2102 if( options::conjectureGenPerRound
.wasSetByUser() ){
2103 if( options::conjectureGenPerRound()>0 ){
2104 options::conjectureGen
.set( true );
2106 options::conjectureGen
.set( false );
2109 //can't pre-skolemize nested quantifiers without UF theory
2110 if( !d_logic
.isTheoryEnabled(THEORY_UF
) && options::preSkolemQuant() ){
2111 if( !options::preSkolemQuantNested
.wasSetByUser() ){
2112 options::preSkolemQuantNested
.set( false );
2115 if( !d_logic
.isTheoryEnabled(THEORY_DATATYPES
) ){
2116 options::quantDynamicSplit
.set( quantifiers::QUANT_DSPLIT_MODE_NONE
);
2119 //until bugs 371,431 are fixed
2120 if( ! options::minisatUseElim
.wasSetByUser()){
2121 //AJR: cannot use minisat elim for new implementation of sets TODO: why?
2122 if( d_logic
.isTheoryEnabled(THEORY_SETS
) || d_logic
.isQuantified() || options::produceModels() || options::produceAssignments() || options::checkModels() ){
2123 options::minisatUseElim
.set( false );
2126 else if (options::minisatUseElim()) {
2127 if (options::produceModels()) {
2128 Notice() << "SmtEngine: turning off produce-models to support minisatUseElim" << endl
;
2129 setOption("produce-models", SExpr("false"));
2131 if (options::produceAssignments()) {
2132 Notice() << "SmtEngine: turning off produce-assignments to support minisatUseElim" << endl
;
2133 setOption("produce-assignments", SExpr("false"));
2135 if (options::checkModels()) {
2136 Notice() << "SmtEngine: turning off check-models to support minisatUseElim" << endl
;
2137 setOption("check-models", SExpr("false"));
2141 // For now, these array theory optimizations do not support model-building
2142 if (options::produceModels() || options::produceAssignments() || options::checkModels()) {
2143 options::arraysOptimizeLinear
.set(false);
2144 options::arraysLazyRIntro1
.set(false);
2147 // Non-linear arithmetic does not support models unless nlExt is enabled
2148 if ((d_logic
.isTheoryEnabled(THEORY_ARITH
) && !d_logic
.isLinear()
2149 && !options::nlExt())
2150 || options::globalNegate())
2152 std::string reason
=
2153 options::globalNegate() ? "--global-negate" : "nonlinear arithmetic";
2154 if (options::produceModels()) {
2155 if(options::produceModels
.wasSetByUser()) {
2156 throw OptionException(
2157 std::string("produce-model not supported with " + reason
));
2160 << "SmtEngine: turning off produce-models because unsupported for "
2162 setOption("produce-models", SExpr("false"));
2164 if (options::produceAssignments()) {
2165 if(options::produceAssignments
.wasSetByUser()) {
2166 throw OptionException(
2167 std::string("produce-assignments not supported with " + reason
));
2169 Warning() << "SmtEngine: turning off produce-assignments because "
2172 setOption("produce-assignments", SExpr("false"));
2174 if (options::checkModels()) {
2175 if(options::checkModels
.wasSetByUser()) {
2176 throw OptionException(
2177 std::string("check-models not supported with " + reason
));
2180 << "SmtEngine: turning off check-models because unsupported for "
2182 setOption("check-models", SExpr("false"));
2186 if(options::incrementalSolving() && options::proof()) {
2187 Warning() << "SmtEngine: turning off incremental solving mode (not yet supported with --proof, try --tear-down-incremental instead)" << endl
;
2188 setOption("incremental", SExpr("false"));
2191 if (options::proof())
2193 if (options::bitvectorAlgebraicSolver())
2195 if (options::bitvectorAlgebraicSolver
.wasSetByUser())
2197 throw OptionException(
2198 "--bv-algebraic-solver is not supported with proofs");
2200 Notice() << "SmtEngine: turning off bv algebraic solver to support proofs"
2202 options::bitvectorAlgebraicSolver
.set(false);
2204 if (options::bitvectorEqualitySolver())
2206 if (options::bitvectorEqualitySolver
.wasSetByUser())
2208 throw OptionException("--bv-eq-solver is not supported with proofs");
2210 Notice() << "SmtEngine: turning off bv eq solver to support proofs"
2212 options::bitvectorEqualitySolver
.set(false);
2214 if (options::bitvectorInequalitySolver())
2216 if (options::bitvectorInequalitySolver
.wasSetByUser())
2218 throw OptionException(
2219 "--bv-inequality-solver is not supported with proofs");
2221 Notice() << "SmtEngine: turning off bv ineq solver to support proofs"
2223 options::bitvectorInequalitySolver
.set(false);
2228 void SmtEngine::setProblemExtended(bool value
)
2230 d_problemExtended
= value
;
2231 if (value
) { d_assumptions
.clear(); }
2234 void SmtEngine::setInfo(const std::string
& key
, const CVC4::SExpr
& value
)
2236 SmtScope
smts(this);
2238 Trace("smt") << "SMT setInfo(" << key
<< ", " << value
<< ")" << endl
;
2240 if(Dump
.isOn("benchmark")) {
2241 if(key
== "status") {
2242 string s
= value
.getValue();
2243 BenchmarkStatus status
=
2244 (s
== "sat") ? SMT_SATISFIABLE
:
2245 ((s
== "unsat") ? SMT_UNSATISFIABLE
: SMT_UNKNOWN
);
2246 Dump("benchmark") << SetBenchmarkStatusCommand(status
);
2248 Dump("benchmark") << SetInfoCommand(key
, value
);
2252 // Check for CVC4-specific info keys (prefixed with "cvc4-" or "cvc4_")
2253 if(key
.length() > 5) {
2254 string prefix
= key
.substr(0, 5);
2255 if(prefix
== "cvc4-" || prefix
== "cvc4_") {
2256 string cvc4key
= key
.substr(5);
2257 if(cvc4key
== "logic") {
2258 if(! value
.isAtom()) {
2259 throw OptionException("argument to (set-info :cvc4-logic ..) must be a string");
2261 SmtScope
smts(this);
2262 d_logic
= value
.getValue();
2266 throw UnrecognizedOptionException();
2271 // Check for standard info keys (SMT-LIB v1, SMT-LIB v2, ...)
2272 if(key
== "source" ||
2273 key
== "category" ||
2274 key
== "difficulty" ||
2278 } else if(key
== "name") {
2279 d_filename
= value
.getValue();
2281 } else if(key
== "smt-lib-version") {
2282 language::input::Language ilang
= language::input::LANG_AUTO
;
2283 if( (value
.isInteger() && value
.getIntegerValue() == Integer(2)) ||
2284 (value
.isRational() && value
.getRationalValue() == Rational(2)) ||
2285 value
.getValue() == "2" ||
2286 value
.getValue() == "2.0" ) {
2287 ilang
= language::input::LANG_SMTLIB_V2_0
;
2288 } else if( (value
.isRational() && value
.getRationalValue() == Rational(5, 2)) ||
2289 value
.getValue() == "2.5" ) {
2290 ilang
= language::input::LANG_SMTLIB_V2_5
;
2291 } else if( (value
.isRational() && value
.getRationalValue() == Rational(13, 5)) ||
2292 value
.getValue() == "2.6" ) {
2293 ilang
= language::input::LANG_SMTLIB_V2_6
;
2295 else if (value
.getValue() == "2.6.1")
2297 ilang
= language::input::LANG_SMTLIB_V2_6_1
;
2301 Warning() << "Warning: unsupported smt-lib-version: " << value
<< endl
;
2302 throw UnrecognizedOptionException();
2304 options::inputLanguage
.set(ilang
);
2305 // also update the output language
2306 if (!options::outputLanguage
.wasSetByUser())
2308 language::output::Language olang
= language::toOutputLanguage(ilang
);
2309 if (options::outputLanguage() != olang
)
2311 options::outputLanguage
.set(olang
);
2312 *options::out() << language::SetLanguage(olang
);
2316 } else if(key
== "status") {
2318 if(value
.isAtom()) {
2319 s
= value
.getValue();
2321 if(s
!= "sat" && s
!= "unsat" && s
!= "unknown") {
2322 throw OptionException("argument to (set-info :status ..) must be "
2323 "`sat' or `unsat' or `unknown'");
2325 d_status
= Result(s
, d_filename
);
2328 throw UnrecognizedOptionException();
2331 CVC4::SExpr
SmtEngine::getInfo(const std::string
& key
) const {
2333 SmtScope
smts(this);
2335 Trace("smt") << "SMT getInfo(" << key
<< ")" << endl
;
2336 if(key
== "all-statistics") {
2337 vector
<SExpr
> stats
;
2338 for(StatisticsRegistry::const_iterator i
= NodeManager::fromExprManager(d_exprManager
)->getStatisticsRegistry()->begin();
2339 i
!= NodeManager::fromExprManager(d_exprManager
)->getStatisticsRegistry()->end();
2342 v
.push_back((*i
).first
);
2343 v
.push_back((*i
).second
);
2346 for(StatisticsRegistry::const_iterator i
= d_statisticsRegistry
->begin();
2347 i
!= d_statisticsRegistry
->end();
2350 v
.push_back((*i
).first
);
2351 v
.push_back((*i
).second
);
2354 return SExpr(stats
);
2355 } else if(key
== "error-behavior") {
2356 // immediate-exit | continued-execution
2357 if( options::continuedExecution() || options::interactive() ) {
2358 return SExpr(SExpr::Keyword("continued-execution"));
2360 return SExpr(SExpr::Keyword("immediate-exit"));
2362 } else if(key
== "name") {
2363 return SExpr(Configuration::getName());
2364 } else if(key
== "version") {
2365 return SExpr(Configuration::getVersionString());
2366 } else if(key
== "authors") {
2367 return SExpr(Configuration::about());
2368 } else if(key
== "status") {
2369 // sat | unsat | unknown
2370 switch(d_status
.asSatisfiabilityResult().isSat()) {
2372 return SExpr(SExpr::Keyword("sat"));
2374 return SExpr(SExpr::Keyword("unsat"));
2376 return SExpr(SExpr::Keyword("unknown"));
2378 } else if(key
== "reason-unknown") {
2379 if(!d_status
.isNull() && d_status
.isUnknown()) {
2381 ss
<< d_status
.whyUnknown();
2382 string s
= ss
.str();
2383 transform(s
.begin(), s
.end(), s
.begin(), ::tolower
);
2384 return SExpr(SExpr::Keyword(s
));
2386 throw ModalException("Can't get-info :reason-unknown when the "
2387 "last result wasn't unknown!");
2389 } else if(key
== "assertion-stack-levels") {
2390 AlwaysAssert(d_userLevels
.size() <=
2391 std::numeric_limits
<unsigned long int>::max());
2392 return SExpr(static_cast<unsigned long int>(d_userLevels
.size()));
2393 } else if(key
== "all-options") {
2394 // get the options, like all-statistics
2395 std::vector
< std::vector
<std::string
> > current_options
=
2396 Options::current()->getOptions();
2397 return SExpr::parseListOfListOfAtoms(current_options
);
2399 throw UnrecognizedOptionException();
2403 void SmtEngine::debugCheckFormals(const std::vector
<Expr
>& formals
, Expr func
)
2405 for(std::vector
<Expr
>::const_iterator i
= formals
.begin(); i
!= formals
.end(); ++i
) {
2406 if((*i
).getKind() != kind::BOUND_VARIABLE
) {
2408 ss
<< "All formal arguments to defined functions must be BOUND_VARIABLEs, but in the\n"
2409 << "definition of function " << func
<< ", formal\n"
2410 << " " << *i
<< "\n"
2411 << "has kind " << (*i
).getKind();
2412 throw TypeCheckingException(func
, ss
.str());
2417 void SmtEngine::debugCheckFunctionBody(Expr formula
,
2418 const std::vector
<Expr
>& formals
,
2421 Type formulaType
= formula
.getType(options::typeChecking());
2422 Type funcType
= func
.getType();
2423 // We distinguish here between definitions of constants and functions,
2424 // because the type checking for them is subtly different. Perhaps we
2425 // should instead have SmtEngine::defineFunction() and
2426 // SmtEngine::defineConstant() for better clarity, although then that
2427 // doesn't match the SMT-LIBv2 standard...
2428 if(formals
.size() > 0) {
2429 Type rangeType
= FunctionType(funcType
).getRangeType();
2430 if(! formulaType
.isComparableTo(rangeType
)) {
2432 ss
<< "Type of defined function does not match its declaration\n"
2433 << "The function : " << func
<< "\n"
2434 << "Declared type : " << rangeType
<< "\n"
2435 << "The body : " << formula
<< "\n"
2436 << "Body type : " << formulaType
;
2437 throw TypeCheckingException(func
, ss
.str());
2440 if(! formulaType
.isComparableTo(funcType
)) {
2442 ss
<< "Declared type of defined constant does not match its definition\n"
2443 << "The constant : " << func
<< "\n"
2444 << "Declared type : " << funcType
<< " " << Type::getTypeNode(funcType
)->getId() << "\n"
2445 << "The definition : " << formula
<< "\n"
2446 << "Definition type: " << formulaType
<< " " << Type::getTypeNode(formulaType
)->getId();
2447 throw TypeCheckingException(func
, ss
.str());
2452 void SmtEngine::defineFunction(Expr func
,
2453 const std::vector
<Expr
>& formals
,
2456 SmtScope
smts(this);
2458 Trace("smt") << "SMT defineFunction(" << func
<< ")" << endl
;
2459 debugCheckFormals(formals
, func
);
2462 ss
<< language::SetLanguage(
2463 language::SetLanguage::getLanguage(Dump
.getStream()))
2465 DefineFunctionCommand
c(ss
.str(), func
, formals
, formula
);
2466 addToModelCommandAndDump(
2467 c
, ExprManager::VAR_FLAG_DEFINED
, true, "declarations");
2469 PROOF(if (options::checkUnsatCores()) {
2470 d_defineCommands
.push_back(c
.clone());
2474 debugCheckFunctionBody(formula
, formals
, func
);
2476 // Substitute out any abstract values in formula
2478 d_private
->substituteAbstractValues(Node::fromExpr(formula
)).toExpr();
2480 TNode funcNode
= func
.getTNode();
2481 vector
<Node
> formalsNodes
;
2482 for(vector
<Expr
>::const_iterator i
= formals
.begin(),
2483 iend
= formals
.end();
2486 formalsNodes
.push_back((*i
).getNode());
2488 TNode formNode
= form
.getTNode();
2489 DefinedFunction
def(funcNode
, formalsNodes
, formNode
);
2490 // Permit (check-sat) (define-fun ...) (get-value ...) sequences.
2491 // Otherwise, (check-sat) (get-value ((! foo :named bar))) breaks
2492 // d_haveAdditions = true;
2493 Debug("smt") << "definedFunctions insert " << funcNode
<< " " << formNode
<< endl
;
2494 d_definedFunctions
->insert(funcNode
, def
);
2497 void SmtEngine::defineFunctionsRec(
2498 const std::vector
<Expr
>& funcs
,
2499 const std::vector
<std::vector
<Expr
> >& formals
,
2500 const std::vector
<Expr
>& formulas
)
2502 SmtScope
smts(this);
2503 finalOptionsAreSet();
2505 Trace("smt") << "SMT defineFunctionsRec(...)" << endl
;
2507 if (funcs
.size() != formals
.size() && funcs
.size() != formulas
.size())
2510 ss
<< "Number of functions, formals, and function bodies passed to "
2511 "defineFunctionsRec do not match:"
2513 << " #functions : " << funcs
.size() << "\n"
2514 << " #arg lists : " << formals
.size() << "\n"
2515 << " #function bodies : " << formulas
.size() << "\n";
2516 throw ModalException(ss
.str());
2518 for (unsigned i
= 0, size
= funcs
.size(); i
< size
; i
++)
2520 // check formal argument list
2521 debugCheckFormals(formals
[i
], funcs
[i
]);
2523 debugCheckFunctionBody(formulas
[i
], formals
[i
], funcs
[i
]);
2526 if (Dump
.isOn("raw-benchmark"))
2528 Dump("raw-benchmark") << DefineFunctionRecCommand(funcs
, formals
, formulas
);
2531 ExprManager
* em
= getExprManager();
2532 for (unsigned i
= 0, size
= funcs
.size(); i
< size
; i
++)
2534 // we assert a quantified formula
2536 // make the function application
2537 if (formals
[i
].empty())
2539 // it has no arguments
2540 func_app
= funcs
[i
];
2544 std::vector
<Expr
> children
;
2545 children
.push_back(funcs
[i
]);
2546 children
.insert(children
.end(), formals
[i
].begin(), formals
[i
].end());
2547 func_app
= em
->mkExpr(kind::APPLY_UF
, children
);
2549 Expr lem
= em
->mkExpr(kind::EQUAL
, func_app
, formulas
[i
]);
2550 if (!formals
[i
].empty())
2552 // set the attribute to denote this is a function definition
2553 std::string
attr_name("fun-def");
2554 Expr aexpr
= em
->mkExpr(kind::INST_ATTRIBUTE
, func_app
);
2555 aexpr
= em
->mkExpr(kind::INST_PATTERN_LIST
, aexpr
);
2556 std::vector
<Expr
> expr_values
;
2557 std::string str_value
;
2558 setUserAttribute(attr_name
, func_app
, expr_values
, str_value
);
2559 // make the quantified formula
2560 Expr boundVars
= em
->mkExpr(kind::BOUND_VAR_LIST
, formals
[i
]);
2561 lem
= em
->mkExpr(kind::FORALL
, boundVars
, lem
, aexpr
);
2563 // assert the quantified formula
2564 // notice we don't call assertFormula directly, since this would
2565 // duplicate the output on raw-benchmark.
2566 Expr e
= d_private
->substituteAbstractValues(Node::fromExpr(lem
)).toExpr();
2567 if (d_assertionList
!= NULL
)
2569 d_assertionList
->push_back(e
);
2571 d_private
->addFormula(e
.getNode(), false);
2575 void SmtEngine::defineFunctionRec(Expr func
,
2576 const std::vector
<Expr
>& formals
,
2579 std::vector
<Expr
> funcs
;
2580 funcs
.push_back(func
);
2581 std::vector
<std::vector
<Expr
> > formals_multi
;
2582 formals_multi
.push_back(formals
);
2583 std::vector
<Expr
> formulas
;
2584 formulas
.push_back(formula
);
2585 defineFunctionsRec(funcs
, formals_multi
, formulas
);
2588 bool SmtEngine::isDefinedFunction( Expr func
){
2589 Node nf
= Node::fromExpr( func
);
2590 Debug("smt") << "isDefined function " << nf
<< "?" << std::endl
;
2591 return d_definedFunctions
->find(nf
) != d_definedFunctions
->end();
2594 void SmtEnginePrivate::finishInit() {
2595 d_preprocessingPassContext
.reset(new PreprocessingPassContext(&d_smt
));
2596 // TODO: register passes here (this will likely change when we add support for
2597 // actually assembling preprocessing pipelines).
2598 std::unique_ptr
<BoolToBV
> boolToBv(
2599 new BoolToBV(d_preprocessingPassContext
.get()));
2600 std::unique_ptr
<BVAckermann
> bvAckermann(
2601 new BVAckermann(d_preprocessingPassContext
.get()));
2602 std::unique_ptr
<BvAbstraction
> bvAbstract(
2603 new BvAbstraction(d_preprocessingPassContext
.get()));
2604 std::unique_ptr
<BVGauss
> bvGauss(
2605 new BVGauss(d_preprocessingPassContext
.get()));
2606 std::unique_ptr
<BvIntroPow2
> bvIntroPow2(
2607 new BvIntroPow2(d_preprocessingPassContext
.get()));
2608 std::unique_ptr
<BVToBool
> bvToBool(
2609 new BVToBool(d_preprocessingPassContext
.get()));
2610 std::unique_ptr
<IntToBV
> intToBV(
2611 new IntToBV(d_preprocessingPassContext
.get()));
2612 std::unique_ptr
<PseudoBooleanProcessor
> pbProc(
2613 new PseudoBooleanProcessor(d_preprocessingPassContext
.get()));
2614 std::unique_ptr
<RealToInt
> realToInt(
2615 new RealToInt(d_preprocessingPassContext
.get()));
2616 std::unique_ptr
<SymBreakerPass
> sbProc(
2617 new SymBreakerPass(d_preprocessingPassContext
.get()));
2618 d_preprocessingPassRegistry
.registerPass("bool-to-bv", std::move(boolToBv
));
2619 d_preprocessingPassRegistry
.registerPass("bv-abstraction",
2620 std::move(bvAbstract
));
2621 d_preprocessingPassRegistry
.registerPass("bv-ackermann",
2622 std::move(bvAckermann
));
2623 d_preprocessingPassRegistry
.registerPass("bv-gauss", std::move(bvGauss
));
2624 d_preprocessingPassRegistry
.registerPass("bv-intro-pow2",
2625 std::move(bvIntroPow2
));
2626 d_preprocessingPassRegistry
.registerPass("bv-to-bool", std::move(bvToBool
));
2627 d_preprocessingPassRegistry
.registerPass("int-to-bv", std::move(intToBV
));
2628 d_preprocessingPassRegistry
.registerPass("pseudo-boolean-processor",
2630 d_preprocessingPassRegistry
.registerPass("real-to-int", std::move(realToInt
));
2631 d_preprocessingPassRegistry
.registerPass("sym-break", std::move(sbProc
));
2634 Node
SmtEnginePrivate::expandDefinitions(TNode n
, unordered_map
<Node
, Node
, NodeHashFunction
>& cache
, bool expandOnly
)
2636 stack
< triple
<Node
, Node
, bool> > worklist
;
2638 worklist
.push(make_triple(Node(n
), Node(n
), false));
2639 // The worklist is made of triples, each is input / original node then the output / rewritten node
2640 // and finally a flag tracking whether the children have been explored (i.e. if this is a downward
2644 spendResource(options::preprocessStep());
2645 n
= worklist
.top().first
; // n is the input / original
2646 Node node
= worklist
.top().second
; // node is the output / result
2647 bool childrenPushed
= worklist
.top().third
;
2650 // Working downwards
2651 if(!childrenPushed
) {
2652 Kind k
= n
.getKind();
2654 // we can short circuit (variable) leaves
2656 SmtEngine::DefinedFunctionMap::const_iterator i
= d_smt
.d_definedFunctions
->find(n
);
2657 if(i
!= d_smt
.d_definedFunctions
->end()) {
2658 // replacement must be closed
2659 if((*i
).second
.getFormals().size() > 0) {
2660 result
.push(d_smt
.d_nodeManager
->mkNode(kind::LAMBDA
, d_smt
.d_nodeManager
->mkNode(kind::BOUND_VAR_LIST
, (*i
).second
.getFormals()), (*i
).second
.getFormula()));
2663 // don't bother putting in the cache
2664 result
.push((*i
).second
.getFormula());
2667 // don't bother putting in the cache
2672 // maybe it's in the cache
2673 unordered_map
<Node
, Node
, NodeHashFunction
>::iterator cacheHit
= cache
.find(n
);
2674 if(cacheHit
!= cache
.end()) {
2675 TNode ret
= (*cacheHit
).second
;
2676 result
.push(ret
.isNull() ? n
: ret
);
2680 // otherwise expand it
2681 bool doExpand
= k
== kind::APPLY
;
2683 if( options::macrosQuant() ){
2684 //expand if we have inferred an operator corresponds to a defined function
2685 doExpand
= k
==kind::APPLY_UF
&& d_smt
.isDefinedFunction( n
.getOperator().toExpr() );
2689 vector
<Node
> formals
;
2691 if( n
.getOperator().getKind() == kind::LAMBDA
){
2692 TNode op
= n
.getOperator();
2694 for( unsigned i
=0; i
<op
[0].getNumChildren(); i
++ ){
2695 formals
.push_back( op
[0][i
] );
2699 // application of a user-defined symbol
2700 TNode func
= n
.getOperator();
2701 SmtEngine::DefinedFunctionMap::const_iterator i
= d_smt
.d_definedFunctions
->find(func
);
2702 if(i
== d_smt
.d_definedFunctions
->end()) {
2703 throw TypeCheckingException(n
.toExpr(), string("Undefined function: `") + func
.toString() + "'");
2705 DefinedFunction def
= (*i
).second
;
2706 formals
= def
.getFormals();
2708 if(Debug
.isOn("expand")) {
2709 Debug("expand") << "found: " << n
<< endl
;
2710 Debug("expand") << " func: " << func
<< endl
;
2711 string name
= func
.getAttribute(expr::VarNameAttr());
2712 Debug("expand") << " : \"" << name
<< "\"" << endl
;
2714 if(Debug
.isOn("expand")) {
2715 Debug("expand") << " defn: " << def
.getFunction() << endl
2717 if(formals
.size() > 0) {
2718 copy( formals
.begin(), formals
.end() - 1,
2719 ostream_iterator
<Node
>(Debug("expand"), ", ") );
2720 Debug("expand") << formals
.back();
2722 Debug("expand") << "]" << endl
2723 << " " << def
.getFunction().getType() << endl
2724 << " " << def
.getFormula() << endl
;
2727 fm
= def
.getFormula();
2730 Node instance
= fm
.substitute(formals
.begin(),
2733 n
.begin() + formals
.size());
2734 Debug("expand") << "made : " << instance
<< endl
;
2736 Node expanded
= expandDefinitions(instance
, cache
, expandOnly
);
2737 cache
[n
] = (n
== expanded
? Node::null() : expanded
);
2738 result
.push(expanded
);
2741 } else if(! expandOnly
) {
2742 // do not do any theory stuff if expandOnly is true
2744 theory::Theory
* t
= d_smt
.d_theoryEngine
->theoryOf(node
);
2747 LogicRequest
req(d_smt
);
2748 node
= t
->expandDefinition(req
, n
);
2751 // the partial functions can fall through, in which case we still
2752 // consider their children
2753 worklist
.push(make_triple(Node(n
), node
, true)); // Original and rewritten result
2755 for(size_t i
= 0; i
< node
.getNumChildren(); ++i
) {
2756 worklist
.push(make_triple(node
[i
], node
[i
], false)); // Rewrite the children of the result only
2761 // Reconstruct the node from it's (now rewritten) children on the stack
2763 Debug("expand") << "cons : " << node
<< endl
;
2764 if(node
.getNumChildren()>0) {
2765 //cout << "cons : " << node << endl;
2766 NodeBuilder
<> nb(node
.getKind());
2767 if(node
.getMetaKind() == kind::metakind::PARAMETERIZED
) {
2768 Debug("expand") << "op : " << node
.getOperator() << endl
;
2769 //cout << "op : " << node.getOperator() << endl;
2770 nb
<< node
.getOperator();
2772 for(size_t i
= 0; i
< node
.getNumChildren(); ++i
) {
2773 Assert(!result
.empty());
2774 Node expanded
= result
.top();
2776 //cout << "exchld : " << expanded << endl;
2777 Debug("expand") << "exchld : " << expanded
<< endl
;
2782 cache
[n
] = n
== node
? Node::null() : node
; // Only cache once all subterms are expanded
2785 } while(!worklist
.empty());
2787 AlwaysAssert(result
.size() == 1);
2789 return result
.top();
2792 typedef std::unordered_map
<Node
, Node
, NodeHashFunction
> NodeMap
;
2794 Node
SmtEnginePrivate::purifyNlTerms(TNode n
, NodeMap
& cache
, NodeMap
& bcache
, std::vector
< Node
>& var_eq
, bool beneathMult
) {
2796 NodeMap::iterator find
= bcache
.find(n
);
2797 if (find
!= bcache
.end()) {
2798 return (*find
).second
;
2801 NodeMap::iterator find
= cache
.find(n
);
2802 if (find
!= cache
.end()) {
2803 return (*find
).second
;
2807 if( n
.getNumChildren()>0 ){
2808 if( beneathMult
&& n
.getKind()!=kind::MULT
){
2810 ret
= NodeManager::currentNM()->mkSkolem("__purifyNl_var", n
.getType(), "Variable introduced in purifyNl pass");
2811 Node np
= purifyNlTerms( n
, cache
, bcache
, var_eq
, false );
2812 var_eq
.push_back( np
.eqNode( ret
) );
2814 bool beneathMultNew
= beneathMult
|| n
.getKind()==kind::MULT
;
2815 bool childChanged
= false;
2816 std::vector
< Node
> children
;
2817 for( unsigned i
=0; i
<n
.getNumChildren(); i
++ ){
2818 Node nc
= purifyNlTerms( n
[i
], cache
, bcache
, var_eq
, beneathMultNew
);
2819 childChanged
= childChanged
|| nc
!=n
[i
];
2820 children
.push_back( nc
);
2823 ret
= NodeManager::currentNM()->mkNode( n
.getKind(), children
);
2835 void SmtEnginePrivate::removeITEs() {
2836 d_smt
.finalOptionsAreSet();
2837 spendResource(options::preprocessStep());
2838 Trace("simplify") << "SmtEnginePrivate::removeITEs()" << endl
;
2840 // Remove all of the ITE occurrences and normalize
2841 d_iteRemover
.run(d_assertions
.ref(), d_iteSkolemMap
, true);
2842 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
2843 d_assertions
.replace(i
, Rewriter::rewrite(d_assertions
[i
]));
2847 void SmtEnginePrivate::staticLearning() {
2848 d_smt
.finalOptionsAreSet();
2849 spendResource(options::preprocessStep());
2851 TimerStat::CodeTimer
staticLearningTimer(d_smt
.d_stats
->d_staticLearningTime
);
2853 Trace("simplify") << "SmtEnginePrivate::staticLearning()" << endl
;
2855 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
2857 NodeBuilder
<> learned(kind::AND
);
2858 learned
<< d_assertions
[i
];
2859 d_smt
.d_theoryEngine
->ppStaticLearn(d_assertions
[i
], learned
);
2860 if(learned
.getNumChildren() == 1) {
2863 d_assertions
.replace(i
, learned
);
2868 // do dumping (before/after any preprocessing pass)
2869 static void dumpAssertions(const char* key
,
2870 const AssertionPipeline
& assertionList
) {
2871 if( Dump
.isOn("assertions") &&
2872 Dump
.isOn(string("assertions:") + key
) ) {
2873 // Push the simplified assertions to the dump output stream
2874 for(unsigned i
= 0; i
< assertionList
.size(); ++ i
) {
2875 TNode n
= assertionList
[i
];
2876 Dump("assertions") << AssertCommand(Expr(n
.toExpr()));
2881 // returns false if it learns a conflict
2882 bool SmtEnginePrivate::nonClausalSimplify() {
2883 spendResource(options::preprocessStep());
2884 d_smt
.finalOptionsAreSet();
2886 if(options::unsatCores() || options::fewerPreprocessingHoles()) {
2890 TimerStat::CodeTimer
nonclausalTimer(d_smt
.d_stats
->d_nonclausalSimplificationTime
);
2892 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify()" << endl
;
2893 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
2894 Trace("simplify") << "Assertion #" << i
<< " : " << d_assertions
[i
] << std::endl
;
2897 if(d_propagatorNeedsFinish
) {
2898 d_propagator
.finish();
2899 d_propagatorNeedsFinish
= false;
2901 d_propagator
.initialize();
2903 // Assert all the assertions to the propagator
2904 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
2905 << "asserting to propagator" << endl
;
2906 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
2907 Assert(Rewriter::rewrite(d_assertions
[i
]) == d_assertions
[i
]);
2908 // Don't reprocess substitutions
2909 if (d_substitutionsIndex
> 0 && i
== d_substitutionsIndex
) {
2912 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): asserting " << d_assertions
[i
] << endl
;
2913 Debug("cores") << "d_propagator assertTrue: " << d_assertions
[i
] << std::endl
;
2914 d_propagator
.assertTrue(d_assertions
[i
]);
2917 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
2918 << "propagating" << endl
;
2919 if (d_propagator
.propagate()) {
2920 // If in conflict, just return false
2921 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
2922 << "conflict in non-clausal propagation" << endl
;
2923 Node falseNode
= NodeManager::currentNM()->mkConst
<bool>(false);
2924 Assert(!options::unsatCores() && !options::fewerPreprocessingHoles());
2925 d_assertions
.clear();
2926 addFormula(falseNode
, false, false);
2927 d_propagatorNeedsFinish
= true;
2932 Trace("simplify") << "Iterate through " << d_nonClausalLearnedLiterals
.size() << " learned literals." << std::endl
;
2933 // No conflict, go through the literals and solve them
2934 SubstitutionMap
constantPropagations(d_smt
.d_context
);
2935 SubstitutionMap
newSubstitutions(d_smt
.d_context
);
2936 SubstitutionMap::iterator pos
;
2938 for(unsigned i
= 0, i_end
= d_nonClausalLearnedLiterals
.size(); i
< i_end
; ++ i
) {
2939 // Simplify the literal we learned wrt previous substitutions
2940 Node learnedLiteral
= d_nonClausalLearnedLiterals
[i
];
2941 Assert(Rewriter::rewrite(learnedLiteral
) == learnedLiteral
);
2942 Assert(d_topLevelSubstitutions
.apply(learnedLiteral
) == learnedLiteral
);
2943 Trace("simplify") << "Process learnedLiteral : " << learnedLiteral
<< std::endl
;
2944 Node learnedLiteralNew
= newSubstitutions
.apply(learnedLiteral
);
2945 if (learnedLiteral
!= learnedLiteralNew
) {
2946 learnedLiteral
= Rewriter::rewrite(learnedLiteralNew
);
2948 Trace("simplify") << "Process learnedLiteral, after newSubs : " << learnedLiteral
<< std::endl
;
2950 learnedLiteralNew
= constantPropagations
.apply(learnedLiteral
);
2951 if (learnedLiteralNew
== learnedLiteral
) {
2954 ++d_smt
.d_stats
->d_numConstantProps
;
2955 learnedLiteral
= Rewriter::rewrite(learnedLiteralNew
);
2957 Trace("simplify") << "Process learnedLiteral, after constProp : " << learnedLiteral
<< std::endl
;
2958 // It might just simplify to a constant
2959 if (learnedLiteral
.isConst()) {
2960 if (learnedLiteral
.getConst
<bool>()) {
2961 // If the learned literal simplifies to true, it's redundant
2964 // If the learned literal simplifies to false, we're in conflict
2965 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
2967 << d_nonClausalLearnedLiterals
[i
] << endl
;
2968 Assert(!options::unsatCores());
2969 d_assertions
.clear();
2970 addFormula(NodeManager::currentNM()->mkConst
<bool>(false), false, false);
2971 d_propagatorNeedsFinish
= true;
2976 // Solve it with the corresponding theory, possibly adding new
2977 // substitutions to newSubstitutions
2978 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
2979 << "solving " << learnedLiteral
<< endl
;
2981 Theory::PPAssertStatus solveStatus
=
2982 d_smt
.d_theoryEngine
->solve(learnedLiteral
, newSubstitutions
);
2984 switch (solveStatus
) {
2985 case Theory::PP_ASSERT_STATUS_SOLVED
: {
2986 // The literal should rewrite to true
2987 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
2988 << "solved " << learnedLiteral
<< endl
;
2989 Assert(Rewriter::rewrite(newSubstitutions
.apply(learnedLiteral
)).isConst());
2990 // vector<pair<Node, Node> > equations;
2991 // constantPropagations.simplifyLHS(d_topLevelSubstitutions, equations, true);
2992 // if (equations.empty()) {
2995 // Assert(equations[0].first.isConst() && equations[0].second.isConst() && equations[0].first != equations[0].second);
2996 // else fall through
2999 case Theory::PP_ASSERT_STATUS_CONFLICT
:
3000 // If in conflict, we return false
3001 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
3002 << "conflict while solving "
3003 << learnedLiteral
<< endl
;
3004 Assert(!options::unsatCores());
3005 d_assertions
.clear();
3006 addFormula(NodeManager::currentNM()->mkConst
<bool>(false), false, false);
3007 d_propagatorNeedsFinish
= true;
3010 if (d_doConstantProp
&& learnedLiteral
.getKind() == kind::EQUAL
&& (learnedLiteral
[0].isConst() || learnedLiteral
[1].isConst())) {
3011 // constant propagation
3014 if (learnedLiteral
[0].isConst()) {
3015 t
= learnedLiteral
[1];
3016 c
= learnedLiteral
[0];
3019 t
= learnedLiteral
[0];
3020 c
= learnedLiteral
[1];
3022 Assert(!t
.isConst());
3023 Assert(constantPropagations
.apply(t
) == t
);
3024 Assert(d_topLevelSubstitutions
.apply(t
) == t
);
3025 Assert(newSubstitutions
.apply(t
) == t
);
3026 constantPropagations
.addSubstitution(t
, c
);
3027 // vector<pair<Node,Node> > equations;
3028 // constantPropagations.simplifyLHS(t, c, equations, true);
3029 // if (!equations.empty()) {
3030 // Assert(equations[0].first.isConst() && equations[0].second.isConst() && equations[0].first != equations[0].second);
3031 // d_assertions.clear();
3032 // addFormula(NodeManager::currentNM()->mkConst<bool>(false), false, false);
3035 // d_topLevelSubstitutions.simplifyRHS(constantPropagations);
3039 d_nonClausalLearnedLiterals
[j
++] = d_nonClausalLearnedLiterals
[i
];
3045 #ifdef CVC4_ASSERTIONS
3046 // NOTE: When debugging this code, consider moving this check inside of the
3047 // loop over d_nonClausalLearnedLiterals. This check has been moved outside
3048 // because it is costly for certain inputs (see bug 508).
3050 // Check data structure invariants:
3051 // 1. for each lhs of d_topLevelSubstitutions, does not appear anywhere in rhs of d_topLevelSubstitutions or anywhere in constantPropagations
3052 // 2. each lhs of constantPropagations rewrites to itself
3053 // 3. if l -> r is a constant propagation and l is a subterm of l' with l' -> r' another constant propagation, then l'[l/r] -> r' should be a
3054 // constant propagation too
3055 // 4. each lhs of constantPropagations is different from each rhs
3056 for (pos
= newSubstitutions
.begin(); pos
!= newSubstitutions
.end(); ++pos
) {
3057 Assert((*pos
).first
.isVar());
3058 Assert(d_topLevelSubstitutions
.apply((*pos
).first
) == (*pos
).first
);
3059 Assert(d_topLevelSubstitutions
.apply((*pos
).second
) == (*pos
).second
);
3060 Assert(newSubstitutions
.apply(newSubstitutions
.apply((*pos
).second
)) == newSubstitutions
.apply((*pos
).second
));
3062 for (pos
= constantPropagations
.begin(); pos
!= constantPropagations
.end(); ++pos
) {
3063 Assert((*pos
).second
.isConst());
3064 Assert(Rewriter::rewrite((*pos
).first
) == (*pos
).first
);
3065 // Node newLeft = d_topLevelSubstitutions.apply((*pos).first);
3066 // if (newLeft != (*pos).first) {
3067 // newLeft = Rewriter::rewrite(newLeft);
3068 // Assert(newLeft == (*pos).second ||
3069 // (constantPropagations.hasSubstitution(newLeft) && constantPropagations.apply(newLeft) == (*pos).second));
3071 // newLeft = constantPropagations.apply((*pos).first);
3072 // if (newLeft != (*pos).first) {
3073 // newLeft = Rewriter::rewrite(newLeft);
3074 // Assert(newLeft == (*pos).second ||
3075 // (constantPropagations.hasSubstitution(newLeft) && constantPropagations.apply(newLeft) == (*pos).second));
3077 Assert(constantPropagations
.apply((*pos
).second
) == (*pos
).second
);
3079 #endif /* CVC4_ASSERTIONS */
3081 // Resize the learnt
3082 Trace("simplify") << "Resize non-clausal learned literals to " << j
<< std::endl
;
3083 d_nonClausalLearnedLiterals
.resize(j
);
3085 unordered_set
<TNode
, TNodeHashFunction
> s
;
3086 Trace("debugging") << "NonClausal simplify pre-preprocess\n";
3087 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
3088 Node assertion
= d_assertions
[i
];
3089 Node assertionNew
= newSubstitutions
.apply(assertion
);
3090 Trace("debugging") << "assertion = " << assertion
<< endl
;
3091 Trace("debugging") << "assertionNew = " << assertionNew
<< endl
;
3092 if (assertion
!= assertionNew
) {
3093 assertion
= Rewriter::rewrite(assertionNew
);
3094 Trace("debugging") << "rewrite(assertion) = " << assertion
<< endl
;
3096 Assert(Rewriter::rewrite(assertion
) == assertion
);
3098 assertionNew
= constantPropagations
.apply(assertion
);
3099 if (assertionNew
== assertion
) {
3102 ++d_smt
.d_stats
->d_numConstantProps
;
3103 Trace("debugging") << "assertionNew = " << assertionNew
<< endl
;
3104 assertion
= Rewriter::rewrite(assertionNew
);
3105 Trace("debugging") << "assertionNew = " << assertionNew
<< endl
;
3107 Trace("debugging") << "\n";
3108 s
.insert(assertion
);
3109 d_assertions
.replace(i
, assertion
);
3110 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
3111 << "non-clausal preprocessed: "
3112 << assertion
<< endl
;
3115 // If in incremental mode, add substitutions to the list of assertions
3116 if (d_substitutionsIndex
> 0) {
3117 NodeBuilder
<> substitutionsBuilder(kind::AND
);
3118 substitutionsBuilder
<< d_assertions
[d_substitutionsIndex
];
3119 pos
= newSubstitutions
.begin();
3120 for (; pos
!= newSubstitutions
.end(); ++pos
) {
3121 // Add back this substitution as an assertion
3122 TNode lhs
= (*pos
).first
, rhs
= newSubstitutions
.apply((*pos
).second
);
3123 Node n
= NodeManager::currentNM()->mkNode(kind::EQUAL
, lhs
, rhs
);
3124 substitutionsBuilder
<< n
;
3125 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): will notify SAT layer of substitution: " << n
<< endl
;
3127 if (substitutionsBuilder
.getNumChildren() > 1) {
3128 d_assertions
.replace(d_substitutionsIndex
,
3129 Rewriter::rewrite(Node(substitutionsBuilder
)));
3132 // If not in incremental mode, must add substitutions to model
3133 TheoryModel
* m
= d_smt
.d_theoryEngine
->getModel();
3135 for(pos
= newSubstitutions
.begin(); pos
!= newSubstitutions
.end(); ++pos
) {
3136 Node n
= (*pos
).first
;
3137 Node v
= newSubstitutions
.apply((*pos
).second
);
3138 Trace("model") << "Add substitution : " << n
<< " " << v
<< endl
;
3139 m
->addSubstitution( n
, v
);
3144 NodeBuilder
<> learnedBuilder(kind::AND
);
3145 Assert(d_realAssertionsEnd
<= d_assertions
.size());
3146 learnedBuilder
<< d_assertions
[d_realAssertionsEnd
- 1];
3148 for (unsigned i
= 0; i
< d_nonClausalLearnedLiterals
.size(); ++ i
) {
3149 Node learned
= d_nonClausalLearnedLiterals
[i
];
3150 Assert(d_topLevelSubstitutions
.apply(learned
) == learned
);
3151 Node learnedNew
= newSubstitutions
.apply(learned
);
3152 if (learned
!= learnedNew
) {
3153 learned
= Rewriter::rewrite(learnedNew
);
3155 Assert(Rewriter::rewrite(learned
) == learned
);
3157 learnedNew
= constantPropagations
.apply(learned
);
3158 if (learnedNew
== learned
) {
3161 ++d_smt
.d_stats
->d_numConstantProps
;
3162 learned
= Rewriter::rewrite(learnedNew
);
3164 if (s
.find(learned
) != s
.end()) {
3168 learnedBuilder
<< learned
;
3169 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
3170 << "non-clausal learned : "
3173 d_nonClausalLearnedLiterals
.clear();
3175 for (pos
= constantPropagations
.begin(); pos
!= constantPropagations
.end(); ++pos
) {
3176 Node cProp
= (*pos
).first
.eqNode((*pos
).second
);
3177 Assert(d_topLevelSubstitutions
.apply(cProp
) == cProp
);
3178 Node cPropNew
= newSubstitutions
.apply(cProp
);
3179 if (cProp
!= cPropNew
) {
3180 cProp
= Rewriter::rewrite(cPropNew
);
3181 Assert(Rewriter::rewrite(cProp
) == cProp
);
3183 if (s
.find(cProp
) != s
.end()) {
3187 learnedBuilder
<< cProp
;
3188 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
3189 << "non-clausal constant propagation : "
3193 // Add new substitutions to topLevelSubstitutions
3194 // Note that we don't have to keep rhs's in full solved form
3195 // because SubstitutionMap::apply does a fixed-point iteration when substituting
3196 d_topLevelSubstitutions
.addSubstitutions(newSubstitutions
);
3198 if(learnedBuilder
.getNumChildren() > 1) {
3199 d_assertions
.replace(d_realAssertionsEnd
- 1,
3200 Rewriter::rewrite(Node(learnedBuilder
)));
3203 d_propagatorNeedsFinish
= true;
3207 bool SmtEnginePrivate::simpITE() {
3208 TimerStat::CodeTimer
simpITETimer(d_smt
.d_stats
->d_simpITETime
);
3210 spendResource(options::preprocessStep());
3212 Trace("simplify") << "SmtEnginePrivate::simpITE()" << endl
;
3214 unsigned numAssertionOnEntry
= d_assertions
.size();
3215 for (unsigned i
= 0; i
< d_assertions
.size(); ++i
) {
3216 spendResource(options::preprocessStep());
3217 Node result
= d_smt
.d_theoryEngine
->ppSimpITE(d_assertions
[i
]);
3218 d_assertions
.replace(i
, result
);
3219 if(result
.isConst() && !result
.getConst
<bool>()){
3223 bool result
= d_smt
.d_theoryEngine
->donePPSimpITE(d_assertions
.ref());
3224 if(numAssertionOnEntry
< d_assertions
.size()){
3225 compressBeforeRealAssertions(numAssertionOnEntry
);
3230 void SmtEnginePrivate::compressBeforeRealAssertions(size_t before
){
3231 size_t curr
= d_assertions
.size();
3232 if(before
>= curr
||
3233 d_realAssertionsEnd
<= 0 ||
3234 d_realAssertionsEnd
>= curr
){
3239 // original: [0 ... d_realAssertionsEnd)
3241 // ites skolems [d_realAssertionsEnd, before)
3243 // added [before, curr)
3245 Assert(0 < d_realAssertionsEnd
);
3246 Assert(d_realAssertionsEnd
<= before
);
3247 Assert(before
< curr
);
3249 std::vector
<Node
> intoConjunction
;
3250 for(size_t i
= before
; i
<curr
; ++i
){
3251 intoConjunction
.push_back(d_assertions
[i
]);
3253 d_assertions
.resize(before
);
3254 size_t lastBeforeItes
= d_realAssertionsEnd
- 1;
3255 intoConjunction
.push_back(d_assertions
[lastBeforeItes
]);
3256 Node newLast
= util::NaryBuilder::mkAssoc(kind::AND
, intoConjunction
);
3257 d_assertions
.replace(lastBeforeItes
, newLast
);
3258 Assert(d_assertions
.size() == before
);
3261 void SmtEnginePrivate::unconstrainedSimp() {
3262 TimerStat::CodeTimer
unconstrainedSimpTimer(d_smt
.d_stats
->d_unconstrainedSimpTime
);
3263 spendResource(options::preprocessStep());
3264 Trace("simplify") << "SmtEnginePrivate::unconstrainedSimp()" << endl
;
3265 d_smt
.d_theoryEngine
->ppUnconstrainedSimp(d_assertions
.ref());
3268 void SmtEnginePrivate::traceBackToAssertions(const std::vector
<Node
>& nodes
, std::vector
<TNode
>& assertions
) {
3269 const booleans::CircuitPropagator::BackEdgesMap
& backEdges
= d_propagator
.getBackEdges();
3270 for(vector
<Node
>::const_iterator i
= nodes
.begin(); i
!= nodes
.end(); ++i
) {
3271 booleans::CircuitPropagator::BackEdgesMap::const_iterator j
= backEdges
.find(*i
);
3272 // term must appear in map, otherwise how did we get here?!
3273 Assert(j
!= backEdges
.end());
3274 // if term maps to empty, that means it's a top-level assertion
3275 if(!(*j
).second
.empty()) {
3276 traceBackToAssertions((*j
).second
, assertions
);
3278 assertions
.push_back(*i
);
3283 size_t SmtEnginePrivate::removeFromConjunction(Node
& n
, const std::unordered_set
<unsigned long>& toRemove
) {
3284 Assert(n
.getKind() == kind::AND
);
3285 size_t removals
= 0;
3286 for(Node::iterator j
= n
.begin(); j
!= n
.end(); ++j
) {
3287 size_t subremovals
= 0;
3289 if(toRemove
.find(sub
.getId()) != toRemove
.end() ||
3290 (sub
.getKind() == kind::AND
&& (subremovals
= removeFromConjunction(sub
, toRemove
)) > 0)) {
3291 NodeBuilder
<> b(kind::AND
);
3292 b
.append(n
.begin(), j
);
3293 if(subremovals
> 0) {
3294 removals
+= subremovals
;
3299 for(++j
; j
!= n
.end(); ++j
) {
3300 if(toRemove
.find((*j
).getId()) != toRemove
.end()) {
3302 } else if((*j
).getKind() == kind::AND
) {
3304 if((subremovals
= removeFromConjunction(sub
, toRemove
)) > 0) {
3305 removals
+= subremovals
;
3314 if(b
.getNumChildren() == 0) {
3317 } else if(b
.getNumChildren() == 1) {
3323 n
= Rewriter::rewrite(n
);
3328 Assert(removals
== 0);
3332 void SmtEnginePrivate::doMiplibTrick() {
3333 Assert(d_realAssertionsEnd
== d_assertions
.size());
3334 Assert(!options::incrementalSolving());
3336 const booleans::CircuitPropagator::BackEdgesMap
& backEdges
= d_propagator
.getBackEdges();
3337 unordered_set
<unsigned long> removeAssertions
;
3339 NodeManager
* nm
= NodeManager::currentNM();
3340 Node zero
= nm
->mkConst(Rational(0)), one
= nm
->mkConst(Rational(1));
3342 unordered_map
<TNode
, Node
, TNodeHashFunction
> intVars
;
3343 for(vector
<Node
>::const_iterator i
= d_boolVars
.begin(); i
!= d_boolVars
.end(); ++i
) {
3344 if(d_propagator
.isAssigned(*i
)) {
3345 Debug("miplib") << "ineligible: " << *i
<< " because assigned " << d_propagator
.getAssignment(*i
) << endl
;
3349 vector
<TNode
> assertions
;
3350 booleans::CircuitPropagator::BackEdgesMap::const_iterator j
= backEdges
.find(*i
);
3351 // if not in back edges map, the bool var is unconstrained, showing up in no assertions.
3352 // if maps to an empty vector, that means the bool var was asserted itself.
3353 if(j
!= backEdges
.end()) {
3354 if(!(*j
).second
.empty()) {
3355 traceBackToAssertions((*j
).second
, assertions
);
3357 assertions
.push_back(*i
);
3360 Debug("miplib") << "for " << *i
<< endl
;
3361 bool eligible
= true;
3362 map
<pair
<Node
, Node
>, uint64_t> marks
;
3363 map
<pair
<Node
, Node
>, vector
<Rational
> > coef
;
3364 map
<pair
<Node
, Node
>, vector
<Rational
> > checks
;
3365 map
<pair
<Node
, Node
>, vector
<TNode
> > asserts
;
3366 for(vector
<TNode
>::const_iterator j
= assertions
.begin(); j
!= assertions
.end(); ++j
) {
3367 Debug("miplib") << " found: " << *j
<< endl
;
3368 if((*j
).getKind() != kind::IMPLIES
) {
3370 Debug("miplib") << " -- INELIGIBLE -- (not =>)" << endl
;
3373 Node conj
= BooleanSimplification::simplify((*j
)[0]);
3374 if(conj
.getKind() == kind::AND
&& conj
.getNumChildren() > 6) {
3376 Debug("miplib") << " -- INELIGIBLE -- (N-ary /\\ too big)" << endl
;
3379 if(conj
.getKind() != kind::AND
&& !conj
.isVar() && !(conj
.getKind() == kind::NOT
&& conj
[0].isVar())) {
3381 Debug("miplib") << " -- INELIGIBLE -- (not /\\ or literal)" << endl
;
3384 if((*j
)[1].getKind() != kind::EQUAL
||
3385 !( ( (*j
)[1][0].isVar() &&
3386 (*j
)[1][1].getKind() == kind::CONST_RATIONAL
) ||
3387 ( (*j
)[1][0].getKind() == kind::CONST_RATIONAL
&&
3388 (*j
)[1][1].isVar() ) )) {
3390 Debug("miplib") << " -- INELIGIBLE -- (=> (and X X) X)" << endl
;
3393 if(conj
.getKind() == kind::AND
) {
3395 bool found_x
= false;
3396 map
<TNode
, bool> neg
;
3397 for(Node::iterator ii
= conj
.begin(); ii
!= conj
.end(); ++ii
) {
3399 posv
.push_back(*ii
);
3401 found_x
= found_x
|| *i
== *ii
;
3402 } else if((*ii
).getKind() == kind::NOT
&& (*ii
)[0].isVar()) {
3403 posv
.push_back((*ii
)[0]);
3404 neg
[(*ii
)[0]] = true;
3405 found_x
= found_x
|| *i
== (*ii
)[0];
3408 Debug("miplib") << " -- INELIGIBLE -- (non-var: " << *ii
<< ")" << endl
;
3411 if(d_propagator
.isAssigned(posv
.back())) {
3413 Debug("miplib") << " -- INELIGIBLE -- (" << posv
.back() << " asserted)" << endl
;
3422 Debug("miplib") << " --INELIGIBLE -- (couldn't find " << *i
<< " in conjunction)" << endl
;
3425 sort(posv
.begin(), posv
.end());
3426 const Node pos
= NodeManager::currentNM()->mkNode(kind::AND
, posv
);
3427 const TNode var
= ((*j
)[1][0].getKind() == kind::CONST_RATIONAL
) ? (*j
)[1][1] : (*j
)[1][0];
3428 const pair
<Node
, Node
> pos_var(pos
, var
);
3429 const Rational
& constant
= ((*j
)[1][0].getKind() == kind::CONST_RATIONAL
) ? (*j
)[1][0].getConst
<Rational
>() : (*j
)[1][1].getConst
<Rational
>();
3431 unsigned countneg
= 0, thepos
= 0;
3432 for(unsigned ii
= 0; ii
< pos
.getNumChildren(); ++ii
) {
3437 mark
|= (0x1 << ii
);
3440 if((marks
[pos_var
] & (1lu << mark
)) != 0) {
3442 Debug("miplib") << " -- INELIGIBLE -- (remarked)" << endl
;
3445 Debug("miplib") << "mark is " << mark
<< " -- " << (1lu << mark
) << endl
;
3446 marks
[pos_var
] |= (1lu << mark
);
3447 Debug("miplib") << "marks[" << pos
<< "," << var
<< "] now " << marks
[pos_var
] << endl
;
3448 if(countneg
== pos
.getNumChildren()) {
3451 Debug("miplib") << " -- INELIGIBLE -- (nonzero constant)" << endl
;
3454 } else if(countneg
== pos
.getNumChildren() - 1) {
3455 Assert(coef
[pos_var
].size() <= 6 && thepos
< 6);
3456 if(coef
[pos_var
].size() <= thepos
) {
3457 coef
[pos_var
].resize(thepos
+ 1);
3459 coef
[pos_var
][thepos
] = constant
;
3461 if(checks
[pos_var
].size() <= mark
) {
3462 checks
[pos_var
].resize(mark
+ 1);
3464 checks
[pos_var
][mark
] = constant
;
3466 asserts
[pos_var
].push_back(*j
);
3469 if(x
!= *i
&& x
!= (*i
).notNode()) {
3471 Debug("miplib") << " -- INELIGIBLE -- (x not present where I expect it)" << endl
;
3474 const bool xneg
= (x
.getKind() == kind::NOT
);
3475 x
= xneg
? x
[0] : x
;
3476 Debug("miplib") << " x:" << x
<< " " << xneg
<< endl
;
3477 const TNode var
= ((*j
)[1][0].getKind() == kind::CONST_RATIONAL
) ? (*j
)[1][1] : (*j
)[1][0];
3478 const pair
<Node
, Node
> x_var(x
, var
);
3479 const Rational
& constant
= ((*j
)[1][0].getKind() == kind::CONST_RATIONAL
) ? (*j
)[1][0].getConst
<Rational
>() : (*j
)[1][1].getConst
<Rational
>();
3480 unsigned mark
= (xneg
? 0 : 1);
3481 if((marks
[x_var
] & (1u << mark
)) != 0) {
3483 Debug("miplib") << " -- INELIGIBLE -- (remarked)" << endl
;
3486 marks
[x_var
] |= (1u << mark
);
3490 Debug("miplib") << " -- INELIGIBLE -- (nonzero constant)" << endl
;
3494 Assert(coef
[x_var
].size() <= 6);
3495 coef
[x_var
].resize(6);
3496 coef
[x_var
][0] = constant
;
3498 asserts
[x_var
].push_back(*j
);
3502 for(map
<pair
<Node
, Node
>, uint64_t>::const_iterator j
= marks
.begin(); j
!= marks
.end(); ++j
) {
3503 const TNode pos
= (*j
).first
.first
;
3504 const TNode var
= (*j
).first
.second
;
3505 const pair
<Node
, Node
>& pos_var
= (*j
).first
;
3506 const uint64_t mark
= (*j
).second
;
3507 const unsigned numVars
= pos
.getKind() == kind::AND
? pos
.getNumChildren() : 1;
3508 uint64_t expected
= (uint64_t(1) << (1 << numVars
)) - 1;
3509 expected
= (expected
== 0) ? -1 : expected
; // fix for overflow
3510 Debug("miplib") << "[" << pos
<< "] => " << hex
<< mark
<< " expect " << expected
<< dec
<< endl
;
3511 Assert(pos
.getKind() == kind::AND
|| pos
.isVar());
3512 if(mark
!= expected
) {
3513 Debug("miplib") << " -- INELIGIBLE " << pos
<< " -- (insufficiently marked, got " << mark
<< " for " << numVars
<< " vars, expected " << expected
<< endl
;
3515 if(mark
!= 3) { // exclude single-var case; nothing to check there
3516 uint64_t sz
= (uint64_t(1) << checks
[pos_var
].size()) - 1;
3517 sz
= (sz
== 0) ? -1 : sz
; // fix for overflow
3518 Assert(sz
== mark
, "expected size %u == mark %u", sz
, mark
);
3519 for(size_t k
= 0; k
< checks
[pos_var
].size(); ++k
) {
3520 if((k
& (k
- 1)) != 0) {
3522 Debug("miplib") << k
<< " => " << checks
[pos_var
][k
] << endl
;
3523 for(size_t v
= 1, kk
= k
; kk
!= 0; ++v
, kk
>>= 1) {
3524 if((kk
& 0x1) == 1) {
3525 Assert(pos
.getKind() == kind::AND
);
3526 Debug("miplib") << "var " << v
<< " : " << pos
[v
- 1] << " coef:" << coef
[pos_var
][v
- 1] << endl
;
3527 sum
+= coef
[pos_var
][v
- 1];
3530 Debug("miplib") << "checkSum is " << sum
<< " input says " << checks
[pos_var
][k
] << endl
;
3531 if(sum
!= checks
[pos_var
][k
]) {
3533 Debug("miplib") << " -- INELIGIBLE " << pos
<< " -- (nonlinear combination)" << endl
;
3537 Assert(checks
[pos_var
][k
] == 0, "checks[(%s,%s)][%u] should be 0, but it's %s", pos
.toString().c_str(), var
.toString().c_str(), k
, checks
[pos_var
][k
].toString().c_str()); // we never set for single-positive-var
3542 eligible
= true; // next is still eligible
3546 Debug("miplib") << " -- ELIGIBLE " << *i
<< " , " << pos
<< " --" << endl
;
3547 vector
<Node
> newVars
;
3548 expr::NodeSelfIterator ii
, iiend
;
3549 if(pos
.getKind() == kind::AND
) {
3553 ii
= expr::NodeSelfIterator::self(pos
);
3554 iiend
= expr::NodeSelfIterator::selfEnd(pos
);
3556 for(; ii
!= iiend
; ++ii
) {
3557 Node
& varRef
= intVars
[*ii
];
3558 if(varRef
.isNull()) {
3560 ss
<< "mipvar_" << *ii
;
3561 Node newVar
= nm
->mkSkolem(ss
.str(), nm
->integerType(), "a variable introduced due to scrubbing a miplib encoding", NodeManager::SKOLEM_EXACT_NAME
);
3562 Node geq
= Rewriter::rewrite(nm
->mkNode(kind::GEQ
, newVar
, zero
));
3563 Node leq
= Rewriter::rewrite(nm
->mkNode(kind::LEQ
, newVar
, one
));
3564 addFormula(Rewriter::rewrite(geq
.andNode(leq
)), false, false);
3565 SubstitutionMap
nullMap(&d_fakeContext
);
3566 Theory::PPAssertStatus status CVC4_UNUSED
; // just for assertions
3567 status
= d_smt
.d_theoryEngine
->solve(geq
, nullMap
);
3568 Assert(status
== Theory::PP_ASSERT_STATUS_UNSOLVED
,
3569 "unexpected solution from arith's ppAssert()");
3570 Assert(nullMap
.empty(),
3571 "unexpected substitution from arith's ppAssert()");
3572 status
= d_smt
.d_theoryEngine
->solve(leq
, nullMap
);
3573 Assert(status
== Theory::PP_ASSERT_STATUS_UNSOLVED
,
3574 "unexpected solution from arith's ppAssert()");
3575 Assert(nullMap
.empty(),
3576 "unexpected substitution from arith's ppAssert()");
3577 d_smt
.d_theoryEngine
->getModel()->addSubstitution(*ii
, newVar
.eqNode(one
));
3578 newVars
.push_back(newVar
);
3581 newVars
.push_back(varRef
);
3583 if(!d_smt
.d_logic
.areIntegersUsed()) {
3584 d_smt
.d_logic
= d_smt
.d_logic
.getUnlockedCopy();
3585 d_smt
.d_logic
.enableIntegers();
3586 d_smt
.d_logic
.lock();
3590 if(pos
.getKind() == kind::AND
) {
3591 NodeBuilder
<> sumb(kind::PLUS
);
3592 for(size_t ii
= 0; ii
< pos
.getNumChildren(); ++ii
) {
3593 sumb
<< nm
->mkNode(kind::MULT
, nm
->mkConst(coef
[pos_var
][ii
]), newVars
[ii
]);
3597 sum
= nm
->mkNode(kind::MULT
, nm
->mkConst(coef
[pos_var
][0]), newVars
[0]);
3599 Debug("miplib") << "vars[] " << var
<< endl
3600 << " eq " << Rewriter::rewrite(sum
) << endl
;
3601 Node newAssertion
= var
.eqNode(Rewriter::rewrite(sum
));
3602 if(d_topLevelSubstitutions
.hasSubstitution(newAssertion
[0])) {
3603 //Warning() << "RE-SUBSTITUTION " << newAssertion[0] << endl;
3604 //Warning() << "REPLACE " << newAssertion[1] << endl;
3605 //Warning() << "ORIG " << d_topLevelSubstitutions.getSubstitution(newAssertion[0]) << endl;
3606 Assert(d_topLevelSubstitutions
.getSubstitution(newAssertion
[0]) == newAssertion
[1]);
3607 } else if(pos
.getNumChildren() <= options::arithMLTrickSubstitutions()) {
3608 d_topLevelSubstitutions
.addSubstitution(newAssertion
[0], newAssertion
[1]);
3609 Debug("miplib") << "addSubs: " << newAssertion
[0] << " to " << newAssertion
[1] << endl
;
3611 Debug("miplib") << "skipSubs: " << newAssertion
[0] << " to " << newAssertion
[1] << " (threshold is " << options::arithMLTrickSubstitutions() << ")" << endl
;
3613 newAssertion
= Rewriter::rewrite(newAssertion
);
3614 Debug("miplib") << " " << newAssertion
<< endl
;
3615 addFormula(newAssertion
, false, false);
3616 Debug("miplib") << " assertions to remove: " << endl
;
3617 for(vector
<TNode
>::const_iterator k
= asserts
[pos_var
].begin(), k_end
= asserts
[pos_var
].end(); k
!= k_end
; ++k
) {
3618 Debug("miplib") << " " << *k
<< endl
;
3619 removeAssertions
.insert((*k
).getId());
3625 if(!removeAssertions
.empty()) {
3626 Debug("miplib") << "SmtEnginePrivate::simplify(): scrubbing miplib encoding..." << endl
;
3627 for(size_t i
= 0; i
< d_realAssertionsEnd
; ++i
) {
3628 if(removeAssertions
.find(d_assertions
[i
].getId()) != removeAssertions
.end()) {
3629 Debug("miplib") << "SmtEnginePrivate::simplify(): - removing " << d_assertions
[i
] << endl
;
3630 d_assertions
[i
] = d_true
;
3631 ++d_smt
.d_stats
->d_numMiplibAssertionsRemoved
;
3632 } else if(d_assertions
[i
].getKind() == kind::AND
) {
3633 size_t removals
= removeFromConjunction(d_assertions
[i
], removeAssertions
);
3635 Debug("miplib") << "SmtEnginePrivate::simplify(): - reduced " << d_assertions
[i
] << endl
;
3636 Debug("miplib") << "SmtEnginePrivate::simplify(): - by " << removals
<< " conjuncts" << endl
;
3637 d_smt
.d_stats
->d_numMiplibAssertionsRemoved
+= removals
;
3640 Debug("miplib") << "had: " << d_assertions
[i
] << endl
;
3641 d_assertions
[i
] = Rewriter::rewrite(d_topLevelSubstitutions
.apply(d_assertions
[i
]));
3642 Debug("miplib") << "now: " << d_assertions
[i
] << endl
;
3645 Debug("miplib") << "SmtEnginePrivate::simplify(): miplib pass found nothing." << endl
;
3647 d_realAssertionsEnd
= d_assertions
.size();
3651 // returns false if simplification led to "false"
3652 bool SmtEnginePrivate::simplifyAssertions()
3654 spendResource(options::preprocessStep());
3655 Assert(d_smt
.d_pendingPops
== 0);
3657 ScopeCounter
depth(d_simplifyAssertionsDepth
);
3659 Trace("simplify") << "SmtEnginePrivate::simplify()" << endl
;
3661 dumpAssertions("pre-nonclausal", d_assertions
);
3663 if(options::simplificationMode() != SIMPLIFICATION_MODE_NONE
) {
3664 // Perform non-clausal simplification
3665 Chat() << "...performing nonclausal simplification..." << endl
;
3666 Trace("simplify") << "SmtEnginePrivate::simplify(): "
3667 << "performing non-clausal simplification" << endl
;
3668 bool noConflict
= nonClausalSimplify();
3673 // We piggy-back off of the BackEdgesMap in the CircuitPropagator to
3674 // do the miplib trick.
3675 if( // check that option is on
3676 options::arithMLTrick() &&
3677 // miplib rewrites aren't safe in incremental mode
3678 ! options::incrementalSolving() &&
3679 // only useful in arith
3680 d_smt
.d_logic
.isTheoryEnabled(THEORY_ARITH
) &&
3681 // we add new assertions and need this (in practice, this
3682 // restriction only disables miplib processing during
3683 // re-simplification, which we don't expect to be useful anyway)
3684 d_realAssertionsEnd
== d_assertions
.size() ) {
3685 Chat() << "...fixing miplib encodings..." << endl
;
3686 Trace("simplify") << "SmtEnginePrivate::simplify(): "
3687 << "looking for miplib pseudobooleans..." << endl
;
3689 TimerStat::CodeTimer
miplibTimer(d_smt
.d_stats
->d_miplibPassTime
);
3693 Trace("simplify") << "SmtEnginePrivate::simplify(): "
3694 << "skipping miplib pseudobooleans pass (either incrementalSolving is on, or miplib pbs are turned off)..." << endl
;
3698 dumpAssertions("post-nonclausal", d_assertions
);
3699 Trace("smt") << "POST nonClausalSimplify" << endl
;
3700 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
3702 // before ppRewrite check if only core theory for BV theory
3703 d_smt
.d_theoryEngine
->staticInitializeBVOptions(d_assertions
.ref());
3705 dumpAssertions("pre-theorypp", d_assertions
);
3707 // Theory preprocessing
3708 if (d_smt
.d_earlyTheoryPP
) {
3709 Chat() << "...doing early theory preprocessing..." << endl
;
3710 TimerStat::CodeTimer
codeTimer(d_smt
.d_stats
->d_theoryPreprocessTime
);
3711 // Call the theory preprocessors
3712 d_smt
.d_theoryEngine
->preprocessStart();
3713 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
3714 Assert(Rewriter::rewrite(d_assertions
[i
]) == d_assertions
[i
]);
3715 d_assertions
.replace(i
, d_smt
.d_theoryEngine
->preprocess(d_assertions
[i
]));
3716 Assert(Rewriter::rewrite(d_assertions
[i
]) == d_assertions
[i
]);
3720 dumpAssertions("post-theorypp", d_assertions
);
3721 Trace("smt") << "POST theoryPP" << endl
;
3722 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
3724 // ITE simplification
3725 if(options::doITESimp() &&
3726 (d_simplifyAssertionsDepth
<= 1 || options::doITESimpOnRepeat())) {
3727 Chat() << "...doing ITE simplification..." << endl
;
3728 bool noConflict
= simpITE();
3730 Chat() << "...ITE simplification found unsat..." << endl
;
3735 dumpAssertions("post-itesimp", d_assertions
);
3736 Trace("smt") << "POST iteSimp" << endl
;
3737 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
3739 // Unconstrained simplification
3740 if(options::unconstrainedSimp()) {
3741 Chat() << "...doing unconstrained simplification..." << endl
;
3742 unconstrainedSimp();
3745 dumpAssertions("post-unconstrained", d_assertions
);
3746 Trace("smt") << "POST unconstrainedSimp" << endl
;
3747 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
3749 if(options::repeatSimp() && options::simplificationMode() != SIMPLIFICATION_MODE_NONE
) {
3750 Chat() << "...doing another round of nonclausal simplification..." << endl
;
3751 Trace("simplify") << "SmtEnginePrivate::simplify(): "
3752 << " doing repeated simplification" << endl
;
3753 bool noConflict
= nonClausalSimplify();
3759 dumpAssertions("post-repeatsimp", d_assertions
);
3760 Trace("smt") << "POST repeatSimp" << endl
;
3761 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
3763 } catch(TypeCheckingExceptionPrivate
& tcep
) {
3764 // Calls to this function should have already weeded out any
3765 // typechecking exceptions via (e.g.) ensureBoolean(). But a
3766 // theory could still create a new expression that isn't
3767 // well-typed, and we don't want the C++ runtime to abort our
3768 // process without any error notice.
3770 ss
<< "A bad expression was produced. Original exception follows:\n"
3772 InternalError(ss
.str().c_str());
3777 Result
SmtEngine::check() {
3778 Assert(d_fullyInited
);
3779 Assert(d_pendingPops
== 0);
3781 Trace("smt") << "SmtEngine::check()" << endl
;
3783 ResourceManager
* resourceManager
= d_private
->getResourceManager();
3785 resourceManager
->beginCall();
3787 // Only way we can be out of resource is if cumulative budget is on
3788 if (resourceManager
->cumulativeLimitOn() &&
3789 resourceManager
->out()) {
3790 Result::UnknownExplanation why
= resourceManager
->outOfResources() ?
3791 Result::RESOURCEOUT
: Result::TIMEOUT
;
3792 return Result(Result::VALIDITY_UNKNOWN
, why
, d_filename
);
3795 // Make sure the prop layer has all of the assertions
3796 Trace("smt") << "SmtEngine::check(): processing assertions" << endl
;
3797 d_private
->processAssertions();
3798 Trace("smt") << "SmtEngine::check(): done processing assertions" << endl
;
3800 // Turn off stop only for QF_LRA
3801 // TODO: Bring up in a meeting where to put this
3802 if(options::decisionStopOnly() && !options::decisionMode
.wasSetByUser() ){
3804 (not d_logic
.isQuantified() &&
3805 d_logic
.isPure(THEORY_ARITH
) && d_logic
.isLinear() && !d_logic
.isDifferenceLogic() && !d_logic
.areIntegersUsed()
3807 if(d_private
->d_iteSkolemMap
.empty()){
3808 options::decisionStopOnly
.set(false);
3809 d_decisionEngine
->clearStrategies();
3810 Trace("smt") << "SmtEngine::check(): turning off stop only" << endl
;
3815 TimerStat::CodeTimer
solveTimer(d_stats
->d_solveTime
);
3817 Chat() << "solving..." << endl
;
3818 Trace("smt") << "SmtEngine::check(): running check" << endl
;
3819 Result result
= d_propEngine
->checkSat();
3821 resourceManager
->endCall();
3822 Trace("limit") << "SmtEngine::check(): cumulative millis " << resourceManager
->getTimeUsage()
3823 << ", resources " << resourceManager
->getResourceUsage() << endl
;
3826 return Result(result
, d_filename
);
3829 Result
SmtEngine::quickCheck() {
3830 Assert(d_fullyInited
);
3831 Trace("smt") << "SMT quickCheck()" << endl
;
3832 return Result(Result::VALIDITY_UNKNOWN
, Result::REQUIRES_FULL_CHECK
, d_filename
);
3836 void SmtEnginePrivate::collectSkolems(TNode n
, set
<TNode
>& skolemSet
, unordered_map
<Node
, bool, NodeHashFunction
>& cache
)
3838 unordered_map
<Node
, bool, NodeHashFunction
>::iterator it
;
3840 if (it
!= cache
.end()) {
3844 size_t sz
= n
.getNumChildren();
3846 IteSkolemMap::iterator it
= d_iteSkolemMap
.find(n
);
3847 if (it
!= d_iteSkolemMap
.end()) {
3848 skolemSet
.insert(n
);
3855 for (; k
< sz
; ++k
) {
3856 collectSkolems(n
[k
], skolemSet
, cache
);
3862 bool SmtEnginePrivate::checkForBadSkolems(TNode n
, TNode skolem
, unordered_map
<Node
, bool, NodeHashFunction
>& cache
)
3864 unordered_map
<Node
, bool, NodeHashFunction
>::iterator it
;
3866 if (it
!= cache
.end()) {
3867 return (*it
).second
;
3870 size_t sz
= n
.getNumChildren();
3872 IteSkolemMap::iterator it
= d_iteSkolemMap
.find(n
);
3874 if (it
!= d_iteSkolemMap
.end()) {
3875 if (!((*it
).first
< n
)) {
3884 for (; k
< sz
; ++k
) {
3885 if (checkForBadSkolems(n
[k
], skolem
, cache
)) {
3895 void SmtEnginePrivate::applySubstitutionsToAssertions() {
3896 if(!options::unsatCores()) {
3897 Chat() << "applying substitutions..." << endl
;
3898 Trace("simplify") << "SmtEnginePrivate::processAssertions(): "
3899 << "applying substitutions" << endl
;
3900 // TODO(b/1255): Substitutions in incremental mode should be managed with a
3901 // proper data structure.
3903 // When solving incrementally, all substitutions are piled into the
3904 // assertion at d_substitutionsIndex: we don't want to apply substitutions
3905 // to this assertion or information will be lost.
3906 unsigned substitutionAssertion
= d_substitutionsIndex
> 0 ? d_substitutionsIndex
: d_assertions
.size();
3907 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
3908 if (i
== substitutionAssertion
) {
3911 Trace("simplify") << "applying to " << d_assertions
[i
] << endl
;
3912 spendResource(options::preprocessStep());
3913 d_assertions
.replace(i
, Rewriter::rewrite(d_topLevelSubstitutions
.apply(d_assertions
[i
])));
3914 Trace("simplify") << " got " << d_assertions
[i
] << endl
;
3919 void SmtEnginePrivate::processAssertions() {
3920 TimerStat::CodeTimer
paTimer(d_smt
.d_stats
->d_processAssertionsTime
);
3921 spendResource(options::preprocessStep());
3922 Assert(d_smt
.d_fullyInited
);
3923 Assert(d_smt
.d_pendingPops
== 0);
3925 // Dump the assertions
3926 dumpAssertions("pre-everything", d_assertions
);
3928 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() begin" << endl
;
3929 Trace("smt") << "SmtEnginePrivate::processAssertions()" << endl
;
3931 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
3933 if (d_assertions
.size() == 0) {
3938 if (options::bvGaussElim())
3940 TimerStat::CodeTimer
gaussElimTimer(d_smt
.d_stats
->d_gaussElimTime
);
3941 d_preprocessingPassRegistry
.getPass("bv-gauss")->apply(&d_assertions
);
3944 if (d_assertionsProcessed
&& options::incrementalSolving()) {
3945 // TODO(b/1255): Substitutions in incremental mode should be managed with a
3946 // proper data structure.
3948 // Placeholder for storing substitutions
3949 d_substitutionsIndex
= d_assertions
.size();
3950 d_assertions
.push_back(NodeManager::currentNM()->mkConst
<bool>(true));
3953 // Add dummy assertion in last position - to be used as a
3954 // placeholder for any new assertions to get added
3955 d_assertions
.push_back(NodeManager::currentNM()->mkConst
<bool>(true));
3956 // any assertions added beyond realAssertionsEnd must NOT affect the
3957 // equisatisfiability
3958 d_realAssertionsEnd
= d_assertions
.size();
3960 // Assertions are NOT guaranteed to be rewritten by this point
3962 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-definition-expansion" << endl
;
3963 dumpAssertions("pre-definition-expansion", d_assertions
);
3965 Chat() << "expanding definitions..." << endl
;
3966 Trace("simplify") << "SmtEnginePrivate::simplify(): expanding definitions" << endl
;
3967 TimerStat::CodeTimer
codeTimer(d_smt
.d_stats
->d_definitionExpansionTime
);
3968 unordered_map
<Node
, Node
, NodeHashFunction
> cache
;
3969 for(unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
3970 d_assertions
.replace(i
, expandDefinitions(d_assertions
[i
], cache
));
3973 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-definition-expansion" << endl
;
3974 dumpAssertions("post-definition-expansion", d_assertions
);
3976 // save the assertions now
3979 for (unsigned i
= 0; i
< d_assertions
.size(); ++i
) {
3980 ProofManager::currentPM()->addAssertion(d_assertions
[i
].toExpr());
3984 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
3986 if (options::sygusInference())
3988 // try recast as sygus
3989 quantifiers::SygusInference si
;
3990 if (si
.simplify(d_assertions
.ref()))
3992 Trace("smt-proc") << "...converted to sygus conjecture." << std::endl
;
3993 d_smt
.d_globalNegation
= !d_smt
.d_globalNegation
;
3996 else if (options::globalNegate())
3998 // global negation of the formula
3999 quantifiers::GlobalNegate gn
;
4000 gn
.simplify(d_assertions
.ref());
4001 d_smt
.d_globalNegation
= !d_smt
.d_globalNegation
;
4004 if( options::nlExtPurify() ){
4005 unordered_map
<Node
, Node
, NodeHashFunction
> cache
;
4006 unordered_map
<Node
, Node
, NodeHashFunction
> bcache
;
4007 std::vector
< Node
> var_eq
;
4008 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
4009 d_assertions
.replace(i
, purifyNlTerms(d_assertions
[i
], cache
, bcache
, var_eq
));
4011 if( !var_eq
.empty() ){
4012 unsigned lastIndex
= d_assertions
.size()-1;
4013 var_eq
.insert( var_eq
.begin(), d_assertions
[lastIndex
] );
4014 d_assertions
.replace(lastIndex
, NodeManager::currentNM()->mkNode( kind::AND
, var_eq
) );
4018 if( options::ceGuidedInst() ){
4019 //register sygus conjecture pre-rewrite (motivated by solution reconstruction)
4020 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
4021 d_smt
.d_theoryEngine
->getQuantifiersEngine()->getCegInstantiation()->preregisterAssertion( d_assertions
[i
] );
4025 if (options::solveRealAsInt()) {
4026 d_preprocessingPassRegistry
.getPass("real-to-int")->apply(&d_assertions
);
4029 if (options::solveIntAsBV() > 0)
4031 d_preprocessingPassRegistry
.getPass("int-to-bv")->apply(&d_assertions
);
4034 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER
&&
4035 !d_smt
.d_logic
.isPure(THEORY_BV
) &&
4036 d_smt
.d_logic
.getLogicString() != "QF_UFBV" &&
4037 d_smt
.d_logic
.getLogicString() != "QF_ABV") {
4038 throw ModalException("Eager bit-blasting does not currently support theory combination. "
4039 "Note that in a QF_BV problem UF symbols can be introduced for division. "
4040 "Try --bv-div-zero-const to interpret division by zero as a constant.");
4043 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER
)
4045 d_preprocessingPassRegistry
.getPass("bv-ackermann")->apply(&d_assertions
);
4048 if (options::bvAbstraction() && !options::incrementalSolving())
4050 d_preprocessingPassRegistry
.getPass("bv-abstraction")->apply(&d_assertions
);
4053 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
4055 bool noConflict
= true;
4057 if (options::extRewPrep())
4059 theory::quantifiers::ExtendedRewriter
extr(options::extRewPrepAgg());
4060 for (unsigned i
= 0; i
< d_assertions
.size(); ++i
)
4062 Node a
= d_assertions
[i
];
4063 d_assertions
.replace(i
, extr
.extendedRewrite(a
));
4067 // Unconstrained simplification
4068 if(options::unconstrainedSimp()) {
4069 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-unconstrained-simp" << endl
;
4070 dumpAssertions("pre-unconstrained-simp", d_assertions
);
4071 Chat() << "...doing unconstrained simplification..." << endl
;
4072 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
4073 d_assertions
.replace(i
, Rewriter::rewrite(d_assertions
[i
]));
4075 unconstrainedSimp();
4076 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-unconstrained-simp" << endl
;
4077 dumpAssertions("post-unconstrained-simp", d_assertions
);
4080 if(options::bvIntroducePow2())
4082 d_preprocessingPassRegistry
.getPass("bv-intro-pow2")->apply(&d_assertions
);
4085 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-substitution" << endl
;
4086 dumpAssertions("pre-substitution", d_assertions
);
4088 if(options::unsatCores()) {
4089 // special rewriting pass for unsat cores, since many of the passes below are skipped
4090 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
4091 d_assertions
.replace(i
, Rewriter::rewrite(d_assertions
[i
]));
4094 applySubstitutionsToAssertions();
4096 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-substitution" << endl
;
4097 dumpAssertions("post-substitution", d_assertions
);
4099 // Assertions ARE guaranteed to be rewritten by this point
4100 #ifdef CVC4_ASSERTIONS
4101 for (unsigned i
= 0; i
< d_assertions
.size(); ++i
)
4103 Assert(Rewriter::rewrite(d_assertions
[i
]) == d_assertions
[i
]);
4107 // Lift bit-vectors of size 1 to bool
4108 if(options::bitvectorToBool()) {
4109 dumpAssertions("pre-bv-to-bool", d_assertions
);
4110 Chat() << "...doing bvToBool..." << endl
;
4111 d_preprocessingPassRegistry
.getPass("bv-to-bool")->apply(&d_assertions
);
4112 dumpAssertions("post-bv-to-bool", d_assertions
);
4113 Trace("smt") << "POST bvToBool" << endl
;
4115 // Convert non-top-level Booleans to bit-vectors of size 1
4116 if(options::boolToBitvector()) {
4117 dumpAssertions("pre-bool-to-bv", d_assertions
);
4118 Chat() << "...doing boolToBv..." << endl
;
4119 d_preprocessingPassRegistry
.getPass("bool-to-bv")->apply(&d_assertions
);
4120 dumpAssertions("post-bool-to-bv", d_assertions
);
4121 Trace("smt") << "POST boolToBv" << endl
;
4123 if(options::sepPreSkolemEmp()) {
4124 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
4125 Node prev
= d_assertions
[i
];
4126 Node next
= sep::TheorySepRewriter::preprocess( prev
);
4128 d_assertions
.replace( i
, Rewriter::rewrite( next
) );
4129 Trace("sep-preprocess") << "*** Preprocess sep " << prev
<< endl
;
4130 Trace("sep-preprocess") << " ...got " << d_assertions
[i
] << endl
;
4135 if( d_smt
.d_logic
.isQuantified() ){
4136 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-quant-preprocess" << endl
;
4138 dumpAssertions("pre-skolem-quant", d_assertions
);
4139 //remove rewrite rules, apply pre-skolemization to existential quantifiers
4140 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
4141 Node prev
= d_assertions
[i
];
4142 Node next
= quantifiers::QuantifiersRewriter::preprocess( prev
);
4144 d_assertions
.replace( i
, Rewriter::rewrite( next
) );
4145 Trace("quantifiers-preprocess") << "*** Pre-skolemize " << prev
<< endl
;
4146 Trace("quantifiers-preprocess") << " ...got " << d_assertions
[i
] << endl
;
4149 dumpAssertions("post-skolem-quant", d_assertions
);
4150 if( options::macrosQuant() ){
4151 //quantifiers macro expansion
4152 quantifiers::QuantifierMacros
qm( d_smt
.d_theoryEngine
->getQuantifiersEngine() );
4155 success
= qm
.simplify( d_assertions
.ref(), true );
4157 //finalize the definitions
4158 qm
.finalizeDefinitions();
4161 //fmf-fun : assume admissible functions, applying preprocessing reduction to FMF
4162 if( options::fmfFunWellDefined() ){
4163 quantifiers::FunDefFmf fdf
;
4164 Assert( d_smt
.d_fmfRecFunctionsDefined
!=NULL
);
4165 //must carry over current definitions (for incremental)
4166 for( context::CDList
<Node
>::const_iterator fit
= d_smt
.d_fmfRecFunctionsDefined
->begin();
4167 fit
!= d_smt
.d_fmfRecFunctionsDefined
->end(); ++fit
) {
4169 Assert( d_smt
.d_fmfRecFunctionsAbs
.find( f
)!=d_smt
.d_fmfRecFunctionsAbs
.end() );
4170 TypeNode ft
= d_smt
.d_fmfRecFunctionsAbs
[f
];
4171 fdf
.d_sorts
[f
] = ft
;
4172 std::map
< Node
, std::vector
< Node
> >::iterator fcit
= d_smt
.d_fmfRecFunctionsConcrete
.find( f
);
4173 Assert( fcit
!=d_smt
.d_fmfRecFunctionsConcrete
.end() );
4174 for( unsigned j
=0; j
<fcit
->second
.size(); j
++ ){
4175 fdf
.d_input_arg_inj
[f
].push_back( fcit
->second
[j
] );
4178 fdf
.simplify( d_assertions
.ref() );
4179 //must store new definitions (for incremental)
4180 for( unsigned i
=0; i
<fdf
.d_funcs
.size(); i
++ ){
4181 Node f
= fdf
.d_funcs
[i
];
4182 d_smt
.d_fmfRecFunctionsAbs
[f
] = fdf
.d_sorts
[f
];
4183 d_smt
.d_fmfRecFunctionsConcrete
[f
].clear();
4184 for( unsigned j
=0; j
<fdf
.d_input_arg_inj
[f
].size(); j
++ ){
4185 d_smt
.d_fmfRecFunctionsConcrete
[f
].push_back( fdf
.d_input_arg_inj
[f
][j
] );
4187 d_smt
.d_fmfRecFunctionsDefined
->push_back( f
);
4190 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-quant-preprocess" << endl
;
4193 if( options::sortInference() || options::ufssFairnessMonotone() ){
4194 //sort inference technique
4195 SortInference
* si
= d_smt
.d_theoryEngine
->getSortInference();
4196 si
->simplify( d_assertions
.ref(), options::sortInference(), options::ufssFairnessMonotone() );
4197 for( std::map
< Node
, Node
>::iterator it
= si
->d_model_replace_f
.begin(); it
!= si
->d_model_replace_f
.end(); ++it
){
4198 d_smt
.setPrintFuncInModel( it
->first
.toExpr(), false );
4199 d_smt
.setPrintFuncInModel( it
->second
.toExpr(), true );
4203 if( options::pbRewrites() ){
4204 d_preprocessingPassRegistry
.getPass("pseudo-boolean-processor")
4205 ->apply(&d_assertions
);
4208 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-simplify" << endl
;
4209 dumpAssertions("pre-simplify", d_assertions
);
4210 Chat() << "simplifying assertions..." << endl
;
4211 noConflict
= simplifyAssertions();
4213 ++(d_smt
.d_stats
->d_simplifiedToFalse
);
4215 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-simplify" << endl
;
4216 dumpAssertions("post-simplify", d_assertions
);
4218 if (options::symmetryBreakerExp())
4220 // apply symmetry breaking
4221 d_preprocessingPassRegistry
.getPass("sym-break")->apply(&d_assertions
);
4224 dumpAssertions("pre-static-learning", d_assertions
);
4225 if(options::doStaticLearning()) {
4226 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-static-learning" << endl
;
4227 // Perform static learning
4228 Chat() << "doing static learning..." << endl
;
4229 Trace("simplify") << "SmtEnginePrivate::simplify(): "
4230 << "performing static learning" << endl
;
4232 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-static-learning" << endl
;
4234 dumpAssertions("post-static-learning", d_assertions
);
4236 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
4239 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-ite-removal" << endl
;
4240 dumpAssertions("pre-ite-removal", d_assertions
);
4242 Chat() << "removing term ITEs..." << endl
;
4243 TimerStat::CodeTimer
codeTimer(d_smt
.d_stats
->d_iteRemovalTime
);
4244 // Remove ITEs, updating d_iteSkolemMap
4245 d_smt
.d_stats
->d_numAssertionsPre
+= d_assertions
.size();
4247 // This is needed because when solving incrementally, removeITEs may introduce
4248 // skolems that were solved for earlier and thus appear in the substitution
4250 applySubstitutionsToAssertions();
4251 d_smt
.d_stats
->d_numAssertionsPost
+= d_assertions
.size();
4253 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-ite-removal" << endl
;
4254 dumpAssertions("post-ite-removal", d_assertions
);
4256 dumpAssertions("pre-repeat-simplify", d_assertions
);
4257 if(options::repeatSimp()) {
4258 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-repeat-simplify" << endl
;
4259 Chat() << "re-simplifying assertions..." << endl
;
4260 ScopeCounter
depth(d_simplifyAssertionsDepth
);
4261 noConflict
&= simplifyAssertions();
4263 // Need to fix up assertion list to maintain invariants:
4264 // Let Sk be the set of Skolem variables introduced by ITE's. Let <_sk be the order in which these variables were introduced
4265 // during ite removal.
4266 // For each skolem variable sk, let iteExpr = iteMap(sk) be the ite expr mapped to by sk.
4268 // cache for expression traversal
4269 unordered_map
<Node
, bool, NodeHashFunction
> cache
;
4271 // First, find all skolems that appear in the substitution map - their associated iteExpr will need
4272 // to be moved to the main assertion set
4273 set
<TNode
> skolemSet
;
4274 SubstitutionMap::iterator pos
= d_topLevelSubstitutions
.begin();
4275 for (; pos
!= d_topLevelSubstitutions
.end(); ++pos
) {
4276 collectSkolems((*pos
).first
, skolemSet
, cache
);
4277 collectSkolems((*pos
).second
, skolemSet
, cache
);
4280 // We need to ensure:
4281 // 1. iteExpr has the form (ite cond (sk = t) (sk = e))
4282 // 2. if some sk' in Sk appears in cond, t, or e, then sk' <_sk sk
4283 // If either of these is violated, we must add iteExpr as a proper assertion
4284 IteSkolemMap::iterator it
= d_iteSkolemMap
.begin();
4285 IteSkolemMap::iterator iend
= d_iteSkolemMap
.end();
4286 NodeBuilder
<> builder(kind::AND
);
4287 builder
<< d_assertions
[d_realAssertionsEnd
- 1];
4288 vector
<TNode
> toErase
;
4289 for (; it
!= iend
; ++it
) {
4290 if (skolemSet
.find((*it
).first
) == skolemSet
.end()) {
4291 TNode iteExpr
= d_assertions
[(*it
).second
];
4292 if (iteExpr
.getKind() == kind::ITE
&&
4293 iteExpr
[1].getKind() == kind::EQUAL
&&
4294 iteExpr
[1][0] == (*it
).first
&&
4295 iteExpr
[2].getKind() == kind::EQUAL
&&
4296 iteExpr
[2][0] == (*it
).first
) {
4298 bool bad
= checkForBadSkolems(iteExpr
[0], (*it
).first
, cache
);
4299 bad
= bad
|| checkForBadSkolems(iteExpr
[1][1], (*it
).first
, cache
);
4300 bad
= bad
|| checkForBadSkolems(iteExpr
[2][1], (*it
).first
, cache
);
4306 // Move this iteExpr into the main assertions
4307 builder
<< d_assertions
[(*it
).second
];
4308 d_assertions
[(*it
).second
] = NodeManager::currentNM()->mkConst
<bool>(true);
4309 toErase
.push_back((*it
).first
);
4311 if(builder
.getNumChildren() > 1) {
4312 while (!toErase
.empty()) {
4313 d_iteSkolemMap
.erase(toErase
.back());
4316 d_assertions
[d_realAssertionsEnd
- 1] = Rewriter::rewrite(Node(builder
));
4318 // TODO(b/1256): For some reason this is needed for some benchmarks, such as
4319 // QF_AUFBV/dwp_formulas/try5_small_difret_functions_dwp_tac.re_node_set_remove_at.il.dwp.smt2
4321 applySubstitutionsToAssertions();
4322 // Assert(iteRewriteAssertionsEnd == d_assertions.size());
4324 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-repeat-simplify" << endl
;
4326 dumpAssertions("post-repeat-simplify", d_assertions
);
4328 dumpAssertions("pre-rewrite-apply-to-const", d_assertions
);
4329 if(options::rewriteApplyToConst()) {
4330 Chat() << "Rewriting applies to constants..." << endl
;
4331 TimerStat::CodeTimer
codeTimer(d_smt
.d_stats
->d_rewriteApplyToConstTime
);
4332 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
4333 d_assertions
[i
] = Rewriter::rewrite(rewriteApplyToConst(d_assertions
[i
]));
4336 dumpAssertions("post-rewrite-apply-to-const", d_assertions
);
4338 // begin: INVARIANT to maintain: no reordering of assertions or
4339 // introducing new ones
4340 #ifdef CVC4_ASSERTIONS
4341 unsigned iteRewriteAssertionsEnd
= d_assertions
.size();
4344 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
4346 Debug("smt") << "SmtEnginePrivate::processAssertions() POST SIMPLIFICATION" << endl
;
4347 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
4349 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-theory-preprocessing" << endl
;
4350 dumpAssertions("pre-theory-preprocessing", d_assertions
);
4352 Chat() << "theory preprocessing..." << endl
;
4353 TimerStat::CodeTimer
codeTimer(d_smt
.d_stats
->d_theoryPreprocessTime
);
4354 // Call the theory preprocessors
4355 d_smt
.d_theoryEngine
->preprocessStart();
4356 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
4357 d_assertions
.replace(i
, d_smt
.d_theoryEngine
->preprocess(d_assertions
[i
]));
4360 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-theory-preprocessing" << endl
;
4361 dumpAssertions("post-theory-preprocessing", d_assertions
);
4363 // If we are using eager bit-blasting wrap assertions in fake atom so that
4364 // everything gets bit-blasted to internal SAT solver
4365 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER
) {
4366 for (unsigned i
= 0; i
< d_assertions
.size(); ++i
) {
4367 TNode atom
= d_assertions
[i
];
4368 Node eager_atom
= NodeManager::currentNM()->mkNode(kind::BITVECTOR_EAGER_ATOM
, atom
);
4369 d_assertions
.replace(i
, eager_atom
);
4370 TheoryModel
* m
= d_smt
.d_theoryEngine
->getModel();
4371 m
->addSubstitution(eager_atom
, atom
);
4375 //notify theory engine new preprocessed assertions
4376 d_smt
.d_theoryEngine
->notifyPreprocessedAssertions( d_assertions
.ref() );
4378 // Push the formula to decision engine
4380 Chat() << "pushing to decision engine..." << endl
;
4381 Assert(iteRewriteAssertionsEnd
== d_assertions
.size());
4382 d_smt
.d_decisionEngine
->addAssertions
4383 (d_assertions
.ref(), d_realAssertionsEnd
, d_iteSkolemMap
);
4386 // end: INVARIANT to maintain: no reordering of assertions or
4387 // introducing new ones
4389 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() end" << endl
;
4390 dumpAssertions("post-everything", d_assertions
);
4392 // Push the formula to SAT
4394 Chat() << "converting to CNF..." << endl
;
4395 TimerStat::CodeTimer
codeTimer(d_smt
.d_stats
->d_cnfConversionTime
);
4396 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
4397 Chat() << "+ " << d_assertions
[i
] << std::endl
;
4398 d_smt
.d_propEngine
->assertFormula(d_assertions
[i
]);
4402 d_assertionsProcessed
= true;
4404 d_assertions
.clear();
4405 d_iteSkolemMap
.clear();
4408 void SmtEnginePrivate::addFormula(TNode n
, bool inUnsatCore
, bool inInput
)
4415 Trace("smt") << "SmtEnginePrivate::addFormula(" << n
<< "), inUnsatCore = " << inUnsatCore
<< ", inInput = " << inInput
<< endl
;
4417 // Give it to proof manager
4420 // n is an input assertion
4421 if (inUnsatCore
|| options::unsatCores() || options::dumpUnsatCores() || options::checkUnsatCores() || options::fewerPreprocessingHoles()) {
4423 ProofManager::currentPM()->addCoreAssertion(n
.toExpr());
4426 // n is the result of an unknown preprocessing step, add it to dependency map to null
4427 ProofManager::currentPM()->addDependence(n
, Node::null());
4429 // rewrite rules are by default in the unsat core because
4430 // they need to be applied until saturation
4431 if(options::unsatCores() &&
4432 n
.getKind() == kind::REWRITE_RULE
){
4433 ProofManager::currentPM()->addUnsatCore(n
.toExpr());
4437 // Add the normalized formula to the queue
4438 d_assertions
.push_back(n
);
4439 //d_assertions.push_back(Rewriter::rewrite(n));
4442 void SmtEngine::ensureBoolean(const Expr
& e
)
4444 Type type
= e
.getType(options::typeChecking());
4445 Type boolType
= d_exprManager
->booleanType();
4446 if(type
!= boolType
) {
4448 ss
<< "Expected " << boolType
<< "\n"
4449 << "The assertion : " << e
<< "\n"
4450 << "Its type : " << type
;
4451 throw TypeCheckingException(e
, ss
.str());
4455 Result
SmtEngine::checkSat(const Expr
& assumption
, bool inUnsatCore
)
4457 return checkSatisfiability(assumption
, inUnsatCore
, false);
4460 Result
SmtEngine::checkSat(const vector
<Expr
>& assumptions
, bool inUnsatCore
)
4462 return checkSatisfiability(assumptions
, inUnsatCore
, false);
4465 Result
SmtEngine::query(const Expr
& assumption
, bool inUnsatCore
)
4467 Assert(!assumption
.isNull());
4468 return checkSatisfiability(assumption
, inUnsatCore
, true);
4471 Result
SmtEngine::query(const vector
<Expr
>& assumptions
, bool inUnsatCore
)
4473 return checkSatisfiability(assumptions
, inUnsatCore
, true);
4476 Result
SmtEngine::checkSatisfiability(const Expr
& expr
,
4480 return checkSatisfiability(
4481 expr
.isNull() ? vector
<Expr
>() : vector
<Expr
>{expr
},
4486 Result
SmtEngine::checkSatisfiability(const vector
<Expr
>& assumptions
,
4492 SmtScope
smts(this);
4493 finalOptionsAreSet();
4496 Trace("smt") << "SmtEngine::" << (isQuery
? "query" : "checkSat") << "("
4497 << assumptions
<< ")" << endl
;
4499 if(d_queryMade
&& !options::incrementalSolving()) {
4500 throw ModalException("Cannot make multiple queries unless "
4501 "incremental solving is enabled "
4502 "(try --incremental)");
4505 // check to see if a postsolve() is pending
4506 if(d_needPostsolve
) {
4507 d_theoryEngine
->postsolve();
4508 d_needPostsolve
= false;
4510 // Note that a query has been made
4512 // reset global negation
4513 d_globalNegation
= false;
4515 bool didInternalPush
= false;
4517 setProblemExtended(true);
4521 size_t size
= assumptions
.size();
4524 /* Assume: not (BIGAND assumptions) */
4525 d_assumptions
.push_back(
4526 d_exprManager
->mkExpr(kind::AND
, assumptions
).notExpr());
4530 /* Assume: not expr */
4531 d_assumptions
.push_back(assumptions
[0].notExpr());
4536 /* Assume: BIGAND assumptions */
4537 d_assumptions
= assumptions
;
4540 if (!d_assumptions
.empty())
4543 didInternalPush
= true;
4546 Result
r(Result::SAT_UNKNOWN
, Result::UNKNOWN_REASON
);
4547 for (Expr e
: d_assumptions
)
4549 // Substitute out any abstract values in ex.
4550 e
= d_private
->substituteAbstractValues(Node::fromExpr(e
)).toExpr();
4551 Assert(e
.getExprManager() == d_exprManager
);
4552 // Ensure expr is type-checked at this point.
4555 /* Add assumption */
4556 if (d_assertionList
!= NULL
)
4558 d_assertionList
->push_back(e
);
4560 d_private
->addFormula(e
.getNode(), inUnsatCore
);
4563 r
= isQuery
? check().asValidityResult() : check().asSatisfiabilityResult();
4565 if ((options::solveRealAsInt() || options::solveIntAsBV() > 0)
4566 && r
.asSatisfiabilityResult().isSat() == Result::UNSAT
)
4568 r
= Result(Result::SAT_UNKNOWN
, Result::UNKNOWN_REASON
);
4570 // flipped if we did a global negation
4571 if (d_globalNegation
)
4573 Trace("smt") << "SmtEngine::process global negate " << r
<< std::endl
;
4574 if (r
.asSatisfiabilityResult().isSat() == Result::UNSAT
)
4576 r
= Result(Result::SAT
);
4578 else if (r
.asSatisfiabilityResult().isSat() == Result::SAT
)
4580 // only if satisfaction complete
4581 if (d_logic
.isPure(THEORY_ARITH
) || d_logic
.isPure(THEORY_BV
))
4583 r
= Result(Result::UNSAT
);
4587 r
= Result(Result::SAT_UNKNOWN
, Result::UNKNOWN_REASON
);
4590 Trace("smt") << "SmtEngine::global negate returned " << r
<< std::endl
;
4593 d_needPostsolve
= true;
4595 // Dump the query if requested
4596 if (Dump
.isOn("benchmark"))
4598 size_t size
= assumptions
.size();
4599 // the expr already got dumped out if assertion-dumping is on
4600 if (isQuery
&& size
== 1)
4602 Dump("benchmark") << QueryCommand(assumptions
[0]);
4606 Dump("benchmark") << CheckSatCommand();
4610 Dump("benchmark") << CheckSatAssumingCommand(d_assumptions
,
4616 if (didInternalPush
)
4621 // Remember the status
4624 setProblemExtended(false);
4626 Trace("smt") << "SmtEngine::" << (isQuery
? "query" : "checkSat") << "("
4627 << assumptions
<< ") => " << r
<< endl
;
4629 // Check that SAT results generate a model correctly.
4630 if(options::checkModels()) {
4631 // TODO (#1693) check model when unknown result?
4632 if (r
.asSatisfiabilityResult().isSat() == Result::SAT
)
4637 // Check that UNSAT results generate a proof correctly.
4638 if(options::checkProofs()) {
4639 if(r
.asSatisfiabilityResult().isSat() == Result::UNSAT
) {
4640 TimerStat::CodeTimer
checkProofTimer(d_stats
->d_checkProofTime
);
4644 // Check that UNSAT results generate an unsat core correctly.
4645 if(options::checkUnsatCores()) {
4646 if(r
.asSatisfiabilityResult().isSat() == Result::UNSAT
) {
4647 TimerStat::CodeTimer
checkUnsatCoreTimer(d_stats
->d_checkUnsatCoreTime
);
4651 // Check that synthesis solutions satisfy the conjecture
4652 if (options::checkSynthSol()
4653 && r
.asSatisfiabilityResult().isSat() == Result::UNSAT
)
4655 checkSynthSolution();
4659 } catch (UnsafeInterruptException
& e
) {
4660 AlwaysAssert(d_private
->getResourceManager()->out());
4661 Result::UnknownExplanation why
= d_private
->getResourceManager()->outOfResources() ?
4662 Result::RESOURCEOUT
: Result::TIMEOUT
;
4663 return Result(Result::SAT_UNKNOWN
, why
, d_filename
);
4667 vector
<Expr
> SmtEngine::getUnsatAssumptions(void)
4669 Trace("smt") << "SMT getUnsatAssumptions()" << endl
;
4670 SmtScope
smts(this);
4671 if (!options::unsatAssumptions())
4673 throw ModalException(
4674 "Cannot get unsat assumptions when produce-unsat-assumptions option "
4677 if (d_status
.isNull()
4678 || d_status
.asSatisfiabilityResult() != Result::UNSAT
4679 || d_problemExtended
)
4681 throw RecoverableModalException(
4682 "Cannot get unsat assumptions unless immediately preceded by "
4683 "UNSAT/VALID response.");
4685 finalOptionsAreSet();
4686 if (Dump
.isOn("benchmark"))
4688 Dump("benchmark") << GetUnsatCoreCommand();
4690 UnsatCore core
= getUnsatCore();
4692 for (const Expr
& e
: d_assumptions
)
4694 if (find(core
.begin(), core
.end(), e
) != core
.end()) { res
.push_back(e
); }
4699 Result
SmtEngine::checkSynth(const Expr
& e
)
4701 SmtScope
smts(this);
4702 Trace("smt") << "Check synth: " << e
<< std::endl
;
4703 Trace("smt-synth") << "Check synthesis conjecture: " << e
<< std::endl
;
4705 if (options::sygusQePreproc())
4707 // the following does quantifier elimination as a preprocess step
4708 // for "non-ground single invocation synthesis conjectures":
4709 // exists f. forall xy. P[ f(x), x, y ]
4710 // We run quantifier elimination:
4711 // exists y. P[ z, x, y ] ----> Q[ z, x ]
4712 // Where we replace the original conjecture with:
4713 // exists f. forall x. Q[ f(x), x ]
4714 // For more details, see Example 6 of Reynolds et al. SYNT 2017.
4715 Node conj
= Node::fromExpr(e
);
4716 if (conj
.getKind() == kind::FORALL
&& conj
[1].getKind() == kind::EXISTS
)
4718 Node conj_se
= Node::fromExpr(expandDefinitions(conj
[1][1].toExpr()));
4720 Trace("smt-synth") << "Compute single invocation for " << conj_se
<< "..."
4722 quantifiers::SingleInvocationPartition sip
;
4723 std::vector
<Node
> funcs
;
4724 funcs
.insert(funcs
.end(), conj
[0].begin(), conj
[0].end());
4725 sip
.init(funcs
, conj_se
.negate());
4726 Trace("smt-synth") << "...finished, got:" << std::endl
;
4727 sip
.debugPrint("smt-synth");
4729 if (!sip
.isPurelySingleInvocation() && sip
.isNonGroundSingleInvocation())
4731 // create new smt engine to do quantifier elimination
4732 SmtEngine
smt_qe(d_exprManager
);
4733 smt_qe
.setLogic(getLogicInfo());
4734 Trace("smt-synth") << "Property is non-ground single invocation, run "
4735 "QE to obtain single invocation."
4737 NodeManager
* nm
= NodeManager::currentNM();
4738 // partition variables
4739 std::vector
<Node
> all_vars
;
4740 sip
.getAllVariables(all_vars
);
4741 std::vector
<Node
> si_vars
;
4742 sip
.getSingleInvocationVariables(si_vars
);
4743 std::vector
<Node
> qe_vars
;
4744 std::vector
<Node
> nqe_vars
;
4745 for (unsigned i
= 0, size
= all_vars
.size(); i
< size
; i
++)
4747 Node v
= all_vars
[i
];
4748 if (std::find(si_vars
.begin(), si_vars
.end(), v
) == si_vars
.end())
4750 qe_vars
.push_back(v
);
4754 nqe_vars
.push_back(v
);
4757 std::vector
<Node
> orig
;
4758 std::vector
<Node
> subs
;
4759 // skolemize non-qe variables
4760 for (unsigned i
= 0; i
< nqe_vars
.size(); i
++)
4762 Node k
= nm
->mkSkolem("k",
4763 nqe_vars
[i
].getType(),
4764 "qe for non-ground single invocation");
4765 orig
.push_back(nqe_vars
[i
]);
4767 Trace("smt-synth") << " subs : " << nqe_vars
[i
] << " -> " << k
4770 std::vector
<Node
> funcs
;
4771 sip
.getFunctions(funcs
);
4772 for (unsigned i
= 0, size
= funcs
.size(); i
< size
; i
++)
4775 Node fi
= sip
.getFunctionInvocationFor(f
);
4776 Node fv
= sip
.getFirstOrderVariableForFunction(f
);
4777 Assert(!fi
.isNull());
4782 "qe for function in non-ground single invocation");
4784 Trace("smt-synth") << " subs : " << fi
<< " -> " << k
<< std::endl
;
4786 Node conj_se_ngsi
= sip
.getFullSpecification();
4787 Trace("smt-synth") << "Full specification is " << conj_se_ngsi
4789 Node conj_se_ngsi_subs
= conj_se_ngsi
.substitute(
4790 orig
.begin(), orig
.end(), subs
.begin(), subs
.end());
4791 Assert(!qe_vars
.empty());
4793 nm
->mkNode(kind::EXISTS
,
4794 nm
->mkNode(kind::BOUND_VAR_LIST
, qe_vars
),
4795 conj_se_ngsi_subs
.negate());
4797 Trace("smt-synth") << "Run quantifier elimination on "
4798 << conj_se_ngsi_subs
<< std::endl
;
4799 Expr qe_res
= smt_qe
.doQuantifierElimination(
4800 conj_se_ngsi_subs
.toExpr(), true, false);
4801 Trace("smt-synth") << "Result : " << qe_res
<< std::endl
;
4803 // create single invocation conjecture
4804 Node qe_res_n
= Node::fromExpr(qe_res
);
4805 qe_res_n
= qe_res_n
.substitute(
4806 subs
.begin(), subs
.end(), orig
.begin(), orig
.end());
4807 if (!nqe_vars
.empty())
4809 qe_res_n
= nm
->mkNode(kind::EXISTS
,
4810 nm
->mkNode(kind::BOUND_VAR_LIST
, nqe_vars
),
4813 Assert(conj
.getNumChildren() == 3);
4814 qe_res_n
= nm
->mkNode(kind::FORALL
, conj
[0], qe_res_n
, conj
[2]);
4815 Trace("smt-synth") << "Converted conjecture after QE : " << qe_res_n
4817 e_check
= qe_res_n
.toExpr();
4822 return checkSatisfiability( e_check
, true, false );
4825 Result
SmtEngine::assertFormula(const Expr
& ex
, bool inUnsatCore
)
4827 Assert(ex
.getExprManager() == d_exprManager
);
4828 SmtScope
smts(this);
4829 finalOptionsAreSet();
4832 Trace("smt") << "SmtEngine::assertFormula(" << ex
<< ")" << endl
;
4834 if (Dump
.isOn("raw-benchmark")) {
4835 Dump("raw-benchmark") << AssertCommand(ex
);
4838 // Substitute out any abstract values in ex
4839 Expr e
= d_private
->substituteAbstractValues(Node::fromExpr(ex
)).toExpr();
4842 if(d_assertionList
!= NULL
) {
4843 d_assertionList
->push_back(e
);
4845 d_private
->addFormula(e
.getNode(), inUnsatCore
);
4846 return quickCheck().asValidityResult();
4847 }/* SmtEngine::assertFormula() */
4849 Node
SmtEngine::postprocess(TNode node
, TypeNode expectedType
) const {
4853 Expr
SmtEngine::simplify(const Expr
& ex
)
4855 Assert(ex
.getExprManager() == d_exprManager
);
4856 SmtScope
smts(this);
4857 finalOptionsAreSet();
4859 Trace("smt") << "SMT simplify(" << ex
<< ")" << endl
;
4861 if(Dump
.isOn("benchmark")) {
4862 Dump("benchmark") << SimplifyCommand(ex
);
4865 Expr e
= d_private
->substituteAbstractValues(Node::fromExpr(ex
)).toExpr();
4866 if( options::typeChecking() ) {
4867 e
.getType(true); // ensure expr is type-checked at this point
4870 // Make sure all preprocessing is done
4871 d_private
->processAssertions();
4872 Node n
= d_private
->simplify(Node::fromExpr(e
));
4873 n
= postprocess(n
, TypeNode::fromType(e
.getType()));
4877 Expr
SmtEngine::expandDefinitions(const Expr
& ex
)
4879 d_private
->spendResource(options::preprocessStep());
4881 Assert(ex
.getExprManager() == d_exprManager
);
4882 SmtScope
smts(this);
4883 finalOptionsAreSet();
4885 Trace("smt") << "SMT expandDefinitions(" << ex
<< ")" << endl
;
4887 // Substitute out any abstract values in ex.
4888 Expr e
= d_private
->substituteAbstractValues(Node::fromExpr(ex
)).toExpr();
4889 if(options::typeChecking()) {
4890 // Ensure expr is type-checked at this point.
4893 if(Dump
.isOn("benchmark")) {
4894 Dump("benchmark") << ExpandDefinitionsCommand(e
);
4896 unordered_map
<Node
, Node
, NodeHashFunction
> cache
;
4897 Node n
= d_private
->expandDefinitions(Node::fromExpr(e
), cache
, /* expandOnly = */ true);
4898 n
= postprocess(n
, TypeNode::fromType(e
.getType()));
4903 // TODO(#1108): Simplify the error reporting of this method.
4904 Expr
SmtEngine::getValue(const Expr
& ex
) const
4906 Assert(ex
.getExprManager() == d_exprManager
);
4907 SmtScope
smts(this);
4909 Trace("smt") << "SMT getValue(" << ex
<< ")" << endl
;
4910 if(Dump
.isOn("benchmark")) {
4911 Dump("benchmark") << GetValueCommand(ex
);
4914 if(!options::produceModels()) {
4916 "Cannot get value when produce-models options is off.";
4917 throw ModalException(msg
);
4919 if(d_status
.isNull() ||
4920 d_status
.asSatisfiabilityResult() == Result::UNSAT
||
4921 d_problemExtended
) {
4923 "Cannot get value unless immediately preceded by SAT/INVALID or UNKNOWN response.";
4924 throw RecoverableModalException(msg
);
4927 // Substitute out any abstract values in ex.
4928 Expr e
= d_private
->substituteAbstractValues(Node::fromExpr(ex
)).toExpr();
4930 // Ensure expr is type-checked at this point.
4931 e
.getType(options::typeChecking());
4933 // do not need to apply preprocessing substitutions (should be recorded
4934 // in model already)
4936 Node n
= Node::fromExpr(e
);
4937 Trace("smt") << "--- getting value of " << n
<< endl
;
4938 TypeNode expectedType
= n
.getType();
4940 // Expand, then normalize
4941 unordered_map
<Node
, Node
, NodeHashFunction
> cache
;
4942 n
= d_private
->expandDefinitions(n
, cache
);
4943 // There are two ways model values for terms are computed (for historical
4944 // reasons). One way is that used in check-model; the other is that
4945 // used by the Model classes. It's not clear to me exactly how these
4946 // two are different, but they need to be unified. This ugly hack here
4947 // is to fix bug 554 until we can revamp boolean-terms and models [MGD]
4950 if(!n
.getType().isFunction()) {
4951 n
= Rewriter::rewrite(n
);
4954 Trace("smt") << "--- getting value of " << n
<< endl
;
4955 TheoryModel
* m
= d_theoryEngine
->getModel();
4958 resultNode
= m
->getValue(n
);
4960 Trace("smt") << "--- got value " << n
<< " = " << resultNode
<< endl
;
4961 resultNode
= postprocess(resultNode
, expectedType
);
4962 Trace("smt") << "--- model-post returned " << resultNode
<< endl
;
4963 Trace("smt") << "--- model-post returned " << resultNode
.getType() << endl
;
4964 Trace("smt") << "--- model-post expected " << expectedType
<< endl
;
4966 // type-check the result we got
4967 Assert(resultNode
.isNull() || resultNode
.getType().isSubtypeOf(expectedType
),
4968 "Run with -t smt for details.");
4970 // ensure it's a constant
4971 Assert(resultNode
.getKind() == kind::LAMBDA
|| resultNode
.isConst());
4973 if(options::abstractValues() && resultNode
.getType().isArray()) {
4974 resultNode
= d_private
->mkAbstractValue(resultNode
);
4975 Trace("smt") << "--- abstract value >> " << resultNode
<< endl
;
4978 return resultNode
.toExpr();
4981 bool SmtEngine::addToAssignment(const Expr
& ex
) {
4982 SmtScope
smts(this);
4983 finalOptionsAreSet();
4985 // Substitute out any abstract values in ex
4986 Expr e
= d_private
->substituteAbstractValues(Node::fromExpr(ex
)).toExpr();
4987 Type type
= e
.getType(options::typeChecking());
4989 PrettyCheckArgument(
4990 type
.isBoolean(), e
,
4991 "expected Boolean-typed variable or function application "
4992 "in addToAssignment()" );
4993 Node n
= e
.getNode();
4994 // must be an APPLY of a zero-ary defined function, or a variable
4995 PrettyCheckArgument(
4996 ( ( n
.getKind() == kind::APPLY
&&
4997 ( d_definedFunctions
->find(n
.getOperator()) !=
4998 d_definedFunctions
->end() ) &&
4999 n
.getNumChildren() == 0 ) ||
5001 "expected variable or defined-function application "
5002 "in addToAssignment(),\ngot %s", e
.toString().c_str() );
5003 if(!options::produceAssignments()) {
5006 if(d_assignments
== NULL
) {
5007 d_assignments
= new(true) AssignmentSet(d_context
);
5009 d_assignments
->insert(n
);
5014 // TODO(#1108): Simplify the error reporting of this method.
5015 vector
<pair
<Expr
, Expr
>> SmtEngine::getAssignment()
5017 Trace("smt") << "SMT getAssignment()" << endl
;
5018 SmtScope
smts(this);
5019 finalOptionsAreSet();
5020 if(Dump
.isOn("benchmark")) {
5021 Dump("benchmark") << GetAssignmentCommand();
5023 if(!options::produceAssignments()) {
5025 "Cannot get the current assignment when "
5026 "produce-assignments option is off.";
5027 throw ModalException(msg
);
5029 if(d_status
.isNull() ||
5030 d_status
.asSatisfiabilityResult() == Result::UNSAT
||
5031 d_problemExtended
) {
5033 "Cannot get the current assignment unless immediately "
5034 "preceded by SAT/INVALID or UNKNOWN response.";
5035 throw RecoverableModalException(msg
);
5038 vector
<pair
<Expr
,Expr
>> res
;
5039 if (d_assignments
!= nullptr)
5041 TypeNode boolType
= d_nodeManager
->booleanType();
5042 TheoryModel
* m
= d_theoryEngine
->getModel();
5043 for (AssignmentSet::key_iterator i
= d_assignments
->key_begin(),
5044 iend
= d_assignments
->key_end();
5049 Assert(as
.getType() == boolType
);
5051 Trace("smt") << "--- getting value of " << as
<< endl
;
5053 // Expand, then normalize
5054 unordered_map
<Node
, Node
, NodeHashFunction
> cache
;
5055 Node n
= d_private
->expandDefinitions(as
, cache
);
5056 n
= Rewriter::rewrite(n
);
5058 Trace("smt") << "--- getting value of " << n
<< endl
;
5062 resultNode
= m
->getValue(n
);
5065 // type-check the result we got
5066 Assert(resultNode
.isNull() || resultNode
.getType() == boolType
);
5068 // ensure it's a constant
5069 Assert(resultNode
.isConst());
5071 Assert(as
.getKind() == kind::APPLY
|| as
.isVar());
5072 Assert(as
.getKind() != kind::APPLY
|| as
.getNumChildren() == 0);
5073 res
.emplace_back(as
.toExpr(), resultNode
.toExpr());
5079 void SmtEngine::addToModelCommandAndDump(const Command
& c
, uint32_t flags
, bool userVisible
, const char* dumpTag
) {
5080 Trace("smt") << "SMT addToModelCommandAndDump(" << c
<< ")" << endl
;
5081 SmtScope
smts(this);
5082 // If we aren't yet fully inited, the user might still turn on
5083 // produce-models. So let's keep any commands around just in
5084 // case. This is useful in two cases: (1) SMT-LIBv1 auto-declares
5085 // sort "U" in QF_UF before setLogic() is run and we still want to
5086 // support finding card(U) with --finite-model-find, and (2) to
5087 // decouple SmtEngine and ExprManager if the user does a few
5088 // ExprManager::mkSort() before SmtEngine::setOption("produce-models")
5089 // and expects to find their cardinalities in the model.
5090 if(/* userVisible && */
5091 (!d_fullyInited
|| options::produceModels()) &&
5092 (flags
& ExprManager::VAR_FLAG_DEFINED
) == 0) {
5094 if(flags
& ExprManager::VAR_FLAG_GLOBAL
) {
5095 d_modelGlobalCommands
.push_back(c
.clone());
5097 d_modelCommands
->push_back(c
.clone());
5100 if(Dump
.isOn(dumpTag
)) {
5104 d_dumpCommands
.push_back(c
.clone());
5109 // TODO(#1108): Simplify the error reporting of this method.
5110 Model
* SmtEngine::getModel() {
5111 Trace("smt") << "SMT getModel()" << endl
;
5112 SmtScope
smts(this);
5114 finalOptionsAreSet();
5116 if(Dump
.isOn("benchmark")) {
5117 Dump("benchmark") << GetModelCommand();
5120 if(d_status
.isNull() ||
5121 d_status
.asSatisfiabilityResult() == Result::UNSAT
||
5122 d_problemExtended
) {
5124 "Cannot get the current model unless immediately "
5125 "preceded by SAT/INVALID or UNKNOWN response.";
5126 throw RecoverableModalException(msg
);
5128 if(!options::produceModels()) {
5130 "Cannot get model when produce-models options is off.";
5131 throw ModalException(msg
);
5133 TheoryModel
* m
= d_theoryEngine
->getModel();
5134 m
->d_inputName
= d_filename
;
5138 void SmtEngine::checkUnsatCore() {
5139 Assert(options::unsatCores(), "cannot check unsat core if unsat cores are turned off");
5141 Notice() << "SmtEngine::checkUnsatCore(): generating unsat core" << endl
;
5142 UnsatCore core
= getUnsatCore();
5144 SmtEngine
coreChecker(d_exprManager
);
5145 coreChecker
.setLogic(getLogicInfo());
5148 std::vector
<Command
*>::const_iterator itg
= d_defineCommands
.begin();
5149 for (; itg
!= d_defineCommands
.end(); ++itg
) {
5150 (*itg
)->invoke(&coreChecker
);
5154 Notice() << "SmtEngine::checkUnsatCore(): pushing core assertions (size == " << core
.size() << ")" << endl
;
5155 for(UnsatCore::iterator i
= core
.begin(); i
!= core
.end(); ++i
) {
5156 Notice() << "SmtEngine::checkUnsatCore(): pushing core member " << *i
<< endl
;
5157 coreChecker
.assertFormula(*i
);
5159 const bool checkUnsatCores
= options::checkUnsatCores();
5162 options::checkUnsatCores
.set(false);
5163 options::checkProofs
.set(false);
5164 r
= coreChecker
.checkSat();
5166 options::checkUnsatCores
.set(checkUnsatCores
);
5169 Notice() << "SmtEngine::checkUnsatCore(): result is " << r
<< endl
;
5170 if(r
.asSatisfiabilityResult().isUnknown()) {
5171 InternalError("SmtEngine::checkUnsatCore(): could not check core result unknown.");
5174 if(r
.asSatisfiabilityResult().isSat()) {
5175 InternalError("SmtEngine::checkUnsatCore(): produced core was satisfiable.");
5179 void SmtEngine::checkModel(bool hardFailure
) {
5180 // --check-model implies --produce-assertions, which enables the
5181 // assertion list, so we should be ok.
5182 Assert(d_assertionList
!= NULL
, "don't have an assertion list to check in SmtEngine::checkModel()");
5184 TimerStat::CodeTimer
checkModelTimer(d_stats
->d_checkModelTime
);
5186 // Throughout, we use Notice() to give diagnostic output.
5188 // If this function is running, the user gave --check-model (or equivalent),
5189 // and if Notice() is on, the user gave --verbose (or equivalent).
5191 Notice() << "SmtEngine::checkModel(): generating model" << endl
;
5192 TheoryModel
* m
= d_theoryEngine
->getModel();
5194 // check-model is not guaranteed to succeed if approximate values were used
5195 if (m
->hasApproximations())
5198 << "WARNING: running check-model on a model with approximate values..."
5202 // Check individual theory assertions
5203 d_theoryEngine
->checkTheoryAssertionsWithModel(hardFailure
);
5208 // We have a "fake context" for the substitution map (we don't need it
5209 // to be context-dependent)
5210 context::Context fakeContext
;
5211 SubstitutionMap
substitutions(&fakeContext
, /* substituteUnderQuantifiers = */ false);
5213 for(size_t k
= 0; k
< m
->getNumCommands(); ++k
) {
5214 const DeclareFunctionCommand
* c
= dynamic_cast<const DeclareFunctionCommand
*>(m
->getCommand(k
));
5215 Notice() << "SmtEngine::checkModel(): model command " << k
<< " : " << m
->getCommand(k
) << endl
;
5217 // we don't care about DECLARE-DATATYPES, DECLARE-SORT, ...
5218 Notice() << "SmtEngine::checkModel(): skipping..." << endl
;
5220 // We have a DECLARE-FUN:
5222 // We'll first do some checks, then add to our substitution map
5223 // the mapping: function symbol |-> value
5225 Expr func
= c
->getFunction();
5226 Node val
= m
->getValue(func
);
5228 Notice() << "SmtEngine::checkModel(): adding substitution: " << func
<< " |-> " << val
<< endl
;
5230 // (1) if the value is a lambda, ensure the lambda doesn't contain the
5231 // function symbol (since then the definition is recursive)
5232 if (val
.getKind() == kind::LAMBDA
) {
5233 // first apply the model substitutions we have so far
5234 Debug("boolean-terms") << "applying subses to " << val
[1] << endl
;
5235 Node n
= substitutions
.apply(val
[1]);
5236 Debug("boolean-terms") << "++ got " << n
<< endl
;
5237 // now check if n contains func by doing a substitution
5238 // [func->func2] and checking equality of the Nodes.
5239 // (this just a way to check if func is in n.)
5240 SubstitutionMap
subs(&fakeContext
);
5241 Node func2
= NodeManager::currentNM()->mkSkolem("", TypeNode::fromType(func
.getType()), "", NodeManager::SKOLEM_NO_NOTIFY
);
5242 subs
.addSubstitution(func
, func2
);
5243 if(subs
.apply(n
) != n
) {
5244 Notice() << "SmtEngine::checkModel(): *** PROBLEM: MODEL VALUE DEFINED IN TERMS OF ITSELF ***" << endl
;
5246 ss
<< "SmtEngine::checkModel(): ERRORS SATISFYING ASSERTIONS WITH MODEL:" << endl
5247 << "considering model value for " << func
<< endl
5248 << "body of lambda is: " << val
<< endl
;
5250 ss
<< "body substitutes to: " << n
<< endl
;
5252 ss
<< "so " << func
<< " is defined in terms of itself." << endl
5253 << "Run with `--check-models -v' for additional diagnostics.";
5254 InternalError(ss
.str());
5258 // (2) check that the value is actually a value
5259 else if (!val
.isConst()) {
5260 Notice() << "SmtEngine::checkModel(): *** PROBLEM: MODEL VALUE NOT A CONSTANT ***" << endl
;
5262 ss
<< "SmtEngine::checkModel(): ERRORS SATISFYING ASSERTIONS WITH MODEL:" << endl
5263 << "model value for " << func
<< endl
5264 << " is " << val
<< endl
5265 << "and that is not a constant (.isConst() == false)." << endl
5266 << "Run with `--check-models -v' for additional diagnostics.";
5267 InternalError(ss
.str());
5270 // (3) check that it's the correct (sub)type
5271 // This was intended to be a more general check, but for now we can't do that because
5272 // e.g. "1" is an INT, which isn't a subrange type [1..10] (etc.).
5273 else if(func
.getType().isInteger() && !val
.getType().isInteger()) {
5274 Notice() << "SmtEngine::checkModel(): *** PROBLEM: MODEL VALUE NOT CORRECT TYPE ***" << endl
;
5276 ss
<< "SmtEngine::checkModel(): ERRORS SATISFYING ASSERTIONS WITH MODEL:" << endl
5277 << "model value for " << func
<< endl
5278 << " is " << val
<< endl
5279 << "value type is " << val
.getType() << endl
5280 << "should be of type " << func
.getType() << endl
5281 << "Run with `--check-models -v' for additional diagnostics.";
5282 InternalError(ss
.str());
5285 // (4) checks complete, add the substitution
5286 Debug("boolean-terms") << "cm: adding subs " << func
<< " :=> " << val
<< endl
;
5287 substitutions
.addSubstitution(func
, val
);
5291 // Now go through all our user assertions checking if they're satisfied.
5292 for(AssertionList::const_iterator i
= d_assertionList
->begin(); i
!= d_assertionList
->end(); ++i
) {
5293 Notice() << "SmtEngine::checkModel(): checking assertion " << *i
<< endl
;
5294 Node n
= Node::fromExpr(*i
);
5296 // Apply any define-funs from the problem.
5298 unordered_map
<Node
, Node
, NodeHashFunction
> cache
;
5299 n
= d_private
->expandDefinitions(n
, cache
);
5301 Notice() << "SmtEngine::checkModel(): -- expands to " << n
<< endl
;
5303 // Apply our model value substitutions.
5304 Debug("boolean-terms") << "applying subses to " << n
<< endl
;
5305 n
= substitutions
.apply(n
);
5306 Debug("boolean-terms") << "++ got " << n
<< endl
;
5307 Notice() << "SmtEngine::checkModel(): -- substitutes to " << n
<< endl
;
5309 if( n
.getKind() != kind::REWRITE_RULE
){
5310 // In case it's a quantifier (or contains one), look up its value before
5311 // simplifying, or the quantifier might be irreparably altered.
5313 Notice() << "SmtEngine::checkModel(): -- get value : " << n
<< std::endl
;
5315 // Note this "skip" is done here, rather than above. This is
5316 // because (1) the quantifier could in principle simplify to false,
5317 // which should be reported, and (2) checking for the quantifier
5318 // above, before simplification, doesn't catch buried quantifiers
5319 // anyway (those not at the top-level).
5320 Notice() << "SmtEngine::checkModel(): -- skipping rewrite-rules assertion"
5325 // Simplify the result.
5326 n
= d_private
->simplify(n
);
5327 Notice() << "SmtEngine::checkModel(): -- simplifies to " << n
<< endl
;
5329 // Replace the already-known ITEs (this is important for ground ITEs under quantifiers).
5330 n
= d_private
->d_iteRemover
.replace(n
);
5331 Notice() << "SmtEngine::checkModel(): -- ite replacement gives " << n
<< endl
;
5333 // Apply our model value substitutions (again), as things may have been simplified.
5334 Debug("boolean-terms") << "applying subses to " << n
<< endl
;
5335 n
= substitutions
.apply(n
);
5336 Debug("boolean-terms") << "++ got " << n
<< endl
;
5337 Notice() << "SmtEngine::checkModel(): -- re-substitutes to " << n
<< endl
;
5339 // As a last-ditch effort, ask model to simplify it.
5340 // Presently, this is only an issue for quantifiers, which can have a value
5341 // but don't show up in our substitution map above.
5343 Notice() << "SmtEngine::checkModel(): -- model-substitutes to " << n
<< endl
;
5345 if( d_logic
.isQuantified() ){
5346 // AJR: since quantified formulas are not checkable, we assign them to true/false based on the satisfying assignment.
5347 // however, quantified formulas can be modified during preprocess, so they may not correspond to those in the satisfying assignment.
5348 // hence we use a relaxed version of check model here.
5349 // this is necessary until preprocessing passes explicitly record how they rewrite quantified formulas
5350 if( hardFailure
&& !n
.isConst() && n
.getKind() != kind::LAMBDA
){
5351 Notice() << "SmtEngine::checkModel(): -- relax check model wrt quantified formulas..." << endl
;
5352 AlwaysAssert( quantifiers::QuantifiersRewriter::containsQuantifiers( n
) );
5353 Warning() << "Warning : SmtEngine::checkModel(): cannot check simplified assertion : " << n
<< endl
;
5357 AlwaysAssert(!hardFailure
|| n
.isConst() || n
.getKind() == kind::LAMBDA
);
5359 // The result should be == true.
5360 if(n
!= NodeManager::currentNM()->mkConst(true)) {
5361 Notice() << "SmtEngine::checkModel(): *** PROBLEM: EXPECTED `TRUE' ***"
5364 ss
<< "SmtEngine::checkModel(): "
5365 << "ERRORS SATISFYING ASSERTIONS WITH MODEL:" << endl
5366 << "assertion: " << *i
<< endl
5367 << "simplifies to: " << n
<< endl
5368 << "expected `true'." << endl
5369 << "Run with `--check-models -v' for additional diagnostics.";
5371 InternalError(ss
.str());
5373 Warning() << ss
.str() << endl
;
5377 Notice() << "SmtEngine::checkModel(): all assertions checked out OK !" << endl
;
5380 void SmtEngine::checkSynthSolution()
5382 NodeManager
* nm
= NodeManager::currentNM();
5383 Notice() << "SmtEngine::checkSynthSolution(): checking synthesis solution" << endl
;
5384 map
<Node
, Node
> sol_map
;
5385 /* Get solutions and build auxiliary vectors for substituting */
5386 d_theoryEngine
->getSynthSolutions(sol_map
);
5387 if (sol_map
.empty())
5389 Trace("check-synth-sol") << "No solution to check!\n";
5392 Trace("check-synth-sol") << "Got solution map:\n";
5393 std::vector
<Node
> function_vars
, function_sols
;
5394 for (const auto& pair
: sol_map
)
5396 Trace("check-synth-sol") << pair
.first
<< " --> " << pair
.second
<< "\n";
5397 function_vars
.push_back(pair
.first
);
5398 function_sols
.push_back(pair
.second
);
5400 Trace("check-synth-sol") << "Starting new SMT Engine\n";
5401 /* Start new SMT engine to check solutions */
5402 SmtEngine
solChecker(d_exprManager
);
5403 solChecker
.setLogic(getLogicInfo());
5404 setOption("check-synth-sol", SExpr("false"));
5406 Trace("check-synth-sol") << "Retrieving assertions\n";
5407 // Build conjecture from original assertions
5408 if (d_assertionList
== NULL
)
5410 Trace("check-synth-sol") << "No assertions to check\n";
5413 for (AssertionList::const_iterator i
= d_assertionList
->begin();
5414 i
!= d_assertionList
->end();
5417 Notice() << "SmtEngine::checkSynthSolution(): checking assertion " << *i
<< endl
;
5418 Trace("check-synth-sol") << "Retrieving assertion " << *i
<< "\n";
5419 Node conj
= Node::fromExpr(*i
);
5420 // Apply any define-funs from the problem.
5422 unordered_map
<Node
, Node
, NodeHashFunction
> cache
;
5423 conj
= d_private
->expandDefinitions(conj
, cache
);
5425 Notice() << "SmtEngine::checkSynthSolution(): -- expands to " << conj
<< endl
;
5426 Trace("check-synth-sol") << "Expanded assertion " << conj
<< "\n";
5428 // Apply solution map to conjecture body
5430 /* Whether property is quantifier free */
5431 if (conj
[1].getKind() != kind::EXISTS
)
5433 conjBody
= conj
[1].substitute(function_vars
.begin(),
5434 function_vars
.end(),
5435 function_sols
.begin(),
5436 function_sols
.end());
5440 conjBody
= conj
[1][1].substitute(function_vars
.begin(),
5441 function_vars
.end(),
5442 function_sols
.begin(),
5443 function_sols
.end());
5445 /* Skolemize property */
5446 std::vector
<Node
> vars
, skos
;
5447 for (unsigned j
= 0, size
= conj
[1][0].getNumChildren(); j
< size
; ++j
)
5449 vars
.push_back(conj
[1][0][j
]);
5450 std::stringstream ss
;
5452 skos
.push_back(nm
->mkSkolem(ss
.str(), conj
[1][0][j
].getType()));
5453 Trace("check-synth-sol") << "\tSkolemizing " << conj
[1][0][j
] << " to "
5454 << skos
.back() << "\n";
5456 conjBody
= conjBody
.substitute(
5457 vars
.begin(), vars
.end(), skos
.begin(), skos
.end());
5459 Notice() << "SmtEngine::checkSynthSolution(): -- body substitutes to "
5460 << conjBody
<< endl
;
5461 Trace("check-synth-sol") << "Substituted body of assertion to " << conjBody
5463 solChecker
.assertFormula(conjBody
.toExpr());
5464 Result r
= solChecker
.checkSat();
5465 Notice() << "SmtEngine::checkSynthSolution(): result is " << r
<< endl
;
5466 Trace("check-synth-sol") << "Satsifiability check: " << r
<< "\n";
5467 if (r
.asSatisfiabilityResult().isUnknown())
5470 "SmtEngine::checkSynthSolution(): could not check solution, result "
5473 else if (r
.asSatisfiabilityResult().isSat())
5476 "SmtEngine::checkSynthSolution(): produced solution leads to "
5477 "satisfiable negated conjecture.");
5479 solChecker
.resetAssertions();
5483 // TODO(#1108): Simplify the error reporting of this method.
5484 UnsatCore
SmtEngine::getUnsatCore() {
5485 Trace("smt") << "SMT getUnsatCore()" << endl
;
5486 SmtScope
smts(this);
5487 finalOptionsAreSet();
5488 if(Dump
.isOn("benchmark")) {
5489 Dump("benchmark") << GetUnsatCoreCommand();
5492 if(!options::unsatCores()) {
5493 throw ModalException("Cannot get an unsat core when produce-unsat-cores option is off.");
5495 if(d_status
.isNull() ||
5496 d_status
.asSatisfiabilityResult() != Result::UNSAT
||
5497 d_problemExtended
) {
5498 throw RecoverableModalException(
5499 "Cannot get an unsat core unless immediately preceded by UNSAT/VALID "
5503 d_proofManager
->traceUnsatCore();// just to trigger core creation
5504 return UnsatCore(this, d_proofManager
->extractUnsatCore());
5505 #else /* IS_PROOFS_BUILD */
5506 throw ModalException("This build of CVC4 doesn't have proof support (required for unsat cores).");
5507 #endif /* IS_PROOFS_BUILD */
5510 // TODO(#1108): Simplify the error reporting of this method.
5511 const Proof
& SmtEngine::getProof()
5513 Trace("smt") << "SMT getProof()" << endl
;
5514 SmtScope
smts(this);
5515 finalOptionsAreSet();
5516 if(Dump
.isOn("benchmark")) {
5517 Dump("benchmark") << GetProofCommand();
5520 if(!options::proof()) {
5521 throw ModalException("Cannot get a proof when produce-proofs option is off.");
5523 if(d_status
.isNull() ||
5524 d_status
.asSatisfiabilityResult() != Result::UNSAT
||
5525 d_problemExtended
) {
5526 throw RecoverableModalException(
5527 "Cannot get a proof unless immediately preceded by UNSAT/VALID "
5531 return ProofManager::getProof(this);
5532 #else /* IS_PROOFS_BUILD */
5533 throw ModalException("This build of CVC4 doesn't have proof support.");
5534 #endif /* IS_PROOFS_BUILD */
5537 void SmtEngine::printInstantiations( std::ostream
& out
) {
5538 SmtScope
smts(this);
5539 if( options::instFormatMode()==INST_FORMAT_MODE_SZS
){
5540 out
<< "% SZS output start Proof for " << d_filename
.c_str() << std::endl
;
5542 if( d_theoryEngine
){
5543 d_theoryEngine
->printInstantiations( out
);
5547 if( options::instFormatMode()==INST_FORMAT_MODE_SZS
){
5548 out
<< "% SZS output end Proof for " << d_filename
.c_str() << std::endl
;
5552 void SmtEngine::printSynthSolution( std::ostream
& out
) {
5553 SmtScope
smts(this);
5554 if( d_theoryEngine
){
5555 d_theoryEngine
->printSynthSolution( out
);
5561 Expr
SmtEngine::doQuantifierElimination(const Expr
& e
, bool doFull
, bool strict
)
5563 SmtScope
smts(this);
5564 if(!d_logic
.isPure(THEORY_ARITH
) && strict
){
5565 Warning() << "Unexpected logic for quantifier elimination " << d_logic
<< endl
;
5567 Trace("smt-qe") << "Do quantifier elimination " << e
<< std::endl
;
5568 Node n_e
= Node::fromExpr( e
);
5569 if (n_e
.getKind() != kind::EXISTS
&& n_e
.getKind() != kind::FORALL
)
5571 throw ModalException(
5572 "Expecting a quantified formula as argument to get-qe.");
5574 //tag the quantified formula with the quant-elim attribute
5575 TypeNode t
= NodeManager::currentNM()->booleanType();
5576 Node n_attr
= NodeManager::currentNM()->mkSkolem("qe", t
, "Auxiliary variable for qe attr.");
5577 std::vector
< Node
> node_values
;
5578 d_theoryEngine
->setUserAttribute( doFull
? "quant-elim" : "quant-elim-partial", n_attr
, node_values
, "");
5579 n_attr
= NodeManager::currentNM()->mkNode(kind::INST_ATTRIBUTE
, n_attr
);
5580 n_attr
= NodeManager::currentNM()->mkNode(kind::INST_PATTERN_LIST
, n_attr
);
5581 std::vector
< Node
> e_children
;
5582 e_children
.push_back( n_e
[0] );
5583 e_children
.push_back(n_e
.getKind() == kind::EXISTS
? n_e
[1]
5585 e_children
.push_back( n_attr
);
5586 Node nn_e
= NodeManager::currentNM()->mkNode( kind::EXISTS
, e_children
);
5587 Trace("smt-qe-debug") << "Query for quantifier elimination : " << nn_e
<< std::endl
;
5588 Assert( nn_e
.getNumChildren()==3 );
5589 Result r
= checkSatisfiability(nn_e
.toExpr(), true, true);
5590 Trace("smt-qe") << "Query returned " << r
<< std::endl
;
5591 if(r
.asSatisfiabilityResult().isSat() != Result::UNSAT
) {
5592 if( r
.asSatisfiabilityResult().isSat() != Result::SAT
&& doFull
){
5594 ss
<< "While performing quantifier elimination, unexpected result : " << r
<< " for query.";
5595 InternalError(ss
.str().c_str());
5597 std::vector
< Node
> inst_qs
;
5598 d_theoryEngine
->getInstantiatedQuantifiedFormulas( inst_qs
);
5599 Assert( inst_qs
.size()<=1 );
5601 if( inst_qs
.size()==1 ){
5602 Node top_q
= inst_qs
[0];
5603 //Node top_q = Rewriter::rewrite( nn_e ).negate();
5604 Assert( top_q
.getKind()==kind::FORALL
);
5605 Trace("smt-qe") << "Get qe for " << top_q
<< std::endl
;
5606 ret_n
= d_theoryEngine
->getInstantiatedConjunction( top_q
);
5607 Trace("smt-qe") << "Returned : " << ret_n
<< std::endl
;
5608 if (n_e
.getKind() == kind::EXISTS
)
5610 ret_n
= Rewriter::rewrite(ret_n
.negate());
5613 ret_n
= NodeManager::currentNM()->mkConst(n_e
.getKind() != kind::EXISTS
);
5615 return ret_n
.toExpr();
5617 return NodeManager::currentNM()
5618 ->mkConst(n_e
.getKind() == kind::EXISTS
)
5623 void SmtEngine::getInstantiatedQuantifiedFormulas( std::vector
< Expr
>& qs
) {
5624 SmtScope
smts(this);
5625 if( d_theoryEngine
){
5626 std::vector
< Node
> qs_n
;
5627 d_theoryEngine
->getInstantiatedQuantifiedFormulas( qs_n
);
5628 for( unsigned i
=0; i
<qs_n
.size(); i
++ ){
5629 qs
.push_back( qs_n
[i
].toExpr() );
5636 void SmtEngine::getInstantiations( Expr q
, std::vector
< Expr
>& insts
) {
5637 SmtScope
smts(this);
5638 if( d_theoryEngine
){
5639 std::vector
< Node
> insts_n
;
5640 d_theoryEngine
->getInstantiations( Node::fromExpr( q
), insts_n
);
5641 for( unsigned i
=0; i
<insts_n
.size(); i
++ ){
5642 insts
.push_back( insts_n
[i
].toExpr() );
5649 void SmtEngine::getInstantiationTermVectors( Expr q
, std::vector
< std::vector
< Expr
> >& tvecs
) {
5650 SmtScope
smts(this);
5651 Assert(options::trackInstLemmas());
5652 if( d_theoryEngine
){
5653 std::vector
< std::vector
< Node
> > tvecs_n
;
5654 d_theoryEngine
->getInstantiationTermVectors( Node::fromExpr( q
), tvecs_n
);
5655 for( unsigned i
=0; i
<tvecs_n
.size(); i
++ ){
5656 std::vector
< Expr
> tvec
;
5657 for( unsigned j
=0; j
<tvecs_n
[i
].size(); j
++ ){
5658 tvec
.push_back( tvecs_n
[i
][j
].toExpr() );
5660 tvecs
.push_back( tvec
);
5667 vector
<Expr
> SmtEngine::getAssertions() {
5668 SmtScope
smts(this);
5669 finalOptionsAreSet();
5671 if(Dump
.isOn("benchmark")) {
5672 Dump("benchmark") << GetAssertionsCommand();
5674 Trace("smt") << "SMT getAssertions()" << endl
;
5675 if(!options::produceAssertions()) {
5677 "Cannot query the current assertion list when not in produce-assertions mode.";
5678 throw ModalException(msg
);
5680 Assert(d_assertionList
!= NULL
);
5681 // copy the result out
5682 return vector
<Expr
>(d_assertionList
->begin(), d_assertionList
->end());
5685 void SmtEngine::push()
5687 SmtScope
smts(this);
5688 finalOptionsAreSet();
5690 Trace("smt") << "SMT push()" << endl
;
5691 d_private
->notifyPush();
5692 d_private
->processAssertions();
5693 if(Dump
.isOn("benchmark")) {
5694 Dump("benchmark") << PushCommand();
5696 if(!options::incrementalSolving()) {
5697 throw ModalException("Cannot push when not solving incrementally (use --incremental)");
5700 // check to see if a postsolve() is pending
5701 if(d_needPostsolve
) {
5702 d_theoryEngine
->postsolve();
5703 d_needPostsolve
= false;
5706 // The problem isn't really "extended" yet, but this disallows
5707 // get-model after a push, simplifying our lives somewhat and
5708 // staying symmtric with pop.
5709 setProblemExtended(true);
5711 d_userLevels
.push_back(d_userContext
->getLevel());
5713 Trace("userpushpop") << "SmtEngine: pushed to level "
5714 << d_userContext
->getLevel() << endl
;
5717 void SmtEngine::pop() {
5718 SmtScope
smts(this);
5719 finalOptionsAreSet();
5720 Trace("smt") << "SMT pop()" << endl
;
5721 if(Dump
.isOn("benchmark")) {
5722 Dump("benchmark") << PopCommand();
5724 if(!options::incrementalSolving()) {
5725 throw ModalException("Cannot pop when not solving incrementally (use --incremental)");
5727 if(d_userLevels
.size() == 0) {
5728 throw ModalException("Cannot pop beyond the first user frame");
5731 // check to see if a postsolve() is pending
5732 if(d_needPostsolve
) {
5733 d_theoryEngine
->postsolve();
5734 d_needPostsolve
= false;
5737 // The problem isn't really "extended" yet, but this disallows
5738 // get-model after a pop, simplifying our lives somewhat. It might
5739 // not be strictly necessary to do so, since the pops occur lazily,
5740 // but also it would be weird to have a legally-executed (get-model)
5741 // that only returns a subset of the assignment (because the rest
5742 // is no longer in scope!).
5743 setProblemExtended(true);
5745 AlwaysAssert(d_userContext
->getLevel() > 0);
5746 AlwaysAssert(d_userLevels
.back() < d_userContext
->getLevel());
5747 while (d_userLevels
.back() < d_userContext
->getLevel()) {
5750 d_userLevels
.pop_back();
5752 // Clear out assertion queues etc., in case anything is still in there
5753 d_private
->notifyPop();
5755 Trace("userpushpop") << "SmtEngine: popped to level "
5756 << d_userContext
->getLevel() << endl
;
5757 // FIXME: should we reset d_status here?
5758 // SMT-LIBv2 spec seems to imply no, but it would make sense to..
5761 void SmtEngine::internalPush() {
5762 Assert(d_fullyInited
);
5763 Trace("smt") << "SmtEngine::internalPush()" << endl
;
5765 if(options::incrementalSolving()) {
5766 d_private
->processAssertions();
5767 TimerStat::CodeTimer
pushPopTimer(d_stats
->d_pushPopTime
);
5768 d_userContext
->push();
5769 // the d_context push is done inside of the SAT solver
5770 d_propEngine
->push();
5774 void SmtEngine::internalPop(bool immediate
) {
5775 Assert(d_fullyInited
);
5776 Trace("smt") << "SmtEngine::internalPop()" << endl
;
5777 if(options::incrementalSolving()) {
5785 void SmtEngine::doPendingPops() {
5786 Assert(d_pendingPops
== 0 || options::incrementalSolving());
5787 while(d_pendingPops
> 0) {
5788 TimerStat::CodeTimer
pushPopTimer(d_stats
->d_pushPopTime
);
5789 d_propEngine
->pop();
5790 // the d_context pop is done inside of the SAT solver
5791 d_userContext
->pop();
5796 void SmtEngine::reset()
5798 SmtScope
smts(this);
5799 ExprManager
*em
= d_exprManager
;
5800 Trace("smt") << "SMT reset()" << endl
;
5801 if(Dump
.isOn("benchmark")) {
5802 Dump("benchmark") << ResetCommand();
5805 opts
.copyValues(d_originalOptions
);
5807 NodeManager::fromExprManager(em
)->getOptions().copyValues(opts
);
5808 new(this) SmtEngine(em
);
5811 void SmtEngine::resetAssertions()
5813 SmtScope
smts(this);
5816 Trace("smt") << "SMT resetAssertions()" << endl
;
5817 if(Dump
.isOn("benchmark")) {
5818 Dump("benchmark") << ResetAssertionsCommand();
5821 while(!d_userLevels
.empty()) {
5825 // Also remember the global push/pop around everything.
5826 Assert(d_userLevels
.size() == 0 && d_userContext
->getLevel() == 1);
5827 d_context
->popto(0);
5828 d_userContext
->popto(0);
5829 DeleteAndClearCommandVector(d_modelGlobalCommands
);
5830 d_userContext
->push();
5834 void SmtEngine::interrupt()
5836 if(!d_fullyInited
) {
5839 d_propEngine
->interrupt();
5840 d_theoryEngine
->interrupt();
5843 void SmtEngine::setResourceLimit(unsigned long units
, bool cumulative
) {
5844 d_private
->getResourceManager()->setResourceLimit(units
, cumulative
);
5846 void SmtEngine::setTimeLimit(unsigned long milis
, bool cumulative
) {
5847 d_private
->getResourceManager()->setTimeLimit(milis
, cumulative
);
5850 unsigned long SmtEngine::getResourceUsage() const {
5851 return d_private
->getResourceManager()->getResourceUsage();
5854 unsigned long SmtEngine::getTimeUsage() const {
5855 return d_private
->getResourceManager()->getTimeUsage();
5858 unsigned long SmtEngine::getResourceRemaining() const
5860 return d_private
->getResourceManager()->getResourceRemaining();
5863 unsigned long SmtEngine::getTimeRemaining() const
5865 return d_private
->getResourceManager()->getTimeRemaining();
5868 Statistics
SmtEngine::getStatistics() const
5870 return Statistics(*d_statisticsRegistry
);
5873 SExpr
SmtEngine::getStatistic(std::string name
) const
5875 return d_statisticsRegistry
->getStatistic(name
);
5878 void SmtEngine::safeFlushStatistics(int fd
) const {
5879 d_statisticsRegistry
->safeFlushInformation(fd
);
5882 void SmtEngine::setUserAttribute(const std::string
& attr
,
5884 const std::vector
<Expr
>& expr_values
,
5885 const std::string
& str_value
)
5887 SmtScope
smts(this);
5888 std::vector
<Node
> node_values
;
5889 for( unsigned i
=0; i
<expr_values
.size(); i
++ ){
5890 node_values
.push_back( expr_values
[i
].getNode() );
5892 d_theoryEngine
->setUserAttribute(attr
, expr
.getNode(), node_values
, str_value
);
5895 void SmtEngine::setPrintFuncInModel(Expr f
, bool p
) {
5896 Trace("setp-model") << "Set printInModel " << f
<< " to " << p
<< std::endl
;
5897 for( unsigned i
=0; i
<d_modelGlobalCommands
.size(); i
++ ){
5898 Command
* c
= d_modelGlobalCommands
[i
];
5899 DeclareFunctionCommand
* dfc
= dynamic_cast<DeclareFunctionCommand
*>(c
);
5901 if( dfc
->getFunction()==f
){
5902 dfc
->setPrintInModel( p
);
5906 for( unsigned i
=0; i
<d_modelCommands
->size(); i
++ ){
5907 Command
* c
= (*d_modelCommands
)[i
];
5908 DeclareFunctionCommand
* dfc
= dynamic_cast<DeclareFunctionCommand
*>(c
);
5910 if( dfc
->getFunction()==f
){
5911 dfc
->setPrintInModel( p
);
5917 void SmtEngine::beforeSearch()
5920 throw ModalException(
5921 "SmtEngine::beforeSearch called after initialization.");
5926 void SmtEngine::setOption(const std::string
& key
, const CVC4::SExpr
& value
)
5928 NodeManagerScope
nms(d_nodeManager
);
5929 Trace("smt") << "SMT setOption(" << key
<< ", " << value
<< ")" << endl
;
5931 if(Dump
.isOn("benchmark")) {
5932 Dump("benchmark") << SetOptionCommand(key
, value
);
5935 if(key
== "command-verbosity") {
5936 if(!value
.isAtom()) {
5937 const vector
<SExpr
>& cs
= value
.getChildren();
5938 if(cs
.size() == 2 &&
5939 (cs
[0].isKeyword() || cs
[0].isString()) &&
5940 cs
[1].isInteger()) {
5941 string c
= cs
[0].getValue();
5942 const Integer
& v
= cs
[1].getIntegerValue();
5943 if(v
< 0 || v
> 2) {
5944 throw OptionException("command-verbosity must be 0, 1, or 2");
5946 d_commandVerbosity
[c
] = v
;
5950 throw OptionException("command-verbosity value must be a tuple (command-name, integer)");
5953 if(!value
.isAtom()) {
5954 throw OptionException("bad value for :" + key
);
5957 string optionarg
= value
.getValue();
5958 Options
& nodeManagerOptions
= NodeManager::currentNM()->getOptions();
5959 nodeManagerOptions
.setOption(key
, optionarg
);
5962 CVC4::SExpr
SmtEngine::getOption(const std::string
& key
) const
5964 NodeManagerScope
nms(d_nodeManager
);
5966 Trace("smt") << "SMT getOption(" << key
<< ")" << endl
;
5968 if(key
.length() >= 18 &&
5969 key
.compare(0, 18, "command-verbosity:") == 0) {
5970 map
<string
, Integer
>::const_iterator i
= d_commandVerbosity
.find(key
.c_str() + 18);
5971 if(i
!= d_commandVerbosity
.end()) {
5972 return SExpr((*i
).second
);
5974 i
= d_commandVerbosity
.find("*");
5975 if(i
!= d_commandVerbosity
.end()) {
5976 return SExpr((*i
).second
);
5978 return SExpr(Integer(2));
5981 if(Dump
.isOn("benchmark")) {
5982 Dump("benchmark") << GetOptionCommand(key
);
5985 if(key
== "command-verbosity") {
5986 vector
<SExpr
> result
;
5987 SExpr defaultVerbosity
;
5988 for(map
<string
, Integer
>::const_iterator i
= d_commandVerbosity
.begin();
5989 i
!= d_commandVerbosity
.end();
5992 v
.push_back(SExpr((*i
).first
));
5993 v
.push_back(SExpr((*i
).second
));
5994 if((*i
).first
== "*") {
5995 // put the default at the end of the SExpr
5996 defaultVerbosity
= SExpr(v
);
5998 result
.push_back(SExpr(v
));
6001 // put the default at the end of the SExpr
6002 if(!defaultVerbosity
.isAtom()) {
6003 result
.push_back(defaultVerbosity
);
6005 // ensure the default is always listed
6007 v
.push_back(SExpr("*"));
6008 v
.push_back(SExpr(Integer(2)));
6009 result
.push_back(SExpr(v
));
6011 return SExpr(result
);
6014 Options
& nodeManagerOptions
= NodeManager::currentNM()->getOptions();
6015 return SExpr::parseAtom(nodeManagerOptions
.getOption(key
));
6018 void SmtEngine::setReplayStream(ExprStream
* replayStream
) {
6019 AlwaysAssert(!d_fullyInited
,
6020 "Cannot set replay stream once fully initialized");
6021 d_replayStream
= replayStream
;
6024 bool SmtEngine::getExpressionName(Expr e
, std::string
& name
) const {
6025 return d_private
->getExpressionName(e
, name
);
6028 void SmtEngine::setExpressionName(Expr e
, const std::string
& name
) {
6029 Trace("smt-debug") << "Set expression name " << e
<< " to " << name
<< std::endl
;
6030 d_private
->setExpressionName(e
,name
);
6033 }/* CVC4 namespace */