1 /********************* */
2 /*! \file smt_engine.cpp
4 ** Top contributors (to current version):
5 ** Morgan Deters, Andrew Reynolds, Tim King
6 ** This file is part of the CVC4 project.
7 ** Copyright (c) 2009-2018 by the authors listed in the file AUTHORS
8 ** in the top-level source directory) and their institutional affiliations.
9 ** All rights reserved. See the file COPYING in the top-level source
10 ** directory for licensing information.\endverbatim
12 ** \brief The main entry point into the CVC4 library's SMT interface
14 ** The main entry point into the CVC4 library's SMT interface.
17 #include "smt/smt_engine.h"
26 #include <unordered_map>
27 #include <unordered_set>
31 #include "base/configuration.h"
32 #include "base/configuration_private.h"
33 #include "base/exception.h"
34 #include "base/listener.h"
35 #include "base/modal_exception.h"
36 #include "base/output.h"
37 #include "context/cdhashmap.h"
38 #include "context/cdhashset.h"
39 #include "context/cdlist.h"
40 #include "context/context.h"
41 #include "decision/decision_engine.h"
42 #include "expr/attribute.h"
43 #include "expr/expr.h"
44 #include "expr/kind.h"
45 #include "expr/metakind.h"
46 #include "expr/node.h"
47 #include "expr/node_builder.h"
48 #include "expr/node_self_iterator.h"
49 #include "options/arith_options.h"
50 #include "options/arrays_options.h"
51 #include "options/base_options.h"
52 #include "options/booleans_options.h"
53 #include "options/bv_options.h"
54 #include "options/datatypes_options.h"
55 #include "options/decision_mode.h"
56 #include "options/decision_options.h"
57 #include "options/language.h"
58 #include "options/main_options.h"
59 #include "options/open_ostream.h"
60 #include "options/option_exception.h"
61 #include "options/printer_options.h"
62 #include "options/proof_options.h"
63 #include "options/prop_options.h"
64 #include "options/quantifiers_options.h"
65 #include "options/sep_options.h"
66 #include "options/set_language.h"
67 #include "options/smt_options.h"
68 #include "options/strings_options.h"
69 #include "options/theory_options.h"
70 #include "options/uf_options.h"
71 #include "preprocessing/passes/apply_substs.h"
72 #include "preprocessing/passes/bool_to_bv.h"
73 #include "preprocessing/passes/bv_abstraction.h"
74 #include "preprocessing/passes/bv_ackermann.h"
75 #include "preprocessing/passes/bv_gauss.h"
76 #include "preprocessing/passes/bv_intro_pow2.h"
77 #include "preprocessing/passes/bv_to_bool.h"
78 #include "preprocessing/passes/int_to_bv.h"
79 #include "preprocessing/passes/pseudo_boolean_processor.h"
80 #include "preprocessing/passes/real_to_int.h"
81 #include "preprocessing/passes/rewrite.h"
82 #include "preprocessing/passes/static_learning.h"
83 #include "preprocessing/passes/symmetry_breaker.h"
84 #include "preprocessing/passes/symmetry_detect.h"
85 #include "preprocessing/passes/synth_rew_rules.h"
86 #include "preprocessing/preprocessing_pass.h"
87 #include "preprocessing/preprocessing_pass_context.h"
88 #include "preprocessing/preprocessing_pass_registry.h"
89 #include "printer/printer.h"
90 #include "proof/proof.h"
91 #include "proof/proof_manager.h"
92 #include "proof/theory_proof.h"
93 #include "proof/unsat_core.h"
94 #include "prop/prop_engine.h"
95 #include "smt/command.h"
96 #include "smt/command_list.h"
97 #include "smt/logic_request.h"
98 #include "smt/managed_ostreams.h"
99 #include "smt/smt_engine_scope.h"
100 #include "smt/term_formula_removal.h"
101 #include "smt/update_ostream.h"
102 #include "smt_util/boolean_simplification.h"
103 #include "smt_util/nary_builder.h"
104 #include "smt_util/node_visitor.h"
105 #include "theory/booleans/circuit_propagator.h"
106 #include "theory/bv/theory_bv_rewriter.h"
107 #include "theory/logic_info.h"
108 #include "theory/quantifiers/fun_def_process.h"
109 #include "theory/quantifiers/global_negate.h"
110 #include "theory/quantifiers/macros.h"
111 #include "theory/quantifiers/quantifiers_rewriter.h"
112 #include "theory/quantifiers/single_inv_partition.h"
113 #include "theory/quantifiers/sygus/ce_guided_instantiation.h"
114 #include "theory/quantifiers/sygus_inference.h"
115 #include "theory/quantifiers/term_util.h"
116 #include "theory/rewriter.h"
117 #include "theory/sort_inference.h"
118 #include "theory/strings/theory_strings.h"
119 #include "theory/substitutions.h"
120 #include "theory/theory_engine.h"
121 #include "theory/theory_model.h"
122 #include "theory/theory_traits.h"
123 #include "util/hash.h"
124 #include "util/proof.h"
125 #include "util/random.h"
126 #include "util/resource_manager.h"
129 using namespace CVC4
;
130 using namespace CVC4::smt
;
131 using namespace CVC4::preprocessing
;
132 using namespace CVC4::preprocessing::passes
;
133 using namespace CVC4::prop
;
134 using namespace CVC4::context
;
135 using namespace CVC4::theory
;
140 struct DeleteCommandFunction
: public std::unary_function
<const Command
*, void>
142 void operator()(const Command
* command
) { delete command
; }
145 void DeleteAndClearCommandVector(std::vector
<Command
*>& commands
) {
146 std::for_each(commands
.begin(), commands
.end(), DeleteCommandFunction());
150 /** Useful for counting the number of recursive calls. */
155 ScopeCounter(unsigned& d
) : d_depth(d
) {
164 * Representation of a defined function. We keep these around in
165 * SmtEngine to permit expanding definitions late (and lazily), to
166 * support getValue() over defined functions, to support user output
167 * in terms of defined functions, etc.
169 class DefinedFunction
{
171 vector
<Node
> d_formals
;
175 DefinedFunction(Node func
, vector
<Node
> formals
, Node formula
) :
180 Node
getFunction() const { return d_func
; }
181 vector
<Node
> getFormals() const { return d_formals
; }
182 Node
getFormula() const { return d_formula
; }
183 };/* class DefinedFunction */
185 struct SmtEngineStatistics
{
186 /** time spent in gaussian elimination */
187 TimerStat d_gaussElimTime
;
188 /** time spent in definition-expansion */
189 TimerStat d_definitionExpansionTime
;
190 /** time spent in non-clausal simplification */
191 TimerStat d_nonclausalSimplificationTime
;
192 /** time spent in miplib pass */
193 TimerStat d_miplibPassTime
;
194 /** number of assertions removed by miplib pass */
195 IntStat d_numMiplibAssertionsRemoved
;
196 /** number of constant propagations found during nonclausal simp */
197 IntStat d_numConstantProps
;
198 /** time spent in simplifying ITEs */
199 TimerStat d_simpITETime
;
200 /** time spent in simplifying ITEs */
201 TimerStat d_unconstrainedSimpTime
;
202 /** time spent removing ITEs */
203 TimerStat d_iteRemovalTime
;
204 /** time spent in theory preprocessing */
205 TimerStat d_theoryPreprocessTime
;
206 /** time spent in theory preprocessing */
207 TimerStat d_rewriteApplyToConstTime
;
208 /** time spent converting to CNF */
209 TimerStat d_cnfConversionTime
;
210 /** Num of assertions before ite removal */
211 IntStat d_numAssertionsPre
;
212 /** Num of assertions after ite removal */
213 IntStat d_numAssertionsPost
;
214 /** time spent in checkModel() */
215 TimerStat d_checkModelTime
;
216 /** time spent in checkProof() */
217 TimerStat d_checkProofTime
;
218 /** time spent in checkUnsatCore() */
219 TimerStat d_checkUnsatCoreTime
;
220 /** time spent in PropEngine::checkSat() */
221 TimerStat d_solveTime
;
222 /** time spent in pushing/popping */
223 TimerStat d_pushPopTime
;
224 /** time spent in processAssertions() */
225 TimerStat d_processAssertionsTime
;
227 /** Has something simplified to false? */
228 IntStat d_simplifiedToFalse
;
229 /** Number of resource units spent. */
230 ReferenceStat
<uint64_t> d_resourceUnitsUsed
;
232 SmtEngineStatistics() :
233 d_gaussElimTime("smt::SmtEngine::gaussElimTime"),
234 d_definitionExpansionTime("smt::SmtEngine::definitionExpansionTime"),
235 d_nonclausalSimplificationTime("smt::SmtEngine::nonclausalSimplificationTime"),
236 d_miplibPassTime("smt::SmtEngine::miplibPassTime"),
237 d_numMiplibAssertionsRemoved("smt::SmtEngine::numMiplibAssertionsRemoved", 0),
238 d_numConstantProps("smt::SmtEngine::numConstantProps", 0),
239 d_simpITETime("smt::SmtEngine::simpITETime"),
240 d_unconstrainedSimpTime("smt::SmtEngine::unconstrainedSimpTime"),
241 d_iteRemovalTime("smt::SmtEngine::iteRemovalTime"),
242 d_theoryPreprocessTime("smt::SmtEngine::theoryPreprocessTime"),
243 d_rewriteApplyToConstTime("smt::SmtEngine::rewriteApplyToConstTime"),
244 d_cnfConversionTime("smt::SmtEngine::cnfConversionTime"),
245 d_numAssertionsPre("smt::SmtEngine::numAssertionsPreITERemoval", 0),
246 d_numAssertionsPost("smt::SmtEngine::numAssertionsPostITERemoval", 0),
247 d_checkModelTime("smt::SmtEngine::checkModelTime"),
248 d_checkProofTime("smt::SmtEngine::checkProofTime"),
249 d_checkUnsatCoreTime("smt::SmtEngine::checkUnsatCoreTime"),
250 d_solveTime("smt::SmtEngine::solveTime"),
251 d_pushPopTime("smt::SmtEngine::pushPopTime"),
252 d_processAssertionsTime("smt::SmtEngine::processAssertionsTime"),
253 d_simplifiedToFalse("smt::SmtEngine::simplifiedToFalse", 0),
254 d_resourceUnitsUsed("smt::SmtEngine::resourceUnitsUsed")
257 smtStatisticsRegistry()->registerStat(&d_gaussElimTime
);
258 smtStatisticsRegistry()->registerStat(&d_definitionExpansionTime
);
259 smtStatisticsRegistry()->registerStat(&d_nonclausalSimplificationTime
);
260 smtStatisticsRegistry()->registerStat(&d_miplibPassTime
);
261 smtStatisticsRegistry()->registerStat(&d_numMiplibAssertionsRemoved
);
262 smtStatisticsRegistry()->registerStat(&d_numConstantProps
);
263 smtStatisticsRegistry()->registerStat(&d_simpITETime
);
264 smtStatisticsRegistry()->registerStat(&d_unconstrainedSimpTime
);
265 smtStatisticsRegistry()->registerStat(&d_iteRemovalTime
);
266 smtStatisticsRegistry()->registerStat(&d_theoryPreprocessTime
);
267 smtStatisticsRegistry()->registerStat(&d_rewriteApplyToConstTime
);
268 smtStatisticsRegistry()->registerStat(&d_cnfConversionTime
);
269 smtStatisticsRegistry()->registerStat(&d_numAssertionsPre
);
270 smtStatisticsRegistry()->registerStat(&d_numAssertionsPost
);
271 smtStatisticsRegistry()->registerStat(&d_checkModelTime
);
272 smtStatisticsRegistry()->registerStat(&d_checkProofTime
);
273 smtStatisticsRegistry()->registerStat(&d_checkUnsatCoreTime
);
274 smtStatisticsRegistry()->registerStat(&d_solveTime
);
275 smtStatisticsRegistry()->registerStat(&d_pushPopTime
);
276 smtStatisticsRegistry()->registerStat(&d_processAssertionsTime
);
277 smtStatisticsRegistry()->registerStat(&d_simplifiedToFalse
);
278 smtStatisticsRegistry()->registerStat(&d_resourceUnitsUsed
);
281 ~SmtEngineStatistics() {
282 smtStatisticsRegistry()->unregisterStat(&d_gaussElimTime
);
283 smtStatisticsRegistry()->unregisterStat(&d_definitionExpansionTime
);
284 smtStatisticsRegistry()->unregisterStat(&d_nonclausalSimplificationTime
);
285 smtStatisticsRegistry()->unregisterStat(&d_miplibPassTime
);
286 smtStatisticsRegistry()->unregisterStat(&d_numMiplibAssertionsRemoved
);
287 smtStatisticsRegistry()->unregisterStat(&d_numConstantProps
);
288 smtStatisticsRegistry()->unregisterStat(&d_simpITETime
);
289 smtStatisticsRegistry()->unregisterStat(&d_unconstrainedSimpTime
);
290 smtStatisticsRegistry()->unregisterStat(&d_iteRemovalTime
);
291 smtStatisticsRegistry()->unregisterStat(&d_theoryPreprocessTime
);
292 smtStatisticsRegistry()->unregisterStat(&d_rewriteApplyToConstTime
);
293 smtStatisticsRegistry()->unregisterStat(&d_cnfConversionTime
);
294 smtStatisticsRegistry()->unregisterStat(&d_numAssertionsPre
);
295 smtStatisticsRegistry()->unregisterStat(&d_numAssertionsPost
);
296 smtStatisticsRegistry()->unregisterStat(&d_checkModelTime
);
297 smtStatisticsRegistry()->unregisterStat(&d_checkProofTime
);
298 smtStatisticsRegistry()->unregisterStat(&d_checkUnsatCoreTime
);
299 smtStatisticsRegistry()->unregisterStat(&d_solveTime
);
300 smtStatisticsRegistry()->unregisterStat(&d_pushPopTime
);
301 smtStatisticsRegistry()->unregisterStat(&d_processAssertionsTime
);
302 smtStatisticsRegistry()->unregisterStat(&d_simplifiedToFalse
);
303 smtStatisticsRegistry()->unregisterStat(&d_resourceUnitsUsed
);
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
;
531 * A context that never pushes/pops, for use by CD structures (like
532 * SubstitutionMaps) that should be "global".
534 context::Context d_fakeContext
;
537 * A map of AbsractValues to their actual constants. Only used if
538 * options::abstractValues() is on.
540 SubstitutionMap d_abstractValueMap
;
543 * A mapping of all abstract values (actual value |-> abstract) that
544 * we've handed out. This is necessary to ensure that we give the
545 * same AbstractValues for the same real constants. Only used if
546 * options::abstractValues() is on.
548 NodeToNodeHashMap d_abstractValues
;
550 /** Number of calls of simplify assertions active.
552 unsigned d_simplifyAssertionsDepth
;
554 /** TODO: whether certain preprocess steps are necessary */
555 //bool d_needsExpandDefs;
557 //------------------------------- expression names
558 /** mapping from expressions to name */
559 context::CDHashMap
< Node
, std::string
, NodeHashFunction
> d_exprNames
;
560 //------------------------------- end expression names
563 * Map from skolem variables to index in d_assertions containing
564 * corresponding introduced Boolean ite
566 IteSkolemMap d_iteSkolemMap
;
568 /** Instance of the ITE remover */
569 RemoveTermFormulas d_iteRemover
;
571 /* Finishes the initialization of the private portion of SMTEngine. */
575 std::unique_ptr
<PreprocessingPassContext
> d_preprocessingPassContext
;
576 PreprocessingPassRegistry d_preprocessingPassRegistry
;
578 static const bool d_doConstantProp
= true;
581 * Runs the nonclausal solver and tries to solve all the assigned
584 * Returns false if the formula simplifies to "false"
586 bool nonClausalSimplify();
589 * Performs static learning on the assertions.
591 void staticLearning();
594 * Remove ITEs from the assertions.
598 Node
realToInt(TNode n
, NodeToNodeHashMap
& cache
, std::vector
< Node
>& var_eq
);
599 Node
purifyNlTerms(TNode n
, NodeToNodeHashMap
& cache
, NodeToNodeHashMap
& bcache
, std::vector
< Node
>& var_eq
, bool beneathMult
= false);
602 * Helper function to fix up assertion list to restore invariants needed after
605 void collectSkolems(TNode n
, set
<TNode
>& skolemSet
, NodeToBoolHashMap
& cache
);
608 * Helper function to fix up assertion list to restore invariants needed after
611 bool checkForBadSkolems(TNode n
, TNode skolem
, NodeToBoolHashMap
& cache
);
613 // Simplify ITE structure
616 // Simplify based on unconstrained values
617 void unconstrainedSimp();
620 * Ensures the assertions asserted after before now effectively come before
621 * d_realAssertionsEnd.
623 void compressBeforeRealAssertions(size_t before
);
626 * Trace nodes back to their assertions using CircuitPropagator's
629 void traceBackToAssertions(const std::vector
<Node
>& nodes
,
630 std::vector
<TNode
>& assertions
);
633 * Remove conjuncts in toRemove from conjunction n. Return # of removed
636 size_t removeFromConjunction(Node
& n
,
637 const std::unordered_set
<unsigned long>& toRemove
);
639 /** Scrub miplib encodings. */
640 void doMiplibTrick();
643 * Perform non-clausal simplification of a Node. This involves
644 * Theory implementations, but does NOT involve the SAT solver in
647 * Returns false if the formula simplifies to "false"
649 bool simplifyAssertions();
652 SmtEnginePrivate(SmtEngine
& smt
)
654 d_managedRegularChannel(),
655 d_managedDiagnosticChannel(),
656 d_managedDumpChannel(),
657 d_managedReplayLog(),
658 d_listenerRegistrations(new ListenerRegistrationList()),
659 d_nonClausalLearnedLiterals(),
660 d_realAssertionsEnd(0),
661 d_propagator(d_nonClausalLearnedLiterals
, true, true),
662 d_propagatorNeedsFinish(false),
663 d_assertions(d_smt
.d_userContext
),
664 d_assertionsProcessed(smt
.d_userContext
, false),
666 d_abstractValueMap(&d_fakeContext
),
668 d_simplifyAssertionsDepth(0),
669 // d_needsExpandDefs(true), //TODO?
670 d_exprNames(smt
.d_userContext
),
672 d_iteRemover(smt
.d_userContext
)
674 d_smt
.d_nodeManager
->subscribeEvents(this);
675 d_true
= NodeManager::currentNM()->mkConst(true);
676 d_resourceManager
= NodeManager::currentResourceManager();
678 d_listenerRegistrations
->add(d_resourceManager
->registerSoftListener(
679 new SoftResourceOutListener(d_smt
)));
681 d_listenerRegistrations
->add(d_resourceManager
->registerHardListener(
682 new HardResourceOutListener(d_smt
)));
684 Options
& nodeManagerOptions
= NodeManager::currentNM()->getOptions();
685 d_listenerRegistrations
->add(
686 nodeManagerOptions
.registerForceLogicListener(
687 new SetLogicListener(d_smt
), true));
689 // Multiple options reuse BeforeSearchListener so registration requires an
690 // extra bit of care.
691 // We can safely not call notify on this before search listener at
692 // registration time. This d_smt cannot be beforeSearch at construction
693 // time. Therefore the BeforeSearchListener is a no-op. Therefore it does
694 // not have to be called.
695 d_listenerRegistrations
->add(
696 nodeManagerOptions
.registerBeforeSearchListener(
697 new BeforeSearchListener(d_smt
)));
699 // These do need registration calls.
700 d_listenerRegistrations
->add(
701 nodeManagerOptions
.registerSetDefaultExprDepthListener(
702 new SetDefaultExprDepthListener(), true));
703 d_listenerRegistrations
->add(
704 nodeManagerOptions
.registerSetDefaultExprDagListener(
705 new SetDefaultExprDagListener(), true));
706 d_listenerRegistrations
->add(
707 nodeManagerOptions
.registerSetPrintExprTypesListener(
708 new SetPrintExprTypesListener(), true));
709 d_listenerRegistrations
->add(
710 nodeManagerOptions
.registerSetDumpModeListener(
711 new DumpModeListener(), true));
712 d_listenerRegistrations
->add(
713 nodeManagerOptions
.registerSetPrintSuccessListener(
714 new PrintSuccessListener(), true));
715 d_listenerRegistrations
->add(
716 nodeManagerOptions
.registerSetRegularOutputChannelListener(
717 new SetToDefaultSourceListener(&d_managedRegularChannel
), true));
718 d_listenerRegistrations
->add(
719 nodeManagerOptions
.registerSetDiagnosticOutputChannelListener(
720 new SetToDefaultSourceListener(&d_managedDiagnosticChannel
), true));
721 d_listenerRegistrations
->add(
722 nodeManagerOptions
.registerDumpToFileNameListener(
723 new SetToDefaultSourceListener(&d_managedDumpChannel
), true));
724 d_listenerRegistrations
->add(
725 nodeManagerOptions
.registerSetReplayLogFilename(
726 new SetToDefaultSourceListener(&d_managedReplayLog
), true));
731 delete d_listenerRegistrations
;
733 if(d_propagatorNeedsFinish
) {
734 d_propagator
.finish();
735 d_propagatorNeedsFinish
= false;
737 d_smt
.d_nodeManager
->unsubscribeEvents(this);
740 void unregisterPreprocessingPasses()
742 d_preprocessingPassRegistry
.unregisterPasses();
745 ResourceManager
* getResourceManager() { return d_resourceManager
; }
746 void spendResource(unsigned amount
)
748 d_resourceManager
->spendResource(amount
);
751 void nmNotifyNewSort(TypeNode tn
, uint32_t flags
) override
753 DeclareTypeCommand
c(tn
.getAttribute(expr::VarNameAttr()),
756 if((flags
& ExprManager::SORT_FLAG_PLACEHOLDER
) == 0) {
757 d_smt
.addToModelCommandAndDump(c
, flags
);
761 void nmNotifyNewSortConstructor(TypeNode tn
) override
763 DeclareTypeCommand
c(tn
.getAttribute(expr::VarNameAttr()),
764 tn
.getAttribute(expr::SortArityAttr()),
766 d_smt
.addToModelCommandAndDump(c
);
769 void nmNotifyNewDatatypes(const std::vector
<DatatypeType
>& dtts
) override
771 DatatypeDeclarationCommand
c(dtts
);
772 d_smt
.addToModelCommandAndDump(c
);
775 void nmNotifyNewVar(TNode n
, uint32_t flags
) override
777 DeclareFunctionCommand
c(n
.getAttribute(expr::VarNameAttr()),
779 n
.getType().toType());
780 if((flags
& ExprManager::VAR_FLAG_DEFINED
) == 0) {
781 d_smt
.addToModelCommandAndDump(c
, flags
);
783 if(n
.getType().isBoolean() && !options::incrementalSolving()) {
784 d_boolVars
.push_back(n
);
788 void nmNotifyNewSkolem(TNode n
,
789 const std::string
& comment
,
790 uint32_t flags
) override
792 string id
= n
.getAttribute(expr::VarNameAttr());
793 DeclareFunctionCommand
c(id
, n
.toExpr(), n
.getType().toType());
794 if(Dump
.isOn("skolems") && comment
!= "") {
795 Dump("skolems") << CommentCommand(id
+ " is " + comment
);
797 if((flags
& ExprManager::VAR_FLAG_DEFINED
) == 0) {
798 d_smt
.addToModelCommandAndDump(c
, flags
, false, "skolems");
800 if(n
.getType().isBoolean() && !options::incrementalSolving()) {
801 d_boolVars
.push_back(n
);
805 void nmNotifyDeleteNode(TNode n
) override
{}
807 Node
applySubstitutions(TNode node
)
809 return Rewriter::rewrite(
810 d_assertions
.getTopLevelSubstitutions().apply(node
));
814 * Process the assertions that have been asserted.
816 void processAssertions();
818 /** Process a user push.
825 * Process a user pop. Clears out the non-context-dependent stuff in this
826 * SmtEnginePrivate. Necessary to clear out our assertion vectors in case
827 * someone does a push-assert-pop without a check-sat. It also pops the
828 * last map of expression names from notifyPush.
831 d_assertions
.clear();
832 d_nonClausalLearnedLiterals
.clear();
833 d_realAssertionsEnd
= 0;
834 d_iteSkolemMap
.clear();
838 * Adds a formula to the current context. Action here depends on
839 * the SimplificationMode (in the current Options scope); the
840 * formula might be pushed out to the propositional layer
841 * immediately, or it might be simplified and kept, or it might not
842 * even be simplified.
843 * the 2nd and 3rd arguments added for bookkeeping for proofs
845 void addFormula(TNode n
, bool inUnsatCore
, bool inInput
= true);
847 /** Expand definitions in n. */
848 Node
expandDefinitions(TNode n
,
849 NodeToNodeHashMap
& cache
,
850 bool expandOnly
= false);
853 * Simplify node "in" by expanding definitions and applying any
854 * substitutions learned from preprocessing.
856 Node
simplify(TNode in
) {
857 // Substitute out any abstract values in ex.
858 // Expand definitions.
859 NodeToNodeHashMap cache
;
860 Node n
= expandDefinitions(in
, cache
).toExpr();
861 // Make sure we've done all preprocessing, etc.
862 Assert(d_assertions
.size() == 0);
863 return applySubstitutions(n
).toExpr();
867 * Substitute away all AbstractValues in a node.
869 Node
substituteAbstractValues(TNode n
) {
870 // We need to do this even if options::abstractValues() is off,
871 // since the setting might have changed after we already gave out
872 // some abstract values.
873 return d_abstractValueMap
.apply(n
);
877 * Make a new (or return an existing) abstract value for a node.
878 * Can only use this if options::abstractValues() is on.
880 Node
mkAbstractValue(TNode n
) {
881 Assert(options::abstractValues());
882 Node
& val
= d_abstractValues
[n
];
884 val
= d_smt
.d_nodeManager
->mkAbstractValue(n
.getType());
885 d_abstractValueMap
.addSubstitution(val
, n
);
887 // We are supposed to ascribe types to all abstract values that go out.
888 NodeManager
* current
= d_smt
.d_nodeManager
;
889 Node ascription
= current
->mkConst(AscriptionType(n
.getType().toType()));
890 Node retval
= current
->mkNode(kind::APPLY_TYPE_ASCRIPTION
, ascription
, val
);
894 NodeToNodeHashMap d_rewriteApplyToConstCache
;
895 Node
rewriteApplyToConst(TNode n
) {
896 Trace("rewriteApplyToConst") << "rewriteApplyToConst :: " << n
<< std::endl
;
898 if(n
.getMetaKind() == kind::metakind::CONSTANT
||
899 n
.getMetaKind() == kind::metakind::VARIABLE
||
900 n
.getMetaKind() == kind::metakind::NULLARY_OPERATOR
)
905 if(d_rewriteApplyToConstCache
.find(n
) != d_rewriteApplyToConstCache
.end()) {
906 Trace("rewriteApplyToConst") << "in cache :: "
907 << d_rewriteApplyToConstCache
[n
]
909 return d_rewriteApplyToConstCache
[n
];
912 if(n
.getKind() == kind::APPLY_UF
) {
913 if(n
.getNumChildren() == 1 && n
[0].isConst() &&
914 n
[0].getType().isInteger())
917 ss
<< n
.getOperator() << "_";
918 if(n
[0].getConst
<Rational
>() < 0) {
919 ss
<< "m" << -n
[0].getConst
<Rational
>();
923 Node newvar
= NodeManager::currentNM()->mkSkolem(
924 ss
.str(), n
.getType(), "rewriteApplyToConst skolem",
925 NodeManager::SKOLEM_EXACT_NAME
);
926 d_rewriteApplyToConstCache
[n
] = newvar
;
927 Trace("rewriteApplyToConst") << "made :: " << newvar
<< std::endl
;
931 ss
<< "The rewrite-apply-to-const preprocessor is currently limited;"
933 << "it only works if all function symbols are unary and with Integer"
935 << "domain, and all applications are to integer values." << std::endl
936 << "Found application: " << n
;
941 NodeBuilder
<> builder(n
.getKind());
942 if(n
.getMetaKind() == kind::metakind::PARAMETERIZED
) {
943 builder
<< n
.getOperator();
945 for(unsigned i
= 0; i
< n
.getNumChildren(); ++i
) {
946 builder
<< rewriteApplyToConst(n
[i
]);
949 d_rewriteApplyToConstCache
[n
] = rewr
;
950 Trace("rewriteApplyToConst") << "built :: " << rewr
<< std::endl
;
954 void addUseTheoryListListener(TheoryEngine
* theoryEngine
){
955 Options
& nodeManagerOptions
= NodeManager::currentNM()->getOptions();
956 d_listenerRegistrations
->add(
957 nodeManagerOptions
.registerUseTheoryListListener(
958 new UseTheoryListListener(theoryEngine
), true));
961 std::ostream
* getReplayLog() const {
962 return d_managedReplayLog
.getReplayLog();
965 //------------------------------- expression names
966 // implements setExpressionName, as described in smt_engine.h
967 void setExpressionName(Expr e
, std::string name
) {
968 d_exprNames
[Node::fromExpr(e
)] = name
;
971 // implements getExpressionName, as described in smt_engine.h
972 bool getExpressionName(Expr e
, std::string
& name
) const {
973 context::CDHashMap
< Node
, std::string
, NodeHashFunction
>::const_iterator it
= d_exprNames
.find(e
);
974 if(it
!=d_exprNames
.end()) {
981 //------------------------------- end expression names
983 };/* class SmtEnginePrivate */
985 }/* namespace CVC4::smt */
987 SmtEngine::SmtEngine(ExprManager
* em
)
988 : d_context(new Context()),
990 d_userContext(new UserContext()),
992 d_nodeManager(d_exprManager
->getNodeManager()),
993 d_decisionEngine(NULL
),
994 d_theoryEngine(NULL
),
996 d_proofManager(NULL
),
997 d_definedFunctions(NULL
),
998 d_fmfRecFunctionsDefined(NULL
),
999 d_assertionList(NULL
),
1000 d_assignments(NULL
),
1001 d_modelGlobalCommands(),
1002 d_modelCommands(NULL
),
1006 d_originalOptions(),
1008 d_fullyInited(false),
1009 d_problemExtended(false),
1011 d_needPostsolve(false),
1012 d_earlyTheoryPP(true),
1013 d_globalNegation(false),
1015 d_replayStream(NULL
),
1017 d_statisticsRegistry(NULL
),
1019 d_channels(new LemmaChannels())
1021 SmtScope
smts(this);
1022 d_originalOptions
.copyValues(em
->getOptions());
1023 d_private
= new smt::SmtEnginePrivate(*this);
1024 d_statisticsRegistry
= new StatisticsRegistry();
1025 d_stats
= new SmtEngineStatistics();
1026 d_stats
->d_resourceUnitsUsed
.setData(
1027 d_private
->getResourceManager()->getResourceUsage());
1029 // The ProofManager is constructed before any other proof objects such as
1030 // SatProof and TheoryProofs. The TheoryProofEngine and the SatProof are
1031 // initialized in TheoryEngine and PropEngine respectively.
1032 Assert(d_proofManager
== NULL
);
1034 // d_proofManager must be created before Options has been finished
1035 // being parsed from the input file. Because of this, we cannot trust
1036 // that options::proof() is set correctly yet.
1038 d_proofManager
= new ProofManager(d_userContext
);
1041 // We have mutual dependency here, so we add the prop engine to the theory
1042 // engine later (it is non-essential there)
1043 d_theoryEngine
= new TheoryEngine(d_context
, d_userContext
,
1044 d_private
->d_iteRemover
,
1045 const_cast<const LogicInfo
&>(d_logic
),
1049 for(TheoryId id
= theory::THEORY_FIRST
; id
< theory::THEORY_LAST
; ++id
) {
1050 TheoryConstructor::addTheory(d_theoryEngine
, id
);
1051 //register with proof engine if applicable
1053 ProofManager::currentPM()->getTheoryProofEngine()->registerTheory(d_theoryEngine
->theoryOf(id
));
1057 d_private
->addUseTheoryListListener(d_theoryEngine
);
1059 // global push/pop around everything, to ensure proper destruction
1060 // of context-dependent data structures
1061 d_userContext
->push();
1064 d_definedFunctions
= new(true) DefinedFunctionMap(d_userContext
);
1065 d_fmfRecFunctionsDefined
= new(true) NodeList(d_userContext
);
1066 d_modelCommands
= new(true) smt::CommandList(d_userContext
);
1069 void SmtEngine::finishInit() {
1070 Trace("smt-debug") << "SmtEngine::finishInit" << std::endl
;
1071 // ensure that our heuristics are properly set up
1074 Trace("smt-debug") << "Making decision engine..." << std::endl
;
1076 d_decisionEngine
= new DecisionEngine(d_context
, d_userContext
);
1077 d_decisionEngine
->init(); // enable appropriate strategies
1079 Trace("smt-debug") << "Making prop engine..." << std::endl
;
1080 d_propEngine
= new PropEngine(d_theoryEngine
, d_decisionEngine
, d_context
,
1081 d_userContext
, d_private
->getReplayLog(),
1082 d_replayStream
, d_channels
);
1084 Trace("smt-debug") << "Setting up theory engine..." << std::endl
;
1085 d_theoryEngine
->setPropEngine(d_propEngine
);
1086 d_theoryEngine
->setDecisionEngine(d_decisionEngine
);
1087 Trace("smt-debug") << "Finishing init for theory engine..." << std::endl
;
1088 d_theoryEngine
->finishInit();
1090 Trace("smt-debug") << "Set up assertion list..." << std::endl
;
1091 // [MGD 10/20/2011] keep around in incremental mode, due to a
1092 // cleanup ordering issue and Nodes/TNodes. If SAT is popped
1093 // first, some user-context-dependent TNodes might still exist
1095 if(options::produceAssertions() ||
1096 options::incrementalSolving()) {
1097 // In the case of incremental solving, we appear to need these to
1098 // ensure the relevant Nodes remain live.
1099 d_assertionList
= new(true) AssertionList(d_userContext
);
1102 // dump out a set-logic command
1103 if(Dump
.isOn("benchmark")) {
1104 if (Dump
.isOn("raw-benchmark")) {
1105 Dump("raw-benchmark") << SetBenchmarkLogicCommand(d_logic
.getLogicString());
1107 LogicInfo everything
;
1109 Dump("benchmark") << CommentCommand("CVC4 always dumps the most general, all-supported logic (below), as some internals might require the use of a logic more general than the input.")
1110 << SetBenchmarkLogicCommand(everything
.getLogicString());
1114 Trace("smt-debug") << "Dump declaration commands..." << std::endl
;
1115 // dump out any pending declaration commands
1116 for(unsigned i
= 0; i
< d_dumpCommands
.size(); ++i
) {
1117 Dump("declarations") << *d_dumpCommands
[i
];
1118 delete d_dumpCommands
[i
];
1120 d_dumpCommands
.clear();
1122 PROOF( ProofManager::currentPM()->setLogic(d_logic
); );
1124 for(TheoryId id
= theory::THEORY_FIRST
; id
< theory::THEORY_LAST
; ++id
) {
1125 ProofManager::currentPM()->getTheoryProofEngine()->
1126 finishRegisterTheory(d_theoryEngine
->theoryOf(id
));
1129 d_private
->finishInit();
1130 Trace("smt-debug") << "SmtEngine::finishInit done" << std::endl
;
1133 void SmtEngine::finalOptionsAreSet() {
1138 if(! d_logic
.isLocked()) {
1142 // finish initialization, create the prop engine, etc.
1145 AlwaysAssert( d_propEngine
->getAssertionLevel() == 0,
1146 "The PropEngine has pushed but the SmtEngine "
1147 "hasn't finished initializing!" );
1149 d_fullyInited
= true;
1150 Assert(d_logic
.isLocked());
1152 d_propEngine
->assertFormula(NodeManager::currentNM()->mkConst
<bool>(true));
1153 d_propEngine
->assertFormula(NodeManager::currentNM()->mkConst
<bool>(false).notNode());
1156 void SmtEngine::shutdown() {
1159 while(options::incrementalSolving() && d_userContext
->getLevel() > 1) {
1163 // check to see if a postsolve() is pending
1164 if(d_needPostsolve
) {
1165 d_theoryEngine
->postsolve();
1166 d_needPostsolve
= false;
1169 if(d_propEngine
!= NULL
) {
1170 d_propEngine
->shutdown();
1172 if(d_theoryEngine
!= NULL
) {
1173 d_theoryEngine
->shutdown();
1175 if(d_decisionEngine
!= NULL
) {
1176 d_decisionEngine
->shutdown();
1180 SmtEngine::~SmtEngine()
1182 SmtScope
smts(this);
1187 // global push/pop around everything, to ensure proper destruction
1188 // of context-dependent data structures
1189 d_context
->popto(0);
1190 d_userContext
->popto(0);
1192 if(d_assignments
!= NULL
) {
1193 d_assignments
->deleteSelf();
1196 if(d_assertionList
!= NULL
) {
1197 d_assertionList
->deleteSelf();
1200 for(unsigned i
= 0; i
< d_dumpCommands
.size(); ++i
) {
1201 delete d_dumpCommands
[i
];
1202 d_dumpCommands
[i
] = NULL
;
1204 d_dumpCommands
.clear();
1206 DeleteAndClearCommandVector(d_modelGlobalCommands
);
1208 if(d_modelCommands
!= NULL
) {
1209 d_modelCommands
->deleteSelf();
1212 d_definedFunctions
->deleteSelf();
1213 d_fmfRecFunctionsDefined
->deleteSelf();
1215 //destroy all passes before destroying things that they refer to
1216 d_private
->unregisterPreprocessingPasses();
1218 delete d_theoryEngine
;
1219 d_theoryEngine
= NULL
;
1220 delete d_propEngine
;
1221 d_propEngine
= NULL
;
1222 delete d_decisionEngine
;
1223 d_decisionEngine
= NULL
;
1226 // d_proofManager is always created when proofs are enabled at configure time.
1227 // Becuase of this, this code should not be wrapped in PROOF() which
1228 // additionally checks flags such as options::proof().
1230 delete d_proofManager
;
1231 d_proofManager
= NULL
;
1236 delete d_statisticsRegistry
;
1237 d_statisticsRegistry
= NULL
;
1242 delete d_userContext
;
1243 d_userContext
= NULL
;
1250 } catch(Exception
& e
) {
1251 Warning() << "CVC4 threw an exception during cleanup." << endl
1256 void SmtEngine::setLogic(const LogicInfo
& logic
)
1258 SmtScope
smts(this);
1260 throw ModalException("Cannot set logic in SmtEngine after the engine has "
1261 "finished initializing.");
1267 void SmtEngine::setLogic(const std::string
& s
)
1269 SmtScope
smts(this);
1271 setLogic(LogicInfo(s
));
1272 } catch(IllegalArgumentException
& e
) {
1273 throw LogicException(e
.what());
1277 void SmtEngine::setLogic(const char* logic
) { setLogic(string(logic
)); }
1278 LogicInfo
SmtEngine::getLogicInfo() const {
1281 void SmtEngine::setLogicInternal()
1283 Assert(!d_fullyInited
, "setting logic in SmtEngine but the engine has already"
1284 " finished initializing for this run");
1288 void SmtEngine::setDefaults() {
1289 Random::getRandom().setSeed(options::seed());
1290 // Language-based defaults
1291 if (!options::bitvectorDivByZeroConst
.wasSetByUser())
1293 options::bitvectorDivByZeroConst
.set(
1294 language::isInputLang_smt2_6(options::inputLanguage()));
1296 bool is_sygus
= false;
1297 if (options::inputLanguage() == language::input::LANG_SYGUS
)
1300 if (!options::ceGuidedInst
.wasSetByUser())
1302 options::ceGuidedInst
.set(true);
1304 // must use Ferrante/Rackoff for real arithmetic
1305 if (!options::cbqiMidpoint
.wasSetByUser())
1307 options::cbqiMidpoint
.set(true);
1309 if (options::sygusRepairConst())
1311 if (!options::cbqi
.wasSetByUser())
1313 options::cbqi
.set(true);
1318 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER
)
1320 if (options::incrementalSolving())
1322 if (options::incrementalSolving
.wasSetByUser())
1324 throw OptionException(std::string(
1325 "Eager bit-blasting does not currently support incremental mode. "
1326 "Try --bitblast=lazy"));
1328 Notice() << "SmtEngine: turning off incremental to support eager "
1329 << "bit-blasting" << endl
;
1330 setOption("incremental", SExpr("false"));
1332 if (options::produceModels()
1333 && (d_logic
.isTheoryEnabled(THEORY_ARRAYS
)
1334 || d_logic
.isTheoryEnabled(THEORY_UF
)))
1336 if (options::bitblastMode
.wasSetByUser()
1337 || options::produceModels
.wasSetByUser())
1339 throw OptionException(std::string(
1340 "Eager bit-blasting currently does not support model generation "
1341 "for the combination of bit-vectors with arrays or uinterpreted "
1342 "functions. Try --bitblast=lazy"));
1344 Notice() << "SmtEngine: setting bit-blast mode to lazy to support model"
1345 << "generation" << endl
;
1346 setOption("bitblastMode", SExpr("lazy"));
1350 if(options::forceLogicString
.wasSetByUser()) {
1351 d_logic
= LogicInfo(options::forceLogicString());
1352 }else if (options::solveIntAsBV() > 0) {
1353 d_logic
= LogicInfo("QF_BV");
1354 }else if (d_logic
.getLogicString() == "QF_NRA" && options::solveRealAsInt()) {
1355 d_logic
= LogicInfo("QF_NIA");
1356 } else if ((d_logic
.getLogicString() == "QF_UFBV" ||
1357 d_logic
.getLogicString() == "QF_ABV") &&
1358 options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER
) {
1359 d_logic
= LogicInfo("QF_BV");
1363 /* - disabled for 1.4 release [MGD 2014.06.25]
1364 if(!d_logic.hasEverything() && d_logic.isTheoryEnabled(THEORY_STRINGS) ) {
1365 if(! options::stringExp.wasSetByUser()) {
1366 options::stringExp.set( true );
1367 Trace("smt") << "turning on strings-exp, for the theory of strings" << std::endl;
1372 if(options::stringExp()) {
1373 if( !d_logic
.isQuantified() ) {
1374 d_logic
= d_logic
.getUnlockedCopy();
1375 d_logic
.enableQuantifiers();
1377 Trace("smt") << "turning on quantifier logic, for strings-exp"
1380 if(! options::fmfBound
.wasSetByUser()) {
1381 options::fmfBound
.set( true );
1382 Trace("smt") << "turning on fmf-bound-int, for strings-exp" << std::endl
;
1384 if(! options::fmfInstEngine
.wasSetByUser()) {
1385 options::fmfInstEngine
.set( true );
1386 Trace("smt") << "turning on fmf-inst-engine, for strings-exp" << std::endl
;
1389 if(! options::rewriteDivk.wasSetByUser()) {
1390 options::rewriteDivk.set( true );
1391 Trace("smt") << "turning on rewrite-divk, for strings-exp" << std::endl;
1394 if(! options::stringFMF.wasSetByUser()) {
1395 options::stringFMF.set( true );
1396 Trace("smt") << "turning on strings-fmf, for strings-exp" << std::endl;
1401 // sygus inference may require datatypes
1402 if (options::sygusInference())
1404 d_logic
= d_logic
.getUnlockedCopy();
1405 d_logic
.enableTheory(THEORY_DATATYPES
);
1409 if ((options::checkModels() || options::checkSynthSol())
1410 && !options::produceAssertions())
1412 Notice() << "SmtEngine: turning on produce-assertions to support "
1413 << "check-models or check-synth-sol." << endl
;
1414 setOption("produce-assertions", SExpr("true"));
1417 // Disable options incompatible with incremental solving, unsat cores, and
1418 // proofs or output an error if enabled explicitly
1419 if (options::incrementalSolving() || options::unsatCores()
1420 || options::proof())
1422 if (options::unconstrainedSimp())
1424 if (options::unconstrainedSimp
.wasSetByUser())
1426 throw OptionException(
1427 "unconstrained simplification not supported with unsat "
1428 "cores/proofs/incremental solving");
1430 Notice() << "SmtEngine: turning off unconstrained simplification to "
1431 "support unsat cores/proofs/incremental solving"
1433 options::unconstrainedSimp
.set(false);
1438 // Turn on unconstrained simplification for QF_AUFBV
1439 if (!options::unconstrainedSimp
.wasSetByUser())
1441 // bool qf_sat = d_logic.isPure(THEORY_BOOL) &&
1442 // !d_logic.isQuantified(); bool uncSimp = false && !qf_sat &&
1443 // !options::incrementalSolving();
1444 bool uncSimp
= !d_logic
.isQuantified() && !options::produceModels()
1445 && !options::produceAssignments()
1446 && !options::checkModels()
1447 && (d_logic
.isTheoryEnabled(THEORY_ARRAYS
)
1448 && d_logic
.isTheoryEnabled(THEORY_BV
));
1449 Trace("smt") << "setting unconstrained simplification to " << uncSimp
1451 options::unconstrainedSimp
.set(uncSimp
);
1455 // Disable options incompatible with unsat cores and proofs or output an
1456 // error if enabled explicitly
1457 if (options::unsatCores() || options::proof())
1459 if (options::simplificationMode() != SIMPLIFICATION_MODE_NONE
)
1461 if (options::simplificationMode
.wasSetByUser())
1463 throw OptionException(
1464 "simplification not supported with unsat cores/proofs");
1466 Notice() << "SmtEngine: turning off simplification to support unsat "
1469 options::simplificationMode
.set(SIMPLIFICATION_MODE_NONE
);
1472 if (options::pbRewrites())
1474 if (options::pbRewrites
.wasSetByUser())
1476 throw OptionException(
1477 "pseudoboolean rewrites not supported with unsat cores/proofs");
1479 Notice() << "SmtEngine: turning off pseudoboolean rewrites to support "
1480 "unsat cores/proofs"
1482 setOption("pb-rewrites", false);
1485 if (options::sortInference())
1487 if (options::sortInference
.wasSetByUser())
1489 throw OptionException(
1490 "sort inference not supported with unsat cores/proofs");
1492 Notice() << "SmtEngine: turning off sort inference to support unsat "
1495 options::sortInference
.set(false);
1498 if (options::preSkolemQuant())
1500 if (options::preSkolemQuant
.wasSetByUser())
1502 throw OptionException(
1503 "pre-skolemization not supported with unsat cores/proofs");
1505 Notice() << "SmtEngine: turning off pre-skolemization to support unsat "
1508 options::preSkolemQuant
.set(false);
1511 if (options::bitvectorToBool())
1513 if (options::bitvectorToBool
.wasSetByUser())
1515 throw OptionException(
1516 "bv-to-bool not supported with unsat cores/proofs");
1518 Notice() << "SmtEngine: turning off bitvector-to-bool to support unsat "
1521 options::bitvectorToBool
.set(false);
1524 if (options::boolToBitvector())
1526 if (options::boolToBitvector
.wasSetByUser())
1528 throw OptionException(
1529 "bool-to-bv not supported with unsat cores/proofs");
1531 Notice() << "SmtEngine: turning off bool-to-bitvector to support unsat "
1534 options::boolToBitvector
.set(false);
1537 if (options::bvIntroducePow2())
1539 if (options::bvIntroducePow2
.wasSetByUser())
1541 throw OptionException(
1542 "bv-intro-pow2 not supported with unsat cores/proofs");
1544 Notice() << "SmtEngine: turning off bv-intro-pow2 to support "
1545 "unsat-cores/proofs"
1547 setOption("bv-intro-pow2", false);
1550 if (options::repeatSimp())
1552 if (options::repeatSimp
.wasSetByUser())
1554 throw OptionException(
1555 "repeat-simp not supported with unsat cores/proofs");
1557 Notice() << "SmtEngine: turning off repeat-simp to support unsat "
1560 setOption("repeat-simp", false);
1563 if (options::globalNegate())
1565 if (options::globalNegate
.wasSetByUser())
1567 throw OptionException(
1568 "global-negate not supported with unsat cores/proofs");
1570 Notice() << "SmtEngine: turning off global-negate to support unsat "
1573 setOption("global-negate", false);
1578 // by default, nonclausal simplification is off for QF_SAT
1579 if (!options::simplificationMode
.wasSetByUser())
1581 bool qf_sat
= d_logic
.isPure(THEORY_BOOL
) && !d_logic
.isQuantified();
1582 Trace("smt") << "setting simplification mode to <"
1583 << d_logic
.getLogicString() << "> " << (!qf_sat
) << endl
;
1584 // simplification=none works better for SMT LIB benchmarks with
1585 // quantifiers, not others options::simplificationMode.set(qf_sat ||
1586 // quantifiers ? SIMPLIFICATION_MODE_NONE : SIMPLIFICATION_MODE_BATCH);
1587 options::simplificationMode
.set(qf_sat
? SIMPLIFICATION_MODE_NONE
1588 : SIMPLIFICATION_MODE_BATCH
);
1592 if (options::cbqiBv() && d_logic
.isQuantified())
1594 if(options::boolToBitvector
.wasSetByUser()) {
1595 throw OptionException(
1596 "bool-to-bv not supported with CBQI BV for quantified logics");
1598 Notice() << "SmtEngine: turning off bool-to-bitvector to support CBQI BV"
1600 options::boolToBitvector
.set(false);
1603 // cases where we need produce models
1604 if (!options::produceModels()
1605 && (options::produceAssignments() || options::sygusRewSynthCheck()
1608 Notice() << "SmtEngine: turning on produce-models" << endl
;
1609 setOption("produce-models", SExpr("true"));
1612 // Set the options for the theoryOf
1613 if(!options::theoryOfMode
.wasSetByUser()) {
1614 if(d_logic
.isSharingEnabled() &&
1615 !d_logic
.isTheoryEnabled(THEORY_BV
) &&
1616 !d_logic
.isTheoryEnabled(THEORY_STRINGS
) &&
1617 !d_logic
.isTheoryEnabled(THEORY_SETS
) ) {
1618 Trace("smt") << "setting theoryof-mode to term-based" << endl
;
1619 options::theoryOfMode
.set(THEORY_OF_TERM_BASED
);
1623 // strings require LIA, UF; widen the logic
1624 if(d_logic
.isTheoryEnabled(THEORY_STRINGS
)) {
1625 LogicInfo
log(d_logic
.getUnlockedCopy());
1626 // Strings requires arith for length constraints, and also UF
1627 if(!d_logic
.isTheoryEnabled(THEORY_UF
)) {
1628 Trace("smt") << "because strings are enabled, also enabling UF" << endl
;
1629 log
.enableTheory(THEORY_UF
);
1631 if(!d_logic
.isTheoryEnabled(THEORY_ARITH
) || d_logic
.isDifferenceLogic() || !d_logic
.areIntegersUsed()) {
1632 Trace("smt") << "because strings are enabled, also enabling linear integer arithmetic" << endl
;
1633 log
.enableTheory(THEORY_ARITH
);
1634 log
.enableIntegers();
1635 log
.arithOnlyLinear();
1640 if(d_logic
.isTheoryEnabled(THEORY_ARRAYS
) || d_logic
.isTheoryEnabled(THEORY_DATATYPES
) || d_logic
.isTheoryEnabled(THEORY_SETS
)) {
1641 if(!d_logic
.isTheoryEnabled(THEORY_UF
)) {
1642 LogicInfo
log(d_logic
.getUnlockedCopy());
1643 Trace("smt") << "because a theory that permits Boolean terms is enabled, also enabling UF" << endl
;
1644 log
.enableTheory(THEORY_UF
);
1650 // by default, symmetry breaker is on only for non-incremental QF_UF
1651 if(! options::ufSymmetryBreaker
.wasSetByUser()) {
1652 bool qf_uf_noinc
= d_logic
.isPure(THEORY_UF
) && !d_logic
.isQuantified()
1653 && !options::incrementalSolving() && !options::proof()
1654 && !options::unsatCores();
1655 Trace("smt") << "setting uf symmetry breaker to " << qf_uf_noinc
<< endl
;
1656 options::ufSymmetryBreaker
.set(qf_uf_noinc
);
1659 // If in arrays, set the UF handler to arrays
1660 if(d_logic
.isTheoryEnabled(THEORY_ARRAYS
) && ( !d_logic
.isQuantified() ||
1661 (d_logic
.isQuantified() && !d_logic
.isTheoryEnabled(THEORY_UF
)))) {
1662 Theory::setUninterpretedSortOwner(THEORY_ARRAYS
);
1664 Theory::setUninterpretedSortOwner(THEORY_UF
);
1667 // Turn on ite simplification for QF_LIA and QF_AUFBV
1668 // WARNING: These checks match much more than just QF_AUFBV and
1669 // QF_LIA logics. --K [2014/10/15]
1670 if(! options::doITESimp
.wasSetByUser()) {
1671 bool qf_aufbv
= !d_logic
.isQuantified() &&
1672 d_logic
.isTheoryEnabled(THEORY_ARRAYS
) &&
1673 d_logic
.isTheoryEnabled(THEORY_UF
) &&
1674 d_logic
.isTheoryEnabled(THEORY_BV
);
1675 bool qf_lia
= !d_logic
.isQuantified() &&
1676 d_logic
.isPure(THEORY_ARITH
) &&
1677 d_logic
.isLinear() &&
1678 !d_logic
.isDifferenceLogic() &&
1679 !d_logic
.areRealsUsed();
1681 bool iteSimp
= (qf_aufbv
|| qf_lia
);
1682 Trace("smt") << "setting ite simplification to " << iteSimp
<< endl
;
1683 options::doITESimp
.set(iteSimp
);
1685 if(! options::compressItes
.wasSetByUser() ){
1686 bool qf_lia
= !d_logic
.isQuantified() &&
1687 d_logic
.isPure(THEORY_ARITH
) &&
1688 d_logic
.isLinear() &&
1689 !d_logic
.isDifferenceLogic() &&
1690 !d_logic
.areRealsUsed();
1692 bool compressIte
= qf_lia
;
1693 Trace("smt") << "setting ite compression to " << compressIte
<< endl
;
1694 options::compressItes
.set(compressIte
);
1696 if(! options::simplifyWithCareEnabled
.wasSetByUser() ){
1697 bool qf_aufbv
= !d_logic
.isQuantified() &&
1698 d_logic
.isTheoryEnabled(THEORY_ARRAYS
) &&
1699 d_logic
.isTheoryEnabled(THEORY_UF
) &&
1700 d_logic
.isTheoryEnabled(THEORY_BV
);
1702 bool withCare
= qf_aufbv
;
1703 Trace("smt") << "setting ite simplify with care to " << withCare
<< endl
;
1704 options::simplifyWithCareEnabled
.set(withCare
);
1706 // Turn off array eager index splitting for QF_AUFLIA
1707 if(! options::arraysEagerIndexSplitting
.wasSetByUser()) {
1708 if (not d_logic
.isQuantified() &&
1709 d_logic
.isTheoryEnabled(THEORY_ARRAYS
) &&
1710 d_logic
.isTheoryEnabled(THEORY_UF
) &&
1711 d_logic
.isTheoryEnabled(THEORY_ARITH
)) {
1712 Trace("smt") << "setting array eager index splitting to false" << endl
;
1713 options::arraysEagerIndexSplitting
.set(false);
1716 // Turn on model-based arrays for QF_AX (unless models are enabled)
1717 // if(! options::arraysModelBased.wasSetByUser()) {
1718 // if (not d_logic.isQuantified() &&
1719 // d_logic.isTheoryEnabled(THEORY_ARRAYS) &&
1720 // d_logic.isPure(THEORY_ARRAYS) &&
1721 // !options::produceModels() &&
1722 // !options::checkModels()) {
1723 // Trace("smt") << "turning on model-based array solver" << endl;
1724 // options::arraysModelBased.set(true);
1727 // Turn on multiple-pass non-clausal simplification for QF_AUFBV
1728 if(! options::repeatSimp
.wasSetByUser()) {
1729 bool repeatSimp
= !d_logic
.isQuantified() &&
1730 (d_logic
.isTheoryEnabled(THEORY_ARRAYS
) &&
1731 d_logic
.isTheoryEnabled(THEORY_UF
) &&
1732 d_logic
.isTheoryEnabled(THEORY_BV
)) &&
1733 !options::unsatCores();
1734 Trace("smt") << "setting repeat simplification to " << repeatSimp
<< endl
;
1735 options::repeatSimp
.set(repeatSimp
);
1737 // Unconstrained simp currently does *not* support model generation
1738 if (options::unconstrainedSimp
.wasSetByUser() && options::unconstrainedSimp()) {
1739 if (options::produceModels()) {
1740 if (options::produceModels
.wasSetByUser()) {
1741 throw OptionException("Cannot use unconstrained-simp with model generation.");
1743 Notice() << "SmtEngine: turning off produce-models to support unconstrainedSimp" << endl
;
1744 setOption("produce-models", SExpr("false"));
1746 if (options::produceAssignments()) {
1747 if (options::produceAssignments
.wasSetByUser()) {
1748 throw OptionException("Cannot use unconstrained-simp with model generation (produce-assignments).");
1750 Notice() << "SmtEngine: turning off produce-assignments to support unconstrainedSimp" << endl
;
1751 setOption("produce-assignments", SExpr("false"));
1753 if (options::checkModels()) {
1754 if (options::checkModels
.wasSetByUser()) {
1755 throw OptionException("Cannot use unconstrained-simp with model generation (check-models).");
1757 Notice() << "SmtEngine: turning off check-models to support unconstrainedSimp" << endl
;
1758 setOption("check-models", SExpr("false"));
1762 if (! options::bvEagerExplanations
.wasSetByUser() &&
1763 d_logic
.isTheoryEnabled(THEORY_ARRAYS
) &&
1764 d_logic
.isTheoryEnabled(THEORY_BV
)) {
1765 Trace("smt") << "enabling eager bit-vector explanations " << endl
;
1766 options::bvEagerExplanations
.set(true);
1769 if( !options::bitvectorEqualitySolver() ){
1770 Trace("smt") << "disabling bvLazyRewriteExtf since equality solver is disabled" << endl
;
1771 options::bvLazyRewriteExtf
.set(false);
1774 // Turn on arith rewrite equalities only for pure arithmetic
1775 if(! options::arithRewriteEq
.wasSetByUser()) {
1776 bool arithRewriteEq
= d_logic
.isPure(THEORY_ARITH
) && d_logic
.isLinear() && !d_logic
.isQuantified();
1777 Trace("smt") << "setting arith rewrite equalities " << arithRewriteEq
<< endl
;
1778 options::arithRewriteEq
.set(arithRewriteEq
);
1780 if(! options::arithHeuristicPivots
.wasSetByUser()) {
1781 int16_t heuristicPivots
= 5;
1782 if(d_logic
.isPure(THEORY_ARITH
) && !d_logic
.isQuantified()) {
1783 if(d_logic
.isDifferenceLogic()) {
1784 heuristicPivots
= -1;
1785 } else if(!d_logic
.areIntegersUsed()) {
1786 heuristicPivots
= 0;
1789 Trace("smt") << "setting arithHeuristicPivots " << heuristicPivots
<< endl
;
1790 options::arithHeuristicPivots
.set(heuristicPivots
);
1792 if(! options::arithPivotThreshold
.wasSetByUser()){
1793 uint16_t pivotThreshold
= 2;
1794 if(d_logic
.isPure(THEORY_ARITH
) && !d_logic
.isQuantified()){
1795 if(d_logic
.isDifferenceLogic()){
1796 pivotThreshold
= 16;
1799 Trace("smt") << "setting arith arithPivotThreshold " << pivotThreshold
<< endl
;
1800 options::arithPivotThreshold
.set(pivotThreshold
);
1802 if(! options::arithStandardCheckVarOrderPivots
.wasSetByUser()){
1803 int16_t varOrderPivots
= -1;
1804 if(d_logic
.isPure(THEORY_ARITH
) && !d_logic
.isQuantified()){
1805 varOrderPivots
= 200;
1807 Trace("smt") << "setting arithStandardCheckVarOrderPivots " << varOrderPivots
<< endl
;
1808 options::arithStandardCheckVarOrderPivots
.set(varOrderPivots
);
1810 // Turn off early theory preprocessing if arithRewriteEq is on
1811 if (options::arithRewriteEq()) {
1812 d_earlyTheoryPP
= false;
1814 if (d_logic
.isPure(THEORY_ARITH
) && !d_logic
.areRealsUsed())
1816 if (!options::nlExtTangentPlanesInterleave
.wasSetByUser())
1818 Trace("smt") << "setting nlExtTangentPlanesInterleave to true" << endl
;
1819 options::nlExtTangentPlanesInterleave
.set(true);
1823 // Set decision mode based on logic (if not set by user)
1824 if(!options::decisionMode
.wasSetByUser()) {
1825 decision::DecisionMode decMode
=
1827 d_logic
.hasEverything() ? decision::DECISION_STRATEGY_JUSTIFICATION
:
1829 (not d_logic
.isQuantified() &&
1830 d_logic
.isPure(THEORY_BV
)
1832 // QF_AUFBV or QF_ABV or QF_UFBV
1833 (not d_logic
.isQuantified() &&
1834 (d_logic
.isTheoryEnabled(THEORY_ARRAYS
) ||
1835 d_logic
.isTheoryEnabled(THEORY_UF
)) &&
1836 d_logic
.isTheoryEnabled(THEORY_BV
)
1838 // QF_AUFLIA (and may be ends up enabling QF_AUFLRA?)
1839 (not d_logic
.isQuantified() &&
1840 d_logic
.isTheoryEnabled(THEORY_ARRAYS
) &&
1841 d_logic
.isTheoryEnabled(THEORY_UF
) &&
1842 d_logic
.isTheoryEnabled(THEORY_ARITH
)
1845 (not d_logic
.isQuantified() &&
1846 d_logic
.isPure(THEORY_ARITH
) && d_logic
.isLinear() && !d_logic
.isDifferenceLogic() && !d_logic
.areIntegersUsed()
1849 d_logic
.isQuantified() ||
1851 d_logic
.isTheoryEnabled(THEORY_STRINGS
)
1852 ? decision::DECISION_STRATEGY_JUSTIFICATION
1853 : decision::DECISION_STRATEGY_INTERNAL
1858 d_logic
.hasEverything() || d_logic
.isTheoryEnabled(THEORY_STRINGS
) ? false :
1860 (not d_logic
.isQuantified() &&
1861 d_logic
.isTheoryEnabled(THEORY_ARRAYS
) &&
1862 d_logic
.isTheoryEnabled(THEORY_UF
) &&
1863 d_logic
.isTheoryEnabled(THEORY_ARITH
)
1866 (not d_logic
.isQuantified() &&
1867 d_logic
.isPure(THEORY_ARITH
) && d_logic
.isLinear() && !d_logic
.isDifferenceLogic() && !d_logic
.areIntegersUsed()
1872 Trace("smt") << "setting decision mode to " << decMode
<< endl
;
1873 options::decisionMode
.set(decMode
);
1874 options::decisionStopOnly
.set(stoponly
);
1876 if( options::incrementalSolving() ){
1877 //disable modes not supported by incremental
1878 options::sortInference
.set( false );
1879 options::ufssFairnessMonotone
.set( false );
1880 options::quantEpr
.set( false );
1881 options::globalNegate
.set(false);
1883 if( d_logic
.hasCardinalityConstraints() ){
1884 //must have finite model finding on
1885 options::finiteModelFind
.set( true );
1888 //if it contains a theory with non-termination, do not strictly enforce that quantifiers and theory combination must be interleaved
1889 if( d_logic
.isTheoryEnabled(THEORY_STRINGS
) || (d_logic
.isTheoryEnabled(THEORY_ARITH
) && !d_logic
.isLinear()) ){
1890 if( !options::instWhenStrictInterleave
.wasSetByUser() ){
1891 options::instWhenStrictInterleave
.set( false );
1895 //local theory extensions
1896 if( options::localTheoryExt() ){
1897 if( !options::instMaxLevel
.wasSetByUser() ){
1898 options::instMaxLevel
.set( 0 );
1901 if( options::instMaxLevel()!=-1 ){
1902 Notice() << "SmtEngine: turning off cbqi to support instMaxLevel" << endl
;
1903 options::cbqi
.set(false);
1905 //track instantiations?
1906 if( options::cbqiNestedQE() || ( options::proof() && !options::trackInstLemmas
.wasSetByUser() ) ){
1907 options::trackInstLemmas
.set( true );
1910 if( ( options::fmfBoundLazy
.wasSetByUser() && options::fmfBoundLazy() ) ||
1911 ( options::fmfBoundInt
.wasSetByUser() && options::fmfBoundInt() ) ) {
1912 options::fmfBound
.set( true );
1914 //now have determined whether fmfBoundInt is on/off
1915 //apply fmfBoundInt options
1916 if( options::fmfBound() ){
1917 //must have finite model finding on
1918 options::finiteModelFind
.set( true );
1919 if (!options::mbqiMode
.wasSetByUser()
1920 || (options::mbqiMode() != quantifiers::MBQI_NONE
1921 && options::mbqiMode() != quantifiers::MBQI_FMC
))
1923 //if bounded integers are set, use no MBQI by default
1924 options::mbqiMode
.set( quantifiers::MBQI_NONE
);
1926 if( ! options::prenexQuant
.wasSetByUser() ){
1927 options::prenexQuant
.set( quantifiers::PRENEX_QUANT_NONE
);
1930 if( options::ufHo() ){
1931 //if higher-order, then current variants of model-based instantiation cannot be used
1932 if( options::mbqiMode()!=quantifiers::MBQI_NONE
){
1933 options::mbqiMode
.set( quantifiers::MBQI_NONE
);
1936 if( options::mbqiMode()==quantifiers::MBQI_ABS
){
1937 if( !d_logic
.isPure(THEORY_UF
) ){
1938 //MBQI_ABS is only supported in pure quantified UF
1939 options::mbqiMode
.set( quantifiers::MBQI_FMC
);
1942 if( options::fmfFunWellDefinedRelevant() ){
1943 if( !options::fmfFunWellDefined
.wasSetByUser() ){
1944 options::fmfFunWellDefined
.set( true );
1947 if( options::fmfFunWellDefined() ){
1948 if( !options::finiteModelFind
.wasSetByUser() ){
1949 options::finiteModelFind
.set( true );
1953 if( options::quantEpr() ){
1954 if( !options::preSkolemQuant
.wasSetByUser() ){
1955 options::preSkolemQuant
.set( true );
1959 //now, have determined whether finite model find is on/off
1960 //apply finite model finding options
1961 if( options::finiteModelFind() ){
1962 //apply conservative quantifiers splitting
1963 if( !options::quantDynamicSplit
.wasSetByUser() ){
1964 options::quantDynamicSplit
.set( quantifiers::QUANT_DSPLIT_MODE_DEFAULT
);
1966 //do not eliminate extended arithmetic symbols from quantified formulas
1967 if( !options::elimExtArithQuant
.wasSetByUser() ){
1968 options::elimExtArithQuant
.set( false );
1970 if( !options::eMatching
.wasSetByUser() ){
1971 options::eMatching
.set( options::fmfInstEngine() );
1973 if( !options::instWhenMode
.wasSetByUser() ){
1974 //instantiate only on last call
1975 if( options::eMatching() ){
1976 options::instWhenMode
.set( quantifiers::INST_WHEN_LAST_CALL
);
1979 if( options::mbqiMode()==quantifiers::MBQI_ABS
){
1980 if( !options::preSkolemQuant
.wasSetByUser() ){
1981 options::preSkolemQuant
.set( true );
1983 if( !options::preSkolemQuantNested
.wasSetByUser() ){
1984 options::preSkolemQuantNested
.set( true );
1986 if( !options::fmfOneInstPerRound
.wasSetByUser() ){
1987 options::fmfOneInstPerRound
.set( true );
1992 //apply counterexample guided instantiation options
1993 // if we are attempting to rewrite everything to SyGuS, use ceGuidedInst
1994 if (options::sygusInference())
1996 if (!options::ceGuidedInst
.wasSetByUser())
1998 options::ceGuidedInst
.set(true);
2000 // optimization: apply preskolemization, makes it succeed more often
2001 if (!options::preSkolemQuant
.wasSetByUser())
2003 options::preSkolemQuant
.set(true);
2005 if (!options::preSkolemQuantNested
.wasSetByUser())
2007 options::preSkolemQuantNested
.set(true);
2010 if( options::cegqiSingleInvMode()!=quantifiers::CEGQI_SI_MODE_NONE
){
2011 if( !options::ceGuidedInst
.wasSetByUser() ){
2012 options::ceGuidedInst
.set( true );
2015 if( options::ceGuidedInst() ){
2016 //counterexample-guided instantiation for sygus
2017 if( !options::cegqiSingleInvMode
.wasSetByUser() ){
2018 options::cegqiSingleInvMode
.set( quantifiers::CEGQI_SI_MODE_USE
);
2020 if( !options::quantConflictFind
.wasSetByUser() ){
2021 options::quantConflictFind
.set( false );
2023 if( !options::instNoEntail
.wasSetByUser() ){
2024 options::instNoEntail
.set( false );
2026 if (options::sygusRew())
2028 options::sygusRewSynth
.set(true);
2029 options::sygusRewVerify
.set(true);
2031 if (options::sygusRewSynth() || options::sygusRewVerify())
2033 // rewrite rule synthesis implies that sygus stream must be true
2034 options::sygusStream
.set(true);
2036 if (options::sygusStream())
2038 // PBE and streaming modes are incompatible
2039 if (!options::sygusSymBreakPbe
.wasSetByUser())
2041 options::sygusSymBreakPbe
.set(false);
2043 if (!options::sygusUnifPbe
.wasSetByUser())
2045 options::sygusUnifPbe
.set(false);
2048 //do not allow partial functions
2049 if( !options::bitvectorDivByZeroConst
.wasSetByUser() ){
2050 options::bitvectorDivByZeroConst
.set( true );
2052 if( !options::dtRewriteErrorSel
.wasSetByUser() ){
2053 options::dtRewriteErrorSel
.set( true );
2056 if( !options::miniscopeQuant
.wasSetByUser() ){
2057 options::miniscopeQuant
.set( false );
2059 if( !options::miniscopeQuantFreeVar
.wasSetByUser() ){
2060 options::miniscopeQuantFreeVar
.set( false );
2063 if( !options::rewriteDivk
.wasSetByUser()) {
2064 options::rewriteDivk
.set( true );
2067 if( !options::macrosQuant
.wasSetByUser()) {
2068 options::macrosQuant
.set( false );
2070 if( !options::cbqiPreRegInst
.wasSetByUser()) {
2071 options::cbqiPreRegInst
.set( true );
2074 //counterexample-guided instantiation for non-sygus
2075 // enable if any possible quantifiers with arithmetic, datatypes or bitvectors
2076 if (d_logic
.isQuantified()
2077 && ((options::decisionMode() != decision::DECISION_STRATEGY_INTERNAL
2078 && (d_logic
.isTheoryEnabled(THEORY_ARITH
)
2079 || d_logic
.isTheoryEnabled(THEORY_DATATYPES
)
2080 || d_logic
.isTheoryEnabled(THEORY_BV
)
2081 || d_logic
.isTheoryEnabled(THEORY_FP
)))
2082 || d_logic
.isPure(THEORY_ARITH
) || d_logic
.isPure(THEORY_BV
)
2083 || options::cbqiAll()))
2085 if( !options::cbqi
.wasSetByUser() ){
2086 options::cbqi
.set( true );
2088 // check whether we should apply full cbqi
2089 if (d_logic
.isPure(THEORY_BV
))
2091 if (!options::cbqiFullEffort
.wasSetByUser())
2093 options::cbqiFullEffort
.set(true);
2097 if( options::cbqi() ){
2099 if( !options::rewriteDivk
.wasSetByUser()) {
2100 options::rewriteDivk
.set( true );
2102 if (options::incrementalSolving())
2104 // cannot do nested quantifier elimination in incremental mode
2105 options::cbqiNestedQE
.set(false);
2107 if (d_logic
.isPure(THEORY_ARITH
) || d_logic
.isPure(THEORY_BV
))
2109 options::cbqiAll
.set( false );
2110 if( !options::quantConflictFind
.wasSetByUser() ){
2111 options::quantConflictFind
.set( false );
2113 if( !options::instNoEntail
.wasSetByUser() ){
2114 options::instNoEntail
.set( false );
2116 if( !options::instWhenMode
.wasSetByUser() && options::cbqiModel() ){
2117 //only instantiation should happen at last call when model is avaiable
2118 options::instWhenMode
.set( quantifiers::INST_WHEN_LAST_CALL
);
2121 // only supported in pure arithmetic or pure BV
2122 options::cbqiNestedQE
.set(false);
2125 if (options::cbqiNestedQE()
2126 || options::decisionMode() == decision::DECISION_STRATEGY_INTERNAL
)
2128 // only complete with prenex = disj_normal or normal
2129 if (options::prenexQuant() <= quantifiers::PRENEX_QUANT_DISJ_NORMAL
)
2131 options::prenexQuant
.set(quantifiers::PRENEX_QUANT_DISJ_NORMAL
);
2134 else if (options::globalNegate())
2136 if (!options::prenexQuant
.wasSetByUser())
2138 options::prenexQuant
.set(quantifiers::PRENEX_QUANT_NONE
);
2142 //implied options...
2143 if( options::strictTriggers() ){
2144 if( !options::userPatternsQuant
.wasSetByUser() ){
2145 options::userPatternsQuant
.set( quantifiers::USER_PAT_MODE_TRUST
);
2148 if( options::qcfMode
.wasSetByUser() || options::qcfTConstraint() ){
2149 options::quantConflictFind
.set( true );
2151 if( options::cbqiNestedQE() ){
2152 options::prenexQuantUser
.set( true );
2153 if( !options::preSkolemQuant
.wasSetByUser() ){
2154 options::preSkolemQuant
.set( true );
2157 //for induction techniques
2158 if( options::quantInduction() ){
2159 if( !options::dtStcInduction
.wasSetByUser() ){
2160 options::dtStcInduction
.set( true );
2162 if( !options::intWfInduction
.wasSetByUser() ){
2163 options::intWfInduction
.set( true );
2166 if( options::dtStcInduction() ){
2167 //try to remove ITEs from quantified formulas
2168 if( !options::iteDtTesterSplitQuant
.wasSetByUser() ){
2169 options::iteDtTesterSplitQuant
.set( true );
2171 if( !options::iteLiftQuant
.wasSetByUser() ){
2172 options::iteLiftQuant
.set( quantifiers::ITE_LIFT_QUANT_MODE_ALL
);
2175 if( options::intWfInduction() ){
2176 if( !options::purifyTriggers
.wasSetByUser() ){
2177 options::purifyTriggers
.set( true );
2180 if( options::conjectureNoFilter() ){
2181 if( !options::conjectureFilterActiveTerms
.wasSetByUser() ){
2182 options::conjectureFilterActiveTerms
.set( false );
2184 if( !options::conjectureFilterCanonical
.wasSetByUser() ){
2185 options::conjectureFilterCanonical
.set( false );
2187 if( !options::conjectureFilterModel
.wasSetByUser() ){
2188 options::conjectureFilterModel
.set( false );
2191 if( options::conjectureGenPerRound
.wasSetByUser() ){
2192 if( options::conjectureGenPerRound()>0 ){
2193 options::conjectureGen
.set( true );
2195 options::conjectureGen
.set( false );
2198 //can't pre-skolemize nested quantifiers without UF theory
2199 if( !d_logic
.isTheoryEnabled(THEORY_UF
) && options::preSkolemQuant() ){
2200 if( !options::preSkolemQuantNested
.wasSetByUser() ){
2201 options::preSkolemQuantNested
.set( false );
2204 if( !d_logic
.isTheoryEnabled(THEORY_DATATYPES
) ){
2205 options::quantDynamicSplit
.set( quantifiers::QUANT_DSPLIT_MODE_NONE
);
2208 //until bugs 371,431 are fixed
2209 if( ! options::minisatUseElim
.wasSetByUser()){
2210 // cannot use minisat elimination for logics where a theory solver
2211 // introduces new literals into the search. This includes quantifiers
2212 // (quantifier instantiation), and the lemma schemas used in non-linear
2213 // and sets. We also can't use it if models are enabled.
2214 if (d_logic
.isTheoryEnabled(THEORY_SETS
) || d_logic
.isQuantified()
2215 || options::produceModels() || options::produceAssignments()
2216 || options::checkModels()
2217 || (d_logic
.isTheoryEnabled(THEORY_ARITH
) && !d_logic
.isLinear()))
2219 options::minisatUseElim
.set( false );
2222 else if (options::minisatUseElim()) {
2223 if (options::produceModels()) {
2224 Notice() << "SmtEngine: turning off produce-models to support minisatUseElim" << endl
;
2225 setOption("produce-models", SExpr("false"));
2227 if (options::produceAssignments()) {
2228 Notice() << "SmtEngine: turning off produce-assignments to support minisatUseElim" << endl
;
2229 setOption("produce-assignments", SExpr("false"));
2231 if (options::checkModels()) {
2232 Notice() << "SmtEngine: turning off check-models to support minisatUseElim" << endl
;
2233 setOption("check-models", SExpr("false"));
2237 // For now, these array theory optimizations do not support model-building
2238 if (options::produceModels() || options::produceAssignments() || options::checkModels()) {
2239 options::arraysOptimizeLinear
.set(false);
2240 options::arraysLazyRIntro1
.set(false);
2243 // Non-linear arithmetic does not support models unless nlExt is enabled
2244 if ((d_logic
.isTheoryEnabled(THEORY_ARITH
) && !d_logic
.isLinear()
2245 && !options::nlExt())
2246 || options::globalNegate())
2248 std::string reason
=
2249 options::globalNegate() ? "--global-negate" : "nonlinear arithmetic";
2250 if (options::produceModels()) {
2251 if(options::produceModels
.wasSetByUser()) {
2252 throw OptionException(
2253 std::string("produce-model not supported with " + reason
));
2256 << "SmtEngine: turning off produce-models because unsupported for "
2258 setOption("produce-models", SExpr("false"));
2260 if (options::produceAssignments()) {
2261 if(options::produceAssignments
.wasSetByUser()) {
2262 throw OptionException(
2263 std::string("produce-assignments not supported with " + reason
));
2265 Warning() << "SmtEngine: turning off produce-assignments because "
2268 setOption("produce-assignments", SExpr("false"));
2270 if (options::checkModels()) {
2271 if(options::checkModels
.wasSetByUser()) {
2272 throw OptionException(
2273 std::string("check-models not supported with " + reason
));
2276 << "SmtEngine: turning off check-models because unsupported for "
2278 setOption("check-models", SExpr("false"));
2282 if(options::incrementalSolving() && options::proof()) {
2283 Warning() << "SmtEngine: turning off incremental solving mode (not yet supported with --proof, try --tear-down-incremental instead)" << endl
;
2284 setOption("incremental", SExpr("false"));
2287 if (options::proof())
2289 if (options::bitvectorAlgebraicSolver())
2291 if (options::bitvectorAlgebraicSolver
.wasSetByUser())
2293 throw OptionException(
2294 "--bv-algebraic-solver is not supported with proofs");
2296 Notice() << "SmtEngine: turning off bv algebraic solver to support proofs"
2298 options::bitvectorAlgebraicSolver
.set(false);
2300 if (options::bitvectorEqualitySolver())
2302 if (options::bitvectorEqualitySolver
.wasSetByUser())
2304 throw OptionException("--bv-eq-solver is not supported with proofs");
2306 Notice() << "SmtEngine: turning off bv eq solver to support proofs"
2308 options::bitvectorEqualitySolver
.set(false);
2310 if (options::bitvectorInequalitySolver())
2312 if (options::bitvectorInequalitySolver
.wasSetByUser())
2314 throw OptionException(
2315 "--bv-inequality-solver is not supported with proofs");
2317 Notice() << "SmtEngine: turning off bv ineq solver to support proofs"
2319 options::bitvectorInequalitySolver
.set(false);
2324 void SmtEngine::setProblemExtended(bool value
)
2326 d_problemExtended
= value
;
2327 if (value
) { d_assumptions
.clear(); }
2330 void SmtEngine::setInfo(const std::string
& key
, const CVC4::SExpr
& value
)
2332 SmtScope
smts(this);
2334 Trace("smt") << "SMT setInfo(" << key
<< ", " << value
<< ")" << endl
;
2336 if(Dump
.isOn("benchmark")) {
2337 if(key
== "status") {
2338 string s
= value
.getValue();
2339 BenchmarkStatus status
=
2340 (s
== "sat") ? SMT_SATISFIABLE
:
2341 ((s
== "unsat") ? SMT_UNSATISFIABLE
: SMT_UNKNOWN
);
2342 Dump("benchmark") << SetBenchmarkStatusCommand(status
);
2344 Dump("benchmark") << SetInfoCommand(key
, value
);
2348 // Check for CVC4-specific info keys (prefixed with "cvc4-" or "cvc4_")
2349 if(key
.length() > 5) {
2350 string prefix
= key
.substr(0, 5);
2351 if(prefix
== "cvc4-" || prefix
== "cvc4_") {
2352 string cvc4key
= key
.substr(5);
2353 if(cvc4key
== "logic") {
2354 if(! value
.isAtom()) {
2355 throw OptionException("argument to (set-info :cvc4-logic ..) must be a string");
2357 SmtScope
smts(this);
2358 d_logic
= value
.getValue();
2362 throw UnrecognizedOptionException();
2367 // Check for standard info keys (SMT-LIB v1, SMT-LIB v2, ...)
2369 || key
== "category"
2370 || key
== "difficulty"
2372 || key
== "license")
2376 } else if(key
== "name") {
2377 d_filename
= value
.getValue();
2380 else if (key
== "smt-lib-version" && !options::inputLanguage
.wasSetByUser())
2382 language::input::Language ilang
= language::input::LANG_AUTO
;
2383 if( (value
.isInteger() && value
.getIntegerValue() == Integer(2)) ||
2384 (value
.isRational() && value
.getRationalValue() == Rational(2)) ||
2385 value
.getValue() == "2" ||
2386 value
.getValue() == "2.0" ) {
2387 ilang
= language::input::LANG_SMTLIB_V2_0
;
2388 } else if( (value
.isRational() && value
.getRationalValue() == Rational(5, 2)) ||
2389 value
.getValue() == "2.5" ) {
2390 ilang
= language::input::LANG_SMTLIB_V2_5
;
2391 } else if( (value
.isRational() && value
.getRationalValue() == Rational(13, 5)) ||
2392 value
.getValue() == "2.6" ) {
2393 ilang
= language::input::LANG_SMTLIB_V2_6
;
2395 else if (value
.getValue() == "2.6.1")
2397 ilang
= language::input::LANG_SMTLIB_V2_6_1
;
2401 Warning() << "Warning: unsupported smt-lib-version: " << value
<< endl
;
2402 throw UnrecognizedOptionException();
2404 options::inputLanguage
.set(ilang
);
2405 // also update the output language
2406 if (!options::outputLanguage
.wasSetByUser())
2408 language::output::Language olang
= language::toOutputLanguage(ilang
);
2409 if (options::outputLanguage() != olang
)
2411 options::outputLanguage
.set(olang
);
2412 *options::out() << language::SetLanguage(olang
);
2416 } else if(key
== "status") {
2418 if(value
.isAtom()) {
2419 s
= value
.getValue();
2421 if(s
!= "sat" && s
!= "unsat" && s
!= "unknown") {
2422 throw OptionException("argument to (set-info :status ..) must be "
2423 "`sat' or `unsat' or `unknown'");
2425 d_status
= Result(s
, d_filename
);
2428 throw UnrecognizedOptionException();
2431 CVC4::SExpr
SmtEngine::getInfo(const std::string
& key
) const {
2433 SmtScope
smts(this);
2435 Trace("smt") << "SMT getInfo(" << key
<< ")" << endl
;
2436 if(key
== "all-statistics") {
2437 vector
<SExpr
> stats
;
2438 for(StatisticsRegistry::const_iterator i
= NodeManager::fromExprManager(d_exprManager
)->getStatisticsRegistry()->begin();
2439 i
!= NodeManager::fromExprManager(d_exprManager
)->getStatisticsRegistry()->end();
2442 v
.push_back((*i
).first
);
2443 v
.push_back((*i
).second
);
2446 for(StatisticsRegistry::const_iterator i
= d_statisticsRegistry
->begin();
2447 i
!= d_statisticsRegistry
->end();
2450 v
.push_back((*i
).first
);
2451 v
.push_back((*i
).second
);
2454 return SExpr(stats
);
2455 } else if(key
== "error-behavior") {
2456 // immediate-exit | continued-execution
2457 if( options::continuedExecution() || options::interactive() ) {
2458 return SExpr(SExpr::Keyword("continued-execution"));
2460 return SExpr(SExpr::Keyword("immediate-exit"));
2462 } else if(key
== "name") {
2463 return SExpr(Configuration::getName());
2464 } else if(key
== "version") {
2465 return SExpr(Configuration::getVersionString());
2466 } else if(key
== "authors") {
2467 return SExpr(Configuration::about());
2468 } else if(key
== "status") {
2469 // sat | unsat | unknown
2470 switch(d_status
.asSatisfiabilityResult().isSat()) {
2472 return SExpr(SExpr::Keyword("sat"));
2474 return SExpr(SExpr::Keyword("unsat"));
2476 return SExpr(SExpr::Keyword("unknown"));
2478 } else if(key
== "reason-unknown") {
2479 if(!d_status
.isNull() && d_status
.isUnknown()) {
2481 ss
<< d_status
.whyUnknown();
2482 string s
= ss
.str();
2483 transform(s
.begin(), s
.end(), s
.begin(), ::tolower
);
2484 return SExpr(SExpr::Keyword(s
));
2486 throw ModalException("Can't get-info :reason-unknown when the "
2487 "last result wasn't unknown!");
2489 } else if(key
== "assertion-stack-levels") {
2490 AlwaysAssert(d_userLevels
.size() <=
2491 std::numeric_limits
<unsigned long int>::max());
2492 return SExpr(static_cast<unsigned long int>(d_userLevels
.size()));
2493 } else if(key
== "all-options") {
2494 // get the options, like all-statistics
2495 std::vector
< std::vector
<std::string
> > current_options
=
2496 Options::current()->getOptions();
2497 return SExpr::parseListOfListOfAtoms(current_options
);
2499 throw UnrecognizedOptionException();
2503 void SmtEngine::debugCheckFormals(const std::vector
<Expr
>& formals
, Expr func
)
2505 for(std::vector
<Expr
>::const_iterator i
= formals
.begin(); i
!= formals
.end(); ++i
) {
2506 if((*i
).getKind() != kind::BOUND_VARIABLE
) {
2508 ss
<< "All formal arguments to defined functions must be BOUND_VARIABLEs, but in the\n"
2509 << "definition of function " << func
<< ", formal\n"
2510 << " " << *i
<< "\n"
2511 << "has kind " << (*i
).getKind();
2512 throw TypeCheckingException(func
, ss
.str());
2517 void SmtEngine::debugCheckFunctionBody(Expr formula
,
2518 const std::vector
<Expr
>& formals
,
2521 Type formulaType
= formula
.getType(options::typeChecking());
2522 Type funcType
= func
.getType();
2523 // We distinguish here between definitions of constants and functions,
2524 // because the type checking for them is subtly different. Perhaps we
2525 // should instead have SmtEngine::defineFunction() and
2526 // SmtEngine::defineConstant() for better clarity, although then that
2527 // doesn't match the SMT-LIBv2 standard...
2528 if(formals
.size() > 0) {
2529 Type rangeType
= FunctionType(funcType
).getRangeType();
2530 if(! formulaType
.isComparableTo(rangeType
)) {
2532 ss
<< "Type of defined function does not match its declaration\n"
2533 << "The function : " << func
<< "\n"
2534 << "Declared type : " << rangeType
<< "\n"
2535 << "The body : " << formula
<< "\n"
2536 << "Body type : " << formulaType
;
2537 throw TypeCheckingException(func
, ss
.str());
2540 if(! formulaType
.isComparableTo(funcType
)) {
2542 ss
<< "Declared type of defined constant does not match its definition\n"
2543 << "The constant : " << func
<< "\n"
2544 << "Declared type : " << funcType
<< " " << Type::getTypeNode(funcType
)->getId() << "\n"
2545 << "The definition : " << formula
<< "\n"
2546 << "Definition type: " << formulaType
<< " " << Type::getTypeNode(formulaType
)->getId();
2547 throw TypeCheckingException(func
, ss
.str());
2552 void SmtEngine::defineFunction(Expr func
,
2553 const std::vector
<Expr
>& formals
,
2556 SmtScope
smts(this);
2558 Trace("smt") << "SMT defineFunction(" << func
<< ")" << endl
;
2559 debugCheckFormals(formals
, func
);
2562 ss
<< language::SetLanguage(
2563 language::SetLanguage::getLanguage(Dump
.getStream()))
2565 DefineFunctionCommand
c(ss
.str(), func
, formals
, formula
);
2566 addToModelCommandAndDump(
2567 c
, ExprManager::VAR_FLAG_DEFINED
, true, "declarations");
2569 PROOF(if (options::checkUnsatCores()) {
2570 d_defineCommands
.push_back(c
.clone());
2574 debugCheckFunctionBody(formula
, formals
, func
);
2576 // Substitute out any abstract values in formula
2578 d_private
->substituteAbstractValues(Node::fromExpr(formula
)).toExpr();
2580 TNode funcNode
= func
.getTNode();
2581 vector
<Node
> formalsNodes
;
2582 for(vector
<Expr
>::const_iterator i
= formals
.begin(),
2583 iend
= formals
.end();
2586 formalsNodes
.push_back((*i
).getNode());
2588 TNode formNode
= form
.getTNode();
2589 DefinedFunction
def(funcNode
, formalsNodes
, formNode
);
2590 // Permit (check-sat) (define-fun ...) (get-value ...) sequences.
2591 // Otherwise, (check-sat) (get-value ((! foo :named bar))) breaks
2592 // d_haveAdditions = true;
2593 Debug("smt") << "definedFunctions insert " << funcNode
<< " " << formNode
<< endl
;
2594 d_definedFunctions
->insert(funcNode
, def
);
2597 void SmtEngine::defineFunctionsRec(
2598 const std::vector
<Expr
>& funcs
,
2599 const std::vector
<std::vector
<Expr
> >& formals
,
2600 const std::vector
<Expr
>& formulas
)
2602 SmtScope
smts(this);
2603 finalOptionsAreSet();
2605 Trace("smt") << "SMT defineFunctionsRec(...)" << endl
;
2607 if (funcs
.size() != formals
.size() && funcs
.size() != formulas
.size())
2610 ss
<< "Number of functions, formals, and function bodies passed to "
2611 "defineFunctionsRec do not match:"
2613 << " #functions : " << funcs
.size() << "\n"
2614 << " #arg lists : " << formals
.size() << "\n"
2615 << " #function bodies : " << formulas
.size() << "\n";
2616 throw ModalException(ss
.str());
2618 for (unsigned i
= 0, size
= funcs
.size(); i
< size
; i
++)
2620 // check formal argument list
2621 debugCheckFormals(formals
[i
], funcs
[i
]);
2623 debugCheckFunctionBody(formulas
[i
], formals
[i
], funcs
[i
]);
2626 if (Dump
.isOn("raw-benchmark"))
2628 Dump("raw-benchmark") << DefineFunctionRecCommand(funcs
, formals
, formulas
);
2631 ExprManager
* em
= getExprManager();
2632 for (unsigned i
= 0, size
= funcs
.size(); i
< size
; i
++)
2634 // we assert a quantified formula
2636 // make the function application
2637 if (formals
[i
].empty())
2639 // it has no arguments
2640 func_app
= funcs
[i
];
2644 std::vector
<Expr
> children
;
2645 children
.push_back(funcs
[i
]);
2646 children
.insert(children
.end(), formals
[i
].begin(), formals
[i
].end());
2647 func_app
= em
->mkExpr(kind::APPLY_UF
, children
);
2649 Expr lem
= em
->mkExpr(kind::EQUAL
, func_app
, formulas
[i
]);
2650 if (!formals
[i
].empty())
2652 // set the attribute to denote this is a function definition
2653 std::string
attr_name("fun-def");
2654 Expr aexpr
= em
->mkExpr(kind::INST_ATTRIBUTE
, func_app
);
2655 aexpr
= em
->mkExpr(kind::INST_PATTERN_LIST
, aexpr
);
2656 std::vector
<Expr
> expr_values
;
2657 std::string str_value
;
2658 setUserAttribute(attr_name
, func_app
, expr_values
, str_value
);
2659 // make the quantified formula
2660 Expr boundVars
= em
->mkExpr(kind::BOUND_VAR_LIST
, formals
[i
]);
2661 lem
= em
->mkExpr(kind::FORALL
, boundVars
, lem
, aexpr
);
2663 // assert the quantified formula
2664 // notice we don't call assertFormula directly, since this would
2665 // duplicate the output on raw-benchmark.
2666 Expr e
= d_private
->substituteAbstractValues(Node::fromExpr(lem
)).toExpr();
2667 if (d_assertionList
!= NULL
)
2669 d_assertionList
->push_back(e
);
2671 d_private
->addFormula(e
.getNode(), false);
2675 void SmtEngine::defineFunctionRec(Expr func
,
2676 const std::vector
<Expr
>& formals
,
2679 std::vector
<Expr
> funcs
;
2680 funcs
.push_back(func
);
2681 std::vector
<std::vector
<Expr
> > formals_multi
;
2682 formals_multi
.push_back(formals
);
2683 std::vector
<Expr
> formulas
;
2684 formulas
.push_back(formula
);
2685 defineFunctionsRec(funcs
, formals_multi
, formulas
);
2688 bool SmtEngine::isDefinedFunction( Expr func
){
2689 Node nf
= Node::fromExpr( func
);
2690 Debug("smt") << "isDefined function " << nf
<< "?" << std::endl
;
2691 return d_definedFunctions
->find(nf
) != d_definedFunctions
->end();
2694 void SmtEnginePrivate::finishInit()
2696 d_preprocessingPassContext
.reset(
2697 new PreprocessingPassContext(&d_smt
, d_resourceManager
));
2698 // TODO: register passes here (this will likely change when we add support for
2699 // actually assembling preprocessing pipelines).
2700 std::unique_ptr
<ApplySubsts
> applySubsts(
2701 new ApplySubsts(d_preprocessingPassContext
.get()));
2702 std::unique_ptr
<BoolToBV
> boolToBv(
2703 new BoolToBV(d_preprocessingPassContext
.get()));
2704 std::unique_ptr
<BvAbstraction
> bvAbstract(
2705 new BvAbstraction(d_preprocessingPassContext
.get()));
2706 std::unique_ptr
<BVAckermann
> bvAckermann(
2707 new BVAckermann(d_preprocessingPassContext
.get()));
2708 std::unique_ptr
<BVGauss
> bvGauss(
2709 new BVGauss(d_preprocessingPassContext
.get()));
2710 std::unique_ptr
<BvIntroPow2
> bvIntroPow2(
2711 new BvIntroPow2(d_preprocessingPassContext
.get()));
2712 std::unique_ptr
<BVToBool
> bvToBool(
2713 new BVToBool(d_preprocessingPassContext
.get()));
2714 std::unique_ptr
<IntToBV
> intToBV(
2715 new IntToBV(d_preprocessingPassContext
.get()));
2716 std::unique_ptr
<PseudoBooleanProcessor
> pbProc(
2717 new PseudoBooleanProcessor(d_preprocessingPassContext
.get()));
2718 std::unique_ptr
<RealToInt
> realToInt(
2719 new RealToInt(d_preprocessingPassContext
.get()));
2720 std::unique_ptr
<Rewrite
> rewrite(
2721 new Rewrite(d_preprocessingPassContext
.get()));
2722 std::unique_ptr
<StaticLearning
> staticLearning(
2723 new StaticLearning(d_preprocessingPassContext
.get()));
2724 std::unique_ptr
<SymBreakerPass
> sbProc(
2725 new SymBreakerPass(d_preprocessingPassContext
.get()));
2726 std::unique_ptr
<SynthRewRulesPass
> srrProc(
2727 new SynthRewRulesPass(d_preprocessingPassContext
.get()));
2728 d_preprocessingPassRegistry
.registerPass("apply-substs",
2729 std::move(applySubsts
));
2730 d_preprocessingPassRegistry
.registerPass("bool-to-bv", std::move(boolToBv
));
2731 d_preprocessingPassRegistry
.registerPass("bv-abstraction",
2732 std::move(bvAbstract
));
2733 d_preprocessingPassRegistry
.registerPass("bv-ackermann",
2734 std::move(bvAckermann
));
2735 d_preprocessingPassRegistry
.registerPass("bv-gauss", std::move(bvGauss
));
2736 d_preprocessingPassRegistry
.registerPass("bv-intro-pow2",
2737 std::move(bvIntroPow2
));
2738 d_preprocessingPassRegistry
.registerPass("bv-to-bool", std::move(bvToBool
));
2739 d_preprocessingPassRegistry
.registerPass("int-to-bv", std::move(intToBV
));
2740 d_preprocessingPassRegistry
.registerPass("pseudo-boolean-processor",
2742 d_preprocessingPassRegistry
.registerPass("real-to-int", std::move(realToInt
));
2743 d_preprocessingPassRegistry
.registerPass("rewrite", std::move(rewrite
));
2744 d_preprocessingPassRegistry
.registerPass("static-learning",
2745 std::move(staticLearning
));
2746 d_preprocessingPassRegistry
.registerPass("sym-break", std::move(sbProc
));
2747 d_preprocessingPassRegistry
.registerPass("synth-rr", std::move(srrProc
));
2750 Node
SmtEnginePrivate::expandDefinitions(TNode n
, unordered_map
<Node
, Node
, NodeHashFunction
>& cache
, bool expandOnly
)
2752 stack
< triple
<Node
, Node
, bool> > worklist
;
2754 worklist
.push(make_triple(Node(n
), Node(n
), false));
2755 // The worklist is made of triples, each is input / original node then the output / rewritten node
2756 // and finally a flag tracking whether the children have been explored (i.e. if this is a downward
2760 spendResource(options::preprocessStep());
2761 n
= worklist
.top().first
; // n is the input / original
2762 Node node
= worklist
.top().second
; // node is the output / result
2763 bool childrenPushed
= worklist
.top().third
;
2766 // Working downwards
2767 if(!childrenPushed
) {
2768 Kind k
= n
.getKind();
2770 // we can short circuit (variable) leaves
2772 SmtEngine::DefinedFunctionMap::const_iterator i
= d_smt
.d_definedFunctions
->find(n
);
2773 if(i
!= d_smt
.d_definedFunctions
->end()) {
2774 // replacement must be closed
2775 if((*i
).second
.getFormals().size() > 0) {
2776 result
.push(d_smt
.d_nodeManager
->mkNode(kind::LAMBDA
, d_smt
.d_nodeManager
->mkNode(kind::BOUND_VAR_LIST
, (*i
).second
.getFormals()), (*i
).second
.getFormula()));
2779 // don't bother putting in the cache
2780 result
.push((*i
).second
.getFormula());
2783 // don't bother putting in the cache
2788 // maybe it's in the cache
2789 unordered_map
<Node
, Node
, NodeHashFunction
>::iterator cacheHit
= cache
.find(n
);
2790 if(cacheHit
!= cache
.end()) {
2791 TNode ret
= (*cacheHit
).second
;
2792 result
.push(ret
.isNull() ? n
: ret
);
2796 // otherwise expand it
2797 bool doExpand
= k
== kind::APPLY
;
2799 // options that assign substitutions to APPLY_UF
2800 if (options::macrosQuant() || options::sygusInference())
2802 //expand if we have inferred an operator corresponds to a defined function
2803 doExpand
= k
==kind::APPLY_UF
&& d_smt
.isDefinedFunction( n
.getOperator().toExpr() );
2807 vector
<Node
> formals
;
2809 if( n
.getOperator().getKind() == kind::LAMBDA
){
2810 TNode op
= n
.getOperator();
2812 for( unsigned i
=0; i
<op
[0].getNumChildren(); i
++ ){
2813 formals
.push_back( op
[0][i
] );
2817 // application of a user-defined symbol
2818 TNode func
= n
.getOperator();
2819 SmtEngine::DefinedFunctionMap::const_iterator i
= d_smt
.d_definedFunctions
->find(func
);
2820 if(i
== d_smt
.d_definedFunctions
->end()) {
2821 throw TypeCheckingException(n
.toExpr(), string("Undefined function: `") + func
.toString() + "'");
2823 DefinedFunction def
= (*i
).second
;
2824 formals
= def
.getFormals();
2826 if(Debug
.isOn("expand")) {
2827 Debug("expand") << "found: " << n
<< endl
;
2828 Debug("expand") << " func: " << func
<< endl
;
2829 string name
= func
.getAttribute(expr::VarNameAttr());
2830 Debug("expand") << " : \"" << name
<< "\"" << endl
;
2832 if(Debug
.isOn("expand")) {
2833 Debug("expand") << " defn: " << def
.getFunction() << endl
2835 if(formals
.size() > 0) {
2836 copy( formals
.begin(), formals
.end() - 1,
2837 ostream_iterator
<Node
>(Debug("expand"), ", ") );
2838 Debug("expand") << formals
.back();
2840 Debug("expand") << "]" << endl
2841 << " " << def
.getFunction().getType() << endl
2842 << " " << def
.getFormula() << endl
;
2845 fm
= def
.getFormula();
2848 Node instance
= fm
.substitute(formals
.begin(),
2851 n
.begin() + formals
.size());
2852 Debug("expand") << "made : " << instance
<< endl
;
2854 Node expanded
= expandDefinitions(instance
, cache
, expandOnly
);
2855 cache
[n
] = (n
== expanded
? Node::null() : expanded
);
2856 result
.push(expanded
);
2859 } else if(! expandOnly
) {
2860 // do not do any theory stuff if expandOnly is true
2862 theory::Theory
* t
= d_smt
.d_theoryEngine
->theoryOf(node
);
2865 LogicRequest
req(d_smt
);
2866 node
= t
->expandDefinition(req
, n
);
2869 // the partial functions can fall through, in which case we still
2870 // consider their children
2871 worklist
.push(make_triple(Node(n
), node
, true)); // Original and rewritten result
2873 for(size_t i
= 0; i
< node
.getNumChildren(); ++i
) {
2874 worklist
.push(make_triple(node
[i
], node
[i
], false)); // Rewrite the children of the result only
2879 // Reconstruct the node from it's (now rewritten) children on the stack
2881 Debug("expand") << "cons : " << node
<< endl
;
2882 if(node
.getNumChildren()>0) {
2883 //cout << "cons : " << node << endl;
2884 NodeBuilder
<> nb(node
.getKind());
2885 if(node
.getMetaKind() == kind::metakind::PARAMETERIZED
) {
2886 Debug("expand") << "op : " << node
.getOperator() << endl
;
2887 //cout << "op : " << node.getOperator() << endl;
2888 nb
<< node
.getOperator();
2890 for(size_t i
= 0; i
< node
.getNumChildren(); ++i
) {
2891 Assert(!result
.empty());
2892 Node expanded
= result
.top();
2894 //cout << "exchld : " << expanded << endl;
2895 Debug("expand") << "exchld : " << expanded
<< endl
;
2900 cache
[n
] = n
== node
? Node::null() : node
; // Only cache once all subterms are expanded
2903 } while(!worklist
.empty());
2905 AlwaysAssert(result
.size() == 1);
2907 return result
.top();
2910 typedef std::unordered_map
<Node
, Node
, NodeHashFunction
> NodeMap
;
2912 Node
SmtEnginePrivate::purifyNlTerms(TNode n
, NodeMap
& cache
, NodeMap
& bcache
, std::vector
< Node
>& var_eq
, bool beneathMult
) {
2914 NodeMap::iterator find
= bcache
.find(n
);
2915 if (find
!= bcache
.end()) {
2916 return (*find
).second
;
2919 NodeMap::iterator find
= cache
.find(n
);
2920 if (find
!= cache
.end()) {
2921 return (*find
).second
;
2925 if( n
.getNumChildren()>0 ){
2927 && (n
.getKind() == kind::PLUS
|| n
.getKind() == kind::MINUS
))
2929 // don't do it if it rewrites to a constant
2930 Node nr
= Rewriter::rewrite(n
);
2933 // return the rewritten constant
2939 ret
= NodeManager::currentNM()->mkSkolem(
2942 "Variable introduced in purifyNl pass");
2943 Node np
= purifyNlTerms(n
, cache
, bcache
, var_eq
, false);
2944 var_eq
.push_back(np
.eqNode(ret
));
2945 Trace("nl-ext-purify")
2946 << "Purify : " << ret
<< " -> " << np
<< std::endl
;
2951 bool beneathMultNew
= beneathMult
|| n
.getKind()==kind::MULT
;
2952 bool childChanged
= false;
2953 std::vector
< Node
> children
;
2954 for( unsigned i
=0; i
<n
.getNumChildren(); i
++ ){
2955 Node nc
= purifyNlTerms( n
[i
], cache
, bcache
, var_eq
, beneathMultNew
);
2956 childChanged
= childChanged
|| nc
!=n
[i
];
2957 children
.push_back( nc
);
2960 ret
= NodeManager::currentNM()->mkNode( n
.getKind(), children
);
2972 void SmtEnginePrivate::removeITEs() {
2973 d_smt
.finalOptionsAreSet();
2974 spendResource(options::preprocessStep());
2975 Trace("simplify") << "SmtEnginePrivate::removeITEs()" << endl
;
2977 // Remove all of the ITE occurrences and normalize
2978 d_iteRemover
.run(d_assertions
.ref(), d_iteSkolemMap
, true);
2979 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
2980 d_assertions
.replace(i
, Rewriter::rewrite(d_assertions
[i
]));
2986 // do dumping (before/after any preprocessing pass)
2987 static void dumpAssertions(const char* key
,
2988 const AssertionPipeline
& assertionList
) {
2989 if( Dump
.isOn("assertions") &&
2990 Dump
.isOn(string("assertions:") + key
) ) {
2991 // Push the simplified assertions to the dump output stream
2992 for(unsigned i
= 0; i
< assertionList
.size(); ++ i
) {
2993 TNode n
= assertionList
[i
];
2994 Dump("assertions") << AssertCommand(Expr(n
.toExpr()));
2999 // returns false if it learns a conflict
3000 bool SmtEnginePrivate::nonClausalSimplify() {
3001 spendResource(options::preprocessStep());
3002 d_smt
.finalOptionsAreSet();
3004 if(options::unsatCores() || options::fewerPreprocessingHoles()) {
3008 TimerStat::CodeTimer
nonclausalTimer(d_smt
.d_stats
->d_nonclausalSimplificationTime
);
3010 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify()" << endl
;
3011 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
3012 Trace("simplify") << "Assertion #" << i
<< " : " << d_assertions
[i
] << std::endl
;
3015 if(d_propagatorNeedsFinish
) {
3016 d_propagator
.finish();
3017 d_propagatorNeedsFinish
= false;
3019 d_propagator
.initialize();
3021 // Assert all the assertions to the propagator
3022 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
3023 << "asserting to propagator" << endl
;
3024 CDO
<unsigned>& substs_index
= d_assertions
.getSubstitutionsIndex();
3025 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
3026 Assert(Rewriter::rewrite(d_assertions
[i
]) == d_assertions
[i
]);
3027 // Don't reprocess substitutions
3028 if (substs_index
> 0 && i
== substs_index
)
3032 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): asserting " << d_assertions
[i
] << endl
;
3033 Debug("cores") << "d_propagator assertTrue: " << d_assertions
[i
] << std::endl
;
3034 d_propagator
.assertTrue(d_assertions
[i
]);
3037 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
3038 << "propagating" << endl
;
3039 if (d_propagator
.propagate()) {
3040 // If in conflict, just return false
3041 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
3042 << "conflict in non-clausal propagation" << endl
;
3043 Node falseNode
= NodeManager::currentNM()->mkConst
<bool>(false);
3044 Assert(!options::unsatCores() && !options::fewerPreprocessingHoles());
3045 d_assertions
.clear();
3046 addFormula(falseNode
, false, false);
3047 d_propagatorNeedsFinish
= true;
3052 Trace("simplify") << "Iterate through " << d_nonClausalLearnedLiterals
.size() << " learned literals." << std::endl
;
3053 // No conflict, go through the literals and solve them
3054 SubstitutionMap
& top_level_substs
= d_assertions
.getTopLevelSubstitutions();
3055 SubstitutionMap
constantPropagations(d_smt
.d_context
);
3056 SubstitutionMap
newSubstitutions(d_smt
.d_context
);
3057 SubstitutionMap::iterator pos
;
3059 for(unsigned i
= 0, i_end
= d_nonClausalLearnedLiterals
.size(); i
< i_end
; ++ i
) {
3060 // Simplify the literal we learned wrt previous substitutions
3061 Node learnedLiteral
= d_nonClausalLearnedLiterals
[i
];
3062 Assert(Rewriter::rewrite(learnedLiteral
) == learnedLiteral
);
3063 Assert(top_level_substs
.apply(learnedLiteral
) == learnedLiteral
);
3064 Trace("simplify") << "Process learnedLiteral : " << learnedLiteral
<< std::endl
;
3065 Node learnedLiteralNew
= newSubstitutions
.apply(learnedLiteral
);
3066 if (learnedLiteral
!= learnedLiteralNew
) {
3067 learnedLiteral
= Rewriter::rewrite(learnedLiteralNew
);
3069 Trace("simplify") << "Process learnedLiteral, after newSubs : " << learnedLiteral
<< std::endl
;
3071 learnedLiteralNew
= constantPropagations
.apply(learnedLiteral
);
3072 if (learnedLiteralNew
== learnedLiteral
) {
3075 ++d_smt
.d_stats
->d_numConstantProps
;
3076 learnedLiteral
= Rewriter::rewrite(learnedLiteralNew
);
3078 Trace("simplify") << "Process learnedLiteral, after constProp : " << learnedLiteral
<< std::endl
;
3079 // It might just simplify to a constant
3080 if (learnedLiteral
.isConst()) {
3081 if (learnedLiteral
.getConst
<bool>()) {
3082 // If the learned literal simplifies to true, it's redundant
3085 // If the learned literal simplifies to false, we're in conflict
3086 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
3088 << d_nonClausalLearnedLiterals
[i
] << endl
;
3089 Assert(!options::unsatCores());
3090 d_assertions
.clear();
3091 addFormula(NodeManager::currentNM()->mkConst
<bool>(false), false, false);
3092 d_propagatorNeedsFinish
= true;
3097 // Solve it with the corresponding theory, possibly adding new
3098 // substitutions to newSubstitutions
3099 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
3100 << "solving " << learnedLiteral
<< endl
;
3102 Theory::PPAssertStatus solveStatus
=
3103 d_smt
.d_theoryEngine
->solve(learnedLiteral
, newSubstitutions
);
3105 switch (solveStatus
) {
3106 case Theory::PP_ASSERT_STATUS_SOLVED
: {
3107 // The literal should rewrite to true
3108 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
3109 << "solved " << learnedLiteral
<< endl
;
3110 Assert(Rewriter::rewrite(newSubstitutions
.apply(learnedLiteral
)).isConst());
3111 // vector<pair<Node, Node> > equations;
3112 // constantPropagations.simplifyLHS(top_level_substs, equations,
3113 // true); if (equations.empty()) {
3116 // Assert(equations[0].first.isConst() &&
3117 // equations[0].second.isConst() && equations[0].first !=
3118 // equations[0].second);
3119 // else fall through
3122 case Theory::PP_ASSERT_STATUS_CONFLICT
:
3123 // If in conflict, we return false
3124 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
3125 << "conflict while solving "
3126 << learnedLiteral
<< endl
;
3127 Assert(!options::unsatCores());
3128 d_assertions
.clear();
3129 addFormula(NodeManager::currentNM()->mkConst
<bool>(false), false, false);
3130 d_propagatorNeedsFinish
= true;
3133 if (d_doConstantProp
&& learnedLiteral
.getKind() == kind::EQUAL
&& (learnedLiteral
[0].isConst() || learnedLiteral
[1].isConst())) {
3134 // constant propagation
3137 if (learnedLiteral
[0].isConst()) {
3138 t
= learnedLiteral
[1];
3139 c
= learnedLiteral
[0];
3142 t
= learnedLiteral
[0];
3143 c
= learnedLiteral
[1];
3145 Assert(!t
.isConst());
3146 Assert(constantPropagations
.apply(t
) == t
);
3147 Assert(top_level_substs
.apply(t
) == t
);
3148 Assert(newSubstitutions
.apply(t
) == t
);
3149 constantPropagations
.addSubstitution(t
, c
);
3150 // vector<pair<Node,Node> > equations;
3151 // constantPropagations.simplifyLHS(t, c, equations, true);
3152 // if (!equations.empty()) {
3153 // Assert(equations[0].first.isConst() &&
3154 // equations[0].second.isConst() && equations[0].first !=
3155 // equations[0].second); d_assertions.clear();
3156 // addFormula(NodeManager::currentNM()->mkConst<bool>(false), false,
3159 // top_level_substs.simplifyRHS(constantPropagations);
3163 d_nonClausalLearnedLiterals
[j
++] = d_nonClausalLearnedLiterals
[i
];
3169 #ifdef CVC4_ASSERTIONS
3170 // NOTE: When debugging this code, consider moving this check inside of the
3171 // loop over d_nonClausalLearnedLiterals. This check has been moved outside
3172 // because it is costly for certain inputs (see bug 508).
3174 // Check data structure invariants:
3175 // 1. for each lhs of top_level_substs, does not appear anywhere in rhs of
3176 // top_level_substs or anywhere in constantPropagations
3177 // 2. each lhs of constantPropagations rewrites to itself
3178 // 3. if l -> r is a constant propagation and l is a subterm of l' with l' ->
3179 // r' another constant propagation, then l'[l/r] -> r' should be a
3180 // constant propagation too
3181 // 4. each lhs of constantPropagations is different from each rhs
3182 for (pos
= newSubstitutions
.begin(); pos
!= newSubstitutions
.end(); ++pos
) {
3183 Assert((*pos
).first
.isVar());
3184 Assert(top_level_substs
.apply((*pos
).first
) == (*pos
).first
);
3185 Assert(top_level_substs
.apply((*pos
).second
) == (*pos
).second
);
3186 Assert(newSubstitutions
.apply(newSubstitutions
.apply((*pos
).second
)) == newSubstitutions
.apply((*pos
).second
));
3188 for (pos
= constantPropagations
.begin(); pos
!= constantPropagations
.end(); ++pos
) {
3189 Assert((*pos
).second
.isConst());
3190 Assert(Rewriter::rewrite((*pos
).first
) == (*pos
).first
);
3191 // Node newLeft = top_level_substs.apply((*pos).first);
3192 // if (newLeft != (*pos).first) {
3193 // newLeft = Rewriter::rewrite(newLeft);
3194 // Assert(newLeft == (*pos).second ||
3195 // (constantPropagations.hasSubstitution(newLeft) &&
3196 // constantPropagations.apply(newLeft) == (*pos).second));
3198 // newLeft = constantPropagations.apply((*pos).first);
3199 // if (newLeft != (*pos).first) {
3200 // newLeft = Rewriter::rewrite(newLeft);
3201 // Assert(newLeft == (*pos).second ||
3202 // (constantPropagations.hasSubstitution(newLeft) &&
3203 // constantPropagations.apply(newLeft) == (*pos).second));
3205 Assert(constantPropagations
.apply((*pos
).second
) == (*pos
).second
);
3207 #endif /* CVC4_ASSERTIONS */
3209 // Resize the learnt
3210 Trace("simplify") << "Resize non-clausal learned literals to " << j
<< std::endl
;
3211 d_nonClausalLearnedLiterals
.resize(j
);
3213 unordered_set
<TNode
, TNodeHashFunction
> s
;
3214 Trace("debugging") << "NonClausal simplify pre-preprocess\n";
3215 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
3216 Node assertion
= d_assertions
[i
];
3217 Node assertionNew
= newSubstitutions
.apply(assertion
);
3218 Trace("debugging") << "assertion = " << assertion
<< endl
;
3219 Trace("debugging") << "assertionNew = " << assertionNew
<< endl
;
3220 if (assertion
!= assertionNew
) {
3221 assertion
= Rewriter::rewrite(assertionNew
);
3222 Trace("debugging") << "rewrite(assertion) = " << assertion
<< endl
;
3224 Assert(Rewriter::rewrite(assertion
) == assertion
);
3226 assertionNew
= constantPropagations
.apply(assertion
);
3227 if (assertionNew
== assertion
) {
3230 ++d_smt
.d_stats
->d_numConstantProps
;
3231 Trace("debugging") << "assertionNew = " << assertionNew
<< endl
;
3232 assertion
= Rewriter::rewrite(assertionNew
);
3233 Trace("debugging") << "assertionNew = " << assertionNew
<< endl
;
3235 Trace("debugging") << "\n";
3236 s
.insert(assertion
);
3237 d_assertions
.replace(i
, assertion
);
3238 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
3239 << "non-clausal preprocessed: "
3240 << assertion
<< endl
;
3243 // If in incremental mode, add substitutions to the list of assertions
3244 if (substs_index
> 0)
3246 NodeBuilder
<> substitutionsBuilder(kind::AND
);
3247 substitutionsBuilder
<< d_assertions
[substs_index
];
3248 pos
= newSubstitutions
.begin();
3249 for (; pos
!= newSubstitutions
.end(); ++pos
) {
3250 // Add back this substitution as an assertion
3251 TNode lhs
= (*pos
).first
, rhs
= newSubstitutions
.apply((*pos
).second
);
3252 Node n
= NodeManager::currentNM()->mkNode(kind::EQUAL
, lhs
, rhs
);
3253 substitutionsBuilder
<< n
;
3254 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): will notify SAT layer of substitution: " << n
<< endl
;
3256 if (substitutionsBuilder
.getNumChildren() > 1) {
3257 d_assertions
.replace(substs_index
,
3258 Rewriter::rewrite(Node(substitutionsBuilder
)));
3261 // If not in incremental mode, must add substitutions to model
3262 TheoryModel
* m
= d_smt
.d_theoryEngine
->getModel();
3264 for(pos
= newSubstitutions
.begin(); pos
!= newSubstitutions
.end(); ++pos
) {
3265 Node n
= (*pos
).first
;
3266 Node v
= newSubstitutions
.apply((*pos
).second
);
3267 Trace("model") << "Add substitution : " << n
<< " " << v
<< endl
;
3268 m
->addSubstitution( n
, v
);
3273 NodeBuilder
<> learnedBuilder(kind::AND
);
3274 Assert(d_realAssertionsEnd
<= d_assertions
.size());
3275 learnedBuilder
<< d_assertions
[d_realAssertionsEnd
- 1];
3277 for (unsigned i
= 0; i
< d_nonClausalLearnedLiterals
.size(); ++ i
) {
3278 Node learned
= d_nonClausalLearnedLiterals
[i
];
3279 Assert(top_level_substs
.apply(learned
) == learned
);
3280 Node learnedNew
= newSubstitutions
.apply(learned
);
3281 if (learned
!= learnedNew
) {
3282 learned
= Rewriter::rewrite(learnedNew
);
3284 Assert(Rewriter::rewrite(learned
) == learned
);
3286 learnedNew
= constantPropagations
.apply(learned
);
3287 if (learnedNew
== learned
) {
3290 ++d_smt
.d_stats
->d_numConstantProps
;
3291 learned
= Rewriter::rewrite(learnedNew
);
3293 if (s
.find(learned
) != s
.end()) {
3297 learnedBuilder
<< learned
;
3298 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
3299 << "non-clausal learned : "
3302 d_nonClausalLearnedLiterals
.clear();
3304 for (pos
= constantPropagations
.begin(); pos
!= constantPropagations
.end(); ++pos
) {
3305 Node cProp
= (*pos
).first
.eqNode((*pos
).second
);
3306 Assert(top_level_substs
.apply(cProp
) == cProp
);
3307 Node cPropNew
= newSubstitutions
.apply(cProp
);
3308 if (cProp
!= cPropNew
) {
3309 cProp
= Rewriter::rewrite(cPropNew
);
3310 Assert(Rewriter::rewrite(cProp
) == cProp
);
3312 if (s
.find(cProp
) != s
.end()) {
3316 learnedBuilder
<< cProp
;
3317 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
3318 << "non-clausal constant propagation : "
3322 // Add new substitutions to topLevelSubstitutions
3323 // Note that we don't have to keep rhs's in full solved form
3324 // because SubstitutionMap::apply does a fixed-point iteration when substituting
3325 top_level_substs
.addSubstitutions(newSubstitutions
);
3327 if(learnedBuilder
.getNumChildren() > 1) {
3328 d_assertions
.replace(d_realAssertionsEnd
- 1,
3329 Rewriter::rewrite(Node(learnedBuilder
)));
3332 d_propagatorNeedsFinish
= true;
3336 bool SmtEnginePrivate::simpITE() {
3337 TimerStat::CodeTimer
simpITETimer(d_smt
.d_stats
->d_simpITETime
);
3339 spendResource(options::preprocessStep());
3341 Trace("simplify") << "SmtEnginePrivate::simpITE()" << endl
;
3343 unsigned numAssertionOnEntry
= d_assertions
.size();
3344 for (unsigned i
= 0; i
< d_assertions
.size(); ++i
) {
3345 spendResource(options::preprocessStep());
3346 Node result
= d_smt
.d_theoryEngine
->ppSimpITE(d_assertions
[i
]);
3347 d_assertions
.replace(i
, result
);
3348 if(result
.isConst() && !result
.getConst
<bool>()){
3352 bool result
= d_smt
.d_theoryEngine
->donePPSimpITE(d_assertions
.ref());
3353 if(numAssertionOnEntry
< d_assertions
.size()){
3354 compressBeforeRealAssertions(numAssertionOnEntry
);
3359 void SmtEnginePrivate::compressBeforeRealAssertions(size_t before
){
3360 size_t curr
= d_assertions
.size();
3361 if(before
>= curr
||
3362 d_realAssertionsEnd
<= 0 ||
3363 d_realAssertionsEnd
>= curr
){
3368 // original: [0 ... d_realAssertionsEnd)
3370 // ites skolems [d_realAssertionsEnd, before)
3372 // added [before, curr)
3374 Assert(0 < d_realAssertionsEnd
);
3375 Assert(d_realAssertionsEnd
<= before
);
3376 Assert(before
< curr
);
3378 std::vector
<Node
> intoConjunction
;
3379 for(size_t i
= before
; i
<curr
; ++i
){
3380 intoConjunction
.push_back(d_assertions
[i
]);
3382 d_assertions
.resize(before
);
3383 size_t lastBeforeItes
= d_realAssertionsEnd
- 1;
3384 intoConjunction
.push_back(d_assertions
[lastBeforeItes
]);
3385 Node newLast
= util::NaryBuilder::mkAssoc(kind::AND
, intoConjunction
);
3386 d_assertions
.replace(lastBeforeItes
, newLast
);
3387 Assert(d_assertions
.size() == before
);
3390 void SmtEnginePrivate::unconstrainedSimp() {
3391 TimerStat::CodeTimer
unconstrainedSimpTimer(d_smt
.d_stats
->d_unconstrainedSimpTime
);
3392 spendResource(options::preprocessStep());
3393 Trace("simplify") << "SmtEnginePrivate::unconstrainedSimp()" << endl
;
3394 d_smt
.d_theoryEngine
->ppUnconstrainedSimp(d_assertions
.ref());
3397 void SmtEnginePrivate::traceBackToAssertions(const std::vector
<Node
>& nodes
, std::vector
<TNode
>& assertions
) {
3398 const booleans::CircuitPropagator::BackEdgesMap
& backEdges
= d_propagator
.getBackEdges();
3399 for(vector
<Node
>::const_iterator i
= nodes
.begin(); i
!= nodes
.end(); ++i
) {
3400 booleans::CircuitPropagator::BackEdgesMap::const_iterator j
= backEdges
.find(*i
);
3401 // term must appear in map, otherwise how did we get here?!
3402 Assert(j
!= backEdges
.end());
3403 // if term maps to empty, that means it's a top-level assertion
3404 if(!(*j
).second
.empty()) {
3405 traceBackToAssertions((*j
).second
, assertions
);
3407 assertions
.push_back(*i
);
3412 size_t SmtEnginePrivate::removeFromConjunction(Node
& n
, const std::unordered_set
<unsigned long>& toRemove
) {
3413 Assert(n
.getKind() == kind::AND
);
3414 size_t removals
= 0;
3415 for(Node::iterator j
= n
.begin(); j
!= n
.end(); ++j
) {
3416 size_t subremovals
= 0;
3418 if(toRemove
.find(sub
.getId()) != toRemove
.end() ||
3419 (sub
.getKind() == kind::AND
&& (subremovals
= removeFromConjunction(sub
, toRemove
)) > 0)) {
3420 NodeBuilder
<> b(kind::AND
);
3421 b
.append(n
.begin(), j
);
3422 if(subremovals
> 0) {
3423 removals
+= subremovals
;
3428 for(++j
; j
!= n
.end(); ++j
) {
3429 if(toRemove
.find((*j
).getId()) != toRemove
.end()) {
3431 } else if((*j
).getKind() == kind::AND
) {
3433 if((subremovals
= removeFromConjunction(sub
, toRemove
)) > 0) {
3434 removals
+= subremovals
;
3443 if(b
.getNumChildren() == 0) {
3446 } else if(b
.getNumChildren() == 1) {
3452 n
= Rewriter::rewrite(n
);
3457 Assert(removals
== 0);
3461 void SmtEnginePrivate::doMiplibTrick() {
3462 Assert(d_realAssertionsEnd
== d_assertions
.size());
3463 Assert(!options::incrementalSolving());
3465 const booleans::CircuitPropagator::BackEdgesMap
& backEdges
= d_propagator
.getBackEdges();
3466 unordered_set
<unsigned long> removeAssertions
;
3468 NodeManager
* nm
= NodeManager::currentNM();
3469 Node zero
= nm
->mkConst(Rational(0)), one
= nm
->mkConst(Rational(1));
3471 SubstitutionMap
& top_level_substs
= d_assertions
.getTopLevelSubstitutions();
3472 unordered_map
<TNode
, Node
, TNodeHashFunction
> intVars
;
3473 for(vector
<Node
>::const_iterator i
= d_boolVars
.begin(); i
!= d_boolVars
.end(); ++i
) {
3474 if(d_propagator
.isAssigned(*i
)) {
3475 Debug("miplib") << "ineligible: " << *i
<< " because assigned " << d_propagator
.getAssignment(*i
) << endl
;
3479 vector
<TNode
> assertions
;
3480 booleans::CircuitPropagator::BackEdgesMap::const_iterator j
= backEdges
.find(*i
);
3481 // if not in back edges map, the bool var is unconstrained, showing up in no assertions.
3482 // if maps to an empty vector, that means the bool var was asserted itself.
3483 if(j
!= backEdges
.end()) {
3484 if(!(*j
).second
.empty()) {
3485 traceBackToAssertions((*j
).second
, assertions
);
3487 assertions
.push_back(*i
);
3490 Debug("miplib") << "for " << *i
<< endl
;
3491 bool eligible
= true;
3492 map
<pair
<Node
, Node
>, uint64_t> marks
;
3493 map
<pair
<Node
, Node
>, vector
<Rational
> > coef
;
3494 map
<pair
<Node
, Node
>, vector
<Rational
> > checks
;
3495 map
<pair
<Node
, Node
>, vector
<TNode
> > asserts
;
3496 for(vector
<TNode
>::const_iterator j
= assertions
.begin(); j
!= assertions
.end(); ++j
) {
3497 Debug("miplib") << " found: " << *j
<< endl
;
3498 if((*j
).getKind() != kind::IMPLIES
) {
3500 Debug("miplib") << " -- INELIGIBLE -- (not =>)" << endl
;
3503 Node conj
= BooleanSimplification::simplify((*j
)[0]);
3504 if(conj
.getKind() == kind::AND
&& conj
.getNumChildren() > 6) {
3506 Debug("miplib") << " -- INELIGIBLE -- (N-ary /\\ too big)" << endl
;
3509 if(conj
.getKind() != kind::AND
&& !conj
.isVar() && !(conj
.getKind() == kind::NOT
&& conj
[0].isVar())) {
3511 Debug("miplib") << " -- INELIGIBLE -- (not /\\ or literal)" << endl
;
3514 if((*j
)[1].getKind() != kind::EQUAL
||
3515 !( ( (*j
)[1][0].isVar() &&
3516 (*j
)[1][1].getKind() == kind::CONST_RATIONAL
) ||
3517 ( (*j
)[1][0].getKind() == kind::CONST_RATIONAL
&&
3518 (*j
)[1][1].isVar() ) )) {
3520 Debug("miplib") << " -- INELIGIBLE -- (=> (and X X) X)" << endl
;
3523 if(conj
.getKind() == kind::AND
) {
3525 bool found_x
= false;
3526 map
<TNode
, bool> neg
;
3527 for(Node::iterator ii
= conj
.begin(); ii
!= conj
.end(); ++ii
) {
3529 posv
.push_back(*ii
);
3531 found_x
= found_x
|| *i
== *ii
;
3532 } else if((*ii
).getKind() == kind::NOT
&& (*ii
)[0].isVar()) {
3533 posv
.push_back((*ii
)[0]);
3534 neg
[(*ii
)[0]] = true;
3535 found_x
= found_x
|| *i
== (*ii
)[0];
3538 Debug("miplib") << " -- INELIGIBLE -- (non-var: " << *ii
<< ")" << endl
;
3541 if(d_propagator
.isAssigned(posv
.back())) {
3543 Debug("miplib") << " -- INELIGIBLE -- (" << posv
.back() << " asserted)" << endl
;
3552 Debug("miplib") << " --INELIGIBLE -- (couldn't find " << *i
<< " in conjunction)" << endl
;
3555 sort(posv
.begin(), posv
.end());
3556 const Node pos
= NodeManager::currentNM()->mkNode(kind::AND
, posv
);
3557 const TNode var
= ((*j
)[1][0].getKind() == kind::CONST_RATIONAL
) ? (*j
)[1][1] : (*j
)[1][0];
3558 const pair
<Node
, Node
> pos_var(pos
, var
);
3559 const Rational
& constant
= ((*j
)[1][0].getKind() == kind::CONST_RATIONAL
) ? (*j
)[1][0].getConst
<Rational
>() : (*j
)[1][1].getConst
<Rational
>();
3561 unsigned countneg
= 0, thepos
= 0;
3562 for(unsigned ii
= 0; ii
< pos
.getNumChildren(); ++ii
) {
3567 mark
|= (0x1 << ii
);
3570 if((marks
[pos_var
] & (1lu << mark
)) != 0) {
3572 Debug("miplib") << " -- INELIGIBLE -- (remarked)" << endl
;
3575 Debug("miplib") << "mark is " << mark
<< " -- " << (1lu << mark
) << endl
;
3576 marks
[pos_var
] |= (1lu << mark
);
3577 Debug("miplib") << "marks[" << pos
<< "," << var
<< "] now " << marks
[pos_var
] << endl
;
3578 if(countneg
== pos
.getNumChildren()) {
3581 Debug("miplib") << " -- INELIGIBLE -- (nonzero constant)" << endl
;
3584 } else if(countneg
== pos
.getNumChildren() - 1) {
3585 Assert(coef
[pos_var
].size() <= 6 && thepos
< 6);
3586 if(coef
[pos_var
].size() <= thepos
) {
3587 coef
[pos_var
].resize(thepos
+ 1);
3589 coef
[pos_var
][thepos
] = constant
;
3591 if(checks
[pos_var
].size() <= mark
) {
3592 checks
[pos_var
].resize(mark
+ 1);
3594 checks
[pos_var
][mark
] = constant
;
3596 asserts
[pos_var
].push_back(*j
);
3599 if(x
!= *i
&& x
!= (*i
).notNode()) {
3601 Debug("miplib") << " -- INELIGIBLE -- (x not present where I expect it)" << endl
;
3604 const bool xneg
= (x
.getKind() == kind::NOT
);
3605 x
= xneg
? x
[0] : x
;
3606 Debug("miplib") << " x:" << x
<< " " << xneg
<< endl
;
3607 const TNode var
= ((*j
)[1][0].getKind() == kind::CONST_RATIONAL
) ? (*j
)[1][1] : (*j
)[1][0];
3608 const pair
<Node
, Node
> x_var(x
, var
);
3609 const Rational
& constant
= ((*j
)[1][0].getKind() == kind::CONST_RATIONAL
) ? (*j
)[1][0].getConst
<Rational
>() : (*j
)[1][1].getConst
<Rational
>();
3610 unsigned mark
= (xneg
? 0 : 1);
3611 if((marks
[x_var
] & (1u << mark
)) != 0) {
3613 Debug("miplib") << " -- INELIGIBLE -- (remarked)" << endl
;
3616 marks
[x_var
] |= (1u << mark
);
3620 Debug("miplib") << " -- INELIGIBLE -- (nonzero constant)" << endl
;
3624 Assert(coef
[x_var
].size() <= 6);
3625 coef
[x_var
].resize(6);
3626 coef
[x_var
][0] = constant
;
3628 asserts
[x_var
].push_back(*j
);
3632 for(map
<pair
<Node
, Node
>, uint64_t>::const_iterator j
= marks
.begin(); j
!= marks
.end(); ++j
) {
3633 const TNode pos
= (*j
).first
.first
;
3634 const TNode var
= (*j
).first
.second
;
3635 const pair
<Node
, Node
>& pos_var
= (*j
).first
;
3636 const uint64_t mark
= (*j
).second
;
3637 const unsigned numVars
= pos
.getKind() == kind::AND
? pos
.getNumChildren() : 1;
3638 uint64_t expected
= (uint64_t(1) << (1 << numVars
)) - 1;
3639 expected
= (expected
== 0) ? -1 : expected
; // fix for overflow
3640 Debug("miplib") << "[" << pos
<< "] => " << hex
<< mark
<< " expect " << expected
<< dec
<< endl
;
3641 Assert(pos
.getKind() == kind::AND
|| pos
.isVar());
3642 if(mark
!= expected
) {
3643 Debug("miplib") << " -- INELIGIBLE " << pos
<< " -- (insufficiently marked, got " << mark
<< " for " << numVars
<< " vars, expected " << expected
<< endl
;
3645 if(mark
!= 3) { // exclude single-var case; nothing to check there
3646 uint64_t sz
= (uint64_t(1) << checks
[pos_var
].size()) - 1;
3647 sz
= (sz
== 0) ? -1 : sz
; // fix for overflow
3648 Assert(sz
== mark
, "expected size %u == mark %u", sz
, mark
);
3649 for(size_t k
= 0; k
< checks
[pos_var
].size(); ++k
) {
3650 if((k
& (k
- 1)) != 0) {
3652 Debug("miplib") << k
<< " => " << checks
[pos_var
][k
] << endl
;
3653 for(size_t v
= 1, kk
= k
; kk
!= 0; ++v
, kk
>>= 1) {
3654 if((kk
& 0x1) == 1) {
3655 Assert(pos
.getKind() == kind::AND
);
3656 Debug("miplib") << "var " << v
<< " : " << pos
[v
- 1] << " coef:" << coef
[pos_var
][v
- 1] << endl
;
3657 sum
+= coef
[pos_var
][v
- 1];
3660 Debug("miplib") << "checkSum is " << sum
<< " input says " << checks
[pos_var
][k
] << endl
;
3661 if(sum
!= checks
[pos_var
][k
]) {
3663 Debug("miplib") << " -- INELIGIBLE " << pos
<< " -- (nonlinear combination)" << endl
;
3667 Assert(checks
[pos_var
][k
] == 0, "checks[(%s,%s)][%u] should be 0, but it's %s", pos
.toString().c_str(), var
.toString().c_str(), k
, checks
[pos_var
][k
].toString().c_str()); // we never set for single-positive-var
3672 eligible
= true; // next is still eligible
3676 Debug("miplib") << " -- ELIGIBLE " << *i
<< " , " << pos
<< " --" << endl
;
3677 vector
<Node
> newVars
;
3678 expr::NodeSelfIterator ii
, iiend
;
3679 if(pos
.getKind() == kind::AND
) {
3683 ii
= expr::NodeSelfIterator::self(pos
);
3684 iiend
= expr::NodeSelfIterator::selfEnd(pos
);
3686 for(; ii
!= iiend
; ++ii
) {
3687 Node
& varRef
= intVars
[*ii
];
3688 if(varRef
.isNull()) {
3690 ss
<< "mipvar_" << *ii
;
3691 Node newVar
= nm
->mkSkolem(ss
.str(), nm
->integerType(), "a variable introduced due to scrubbing a miplib encoding", NodeManager::SKOLEM_EXACT_NAME
);
3692 Node geq
= Rewriter::rewrite(nm
->mkNode(kind::GEQ
, newVar
, zero
));
3693 Node leq
= Rewriter::rewrite(nm
->mkNode(kind::LEQ
, newVar
, one
));
3694 addFormula(Rewriter::rewrite(geq
.andNode(leq
)), false, false);
3695 SubstitutionMap
nullMap(&d_fakeContext
);
3696 Theory::PPAssertStatus status CVC4_UNUSED
; // just for assertions
3697 status
= d_smt
.d_theoryEngine
->solve(geq
, nullMap
);
3698 Assert(status
== Theory::PP_ASSERT_STATUS_UNSOLVED
,
3699 "unexpected solution from arith's ppAssert()");
3700 Assert(nullMap
.empty(),
3701 "unexpected substitution from arith's ppAssert()");
3702 status
= d_smt
.d_theoryEngine
->solve(leq
, nullMap
);
3703 Assert(status
== Theory::PP_ASSERT_STATUS_UNSOLVED
,
3704 "unexpected solution from arith's ppAssert()");
3705 Assert(nullMap
.empty(),
3706 "unexpected substitution from arith's ppAssert()");
3707 d_smt
.d_theoryEngine
->getModel()->addSubstitution(*ii
, newVar
.eqNode(one
));
3708 newVars
.push_back(newVar
);
3711 newVars
.push_back(varRef
);
3713 if(!d_smt
.d_logic
.areIntegersUsed()) {
3714 d_smt
.d_logic
= d_smt
.d_logic
.getUnlockedCopy();
3715 d_smt
.d_logic
.enableIntegers();
3716 d_smt
.d_logic
.lock();
3720 if(pos
.getKind() == kind::AND
) {
3721 NodeBuilder
<> sumb(kind::PLUS
);
3722 for(size_t ii
= 0; ii
< pos
.getNumChildren(); ++ii
) {
3723 sumb
<< nm
->mkNode(kind::MULT
, nm
->mkConst(coef
[pos_var
][ii
]), newVars
[ii
]);
3727 sum
= nm
->mkNode(kind::MULT
, nm
->mkConst(coef
[pos_var
][0]), newVars
[0]);
3729 Debug("miplib") << "vars[] " << var
<< endl
3730 << " eq " << Rewriter::rewrite(sum
) << endl
;
3731 Node newAssertion
= var
.eqNode(Rewriter::rewrite(sum
));
3732 if (top_level_substs
.hasSubstitution(newAssertion
[0]))
3734 // Warning() << "RE-SUBSTITUTION " << newAssertion[0] << endl;
3735 // Warning() << "REPLACE " << newAssertion[1] << endl;
3736 // Warning() << "ORIG " <<
3737 // top_level_substs.getSubstitution(newAssertion[0]) << endl;
3738 Assert(top_level_substs
.getSubstitution(newAssertion
[0])
3739 == newAssertion
[1]);
3740 } else if(pos
.getNumChildren() <= options::arithMLTrickSubstitutions()) {
3741 top_level_substs
.addSubstitution(newAssertion
[0], newAssertion
[1]);
3742 Debug("miplib") << "addSubs: " << newAssertion
[0] << " to " << newAssertion
[1] << endl
;
3744 Debug("miplib") << "skipSubs: " << newAssertion
[0] << " to " << newAssertion
[1] << " (threshold is " << options::arithMLTrickSubstitutions() << ")" << endl
;
3746 newAssertion
= Rewriter::rewrite(newAssertion
);
3747 Debug("miplib") << " " << newAssertion
<< endl
;
3748 addFormula(newAssertion
, false, false);
3749 Debug("miplib") << " assertions to remove: " << endl
;
3750 for(vector
<TNode
>::const_iterator k
= asserts
[pos_var
].begin(), k_end
= asserts
[pos_var
].end(); k
!= k_end
; ++k
) {
3751 Debug("miplib") << " " << *k
<< endl
;
3752 removeAssertions
.insert((*k
).getId());
3758 if(!removeAssertions
.empty()) {
3759 Debug("miplib") << "SmtEnginePrivate::simplify(): scrubbing miplib encoding..." << endl
;
3760 for(size_t i
= 0; i
< d_realAssertionsEnd
; ++i
) {
3761 if(removeAssertions
.find(d_assertions
[i
].getId()) != removeAssertions
.end()) {
3762 Debug("miplib") << "SmtEnginePrivate::simplify(): - removing " << d_assertions
[i
] << endl
;
3763 d_assertions
[i
] = d_true
;
3764 ++d_smt
.d_stats
->d_numMiplibAssertionsRemoved
;
3765 } else if(d_assertions
[i
].getKind() == kind::AND
) {
3766 size_t removals
= removeFromConjunction(d_assertions
[i
], removeAssertions
);
3768 Debug("miplib") << "SmtEnginePrivate::simplify(): - reduced " << d_assertions
[i
] << endl
;
3769 Debug("miplib") << "SmtEnginePrivate::simplify(): - by " << removals
<< " conjuncts" << endl
;
3770 d_smt
.d_stats
->d_numMiplibAssertionsRemoved
+= removals
;
3773 Debug("miplib") << "had: " << d_assertions
[i
] << endl
;
3775 Rewriter::rewrite(top_level_substs
.apply(d_assertions
[i
]));
3776 Debug("miplib") << "now: " << d_assertions
[i
] << endl
;
3779 Debug("miplib") << "SmtEnginePrivate::simplify(): miplib pass found nothing." << endl
;
3781 d_realAssertionsEnd
= d_assertions
.size();
3785 // returns false if simplification led to "false"
3786 bool SmtEnginePrivate::simplifyAssertions()
3788 spendResource(options::preprocessStep());
3789 Assert(d_smt
.d_pendingPops
== 0);
3791 ScopeCounter
depth(d_simplifyAssertionsDepth
);
3793 Trace("simplify") << "SmtEnginePrivate::simplify()" << endl
;
3795 dumpAssertions("pre-nonclausal", d_assertions
);
3797 if(options::simplificationMode() != SIMPLIFICATION_MODE_NONE
) {
3798 // Perform non-clausal simplification
3799 Chat() << "...performing nonclausal simplification..." << endl
;
3800 Trace("simplify") << "SmtEnginePrivate::simplify(): "
3801 << "performing non-clausal simplification" << endl
;
3802 bool noConflict
= nonClausalSimplify();
3807 // We piggy-back off of the BackEdgesMap in the CircuitPropagator to
3808 // do the miplib trick.
3809 if( // check that option is on
3810 options::arithMLTrick() &&
3811 // miplib rewrites aren't safe in incremental mode
3812 ! options::incrementalSolving() &&
3813 // only useful in arith
3814 d_smt
.d_logic
.isTheoryEnabled(THEORY_ARITH
) &&
3815 // we add new assertions and need this (in practice, this
3816 // restriction only disables miplib processing during
3817 // re-simplification, which we don't expect to be useful anyway)
3818 d_realAssertionsEnd
== d_assertions
.size() ) {
3819 Chat() << "...fixing miplib encodings..." << endl
;
3820 Trace("simplify") << "SmtEnginePrivate::simplify(): "
3821 << "looking for miplib pseudobooleans..." << endl
;
3823 TimerStat::CodeTimer
miplibTimer(d_smt
.d_stats
->d_miplibPassTime
);
3827 Trace("simplify") << "SmtEnginePrivate::simplify(): "
3828 << "skipping miplib pseudobooleans pass (either incrementalSolving is on, or miplib pbs are turned off)..." << endl
;
3832 dumpAssertions("post-nonclausal", d_assertions
);
3833 Trace("smt") << "POST nonClausalSimplify" << endl
;
3834 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
3836 // before ppRewrite check if only core theory for BV theory
3837 d_smt
.d_theoryEngine
->staticInitializeBVOptions(d_assertions
.ref());
3839 dumpAssertions("pre-theorypp", d_assertions
);
3841 // Theory preprocessing
3842 if (d_smt
.d_earlyTheoryPP
) {
3843 Chat() << "...doing early theory preprocessing..." << endl
;
3844 TimerStat::CodeTimer
codeTimer(d_smt
.d_stats
->d_theoryPreprocessTime
);
3845 // Call the theory preprocessors
3846 d_smt
.d_theoryEngine
->preprocessStart();
3847 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
3848 Assert(Rewriter::rewrite(d_assertions
[i
]) == d_assertions
[i
]);
3849 d_assertions
.replace(i
, d_smt
.d_theoryEngine
->preprocess(d_assertions
[i
]));
3850 Assert(Rewriter::rewrite(d_assertions
[i
]) == d_assertions
[i
]);
3854 dumpAssertions("post-theorypp", d_assertions
);
3855 Trace("smt") << "POST theoryPP" << endl
;
3856 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
3858 // ITE simplification
3859 if(options::doITESimp() &&
3860 (d_simplifyAssertionsDepth
<= 1 || options::doITESimpOnRepeat())) {
3861 Chat() << "...doing ITE simplification..." << endl
;
3862 bool noConflict
= simpITE();
3864 Chat() << "...ITE simplification found unsat..." << endl
;
3869 dumpAssertions("post-itesimp", d_assertions
);
3870 Trace("smt") << "POST iteSimp" << endl
;
3871 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
3873 // Unconstrained simplification
3874 if(options::unconstrainedSimp()) {
3875 Chat() << "...doing unconstrained simplification..." << endl
;
3876 unconstrainedSimp();
3879 dumpAssertions("post-unconstrained", d_assertions
);
3880 Trace("smt") << "POST unconstrainedSimp" << endl
;
3881 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
3883 if(options::repeatSimp() && options::simplificationMode() != SIMPLIFICATION_MODE_NONE
) {
3884 Chat() << "...doing another round of nonclausal simplification..." << endl
;
3885 Trace("simplify") << "SmtEnginePrivate::simplify(): "
3886 << " doing repeated simplification" << endl
;
3887 bool noConflict
= nonClausalSimplify();
3893 dumpAssertions("post-repeatsimp", d_assertions
);
3894 Trace("smt") << "POST repeatSimp" << endl
;
3895 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
3897 } catch(TypeCheckingExceptionPrivate
& tcep
) {
3898 // Calls to this function should have already weeded out any
3899 // typechecking exceptions via (e.g.) ensureBoolean(). But a
3900 // theory could still create a new expression that isn't
3901 // well-typed, and we don't want the C++ runtime to abort our
3902 // process without any error notice.
3904 ss
<< "A bad expression was produced. Original exception follows:\n"
3906 InternalError(ss
.str().c_str());
3911 Result
SmtEngine::check() {
3912 Assert(d_fullyInited
);
3913 Assert(d_pendingPops
== 0);
3915 Trace("smt") << "SmtEngine::check()" << endl
;
3917 ResourceManager
* resourceManager
= d_private
->getResourceManager();
3919 resourceManager
->beginCall();
3921 // Only way we can be out of resource is if cumulative budget is on
3922 if (resourceManager
->cumulativeLimitOn() &&
3923 resourceManager
->out()) {
3924 Result::UnknownExplanation why
= resourceManager
->outOfResources() ?
3925 Result::RESOURCEOUT
: Result::TIMEOUT
;
3926 return Result(Result::VALIDITY_UNKNOWN
, why
, d_filename
);
3929 // Make sure the prop layer has all of the assertions
3930 Trace("smt") << "SmtEngine::check(): processing assertions" << endl
;
3931 d_private
->processAssertions();
3932 Trace("smt") << "SmtEngine::check(): done processing assertions" << endl
;
3934 // Turn off stop only for QF_LRA
3935 // TODO: Bring up in a meeting where to put this
3936 if(options::decisionStopOnly() && !options::decisionMode
.wasSetByUser() ){
3938 (not d_logic
.isQuantified() &&
3939 d_logic
.isPure(THEORY_ARITH
) && d_logic
.isLinear() && !d_logic
.isDifferenceLogic() && !d_logic
.areIntegersUsed()
3941 if(d_private
->d_iteSkolemMap
.empty()){
3942 options::decisionStopOnly
.set(false);
3943 d_decisionEngine
->clearStrategies();
3944 Trace("smt") << "SmtEngine::check(): turning off stop only" << endl
;
3949 TimerStat::CodeTimer
solveTimer(d_stats
->d_solveTime
);
3951 Chat() << "solving..." << endl
;
3952 Trace("smt") << "SmtEngine::check(): running check" << endl
;
3953 Result result
= d_propEngine
->checkSat();
3955 resourceManager
->endCall();
3956 Trace("limit") << "SmtEngine::check(): cumulative millis " << resourceManager
->getTimeUsage()
3957 << ", resources " << resourceManager
->getResourceUsage() << endl
;
3960 return Result(result
, d_filename
);
3963 Result
SmtEngine::quickCheck() {
3964 Assert(d_fullyInited
);
3965 Trace("smt") << "SMT quickCheck()" << endl
;
3966 return Result(Result::VALIDITY_UNKNOWN
, Result::REQUIRES_FULL_CHECK
, d_filename
);
3970 void SmtEnginePrivate::collectSkolems(TNode n
, set
<TNode
>& skolemSet
, unordered_map
<Node
, bool, NodeHashFunction
>& cache
)
3972 unordered_map
<Node
, bool, NodeHashFunction
>::iterator it
;
3974 if (it
!= cache
.end()) {
3978 size_t sz
= n
.getNumChildren();
3980 IteSkolemMap::iterator it
= d_iteSkolemMap
.find(n
);
3981 if (it
!= d_iteSkolemMap
.end()) {
3982 skolemSet
.insert(n
);
3989 for (; k
< sz
; ++k
) {
3990 collectSkolems(n
[k
], skolemSet
, cache
);
3996 bool SmtEnginePrivate::checkForBadSkolems(TNode n
, TNode skolem
, unordered_map
<Node
, bool, NodeHashFunction
>& cache
)
3998 unordered_map
<Node
, bool, NodeHashFunction
>::iterator it
;
4000 if (it
!= cache
.end()) {
4001 return (*it
).second
;
4004 size_t sz
= n
.getNumChildren();
4006 IteSkolemMap::iterator it
= d_iteSkolemMap
.find(n
);
4008 if (it
!= d_iteSkolemMap
.end()) {
4009 if (!((*it
).first
< n
)) {
4018 for (; k
< sz
; ++k
) {
4019 if (checkForBadSkolems(n
[k
], skolem
, cache
)) {
4029 void SmtEnginePrivate::processAssertions() {
4030 TimerStat::CodeTimer
paTimer(d_smt
.d_stats
->d_processAssertionsTime
);
4031 spendResource(options::preprocessStep());
4032 Assert(d_smt
.d_fullyInited
);
4033 Assert(d_smt
.d_pendingPops
== 0);
4034 SubstitutionMap
& top_level_substs
= d_assertions
.getTopLevelSubstitutions();
4036 // Dump the assertions
4037 dumpAssertions("pre-everything", d_assertions
);
4039 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() begin" << endl
;
4040 Trace("smt") << "SmtEnginePrivate::processAssertions()" << endl
;
4042 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
4044 if (d_assertions
.size() == 0) {
4049 if (options::bvGaussElim())
4051 TimerStat::CodeTimer
gaussElimTimer(d_smt
.d_stats
->d_gaussElimTime
);
4052 d_preprocessingPassRegistry
.getPass("bv-gauss")->apply(&d_assertions
);
4055 if (d_assertionsProcessed
&& options::incrementalSolving()) {
4056 // TODO(b/1255): Substitutions in incremental mode should be managed with a
4057 // proper data structure.
4059 // Placeholder for storing substitutions
4060 d_assertions
.getSubstitutionsIndex() = d_assertions
.size();
4061 d_assertions
.push_back(NodeManager::currentNM()->mkConst
<bool>(true));
4064 // Add dummy assertion in last position - to be used as a
4065 // placeholder for any new assertions to get added
4066 d_assertions
.push_back(NodeManager::currentNM()->mkConst
<bool>(true));
4067 // any assertions added beyond realAssertionsEnd must NOT affect the
4068 // equisatisfiability
4069 d_realAssertionsEnd
= d_assertions
.size();
4071 // Assertions are NOT guaranteed to be rewritten by this point
4073 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-definition-expansion" << endl
;
4074 dumpAssertions("pre-definition-expansion", d_assertions
);
4076 Chat() << "expanding definitions..." << endl
;
4077 Trace("simplify") << "SmtEnginePrivate::simplify(): expanding definitions" << endl
;
4078 TimerStat::CodeTimer
codeTimer(d_smt
.d_stats
->d_definitionExpansionTime
);
4079 unordered_map
<Node
, Node
, NodeHashFunction
> cache
;
4080 for(unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
4081 d_assertions
.replace(i
, expandDefinitions(d_assertions
[i
], cache
));
4084 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-definition-expansion" << endl
;
4085 dumpAssertions("post-definition-expansion", d_assertions
);
4087 // save the assertions now
4090 for (unsigned i
= 0; i
< d_assertions
.size(); ++i
) {
4091 ProofManager::currentPM()->addAssertion(d_assertions
[i
].toExpr());
4095 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
4097 if (options::globalNegate())
4099 // global negation of the formula
4100 quantifiers::GlobalNegate gn
;
4101 gn
.simplify(d_assertions
.ref());
4102 d_smt
.d_globalNegation
= !d_smt
.d_globalNegation
;
4105 if( options::nlExtPurify() ){
4106 unordered_map
<Node
, Node
, NodeHashFunction
> cache
;
4107 unordered_map
<Node
, Node
, NodeHashFunction
> bcache
;
4108 std::vector
< Node
> var_eq
;
4109 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
4110 Node a
= d_assertions
[i
];
4111 d_assertions
.replace(i
, purifyNlTerms(a
, cache
, bcache
, var_eq
));
4112 Trace("nl-ext-purify")
4113 << "Purify : " << a
<< " -> " << d_assertions
[i
] << std::endl
;
4115 if( !var_eq
.empty() ){
4116 unsigned lastIndex
= d_assertions
.size()-1;
4117 var_eq
.insert( var_eq
.begin(), d_assertions
[lastIndex
] );
4118 d_assertions
.replace(lastIndex
, NodeManager::currentNM()->mkNode( kind::AND
, var_eq
) );
4122 if( options::ceGuidedInst() ){
4123 //register sygus conjecture pre-rewrite (motivated by solution reconstruction)
4124 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
4125 d_smt
.d_theoryEngine
->getQuantifiersEngine()->getCegInstantiation()->preregisterAssertion( d_assertions
[i
] );
4129 if (options::solveRealAsInt()) {
4130 d_preprocessingPassRegistry
.getPass("real-to-int")->apply(&d_assertions
);
4133 if (options::solveIntAsBV() > 0)
4135 d_preprocessingPassRegistry
.getPass("int-to-bv")->apply(&d_assertions
);
4138 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER
&&
4139 !d_smt
.d_logic
.isPure(THEORY_BV
) &&
4140 d_smt
.d_logic
.getLogicString() != "QF_UFBV" &&
4141 d_smt
.d_logic
.getLogicString() != "QF_ABV") {
4142 throw ModalException("Eager bit-blasting does not currently support theory combination. "
4143 "Note that in a QF_BV problem UF symbols can be introduced for division. "
4144 "Try --bv-div-zero-const to interpret division by zero as a constant.");
4147 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER
)
4149 d_preprocessingPassRegistry
.getPass("bv-ackermann")->apply(&d_assertions
);
4152 if (options::bvAbstraction() && !options::incrementalSolving())
4154 d_preprocessingPassRegistry
.getPass("bv-abstraction")->apply(&d_assertions
);
4157 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
4159 bool noConflict
= true;
4161 if (options::extRewPrep())
4163 theory::quantifiers::ExtendedRewriter
extr(options::extRewPrepAgg());
4164 for (unsigned i
= 0; i
< d_assertions
.size(); ++i
)
4166 Node a
= d_assertions
[i
];
4167 d_assertions
.replace(i
, extr
.extendedRewrite(a
));
4171 // Unconstrained simplification
4172 if(options::unconstrainedSimp()) {
4173 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-unconstrained-simp" << endl
;
4174 dumpAssertions("pre-unconstrained-simp", d_assertions
);
4175 d_preprocessingPassRegistry
.getPass("rewrite")->apply(&d_assertions
);
4176 unconstrainedSimp();
4177 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-unconstrained-simp" << endl
;
4178 dumpAssertions("post-unconstrained-simp", d_assertions
);
4181 if(options::bvIntroducePow2())
4183 d_preprocessingPassRegistry
.getPass("bv-intro-pow2")->apply(&d_assertions
);
4186 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-substitution" << endl
;
4187 dumpAssertions("pre-substitution", d_assertions
);
4189 if (options::unsatCores())
4191 // special rewriting pass for unsat cores, since many of the passes below
4193 d_preprocessingPassRegistry
.getPass("rewrite")->apply(&d_assertions
);
4197 d_preprocessingPassRegistry
.getPass("apply-substs")->apply(&d_assertions
);
4199 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-substitution" << endl
;
4200 dumpAssertions("post-substitution", d_assertions
);
4202 // Assertions ARE guaranteed to be rewritten by this point
4203 #ifdef CVC4_ASSERTIONS
4204 for (unsigned i
= 0; i
< d_assertions
.size(); ++i
)
4206 Assert(Rewriter::rewrite(d_assertions
[i
]) == d_assertions
[i
]);
4210 // Lift bit-vectors of size 1 to bool
4211 if(options::bitvectorToBool()) {
4212 dumpAssertions("pre-bv-to-bool", d_assertions
);
4213 Chat() << "...doing bvToBool..." << endl
;
4214 d_preprocessingPassRegistry
.getPass("bv-to-bool")->apply(&d_assertions
);
4215 dumpAssertions("post-bv-to-bool", d_assertions
);
4216 Trace("smt") << "POST bvToBool" << endl
;
4218 // Convert non-top-level Booleans to bit-vectors of size 1
4219 if(options::boolToBitvector()) {
4220 dumpAssertions("pre-bool-to-bv", d_assertions
);
4221 Chat() << "...doing boolToBv..." << endl
;
4222 d_preprocessingPassRegistry
.getPass("bool-to-bv")->apply(&d_assertions
);
4223 dumpAssertions("post-bool-to-bv", d_assertions
);
4224 Trace("smt") << "POST boolToBv" << endl
;
4226 if(options::sepPreSkolemEmp()) {
4227 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
4228 Node prev
= d_assertions
[i
];
4229 Node next
= sep::TheorySepRewriter::preprocess( prev
);
4231 d_assertions
.replace( i
, Rewriter::rewrite( next
) );
4232 Trace("sep-preprocess") << "*** Preprocess sep " << prev
<< endl
;
4233 Trace("sep-preprocess") << " ...got " << d_assertions
[i
] << endl
;
4238 if( d_smt
.d_logic
.isQuantified() ){
4239 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-quant-preprocess" << endl
;
4241 dumpAssertions("pre-skolem-quant", d_assertions
);
4242 //remove rewrite rules, apply pre-skolemization to existential quantifiers
4243 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
4244 Node prev
= d_assertions
[i
];
4245 Node next
= quantifiers::QuantifiersRewriter::preprocess( prev
);
4247 d_assertions
.replace( i
, Rewriter::rewrite( next
) );
4248 Trace("quantifiers-preprocess") << "*** Pre-skolemize " << prev
<< endl
;
4249 Trace("quantifiers-preprocess") << " ...got " << d_assertions
[i
] << endl
;
4252 dumpAssertions("post-skolem-quant", d_assertions
);
4253 if( options::macrosQuant() ){
4254 //quantifiers macro expansion
4255 quantifiers::QuantifierMacros
qm( d_smt
.d_theoryEngine
->getQuantifiersEngine() );
4258 success
= qm
.simplify( d_assertions
.ref(), true );
4260 //finalize the definitions
4261 qm
.finalizeDefinitions();
4264 //fmf-fun : assume admissible functions, applying preprocessing reduction to FMF
4265 if( options::fmfFunWellDefined() ){
4266 quantifiers::FunDefFmf fdf
;
4267 Assert( d_smt
.d_fmfRecFunctionsDefined
!=NULL
);
4268 //must carry over current definitions (for incremental)
4269 for( context::CDList
<Node
>::const_iterator fit
= d_smt
.d_fmfRecFunctionsDefined
->begin();
4270 fit
!= d_smt
.d_fmfRecFunctionsDefined
->end(); ++fit
) {
4272 Assert( d_smt
.d_fmfRecFunctionsAbs
.find( f
)!=d_smt
.d_fmfRecFunctionsAbs
.end() );
4273 TypeNode ft
= d_smt
.d_fmfRecFunctionsAbs
[f
];
4274 fdf
.d_sorts
[f
] = ft
;
4275 std::map
< Node
, std::vector
< Node
> >::iterator fcit
= d_smt
.d_fmfRecFunctionsConcrete
.find( f
);
4276 Assert( fcit
!=d_smt
.d_fmfRecFunctionsConcrete
.end() );
4277 for( unsigned j
=0; j
<fcit
->second
.size(); j
++ ){
4278 fdf
.d_input_arg_inj
[f
].push_back( fcit
->second
[j
] );
4281 fdf
.simplify( d_assertions
.ref() );
4282 //must store new definitions (for incremental)
4283 for( unsigned i
=0; i
<fdf
.d_funcs
.size(); i
++ ){
4284 Node f
= fdf
.d_funcs
[i
];
4285 d_smt
.d_fmfRecFunctionsAbs
[f
] = fdf
.d_sorts
[f
];
4286 d_smt
.d_fmfRecFunctionsConcrete
[f
].clear();
4287 for( unsigned j
=0; j
<fdf
.d_input_arg_inj
[f
].size(); j
++ ){
4288 d_smt
.d_fmfRecFunctionsConcrete
[f
].push_back( fdf
.d_input_arg_inj
[f
][j
] );
4290 d_smt
.d_fmfRecFunctionsDefined
->push_back( f
);
4293 if (options::sygusInference())
4295 // try recast as sygus
4296 quantifiers::SygusInference si
;
4297 if (si
.simplify(d_assertions
.ref()))
4299 Trace("smt-proc") << "...converted to sygus conjecture." << std::endl
;
4302 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-quant-preprocess" << endl
;
4305 if( options::sortInference() || options::ufssFairnessMonotone() ){
4306 //sort inference technique
4307 SortInference
* si
= d_smt
.d_theoryEngine
->getSortInference();
4308 si
->simplify( d_assertions
.ref(), options::sortInference(), options::ufssFairnessMonotone() );
4309 for( std::map
< Node
, Node
>::iterator it
= si
->d_model_replace_f
.begin(); it
!= si
->d_model_replace_f
.end(); ++it
){
4310 d_smt
.setPrintFuncInModel( it
->first
.toExpr(), false );
4311 d_smt
.setPrintFuncInModel( it
->second
.toExpr(), true );
4315 if( options::pbRewrites() ){
4316 d_preprocessingPassRegistry
.getPass("pseudo-boolean-processor")
4317 ->apply(&d_assertions
);
4320 if (options::synthRrPrep())
4322 // do candidate rewrite rule synthesis
4323 d_preprocessingPassRegistry
.getPass("synth-rr")->apply(&d_assertions
);
4326 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-simplify" << endl
;
4327 dumpAssertions("pre-simplify", d_assertions
);
4328 Chat() << "simplifying assertions..." << endl
;
4329 noConflict
= simplifyAssertions();
4331 ++(d_smt
.d_stats
->d_simplifiedToFalse
);
4333 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-simplify" << endl
;
4334 dumpAssertions("post-simplify", d_assertions
);
4336 if (options::symmetryBreakerExp())
4338 // apply symmetry breaking
4339 d_preprocessingPassRegistry
.getPass("sym-break")->apply(&d_assertions
);
4342 if(options::doStaticLearning()) {
4343 d_preprocessingPassRegistry
.getPass("static-learning")
4344 ->apply(&d_assertions
);
4346 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
4348 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-ite-removal" << endl
;
4349 dumpAssertions("pre-ite-removal", d_assertions
);
4351 Chat() << "removing term ITEs..." << endl
;
4352 TimerStat::CodeTimer
codeTimer(d_smt
.d_stats
->d_iteRemovalTime
);
4353 // Remove ITEs, updating d_iteSkolemMap
4354 d_smt
.d_stats
->d_numAssertionsPre
+= d_assertions
.size();
4356 // This is needed because when solving incrementally, removeITEs may introduce
4357 // skolems that were solved for earlier and thus appear in the substitution
4359 d_preprocessingPassRegistry
.getPass("apply-substs")->apply(&d_assertions
);
4360 d_smt
.d_stats
->d_numAssertionsPost
+= d_assertions
.size();
4362 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-ite-removal" << endl
;
4363 dumpAssertions("post-ite-removal", d_assertions
);
4365 dumpAssertions("pre-repeat-simplify", d_assertions
);
4366 if(options::repeatSimp()) {
4367 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-repeat-simplify" << endl
;
4368 Chat() << "re-simplifying assertions..." << endl
;
4369 ScopeCounter
depth(d_simplifyAssertionsDepth
);
4370 noConflict
&= simplifyAssertions();
4372 // Need to fix up assertion list to maintain invariants:
4373 // Let Sk be the set of Skolem variables introduced by ITE's. Let <_sk be the order in which these variables were introduced
4374 // during ite removal.
4375 // For each skolem variable sk, let iteExpr = iteMap(sk) be the ite expr mapped to by sk.
4377 // cache for expression traversal
4378 unordered_map
<Node
, bool, NodeHashFunction
> cache
;
4380 // First, find all skolems that appear in the substitution map - their associated iteExpr will need
4381 // to be moved to the main assertion set
4382 set
<TNode
> skolemSet
;
4383 SubstitutionMap::iterator pos
= top_level_substs
.begin();
4384 for (; pos
!= top_level_substs
.end(); ++pos
)
4386 collectSkolems((*pos
).first
, skolemSet
, cache
);
4387 collectSkolems((*pos
).second
, skolemSet
, cache
);
4390 // We need to ensure:
4391 // 1. iteExpr has the form (ite cond (sk = t) (sk = e))
4392 // 2. if some sk' in Sk appears in cond, t, or e, then sk' <_sk sk
4393 // If either of these is violated, we must add iteExpr as a proper assertion
4394 IteSkolemMap::iterator it
= d_iteSkolemMap
.begin();
4395 IteSkolemMap::iterator iend
= d_iteSkolemMap
.end();
4396 NodeBuilder
<> builder(kind::AND
);
4397 builder
<< d_assertions
[d_realAssertionsEnd
- 1];
4398 vector
<TNode
> toErase
;
4399 for (; it
!= iend
; ++it
) {
4400 if (skolemSet
.find((*it
).first
) == skolemSet
.end()) {
4401 TNode iteExpr
= d_assertions
[(*it
).second
];
4402 if (iteExpr
.getKind() == kind::ITE
&&
4403 iteExpr
[1].getKind() == kind::EQUAL
&&
4404 iteExpr
[1][0] == (*it
).first
&&
4405 iteExpr
[2].getKind() == kind::EQUAL
&&
4406 iteExpr
[2][0] == (*it
).first
) {
4408 bool bad
= checkForBadSkolems(iteExpr
[0], (*it
).first
, cache
);
4409 bad
= bad
|| checkForBadSkolems(iteExpr
[1][1], (*it
).first
, cache
);
4410 bad
= bad
|| checkForBadSkolems(iteExpr
[2][1], (*it
).first
, cache
);
4416 // Move this iteExpr into the main assertions
4417 builder
<< d_assertions
[(*it
).second
];
4418 d_assertions
[(*it
).second
] = NodeManager::currentNM()->mkConst
<bool>(true);
4419 toErase
.push_back((*it
).first
);
4421 if(builder
.getNumChildren() > 1) {
4422 while (!toErase
.empty()) {
4423 d_iteSkolemMap
.erase(toErase
.back());
4426 d_assertions
[d_realAssertionsEnd
- 1] = Rewriter::rewrite(Node(builder
));
4428 // TODO(b/1256): For some reason this is needed for some benchmarks, such as
4429 // QF_AUFBV/dwp_formulas/try5_small_difret_functions_dwp_tac.re_node_set_remove_at.il.dwp.smt2
4431 d_preprocessingPassRegistry
.getPass("apply-substs")->apply(&d_assertions
);
4432 // Assert(iteRewriteAssertionsEnd == d_assertions.size());
4434 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-repeat-simplify" << endl
;
4436 dumpAssertions("post-repeat-simplify", d_assertions
);
4438 dumpAssertions("pre-rewrite-apply-to-const", d_assertions
);
4439 if(options::rewriteApplyToConst()) {
4440 Chat() << "Rewriting applies to constants..." << endl
;
4441 TimerStat::CodeTimer
codeTimer(d_smt
.d_stats
->d_rewriteApplyToConstTime
);
4442 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
4443 d_assertions
[i
] = Rewriter::rewrite(rewriteApplyToConst(d_assertions
[i
]));
4446 dumpAssertions("post-rewrite-apply-to-const", d_assertions
);
4448 // begin: INVARIANT to maintain: no reordering of assertions or
4449 // introducing new ones
4450 #ifdef CVC4_ASSERTIONS
4451 unsigned iteRewriteAssertionsEnd
= d_assertions
.size();
4454 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
4456 Debug("smt") << "SmtEnginePrivate::processAssertions() POST SIMPLIFICATION" << endl
;
4457 Debug("smt") << " d_assertions : " << d_assertions
.size() << endl
;
4459 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : pre-theory-preprocessing" << endl
;
4460 dumpAssertions("pre-theory-preprocessing", d_assertions
);
4462 Chat() << "theory preprocessing..." << endl
;
4463 TimerStat::CodeTimer
codeTimer(d_smt
.d_stats
->d_theoryPreprocessTime
);
4464 // Call the theory preprocessors
4465 d_smt
.d_theoryEngine
->preprocessStart();
4466 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
4467 d_assertions
.replace(i
, d_smt
.d_theoryEngine
->preprocess(d_assertions
[i
]));
4470 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() : post-theory-preprocessing" << endl
;
4471 dumpAssertions("post-theory-preprocessing", d_assertions
);
4473 // If we are using eager bit-blasting wrap assertions in fake atom so that
4474 // everything gets bit-blasted to internal SAT solver
4475 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER
) {
4476 for (unsigned i
= 0; i
< d_assertions
.size(); ++i
) {
4477 TNode atom
= d_assertions
[i
];
4478 Node eager_atom
= NodeManager::currentNM()->mkNode(kind::BITVECTOR_EAGER_ATOM
, atom
);
4479 d_assertions
.replace(i
, eager_atom
);
4480 TheoryModel
* m
= d_smt
.d_theoryEngine
->getModel();
4481 m
->addSubstitution(eager_atom
, atom
);
4485 //notify theory engine new preprocessed assertions
4486 d_smt
.d_theoryEngine
->notifyPreprocessedAssertions( d_assertions
.ref() );
4488 // Push the formula to decision engine
4490 Chat() << "pushing to decision engine..." << endl
;
4491 Assert(iteRewriteAssertionsEnd
== d_assertions
.size());
4492 d_smt
.d_decisionEngine
->addAssertions
4493 (d_assertions
.ref(), d_realAssertionsEnd
, d_iteSkolemMap
);
4496 // end: INVARIANT to maintain: no reordering of assertions or
4497 // introducing new ones
4499 Trace("smt-proc") << "SmtEnginePrivate::processAssertions() end" << endl
;
4500 dumpAssertions("post-everything", d_assertions
);
4502 // Push the formula to SAT
4504 Chat() << "converting to CNF..." << endl
;
4505 TimerStat::CodeTimer
codeTimer(d_smt
.d_stats
->d_cnfConversionTime
);
4506 for (unsigned i
= 0; i
< d_assertions
.size(); ++ i
) {
4507 Chat() << "+ " << d_assertions
[i
] << std::endl
;
4508 d_smt
.d_propEngine
->assertFormula(d_assertions
[i
]);
4512 d_assertionsProcessed
= true;
4514 d_assertions
.clear();
4515 d_iteSkolemMap
.clear();
4518 void SmtEnginePrivate::addFormula(TNode n
, bool inUnsatCore
, bool inInput
)
4525 Trace("smt") << "SmtEnginePrivate::addFormula(" << n
<< "), inUnsatCore = " << inUnsatCore
<< ", inInput = " << inInput
<< endl
;
4527 // Give it to proof manager
4530 // n is an input assertion
4531 if (inUnsatCore
|| options::unsatCores() || options::dumpUnsatCores() || options::checkUnsatCores() || options::fewerPreprocessingHoles()) {
4533 ProofManager::currentPM()->addCoreAssertion(n
.toExpr());
4536 // n is the result of an unknown preprocessing step, add it to dependency map to null
4537 ProofManager::currentPM()->addDependence(n
, Node::null());
4539 // rewrite rules are by default in the unsat core because
4540 // they need to be applied until saturation
4541 if(options::unsatCores() &&
4542 n
.getKind() == kind::REWRITE_RULE
){
4543 ProofManager::currentPM()->addUnsatCore(n
.toExpr());
4547 // Add the normalized formula to the queue
4548 d_assertions
.push_back(n
);
4549 //d_assertions.push_back(Rewriter::rewrite(n));
4552 void SmtEngine::ensureBoolean(const Expr
& e
)
4554 Type type
= e
.getType(options::typeChecking());
4555 Type boolType
= d_exprManager
->booleanType();
4556 if(type
!= boolType
) {
4558 ss
<< "Expected " << boolType
<< "\n"
4559 << "The assertion : " << e
<< "\n"
4560 << "Its type : " << type
;
4561 throw TypeCheckingException(e
, ss
.str());
4565 Result
SmtEngine::checkSat(const Expr
& assumption
, bool inUnsatCore
)
4567 return checkSatisfiability(assumption
, inUnsatCore
, false);
4570 Result
SmtEngine::checkSat(const vector
<Expr
>& assumptions
, bool inUnsatCore
)
4572 return checkSatisfiability(assumptions
, inUnsatCore
, false);
4575 Result
SmtEngine::query(const Expr
& assumption
, bool inUnsatCore
)
4577 Assert(!assumption
.isNull());
4578 return checkSatisfiability(assumption
, inUnsatCore
, true);
4581 Result
SmtEngine::query(const vector
<Expr
>& assumptions
, bool inUnsatCore
)
4583 return checkSatisfiability(assumptions
, inUnsatCore
, true);
4586 Result
SmtEngine::checkSatisfiability(const Expr
& expr
,
4590 return checkSatisfiability(
4591 expr
.isNull() ? vector
<Expr
>() : vector
<Expr
>{expr
},
4596 Result
SmtEngine::checkSatisfiability(const vector
<Expr
>& assumptions
,
4602 SmtScope
smts(this);
4603 finalOptionsAreSet();
4606 Trace("smt") << "SmtEngine::" << (isQuery
? "query" : "checkSat") << "("
4607 << assumptions
<< ")" << endl
;
4609 if(d_queryMade
&& !options::incrementalSolving()) {
4610 throw ModalException("Cannot make multiple queries unless "
4611 "incremental solving is enabled "
4612 "(try --incremental)");
4615 // check to see if a postsolve() is pending
4616 if(d_needPostsolve
) {
4617 d_theoryEngine
->postsolve();
4618 d_needPostsolve
= false;
4620 // Note that a query has been made
4622 // reset global negation
4623 d_globalNegation
= false;
4625 bool didInternalPush
= false;
4627 setProblemExtended(true);
4631 size_t size
= assumptions
.size();
4634 /* Assume: not (BIGAND assumptions) */
4635 d_assumptions
.push_back(
4636 d_exprManager
->mkExpr(kind::AND
, assumptions
).notExpr());
4640 /* Assume: not expr */
4641 d_assumptions
.push_back(assumptions
[0].notExpr());
4646 /* Assume: BIGAND assumptions */
4647 d_assumptions
= assumptions
;
4650 if (!d_assumptions
.empty())
4653 didInternalPush
= true;
4656 Result
r(Result::SAT_UNKNOWN
, Result::UNKNOWN_REASON
);
4657 for (Expr e
: d_assumptions
)
4659 // Substitute out any abstract values in ex.
4660 e
= d_private
->substituteAbstractValues(Node::fromExpr(e
)).toExpr();
4661 Assert(e
.getExprManager() == d_exprManager
);
4662 // Ensure expr is type-checked at this point.
4665 /* Add assumption */
4666 if (d_assertionList
!= NULL
)
4668 d_assertionList
->push_back(e
);
4670 d_private
->addFormula(e
.getNode(), inUnsatCore
);
4673 r
= isQuery
? check().asValidityResult() : check().asSatisfiabilityResult();
4675 if ((options::solveRealAsInt() || options::solveIntAsBV() > 0)
4676 && r
.asSatisfiabilityResult().isSat() == Result::UNSAT
)
4678 r
= Result(Result::SAT_UNKNOWN
, Result::UNKNOWN_REASON
);
4680 // flipped if we did a global negation
4681 if (d_globalNegation
)
4683 Trace("smt") << "SmtEngine::process global negate " << r
<< std::endl
;
4684 if (r
.asSatisfiabilityResult().isSat() == Result::UNSAT
)
4686 r
= Result(Result::SAT
);
4688 else if (r
.asSatisfiabilityResult().isSat() == Result::SAT
)
4690 // only if satisfaction complete
4691 if (d_logic
.isPure(THEORY_ARITH
) || d_logic
.isPure(THEORY_BV
))
4693 r
= Result(Result::UNSAT
);
4697 r
= Result(Result::SAT_UNKNOWN
, Result::UNKNOWN_REASON
);
4700 Trace("smt") << "SmtEngine::global negate returned " << r
<< std::endl
;
4703 d_needPostsolve
= true;
4705 // Dump the query if requested
4706 if (Dump
.isOn("benchmark"))
4708 size_t size
= assumptions
.size();
4709 // the expr already got dumped out if assertion-dumping is on
4710 if (isQuery
&& size
== 1)
4712 Dump("benchmark") << QueryCommand(assumptions
[0]);
4716 Dump("benchmark") << CheckSatCommand();
4720 Dump("benchmark") << CheckSatAssumingCommand(d_assumptions
,
4725 d_propEngine
->resetTrail();
4728 if (didInternalPush
)
4733 // Remember the status
4736 setProblemExtended(false);
4738 Trace("smt") << "SmtEngine::" << (isQuery
? "query" : "checkSat") << "("
4739 << assumptions
<< ") => " << r
<< endl
;
4741 // Check that SAT results generate a model correctly.
4742 if(options::checkModels()) {
4743 // TODO (#1693) check model when unknown result?
4744 if (r
.asSatisfiabilityResult().isSat() == Result::SAT
)
4749 // Check that UNSAT results generate a proof correctly.
4750 if(options::checkProofs()) {
4751 if(r
.asSatisfiabilityResult().isSat() == Result::UNSAT
) {
4752 TimerStat::CodeTimer
checkProofTimer(d_stats
->d_checkProofTime
);
4756 // Check that UNSAT results generate an unsat core correctly.
4757 if(options::checkUnsatCores()) {
4758 if(r
.asSatisfiabilityResult().isSat() == Result::UNSAT
) {
4759 TimerStat::CodeTimer
checkUnsatCoreTimer(d_stats
->d_checkUnsatCoreTime
);
4763 // Check that synthesis solutions satisfy the conjecture
4764 if (options::checkSynthSol()
4765 && r
.asSatisfiabilityResult().isSat() == Result::UNSAT
)
4767 checkSynthSolution();
4771 } catch (UnsafeInterruptException
& e
) {
4772 AlwaysAssert(d_private
->getResourceManager()->out());
4773 Result::UnknownExplanation why
= d_private
->getResourceManager()->outOfResources() ?
4774 Result::RESOURCEOUT
: Result::TIMEOUT
;
4775 return Result(Result::SAT_UNKNOWN
, why
, d_filename
);
4779 vector
<Expr
> SmtEngine::getUnsatAssumptions(void)
4781 Trace("smt") << "SMT getUnsatAssumptions()" << endl
;
4782 SmtScope
smts(this);
4783 if (!options::unsatAssumptions())
4785 throw ModalException(
4786 "Cannot get unsat assumptions when produce-unsat-assumptions option "
4789 if (d_status
.isNull()
4790 || d_status
.asSatisfiabilityResult() != Result::UNSAT
4791 || d_problemExtended
)
4793 throw RecoverableModalException(
4794 "Cannot get unsat assumptions unless immediately preceded by "
4795 "UNSAT/VALID response.");
4797 finalOptionsAreSet();
4798 if (Dump
.isOn("benchmark"))
4800 Dump("benchmark") << GetUnsatCoreCommand();
4802 UnsatCore core
= getUnsatCore();
4804 for (const Expr
& e
: d_assumptions
)
4806 if (find(core
.begin(), core
.end(), e
) != core
.end()) { res
.push_back(e
); }
4811 Result
SmtEngine::checkSynth(const Expr
& e
)
4813 SmtScope
smts(this);
4814 Trace("smt") << "Check synth: " << e
<< std::endl
;
4815 Trace("smt-synth") << "Check synthesis conjecture: " << e
<< std::endl
;
4817 if (options::sygusQePreproc())
4819 // the following does quantifier elimination as a preprocess step
4820 // for "non-ground single invocation synthesis conjectures":
4821 // exists f. forall xy. P[ f(x), x, y ]
4822 // We run quantifier elimination:
4823 // exists y. P[ z, x, y ] ----> Q[ z, x ]
4824 // Where we replace the original conjecture with:
4825 // exists f. forall x. Q[ f(x), x ]
4826 // For more details, see Example 6 of Reynolds et al. SYNT 2017.
4827 Node conj
= Node::fromExpr(e
);
4828 if (conj
.getKind() == kind::FORALL
&& conj
[1].getKind() == kind::EXISTS
)
4830 Node conj_se
= Node::fromExpr(expandDefinitions(conj
[1][1].toExpr()));
4832 Trace("smt-synth") << "Compute single invocation for " << conj_se
<< "..."
4834 quantifiers::SingleInvocationPartition sip
;
4835 std::vector
<Node
> funcs
;
4836 funcs
.insert(funcs
.end(), conj
[0].begin(), conj
[0].end());
4837 sip
.init(funcs
, conj_se
.negate());
4838 Trace("smt-synth") << "...finished, got:" << std::endl
;
4839 sip
.debugPrint("smt-synth");
4841 if (!sip
.isPurelySingleInvocation() && sip
.isNonGroundSingleInvocation())
4843 // create new smt engine to do quantifier elimination
4844 SmtEngine
smt_qe(d_exprManager
);
4845 smt_qe
.setLogic(getLogicInfo());
4846 Trace("smt-synth") << "Property is non-ground single invocation, run "
4847 "QE to obtain single invocation."
4849 NodeManager
* nm
= NodeManager::currentNM();
4850 // partition variables
4851 std::vector
<Node
> all_vars
;
4852 sip
.getAllVariables(all_vars
);
4853 std::vector
<Node
> si_vars
;
4854 sip
.getSingleInvocationVariables(si_vars
);
4855 std::vector
<Node
> qe_vars
;
4856 std::vector
<Node
> nqe_vars
;
4857 for (unsigned i
= 0, size
= all_vars
.size(); i
< size
; i
++)
4859 Node v
= all_vars
[i
];
4860 if (std::find(si_vars
.begin(), si_vars
.end(), v
) == si_vars
.end())
4862 qe_vars
.push_back(v
);
4866 nqe_vars
.push_back(v
);
4869 std::vector
<Node
> orig
;
4870 std::vector
<Node
> subs
;
4871 // skolemize non-qe variables
4872 for (unsigned i
= 0; i
< nqe_vars
.size(); i
++)
4874 Node k
= nm
->mkSkolem("k",
4875 nqe_vars
[i
].getType(),
4876 "qe for non-ground single invocation");
4877 orig
.push_back(nqe_vars
[i
]);
4879 Trace("smt-synth") << " subs : " << nqe_vars
[i
] << " -> " << k
4882 std::vector
<Node
> funcs
;
4883 sip
.getFunctions(funcs
);
4884 for (unsigned i
= 0, size
= funcs
.size(); i
< size
; i
++)
4887 Node fi
= sip
.getFunctionInvocationFor(f
);
4888 Node fv
= sip
.getFirstOrderVariableForFunction(f
);
4889 Assert(!fi
.isNull());
4894 "qe for function in non-ground single invocation");
4896 Trace("smt-synth") << " subs : " << fi
<< " -> " << k
<< std::endl
;
4898 Node conj_se_ngsi
= sip
.getFullSpecification();
4899 Trace("smt-synth") << "Full specification is " << conj_se_ngsi
4901 Node conj_se_ngsi_subs
= conj_se_ngsi
.substitute(
4902 orig
.begin(), orig
.end(), subs
.begin(), subs
.end());
4903 Assert(!qe_vars
.empty());
4905 nm
->mkNode(kind::EXISTS
,
4906 nm
->mkNode(kind::BOUND_VAR_LIST
, qe_vars
),
4907 conj_se_ngsi_subs
.negate());
4909 Trace("smt-synth") << "Run quantifier elimination on "
4910 << conj_se_ngsi_subs
<< std::endl
;
4911 Expr qe_res
= smt_qe
.doQuantifierElimination(
4912 conj_se_ngsi_subs
.toExpr(), true, false);
4913 Trace("smt-synth") << "Result : " << qe_res
<< std::endl
;
4915 // create single invocation conjecture
4916 Node qe_res_n
= Node::fromExpr(qe_res
);
4917 qe_res_n
= qe_res_n
.substitute(
4918 subs
.begin(), subs
.end(), orig
.begin(), orig
.end());
4919 if (!nqe_vars
.empty())
4921 qe_res_n
= nm
->mkNode(kind::EXISTS
,
4922 nm
->mkNode(kind::BOUND_VAR_LIST
, nqe_vars
),
4925 Assert(conj
.getNumChildren() == 3);
4926 qe_res_n
= nm
->mkNode(kind::FORALL
, conj
[0], qe_res_n
, conj
[2]);
4927 Trace("smt-synth") << "Converted conjecture after QE : " << qe_res_n
4929 e_check
= qe_res_n
.toExpr();
4934 return checkSatisfiability( e_check
, true, false );
4937 Result
SmtEngine::assertFormula(const Expr
& ex
, bool inUnsatCore
)
4939 Assert(ex
.getExprManager() == d_exprManager
);
4940 SmtScope
smts(this);
4941 finalOptionsAreSet();
4944 Trace("smt") << "SmtEngine::assertFormula(" << ex
<< ")" << endl
;
4946 if (Dump
.isOn("raw-benchmark")) {
4947 Dump("raw-benchmark") << AssertCommand(ex
);
4950 // Substitute out any abstract values in ex
4951 Expr e
= d_private
->substituteAbstractValues(Node::fromExpr(ex
)).toExpr();
4954 if(d_assertionList
!= NULL
) {
4955 d_assertionList
->push_back(e
);
4957 d_private
->addFormula(e
.getNode(), inUnsatCore
);
4958 return quickCheck().asValidityResult();
4959 }/* SmtEngine::assertFormula() */
4961 Node
SmtEngine::postprocess(TNode node
, TypeNode expectedType
) const {
4965 Expr
SmtEngine::simplify(const Expr
& ex
)
4967 Assert(ex
.getExprManager() == d_exprManager
);
4968 SmtScope
smts(this);
4969 finalOptionsAreSet();
4971 Trace("smt") << "SMT simplify(" << ex
<< ")" << endl
;
4973 if(Dump
.isOn("benchmark")) {
4974 Dump("benchmark") << SimplifyCommand(ex
);
4977 Expr e
= d_private
->substituteAbstractValues(Node::fromExpr(ex
)).toExpr();
4978 if( options::typeChecking() ) {
4979 e
.getType(true); // ensure expr is type-checked at this point
4982 // Make sure all preprocessing is done
4983 d_private
->processAssertions();
4984 Node n
= d_private
->simplify(Node::fromExpr(e
));
4985 n
= postprocess(n
, TypeNode::fromType(e
.getType()));
4989 Expr
SmtEngine::expandDefinitions(const Expr
& ex
)
4991 d_private
->spendResource(options::preprocessStep());
4993 Assert(ex
.getExprManager() == d_exprManager
);
4994 SmtScope
smts(this);
4995 finalOptionsAreSet();
4997 Trace("smt") << "SMT expandDefinitions(" << ex
<< ")" << endl
;
4999 // Substitute out any abstract values in ex.
5000 Expr e
= d_private
->substituteAbstractValues(Node::fromExpr(ex
)).toExpr();
5001 if(options::typeChecking()) {
5002 // Ensure expr is type-checked at this point.
5005 if(Dump
.isOn("benchmark")) {
5006 Dump("benchmark") << ExpandDefinitionsCommand(e
);
5008 unordered_map
<Node
, Node
, NodeHashFunction
> cache
;
5009 Node n
= d_private
->expandDefinitions(Node::fromExpr(e
), cache
, /* expandOnly = */ true);
5010 n
= postprocess(n
, TypeNode::fromType(e
.getType()));
5015 // TODO(#1108): Simplify the error reporting of this method.
5016 Expr
SmtEngine::getValue(const Expr
& ex
) const
5018 Assert(ex
.getExprManager() == d_exprManager
);
5019 SmtScope
smts(this);
5021 Trace("smt") << "SMT getValue(" << ex
<< ")" << endl
;
5022 if(Dump
.isOn("benchmark")) {
5023 Dump("benchmark") << GetValueCommand(ex
);
5026 if(!options::produceModels()) {
5028 "Cannot get value when produce-models options is off.";
5029 throw ModalException(msg
);
5031 if(d_status
.isNull() ||
5032 d_status
.asSatisfiabilityResult() == Result::UNSAT
||
5033 d_problemExtended
) {
5035 "Cannot get value unless immediately preceded by SAT/INVALID or UNKNOWN response.";
5036 throw RecoverableModalException(msg
);
5039 // Substitute out any abstract values in ex.
5040 Expr e
= d_private
->substituteAbstractValues(Node::fromExpr(ex
)).toExpr();
5042 // Ensure expr is type-checked at this point.
5043 e
.getType(options::typeChecking());
5045 // do not need to apply preprocessing substitutions (should be recorded
5046 // in model already)
5048 Node n
= Node::fromExpr(e
);
5049 Trace("smt") << "--- getting value of " << n
<< endl
;
5050 TypeNode expectedType
= n
.getType();
5052 // Expand, then normalize
5053 unordered_map
<Node
, Node
, NodeHashFunction
> cache
;
5054 n
= d_private
->expandDefinitions(n
, cache
);
5055 // There are two ways model values for terms are computed (for historical
5056 // reasons). One way is that used in check-model; the other is that
5057 // used by the Model classes. It's not clear to me exactly how these
5058 // two are different, but they need to be unified. This ugly hack here
5059 // is to fix bug 554 until we can revamp boolean-terms and models [MGD]
5062 if(!n
.getType().isFunction()) {
5063 n
= Rewriter::rewrite(n
);
5066 Trace("smt") << "--- getting value of " << n
<< endl
;
5067 TheoryModel
* m
= d_theoryEngine
->getModel();
5070 resultNode
= m
->getValue(n
);
5072 Trace("smt") << "--- got value " << n
<< " = " << resultNode
<< endl
;
5073 resultNode
= postprocess(resultNode
, expectedType
);
5074 Trace("smt") << "--- model-post returned " << resultNode
<< endl
;
5075 Trace("smt") << "--- model-post returned " << resultNode
.getType() << endl
;
5076 Trace("smt") << "--- model-post expected " << expectedType
<< endl
;
5078 // type-check the result we got
5079 Assert(resultNode
.isNull() || resultNode
.getType().isSubtypeOf(expectedType
),
5080 "Run with -t smt for details.");
5082 // ensure it's a constant
5083 Assert(resultNode
.getKind() == kind::LAMBDA
|| resultNode
.isConst());
5085 if(options::abstractValues() && resultNode
.getType().isArray()) {
5086 resultNode
= d_private
->mkAbstractValue(resultNode
);
5087 Trace("smt") << "--- abstract value >> " << resultNode
<< endl
;
5090 return resultNode
.toExpr();
5093 bool SmtEngine::addToAssignment(const Expr
& ex
) {
5094 SmtScope
smts(this);
5095 finalOptionsAreSet();
5097 // Substitute out any abstract values in ex
5098 Expr e
= d_private
->substituteAbstractValues(Node::fromExpr(ex
)).toExpr();
5099 Type type
= e
.getType(options::typeChecking());
5101 PrettyCheckArgument(
5102 type
.isBoolean(), e
,
5103 "expected Boolean-typed variable or function application "
5104 "in addToAssignment()" );
5105 Node n
= e
.getNode();
5106 // must be an APPLY of a zero-ary defined function, or a variable
5107 PrettyCheckArgument(
5108 ( ( n
.getKind() == kind::APPLY
&&
5109 ( d_definedFunctions
->find(n
.getOperator()) !=
5110 d_definedFunctions
->end() ) &&
5111 n
.getNumChildren() == 0 ) ||
5113 "expected variable or defined-function application "
5114 "in addToAssignment(),\ngot %s", e
.toString().c_str() );
5115 if(!options::produceAssignments()) {
5118 if(d_assignments
== NULL
) {
5119 d_assignments
= new(true) AssignmentSet(d_context
);
5121 d_assignments
->insert(n
);
5126 // TODO(#1108): Simplify the error reporting of this method.
5127 vector
<pair
<Expr
, Expr
>> SmtEngine::getAssignment()
5129 Trace("smt") << "SMT getAssignment()" << endl
;
5130 SmtScope
smts(this);
5131 finalOptionsAreSet();
5132 if(Dump
.isOn("benchmark")) {
5133 Dump("benchmark") << GetAssignmentCommand();
5135 if(!options::produceAssignments()) {
5137 "Cannot get the current assignment when "
5138 "produce-assignments option is off.";
5139 throw ModalException(msg
);
5141 if(d_status
.isNull() ||
5142 d_status
.asSatisfiabilityResult() == Result::UNSAT
||
5143 d_problemExtended
) {
5145 "Cannot get the current assignment unless immediately "
5146 "preceded by SAT/INVALID or UNKNOWN response.";
5147 throw RecoverableModalException(msg
);
5150 vector
<pair
<Expr
,Expr
>> res
;
5151 if (d_assignments
!= nullptr)
5153 TypeNode boolType
= d_nodeManager
->booleanType();
5154 TheoryModel
* m
= d_theoryEngine
->getModel();
5155 for (AssignmentSet::key_iterator i
= d_assignments
->key_begin(),
5156 iend
= d_assignments
->key_end();
5161 Assert(as
.getType() == boolType
);
5163 Trace("smt") << "--- getting value of " << as
<< endl
;
5165 // Expand, then normalize
5166 unordered_map
<Node
, Node
, NodeHashFunction
> cache
;
5167 Node n
= d_private
->expandDefinitions(as
, cache
);
5168 n
= Rewriter::rewrite(n
);
5170 Trace("smt") << "--- getting value of " << n
<< endl
;
5174 resultNode
= m
->getValue(n
);
5177 // type-check the result we got
5178 Assert(resultNode
.isNull() || resultNode
.getType() == boolType
);
5180 // ensure it's a constant
5181 Assert(resultNode
.isConst());
5183 Assert(as
.getKind() == kind::APPLY
|| as
.isVar());
5184 Assert(as
.getKind() != kind::APPLY
|| as
.getNumChildren() == 0);
5185 res
.emplace_back(as
.toExpr(), resultNode
.toExpr());
5191 void SmtEngine::addToModelCommandAndDump(const Command
& c
, uint32_t flags
, bool userVisible
, const char* dumpTag
) {
5192 Trace("smt") << "SMT addToModelCommandAndDump(" << c
<< ")" << endl
;
5193 SmtScope
smts(this);
5194 // If we aren't yet fully inited, the user might still turn on
5195 // produce-models. So let's keep any commands around just in
5196 // case. This is useful in two cases: (1) SMT-LIBv1 auto-declares
5197 // sort "U" in QF_UF before setLogic() is run and we still want to
5198 // support finding card(U) with --finite-model-find, and (2) to
5199 // decouple SmtEngine and ExprManager if the user does a few
5200 // ExprManager::mkSort() before SmtEngine::setOption("produce-models")
5201 // and expects to find their cardinalities in the model.
5202 if(/* userVisible && */
5203 (!d_fullyInited
|| options::produceModels()) &&
5204 (flags
& ExprManager::VAR_FLAG_DEFINED
) == 0) {
5206 if(flags
& ExprManager::VAR_FLAG_GLOBAL
) {
5207 d_modelGlobalCommands
.push_back(c
.clone());
5209 d_modelCommands
->push_back(c
.clone());
5212 if(Dump
.isOn(dumpTag
)) {
5216 d_dumpCommands
.push_back(c
.clone());
5221 // TODO(#1108): Simplify the error reporting of this method.
5222 Model
* SmtEngine::getModel() {
5223 Trace("smt") << "SMT getModel()" << endl
;
5224 SmtScope
smts(this);
5226 finalOptionsAreSet();
5228 if(Dump
.isOn("benchmark")) {
5229 Dump("benchmark") << GetModelCommand();
5232 if (!options::assignFunctionValues())
5235 "Cannot get the model when --assign-function-values is false.";
5236 throw RecoverableModalException(msg
);
5239 if(d_status
.isNull() ||
5240 d_status
.asSatisfiabilityResult() == Result::UNSAT
||
5241 d_problemExtended
) {
5243 "Cannot get the current model unless immediately "
5244 "preceded by SAT/INVALID or UNKNOWN response.";
5245 throw RecoverableModalException(msg
);
5247 if(!options::produceModels()) {
5249 "Cannot get model when produce-models options is off.";
5250 throw ModalException(msg
);
5252 TheoryModel
* m
= d_theoryEngine
->getModel();
5253 m
->d_inputName
= d_filename
;
5257 void SmtEngine::checkUnsatCore() {
5258 Assert(options::unsatCores(), "cannot check unsat core if unsat cores are turned off");
5260 Notice() << "SmtEngine::checkUnsatCore(): generating unsat core" << endl
;
5261 UnsatCore core
= getUnsatCore();
5263 SmtEngine
coreChecker(d_exprManager
);
5264 coreChecker
.setLogic(getLogicInfo());
5267 std::vector
<Command
*>::const_iterator itg
= d_defineCommands
.begin();
5268 for (; itg
!= d_defineCommands
.end(); ++itg
) {
5269 (*itg
)->invoke(&coreChecker
);
5273 Notice() << "SmtEngine::checkUnsatCore(): pushing core assertions (size == " << core
.size() << ")" << endl
;
5274 for(UnsatCore::iterator i
= core
.begin(); i
!= core
.end(); ++i
) {
5275 Notice() << "SmtEngine::checkUnsatCore(): pushing core member " << *i
<< endl
;
5276 coreChecker
.assertFormula(*i
);
5278 const bool checkUnsatCores
= options::checkUnsatCores();
5281 options::checkUnsatCores
.set(false);
5282 options::checkProofs
.set(false);
5283 r
= coreChecker
.checkSat();
5285 options::checkUnsatCores
.set(checkUnsatCores
);
5288 Notice() << "SmtEngine::checkUnsatCore(): result is " << r
<< endl
;
5289 if(r
.asSatisfiabilityResult().isUnknown()) {
5290 InternalError("SmtEngine::checkUnsatCore(): could not check core result unknown.");
5293 if(r
.asSatisfiabilityResult().isSat()) {
5294 InternalError("SmtEngine::checkUnsatCore(): produced core was satisfiable.");
5298 void SmtEngine::checkModel(bool hardFailure
) {
5299 // --check-model implies --produce-assertions, which enables the
5300 // assertion list, so we should be ok.
5301 Assert(d_assertionList
!= NULL
, "don't have an assertion list to check in SmtEngine::checkModel()");
5303 TimerStat::CodeTimer
checkModelTimer(d_stats
->d_checkModelTime
);
5305 // Throughout, we use Notice() to give diagnostic output.
5307 // If this function is running, the user gave --check-model (or equivalent),
5308 // and if Notice() is on, the user gave --verbose (or equivalent).
5310 Notice() << "SmtEngine::checkModel(): generating model" << endl
;
5311 TheoryModel
* m
= d_theoryEngine
->getModel();
5313 // check-model is not guaranteed to succeed if approximate values were used
5314 if (m
->hasApproximations())
5317 << "WARNING: running check-model on a model with approximate values..."
5321 // Check individual theory assertions
5322 d_theoryEngine
->checkTheoryAssertionsWithModel(hardFailure
);
5327 // We have a "fake context" for the substitution map (we don't need it
5328 // to be context-dependent)
5329 context::Context fakeContext
;
5330 SubstitutionMap
substitutions(&fakeContext
, /* substituteUnderQuantifiers = */ false);
5332 for(size_t k
= 0; k
< m
->getNumCommands(); ++k
) {
5333 const DeclareFunctionCommand
* c
= dynamic_cast<const DeclareFunctionCommand
*>(m
->getCommand(k
));
5334 Notice() << "SmtEngine::checkModel(): model command " << k
<< " : " << m
->getCommand(k
) << endl
;
5336 // we don't care about DECLARE-DATATYPES, DECLARE-SORT, ...
5337 Notice() << "SmtEngine::checkModel(): skipping..." << endl
;
5339 // We have a DECLARE-FUN:
5341 // We'll first do some checks, then add to our substitution map
5342 // the mapping: function symbol |-> value
5344 Expr func
= c
->getFunction();
5345 Node val
= m
->getValue(func
);
5347 Notice() << "SmtEngine::checkModel(): adding substitution: " << func
<< " |-> " << val
<< endl
;
5349 // (1) if the value is a lambda, ensure the lambda doesn't contain the
5350 // function symbol (since then the definition is recursive)
5351 if (val
.getKind() == kind::LAMBDA
) {
5352 // first apply the model substitutions we have so far
5353 Debug("boolean-terms") << "applying subses to " << val
[1] << endl
;
5354 Node n
= substitutions
.apply(val
[1]);
5355 Debug("boolean-terms") << "++ got " << n
<< endl
;
5356 // now check if n contains func by doing a substitution
5357 // [func->func2] and checking equality of the Nodes.
5358 // (this just a way to check if func is in n.)
5359 SubstitutionMap
subs(&fakeContext
);
5360 Node func2
= NodeManager::currentNM()->mkSkolem("", TypeNode::fromType(func
.getType()), "", NodeManager::SKOLEM_NO_NOTIFY
);
5361 subs
.addSubstitution(func
, func2
);
5362 if(subs
.apply(n
) != n
) {
5363 Notice() << "SmtEngine::checkModel(): *** PROBLEM: MODEL VALUE DEFINED IN TERMS OF ITSELF ***" << endl
;
5365 ss
<< "SmtEngine::checkModel(): ERRORS SATISFYING ASSERTIONS WITH MODEL:" << endl
5366 << "considering model value for " << func
<< endl
5367 << "body of lambda is: " << val
<< endl
;
5369 ss
<< "body substitutes to: " << n
<< endl
;
5371 ss
<< "so " << func
<< " is defined in terms of itself." << endl
5372 << "Run with `--check-models -v' for additional diagnostics.";
5373 InternalError(ss
.str());
5377 // (2) check that the value is actually a value
5378 else if (!val
.isConst()) {
5379 Notice() << "SmtEngine::checkModel(): *** PROBLEM: MODEL VALUE NOT A CONSTANT ***" << endl
;
5381 ss
<< "SmtEngine::checkModel(): ERRORS SATISFYING ASSERTIONS WITH MODEL:" << endl
5382 << "model value for " << func
<< endl
5383 << " is " << val
<< endl
5384 << "and that is not a constant (.isConst() == false)." << endl
5385 << "Run with `--check-models -v' for additional diagnostics.";
5386 InternalError(ss
.str());
5389 // (3) check that it's the correct (sub)type
5390 // This was intended to be a more general check, but for now we can't do that because
5391 // e.g. "1" is an INT, which isn't a subrange type [1..10] (etc.).
5392 else if(func
.getType().isInteger() && !val
.getType().isInteger()) {
5393 Notice() << "SmtEngine::checkModel(): *** PROBLEM: MODEL VALUE NOT CORRECT TYPE ***" << endl
;
5395 ss
<< "SmtEngine::checkModel(): ERRORS SATISFYING ASSERTIONS WITH MODEL:" << endl
5396 << "model value for " << func
<< endl
5397 << " is " << val
<< endl
5398 << "value type is " << val
.getType() << endl
5399 << "should be of type " << func
.getType() << endl
5400 << "Run with `--check-models -v' for additional diagnostics.";
5401 InternalError(ss
.str());
5404 // (4) checks complete, add the substitution
5405 Debug("boolean-terms") << "cm: adding subs " << func
<< " :=> " << val
<< endl
;
5406 substitutions
.addSubstitution(func
, val
);
5410 // Now go through all our user assertions checking if they're satisfied.
5411 for(AssertionList::const_iterator i
= d_assertionList
->begin(); i
!= d_assertionList
->end(); ++i
) {
5412 Notice() << "SmtEngine::checkModel(): checking assertion " << *i
<< endl
;
5413 Node n
= Node::fromExpr(*i
);
5415 // Apply any define-funs from the problem.
5417 unordered_map
<Node
, Node
, NodeHashFunction
> cache
;
5418 n
= d_private
->expandDefinitions(n
, cache
);
5420 Notice() << "SmtEngine::checkModel(): -- expands to " << n
<< endl
;
5422 // Apply our model value substitutions.
5423 Debug("boolean-terms") << "applying subses to " << n
<< endl
;
5424 n
= substitutions
.apply(n
);
5425 Debug("boolean-terms") << "++ got " << n
<< endl
;
5426 Notice() << "SmtEngine::checkModel(): -- substitutes to " << n
<< endl
;
5428 if( n
.getKind() != kind::REWRITE_RULE
){
5429 // In case it's a quantifier (or contains one), look up its value before
5430 // simplifying, or the quantifier might be irreparably altered.
5432 Notice() << "SmtEngine::checkModel(): -- get value : " << n
<< std::endl
;
5434 // Note this "skip" is done here, rather than above. This is
5435 // because (1) the quantifier could in principle simplify to false,
5436 // which should be reported, and (2) checking for the quantifier
5437 // above, before simplification, doesn't catch buried quantifiers
5438 // anyway (those not at the top-level).
5439 Notice() << "SmtEngine::checkModel(): -- skipping rewrite-rules assertion"
5444 // Simplify the result.
5445 n
= d_private
->simplify(n
);
5446 Notice() << "SmtEngine::checkModel(): -- simplifies to " << n
<< endl
;
5448 // Replace the already-known ITEs (this is important for ground ITEs under quantifiers).
5449 n
= d_private
->d_iteRemover
.replace(n
);
5450 Notice() << "SmtEngine::checkModel(): -- ite replacement gives " << n
<< endl
;
5452 // Apply our model value substitutions (again), as things may have been simplified.
5453 Debug("boolean-terms") << "applying subses to " << n
<< endl
;
5454 n
= substitutions
.apply(n
);
5455 Debug("boolean-terms") << "++ got " << n
<< endl
;
5456 Notice() << "SmtEngine::checkModel(): -- re-substitutes to " << n
<< endl
;
5458 // As a last-ditch effort, ask model to simplify it.
5459 // Presently, this is only an issue for quantifiers, which can have a value
5460 // but don't show up in our substitution map above.
5462 Notice() << "SmtEngine::checkModel(): -- model-substitutes to " << n
<< endl
;
5464 if( d_logic
.isQuantified() ){
5465 // AJR: since quantified formulas are not checkable, we assign them to true/false based on the satisfying assignment.
5466 // however, quantified formulas can be modified during preprocess, so they may not correspond to those in the satisfying assignment.
5467 // hence we use a relaxed version of check model here.
5468 // this is necessary until preprocessing passes explicitly record how they rewrite quantified formulas
5469 if( hardFailure
&& !n
.isConst() && n
.getKind() != kind::LAMBDA
){
5470 Notice() << "SmtEngine::checkModel(): -- relax check model wrt quantified formulas..." << endl
;
5471 AlwaysAssert( quantifiers::QuantifiersRewriter::containsQuantifiers( n
) );
5472 Warning() << "Warning : SmtEngine::checkModel(): cannot check simplified assertion : " << n
<< endl
;
5476 AlwaysAssert(!hardFailure
|| n
.isConst() || n
.getKind() == kind::LAMBDA
);
5478 // The result should be == true.
5479 if(n
!= NodeManager::currentNM()->mkConst(true)) {
5480 Notice() << "SmtEngine::checkModel(): *** PROBLEM: EXPECTED `TRUE' ***"
5483 ss
<< "SmtEngine::checkModel(): "
5484 << "ERRORS SATISFYING ASSERTIONS WITH MODEL:" << endl
5485 << "assertion: " << *i
<< endl
5486 << "simplifies to: " << n
<< endl
5487 << "expected `true'." << endl
5488 << "Run with `--check-models -v' for additional diagnostics.";
5490 InternalError(ss
.str());
5492 Warning() << ss
.str() << endl
;
5496 Notice() << "SmtEngine::checkModel(): all assertions checked out OK !" << endl
;
5499 void SmtEngine::checkSynthSolution()
5501 NodeManager
* nm
= NodeManager::currentNM();
5502 Notice() << "SmtEngine::checkSynthSolution(): checking synthesis solution" << endl
;
5503 map
<Node
, Node
> sol_map
;
5504 /* Get solutions and build auxiliary vectors for substituting */
5505 d_theoryEngine
->getSynthSolutions(sol_map
);
5506 if (sol_map
.empty())
5508 Trace("check-synth-sol") << "No solution to check!\n";
5511 Trace("check-synth-sol") << "Got solution map:\n";
5512 std::vector
<Node
> function_vars
, function_sols
;
5513 for (const auto& pair
: sol_map
)
5515 Trace("check-synth-sol") << pair
.first
<< " --> " << pair
.second
<< "\n";
5516 function_vars
.push_back(pair
.first
);
5517 function_sols
.push_back(pair
.second
);
5519 Trace("check-synth-sol") << "Starting new SMT Engine\n";
5520 /* Start new SMT engine to check solutions */
5521 SmtEngine
solChecker(d_exprManager
);
5522 solChecker
.setLogic(getLogicInfo());
5523 setOption("check-synth-sol", SExpr("false"));
5525 Trace("check-synth-sol") << "Retrieving assertions\n";
5526 // Build conjecture from original assertions
5527 if (d_assertionList
== NULL
)
5529 Trace("check-synth-sol") << "No assertions to check\n";
5532 for (AssertionList::const_iterator i
= d_assertionList
->begin();
5533 i
!= d_assertionList
->end();
5536 Notice() << "SmtEngine::checkSynthSolution(): checking assertion " << *i
<< endl
;
5537 Trace("check-synth-sol") << "Retrieving assertion " << *i
<< "\n";
5538 Node conj
= Node::fromExpr(*i
);
5539 // Apply any define-funs from the problem.
5541 unordered_map
<Node
, Node
, NodeHashFunction
> cache
;
5542 conj
= d_private
->expandDefinitions(conj
, cache
);
5544 Notice() << "SmtEngine::checkSynthSolution(): -- expands to " << conj
<< endl
;
5545 Trace("check-synth-sol") << "Expanded assertion " << conj
<< "\n";
5547 // Apply solution map to conjecture body
5549 /* Whether property is quantifier free */
5550 if (conj
[1].getKind() != kind::EXISTS
)
5552 conjBody
= conj
[1].substitute(function_vars
.begin(),
5553 function_vars
.end(),
5554 function_sols
.begin(),
5555 function_sols
.end());
5559 conjBody
= conj
[1][1].substitute(function_vars
.begin(),
5560 function_vars
.end(),
5561 function_sols
.begin(),
5562 function_sols
.end());
5564 /* Skolemize property */
5565 std::vector
<Node
> vars
, skos
;
5566 for (unsigned j
= 0, size
= conj
[1][0].getNumChildren(); j
< size
; ++j
)
5568 vars
.push_back(conj
[1][0][j
]);
5569 std::stringstream ss
;
5571 skos
.push_back(nm
->mkSkolem(ss
.str(), conj
[1][0][j
].getType()));
5572 Trace("check-synth-sol") << "\tSkolemizing " << conj
[1][0][j
] << " to "
5573 << skos
.back() << "\n";
5575 conjBody
= conjBody
.substitute(
5576 vars
.begin(), vars
.end(), skos
.begin(), skos
.end());
5578 Notice() << "SmtEngine::checkSynthSolution(): -- body substitutes to "
5579 << conjBody
<< endl
;
5580 Trace("check-synth-sol") << "Substituted body of assertion to " << conjBody
5582 solChecker
.assertFormula(conjBody
.toExpr());
5583 Result r
= solChecker
.checkSat();
5584 Notice() << "SmtEngine::checkSynthSolution(): result is " << r
<< endl
;
5585 Trace("check-synth-sol") << "Satsifiability check: " << r
<< "\n";
5586 if (r
.asSatisfiabilityResult().isUnknown())
5589 "SmtEngine::checkSynthSolution(): could not check solution, result "
5592 else if (r
.asSatisfiabilityResult().isSat())
5595 "SmtEngine::checkSynthSolution(): produced solution leads to "
5596 "satisfiable negated conjecture.");
5598 solChecker
.resetAssertions();
5602 // TODO(#1108): Simplify the error reporting of this method.
5603 UnsatCore
SmtEngine::getUnsatCore() {
5604 Trace("smt") << "SMT getUnsatCore()" << endl
;
5605 SmtScope
smts(this);
5606 finalOptionsAreSet();
5607 if(Dump
.isOn("benchmark")) {
5608 Dump("benchmark") << GetUnsatCoreCommand();
5611 if(!options::unsatCores()) {
5612 throw ModalException("Cannot get an unsat core when produce-unsat-cores option is off.");
5614 if(d_status
.isNull() ||
5615 d_status
.asSatisfiabilityResult() != Result::UNSAT
||
5616 d_problemExtended
) {
5617 throw RecoverableModalException(
5618 "Cannot get an unsat core unless immediately preceded by UNSAT/VALID "
5622 d_proofManager
->traceUnsatCore();// just to trigger core creation
5623 return UnsatCore(this, d_proofManager
->extractUnsatCore());
5624 #else /* IS_PROOFS_BUILD */
5625 throw ModalException("This build of CVC4 doesn't have proof support (required for unsat cores).");
5626 #endif /* IS_PROOFS_BUILD */
5629 // TODO(#1108): Simplify the error reporting of this method.
5630 const Proof
& SmtEngine::getProof()
5632 Trace("smt") << "SMT getProof()" << endl
;
5633 SmtScope
smts(this);
5634 finalOptionsAreSet();
5635 if(Dump
.isOn("benchmark")) {
5636 Dump("benchmark") << GetProofCommand();
5639 if(!options::proof()) {
5640 throw ModalException("Cannot get a proof when produce-proofs option is off.");
5642 if(d_status
.isNull() ||
5643 d_status
.asSatisfiabilityResult() != Result::UNSAT
||
5644 d_problemExtended
) {
5645 throw RecoverableModalException(
5646 "Cannot get a proof unless immediately preceded by UNSAT/VALID "
5650 return ProofManager::getProof(this);
5651 #else /* IS_PROOFS_BUILD */
5652 throw ModalException("This build of CVC4 doesn't have proof support.");
5653 #endif /* IS_PROOFS_BUILD */
5656 void SmtEngine::printInstantiations( std::ostream
& out
) {
5657 SmtScope
smts(this);
5658 if( options::instFormatMode()==INST_FORMAT_MODE_SZS
){
5659 out
<< "% SZS output start Proof for " << d_filename
.c_str() << std::endl
;
5661 if( d_theoryEngine
){
5662 d_theoryEngine
->printInstantiations( out
);
5666 if( options::instFormatMode()==INST_FORMAT_MODE_SZS
){
5667 out
<< "% SZS output end Proof for " << d_filename
.c_str() << std::endl
;
5671 void SmtEngine::printSynthSolution( std::ostream
& out
) {
5672 SmtScope
smts(this);
5673 if( d_theoryEngine
){
5674 d_theoryEngine
->printSynthSolution( out
);
5680 void SmtEngine::getSynthSolutions(std::map
<Expr
, Expr
>& sol_map
)
5682 SmtScope
smts(this);
5683 map
<Node
, Node
> sol_mapn
;
5684 Assert(d_theoryEngine
!= nullptr);
5685 d_theoryEngine
->getSynthSolutions(sol_mapn
);
5686 for (std::pair
<const Node
, Node
>& s
: sol_mapn
)
5688 sol_map
[s
.first
.toExpr()] = s
.second
.toExpr();
5692 Expr
SmtEngine::doQuantifierElimination(const Expr
& e
, bool doFull
, bool strict
)
5694 SmtScope
smts(this);
5695 if(!d_logic
.isPure(THEORY_ARITH
) && strict
){
5696 Warning() << "Unexpected logic for quantifier elimination " << d_logic
<< endl
;
5698 Trace("smt-qe") << "Do quantifier elimination " << e
<< std::endl
;
5699 Node n_e
= Node::fromExpr( e
);
5700 if (n_e
.getKind() != kind::EXISTS
&& n_e
.getKind() != kind::FORALL
)
5702 throw ModalException(
5703 "Expecting a quantified formula as argument to get-qe.");
5705 //tag the quantified formula with the quant-elim attribute
5706 TypeNode t
= NodeManager::currentNM()->booleanType();
5707 Node n_attr
= NodeManager::currentNM()->mkSkolem("qe", t
, "Auxiliary variable for qe attr.");
5708 std::vector
< Node
> node_values
;
5709 d_theoryEngine
->setUserAttribute( doFull
? "quant-elim" : "quant-elim-partial", n_attr
, node_values
, "");
5710 n_attr
= NodeManager::currentNM()->mkNode(kind::INST_ATTRIBUTE
, n_attr
);
5711 n_attr
= NodeManager::currentNM()->mkNode(kind::INST_PATTERN_LIST
, n_attr
);
5712 std::vector
< Node
> e_children
;
5713 e_children
.push_back( n_e
[0] );
5714 e_children
.push_back(n_e
.getKind() == kind::EXISTS
? n_e
[1]
5716 e_children
.push_back( n_attr
);
5717 Node nn_e
= NodeManager::currentNM()->mkNode( kind::EXISTS
, e_children
);
5718 Trace("smt-qe-debug") << "Query for quantifier elimination : " << nn_e
<< std::endl
;
5719 Assert( nn_e
.getNumChildren()==3 );
5720 Result r
= checkSatisfiability(nn_e
.toExpr(), true, true);
5721 Trace("smt-qe") << "Query returned " << r
<< std::endl
;
5722 if(r
.asSatisfiabilityResult().isSat() != Result::UNSAT
) {
5723 if( r
.asSatisfiabilityResult().isSat() != Result::SAT
&& doFull
){
5725 ss
<< "While performing quantifier elimination, unexpected result : " << r
<< " for query.";
5726 InternalError(ss
.str().c_str());
5728 std::vector
< Node
> inst_qs
;
5729 d_theoryEngine
->getInstantiatedQuantifiedFormulas( inst_qs
);
5730 Assert( inst_qs
.size()<=1 );
5732 if( inst_qs
.size()==1 ){
5733 Node top_q
= inst_qs
[0];
5734 //Node top_q = Rewriter::rewrite( nn_e ).negate();
5735 Assert( top_q
.getKind()==kind::FORALL
);
5736 Trace("smt-qe") << "Get qe for " << top_q
<< std::endl
;
5737 ret_n
= d_theoryEngine
->getInstantiatedConjunction( top_q
);
5738 Trace("smt-qe") << "Returned : " << ret_n
<< std::endl
;
5739 if (n_e
.getKind() == kind::EXISTS
)
5741 ret_n
= Rewriter::rewrite(ret_n
.negate());
5744 ret_n
= NodeManager::currentNM()->mkConst(n_e
.getKind() != kind::EXISTS
);
5746 return ret_n
.toExpr();
5748 return NodeManager::currentNM()
5749 ->mkConst(n_e
.getKind() == kind::EXISTS
)
5754 void SmtEngine::getInstantiatedQuantifiedFormulas( std::vector
< Expr
>& qs
) {
5755 SmtScope
smts(this);
5756 if( d_theoryEngine
){
5757 std::vector
< Node
> qs_n
;
5758 d_theoryEngine
->getInstantiatedQuantifiedFormulas( qs_n
);
5759 for( unsigned i
=0; i
<qs_n
.size(); i
++ ){
5760 qs
.push_back( qs_n
[i
].toExpr() );
5767 void SmtEngine::getInstantiations( Expr q
, std::vector
< Expr
>& insts
) {
5768 SmtScope
smts(this);
5769 if( d_theoryEngine
){
5770 std::vector
< Node
> insts_n
;
5771 d_theoryEngine
->getInstantiations( Node::fromExpr( q
), insts_n
);
5772 for( unsigned i
=0; i
<insts_n
.size(); i
++ ){
5773 insts
.push_back( insts_n
[i
].toExpr() );
5780 void SmtEngine::getInstantiationTermVectors( Expr q
, std::vector
< std::vector
< Expr
> >& tvecs
) {
5781 SmtScope
smts(this);
5782 Assert(options::trackInstLemmas());
5783 if( d_theoryEngine
){
5784 std::vector
< std::vector
< Node
> > tvecs_n
;
5785 d_theoryEngine
->getInstantiationTermVectors( Node::fromExpr( q
), tvecs_n
);
5786 for( unsigned i
=0; i
<tvecs_n
.size(); i
++ ){
5787 std::vector
< Expr
> tvec
;
5788 for( unsigned j
=0; j
<tvecs_n
[i
].size(); j
++ ){
5789 tvec
.push_back( tvecs_n
[i
][j
].toExpr() );
5791 tvecs
.push_back( tvec
);
5798 vector
<Expr
> SmtEngine::getAssertions() {
5799 SmtScope
smts(this);
5800 finalOptionsAreSet();
5802 if(Dump
.isOn("benchmark")) {
5803 Dump("benchmark") << GetAssertionsCommand();
5805 Trace("smt") << "SMT getAssertions()" << endl
;
5806 if(!options::produceAssertions()) {
5808 "Cannot query the current assertion list when not in produce-assertions mode.";
5809 throw ModalException(msg
);
5811 Assert(d_assertionList
!= NULL
);
5812 // copy the result out
5813 return vector
<Expr
>(d_assertionList
->begin(), d_assertionList
->end());
5816 void SmtEngine::push()
5818 SmtScope
smts(this);
5819 finalOptionsAreSet();
5821 Trace("smt") << "SMT push()" << endl
;
5822 d_private
->notifyPush();
5823 d_private
->processAssertions();
5824 if(Dump
.isOn("benchmark")) {
5825 Dump("benchmark") << PushCommand();
5827 if(!options::incrementalSolving()) {
5828 throw ModalException("Cannot push when not solving incrementally (use --incremental)");
5831 // check to see if a postsolve() is pending
5832 if(d_needPostsolve
) {
5833 d_theoryEngine
->postsolve();
5834 d_needPostsolve
= false;
5837 // The problem isn't really "extended" yet, but this disallows
5838 // get-model after a push, simplifying our lives somewhat and
5839 // staying symmtric with pop.
5840 setProblemExtended(true);
5842 d_userLevels
.push_back(d_userContext
->getLevel());
5844 Trace("userpushpop") << "SmtEngine: pushed to level "
5845 << d_userContext
->getLevel() << endl
;
5848 void SmtEngine::pop() {
5849 SmtScope
smts(this);
5850 finalOptionsAreSet();
5851 Trace("smt") << "SMT pop()" << endl
;
5852 if(Dump
.isOn("benchmark")) {
5853 Dump("benchmark") << PopCommand();
5855 if(!options::incrementalSolving()) {
5856 throw ModalException("Cannot pop when not solving incrementally (use --incremental)");
5858 if(d_userLevels
.size() == 0) {
5859 throw ModalException("Cannot pop beyond the first user frame");
5862 // check to see if a postsolve() is pending
5863 if(d_needPostsolve
) {
5864 d_theoryEngine
->postsolve();
5865 d_needPostsolve
= false;
5868 // The problem isn't really "extended" yet, but this disallows
5869 // get-model after a pop, simplifying our lives somewhat. It might
5870 // not be strictly necessary to do so, since the pops occur lazily,
5871 // but also it would be weird to have a legally-executed (get-model)
5872 // that only returns a subset of the assignment (because the rest
5873 // is no longer in scope!).
5874 setProblemExtended(true);
5876 AlwaysAssert(d_userContext
->getLevel() > 0);
5877 AlwaysAssert(d_userLevels
.back() < d_userContext
->getLevel());
5878 while (d_userLevels
.back() < d_userContext
->getLevel()) {
5881 d_userLevels
.pop_back();
5883 // Clear out assertion queues etc., in case anything is still in there
5884 d_private
->notifyPop();
5886 Trace("userpushpop") << "SmtEngine: popped to level "
5887 << d_userContext
->getLevel() << endl
;
5888 // FIXME: should we reset d_status here?
5889 // SMT-LIBv2 spec seems to imply no, but it would make sense to..
5892 void SmtEngine::internalPush() {
5893 Assert(d_fullyInited
);
5894 Trace("smt") << "SmtEngine::internalPush()" << endl
;
5896 if(options::incrementalSolving()) {
5897 d_private
->processAssertions();
5898 TimerStat::CodeTimer
pushPopTimer(d_stats
->d_pushPopTime
);
5899 d_userContext
->push();
5900 // the d_context push is done inside of the SAT solver
5901 d_propEngine
->push();
5905 void SmtEngine::internalPop(bool immediate
) {
5906 Assert(d_fullyInited
);
5907 Trace("smt") << "SmtEngine::internalPop()" << endl
;
5908 if(options::incrementalSolving()) {
5916 void SmtEngine::doPendingPops() {
5917 Assert(d_pendingPops
== 0 || options::incrementalSolving());
5918 while(d_pendingPops
> 0) {
5919 TimerStat::CodeTimer
pushPopTimer(d_stats
->d_pushPopTime
);
5920 d_propEngine
->pop();
5921 // the d_context pop is done inside of the SAT solver
5922 d_userContext
->pop();
5927 void SmtEngine::reset()
5929 SmtScope
smts(this);
5930 ExprManager
*em
= d_exprManager
;
5931 Trace("smt") << "SMT reset()" << endl
;
5932 if(Dump
.isOn("benchmark")) {
5933 Dump("benchmark") << ResetCommand();
5936 opts
.copyValues(d_originalOptions
);
5938 NodeManager::fromExprManager(em
)->getOptions().copyValues(opts
);
5939 new(this) SmtEngine(em
);
5942 void SmtEngine::resetAssertions()
5944 SmtScope
smts(this);
5947 Trace("smt") << "SMT resetAssertions()" << endl
;
5948 if(Dump
.isOn("benchmark")) {
5949 Dump("benchmark") << ResetAssertionsCommand();
5952 while(!d_userLevels
.empty()) {
5956 // Also remember the global push/pop around everything.
5957 Assert(d_userLevels
.size() == 0 && d_userContext
->getLevel() == 1);
5958 d_context
->popto(0);
5959 d_userContext
->popto(0);
5960 DeleteAndClearCommandVector(d_modelGlobalCommands
);
5961 d_userContext
->push();
5965 void SmtEngine::interrupt()
5967 if(!d_fullyInited
) {
5970 d_propEngine
->interrupt();
5971 d_theoryEngine
->interrupt();
5974 void SmtEngine::setResourceLimit(unsigned long units
, bool cumulative
) {
5975 d_private
->getResourceManager()->setResourceLimit(units
, cumulative
);
5977 void SmtEngine::setTimeLimit(unsigned long milis
, bool cumulative
) {
5978 d_private
->getResourceManager()->setTimeLimit(milis
, cumulative
);
5981 unsigned long SmtEngine::getResourceUsage() const {
5982 return d_private
->getResourceManager()->getResourceUsage();
5985 unsigned long SmtEngine::getTimeUsage() const {
5986 return d_private
->getResourceManager()->getTimeUsage();
5989 unsigned long SmtEngine::getResourceRemaining() const
5991 return d_private
->getResourceManager()->getResourceRemaining();
5994 unsigned long SmtEngine::getTimeRemaining() const
5996 return d_private
->getResourceManager()->getTimeRemaining();
5999 Statistics
SmtEngine::getStatistics() const
6001 return Statistics(*d_statisticsRegistry
);
6004 SExpr
SmtEngine::getStatistic(std::string name
) const
6006 return d_statisticsRegistry
->getStatistic(name
);
6009 void SmtEngine::safeFlushStatistics(int fd
) const {
6010 d_statisticsRegistry
->safeFlushInformation(fd
);
6013 void SmtEngine::setUserAttribute(const std::string
& attr
,
6015 const std::vector
<Expr
>& expr_values
,
6016 const std::string
& str_value
)
6018 SmtScope
smts(this);
6019 std::vector
<Node
> node_values
;
6020 for( unsigned i
=0; i
<expr_values
.size(); i
++ ){
6021 node_values
.push_back( expr_values
[i
].getNode() );
6023 d_theoryEngine
->setUserAttribute(attr
, expr
.getNode(), node_values
, str_value
);
6026 void SmtEngine::setPrintFuncInModel(Expr f
, bool p
) {
6027 Trace("setp-model") << "Set printInModel " << f
<< " to " << p
<< std::endl
;
6028 for( unsigned i
=0; i
<d_modelGlobalCommands
.size(); i
++ ){
6029 Command
* c
= d_modelGlobalCommands
[i
];
6030 DeclareFunctionCommand
* dfc
= dynamic_cast<DeclareFunctionCommand
*>(c
);
6032 if( dfc
->getFunction()==f
){
6033 dfc
->setPrintInModel( p
);
6037 for( unsigned i
=0; i
<d_modelCommands
->size(); i
++ ){
6038 Command
* c
= (*d_modelCommands
)[i
];
6039 DeclareFunctionCommand
* dfc
= dynamic_cast<DeclareFunctionCommand
*>(c
);
6041 if( dfc
->getFunction()==f
){
6042 dfc
->setPrintInModel( p
);
6048 void SmtEngine::beforeSearch()
6051 throw ModalException(
6052 "SmtEngine::beforeSearch called after initialization.");
6057 void SmtEngine::setOption(const std::string
& key
, const CVC4::SExpr
& value
)
6059 NodeManagerScope
nms(d_nodeManager
);
6060 Trace("smt") << "SMT setOption(" << key
<< ", " << value
<< ")" << endl
;
6062 if(Dump
.isOn("benchmark")) {
6063 Dump("benchmark") << SetOptionCommand(key
, value
);
6066 if(key
== "command-verbosity") {
6067 if(!value
.isAtom()) {
6068 const vector
<SExpr
>& cs
= value
.getChildren();
6069 if(cs
.size() == 2 &&
6070 (cs
[0].isKeyword() || cs
[0].isString()) &&
6071 cs
[1].isInteger()) {
6072 string c
= cs
[0].getValue();
6073 const Integer
& v
= cs
[1].getIntegerValue();
6074 if(v
< 0 || v
> 2) {
6075 throw OptionException("command-verbosity must be 0, 1, or 2");
6077 d_commandVerbosity
[c
] = v
;
6081 throw OptionException("command-verbosity value must be a tuple (command-name, integer)");
6084 if(!value
.isAtom()) {
6085 throw OptionException("bad value for :" + key
);
6088 string optionarg
= value
.getValue();
6089 Options
& nodeManagerOptions
= NodeManager::currentNM()->getOptions();
6090 nodeManagerOptions
.setOption(key
, optionarg
);
6093 CVC4::SExpr
SmtEngine::getOption(const std::string
& key
) const
6095 NodeManagerScope
nms(d_nodeManager
);
6097 Trace("smt") << "SMT getOption(" << key
<< ")" << endl
;
6099 if(key
.length() >= 18 &&
6100 key
.compare(0, 18, "command-verbosity:") == 0) {
6101 map
<string
, Integer
>::const_iterator i
= d_commandVerbosity
.find(key
.c_str() + 18);
6102 if(i
!= d_commandVerbosity
.end()) {
6103 return SExpr((*i
).second
);
6105 i
= d_commandVerbosity
.find("*");
6106 if(i
!= d_commandVerbosity
.end()) {
6107 return SExpr((*i
).second
);
6109 return SExpr(Integer(2));
6112 if(Dump
.isOn("benchmark")) {
6113 Dump("benchmark") << GetOptionCommand(key
);
6116 if(key
== "command-verbosity") {
6117 vector
<SExpr
> result
;
6118 SExpr defaultVerbosity
;
6119 for(map
<string
, Integer
>::const_iterator i
= d_commandVerbosity
.begin();
6120 i
!= d_commandVerbosity
.end();
6123 v
.push_back(SExpr((*i
).first
));
6124 v
.push_back(SExpr((*i
).second
));
6125 if((*i
).first
== "*") {
6126 // put the default at the end of the SExpr
6127 defaultVerbosity
= SExpr(v
);
6129 result
.push_back(SExpr(v
));
6132 // put the default at the end of the SExpr
6133 if(!defaultVerbosity
.isAtom()) {
6134 result
.push_back(defaultVerbosity
);
6136 // ensure the default is always listed
6138 v
.push_back(SExpr("*"));
6139 v
.push_back(SExpr(Integer(2)));
6140 result
.push_back(SExpr(v
));
6142 return SExpr(result
);
6145 Options
& nodeManagerOptions
= NodeManager::currentNM()->getOptions();
6146 return SExpr::parseAtom(nodeManagerOptions
.getOption(key
));
6149 void SmtEngine::setReplayStream(ExprStream
* replayStream
) {
6150 AlwaysAssert(!d_fullyInited
,
6151 "Cannot set replay stream once fully initialized");
6152 d_replayStream
= replayStream
;
6155 bool SmtEngine::getExpressionName(Expr e
, std::string
& name
) const {
6156 return d_private
->getExpressionName(e
, name
);
6159 void SmtEngine::setExpressionName(Expr e
, const std::string
& name
) {
6160 Trace("smt-debug") << "Set expression name " << e
<< " to " << name
<< std::endl
;
6161 d_private
->setExpressionName(e
,name
);
6164 }/* CVC4 namespace */