98cc7813dd18745fb8ffc3ca529fe4af33107105
[cvc5.git] / src / smt / smt_engine.cpp
1 /********************* */
2 /*! \file smt_engine.cpp
3 ** \verbatim
4 ** Original author: Morgan Deters
5 ** Major contributors: Clark Barrett
6 ** Minor contributors (to current version): Christopher L. Conway, Tianyi Liang, Martin Brain <>, Kshitij Bansal, Liana Hadarean, Dejan Jovanovic, Tim King, Andrew Reynolds
7 ** This file is part of the CVC4 project.
8 ** Copyright (c) 2009-2014 New York University and The University of Iowa
9 ** See the file COPYING in the top-level source directory for licensing
10 ** information.\endverbatim
11 **
12 ** \brief The main entry point into the CVC4 library's SMT interface
13 **
14 ** The main entry point into the CVC4 library's SMT interface.
15 **/
16
17 #include <vector>
18 #include <string>
19 #include <iterator>
20 #include <utility>
21 #include <sstream>
22 #include <stack>
23 #include <cctype>
24 #include <algorithm>
25 #include <ext/hash_map>
26
27 #include "context/cdlist.h"
28 #include "context/cdhashset.h"
29 #include "context/context.h"
30 #include "decision/decision_engine.h"
31 #include "decision/decision_mode.h"
32 #include "decision/options.h"
33 #include "expr/command.h"
34 #include "expr/expr.h"
35 #include "expr/kind.h"
36 #include "expr/metakind.h"
37 #include "expr/node_builder.h"
38 #include "expr/node.h"
39 #include "expr/node_self_iterator.h"
40 #include "prop/prop_engine.h"
41 #include "proof/theory_proof.h"
42 #include "smt/modal_exception.h"
43 #include "smt/smt_engine.h"
44 #include "smt/smt_engine_scope.h"
45 #include "smt/model_postprocessor.h"
46 #include "smt/logic_request.h"
47 #include "theory/theory_engine.h"
48 #include "theory/bv/theory_bv_rewriter.h"
49 #include "proof/proof_manager.h"
50 #include "main/options.h"
51 #include "util/unsat_core.h"
52 #include "util/proof.h"
53 #include "proof/proof.h"
54 #include "proof/proof_manager.h"
55 #include "util/boolean_simplification.h"
56 #include "util/node_visitor.h"
57 #include "util/configuration.h"
58 #include "util/exception.h"
59 #include "util/nary_builder.h"
60 #include "smt/command_list.h"
61 #include "smt/boolean_terms.h"
62 #include "smt/options.h"
63 #include "options/option_exception.h"
64 #include "util/output.h"
65 #include "util/hash.h"
66 #include "theory/substitutions.h"
67 #include "theory/uf/options.h"
68 #include "theory/arith/options.h"
69 #include "theory/strings/options.h"
70 #include "theory/bv/options.h"
71 #include "theory/theory_traits.h"
72 #include "theory/logic_info.h"
73 #include "theory/options.h"
74 #include "theory/booleans/circuit_propagator.h"
75 #include "theory/booleans/boolean_term_conversion_mode.h"
76 #include "theory/booleans/options.h"
77 #include "util/ite_removal.h"
78 #include "theory/theory_model.h"
79 #include "printer/printer.h"
80 #include "prop/options.h"
81 #include "theory/arrays/options.h"
82 #include "util/sort_inference.h"
83 #include "theory/quantifiers/quant_conflict_find.h"
84 #include "theory/quantifiers/macros.h"
85 #include "theory/quantifiers/first_order_reasoning.h"
86 #include "theory/quantifiers/quantifiers_rewriter.h"
87 #include "theory/quantifiers/options.h"
88 #include "theory/datatypes/options.h"
89 #include "theory/strings/theory_strings_preprocess.h"
90 #include "printer/options.h"
91
92 #include "theory/arith/pseudoboolean_proc.h"
93 #include "theory/bv/bvintropow2.h"
94
95 using namespace std;
96 using namespace CVC4;
97 using namespace CVC4::smt;
98 using namespace CVC4::prop;
99 using namespace CVC4::context;
100 using namespace CVC4::theory;
101
102 namespace CVC4 {
103
104 namespace smt {
105
106 /** Useful for counting the number of recursive calls. */
107 class ScopeCounter {
108 private:
109 unsigned& d_depth;
110 public:
111 ScopeCounter(unsigned& d) : d_depth(d) {
112 ++d_depth;
113 }
114 ~ScopeCounter(){
115 --d_depth;
116 }
117 };
118
119 /**
120 * Representation of a defined function. We keep these around in
121 * SmtEngine to permit expanding definitions late (and lazily), to
122 * support getValue() over defined functions, to support user output
123 * in terms of defined functions, etc.
124 */
125 class DefinedFunction {
126 Node d_func;
127 vector<Node> d_formals;
128 Node d_formula;
129 public:
130 DefinedFunction() {}
131 DefinedFunction(Node func, vector<Node> formals, Node formula) :
132 d_func(func),
133 d_formals(formals),
134 d_formula(formula) {
135 }
136 Node getFunction() const { return d_func; }
137 vector<Node> getFormals() const { return d_formals; }
138 Node getFormula() const { return d_formula; }
139 };/* class DefinedFunction */
140
141 class AssertionPipeline {
142 vector<Node> d_nodes;
143
144 public:
145
146 size_t size() const { return d_nodes.size(); }
147
148 void resize(size_t n) { d_nodes.resize(n); }
149 void clear() { d_nodes.clear(); }
150
151 Node& operator[](size_t i) { return d_nodes[i]; }
152 const Node& operator[](size_t i) const { return d_nodes[i]; }
153 void push_back(Node n) { d_nodes.push_back(n); }
154
155 vector<Node>& ref() { return d_nodes; }
156 const vector<Node>& ref() const { return d_nodes; }
157
158 void replace(size_t i, Node n) {
159 PROOF( ProofManager::currentPM()->addDependence(n, d_nodes[i]); );
160 d_nodes[i] = n;
161 }
162
163 };/* class AssertionPipeline */
164
165 struct SmtEngineStatistics {
166 /** time spent in definition-expansion */
167 TimerStat d_definitionExpansionTime;
168 /** time spent in Boolean term rewriting */
169 TimerStat d_rewriteBooleanTermsTime;
170 /** time spent in non-clausal simplification */
171 TimerStat d_nonclausalSimplificationTime;
172 /** time spent in miplib pass */
173 TimerStat d_miplibPassTime;
174 /** number of assertions removed by miplib pass */
175 IntStat d_numMiplibAssertionsRemoved;
176 /** number of constant propagations found during nonclausal simp */
177 IntStat d_numConstantProps;
178 /** time spent in static learning */
179 TimerStat d_staticLearningTime;
180 /** time spent in simplifying ITEs */
181 TimerStat d_simpITETime;
182 /** time spent in simplifying ITEs */
183 TimerStat d_unconstrainedSimpTime;
184 /** time spent removing ITEs */
185 TimerStat d_iteRemovalTime;
186 /** time spent in theory preprocessing */
187 TimerStat d_theoryPreprocessTime;
188 /** time spent in theory preprocessing */
189 TimerStat d_rewriteApplyToConstTime;
190 /** time spent converting to CNF */
191 TimerStat d_cnfConversionTime;
192 /** Num of assertions before ite removal */
193 IntStat d_numAssertionsPre;
194 /** Num of assertions after ite removal */
195 IntStat d_numAssertionsPost;
196 /** time spent in checkModel() */
197 TimerStat d_checkModelTime;
198 /** time spent in checkProof() */
199 TimerStat d_checkProofTime;
200 /** time spent in PropEngine::checkSat() */
201 TimerStat d_solveTime;
202 /** time spent in pushing/popping */
203 TimerStat d_pushPopTime;
204 /** time spent in processAssertions() */
205 TimerStat d_processAssertionsTime;
206
207 /** Has something simplified to false? */
208 IntStat d_simplifiedToFalse;
209
210 SmtEngineStatistics() :
211 d_definitionExpansionTime("smt::SmtEngine::definitionExpansionTime"),
212 d_rewriteBooleanTermsTime("smt::SmtEngine::rewriteBooleanTermsTime"),
213 d_nonclausalSimplificationTime("smt::SmtEngine::nonclausalSimplificationTime"),
214 d_miplibPassTime("smt::SmtEngine::miplibPassTime"),
215 d_numMiplibAssertionsRemoved("smt::SmtEngine::numMiplibAssertionsRemoved", 0),
216 d_numConstantProps("smt::SmtEngine::numConstantProps", 0),
217 d_staticLearningTime("smt::SmtEngine::staticLearningTime"),
218 d_simpITETime("smt::SmtEngine::simpITETime"),
219 d_unconstrainedSimpTime("smt::SmtEngine::unconstrainedSimpTime"),
220 d_iteRemovalTime("smt::SmtEngine::iteRemovalTime"),
221 d_theoryPreprocessTime("smt::SmtEngine::theoryPreprocessTime"),
222 d_rewriteApplyToConstTime("smt::SmtEngine::rewriteApplyToConstTime"),
223 d_cnfConversionTime("smt::SmtEngine::cnfConversionTime"),
224 d_numAssertionsPre("smt::SmtEngine::numAssertionsPreITERemoval", 0),
225 d_numAssertionsPost("smt::SmtEngine::numAssertionsPostITERemoval", 0),
226 d_checkModelTime("smt::SmtEngine::checkModelTime"),
227 d_checkProofTime("smt::SmtEngine::checkProofTime"),
228 d_solveTime("smt::SmtEngine::solveTime"),
229 d_pushPopTime("smt::SmtEngine::pushPopTime"),
230 d_processAssertionsTime("smt::SmtEngine::processAssertionsTime"),
231 d_simplifiedToFalse("smt::SmtEngine::simplifiedToFalse", 0)
232 {
233
234 StatisticsRegistry::registerStat(&d_definitionExpansionTime);
235 StatisticsRegistry::registerStat(&d_rewriteBooleanTermsTime);
236 StatisticsRegistry::registerStat(&d_nonclausalSimplificationTime);
237 StatisticsRegistry::registerStat(&d_miplibPassTime);
238 StatisticsRegistry::registerStat(&d_numMiplibAssertionsRemoved);
239 StatisticsRegistry::registerStat(&d_numConstantProps);
240 StatisticsRegistry::registerStat(&d_staticLearningTime);
241 StatisticsRegistry::registerStat(&d_simpITETime);
242 StatisticsRegistry::registerStat(&d_unconstrainedSimpTime);
243 StatisticsRegistry::registerStat(&d_iteRemovalTime);
244 StatisticsRegistry::registerStat(&d_theoryPreprocessTime);
245 StatisticsRegistry::registerStat(&d_rewriteApplyToConstTime);
246 StatisticsRegistry::registerStat(&d_cnfConversionTime);
247 StatisticsRegistry::registerStat(&d_numAssertionsPre);
248 StatisticsRegistry::registerStat(&d_numAssertionsPost);
249 StatisticsRegistry::registerStat(&d_checkModelTime);
250 StatisticsRegistry::registerStat(&d_checkProofTime);
251 StatisticsRegistry::registerStat(&d_solveTime);
252 StatisticsRegistry::registerStat(&d_pushPopTime);
253 StatisticsRegistry::registerStat(&d_processAssertionsTime);
254 StatisticsRegistry::registerStat(&d_simplifiedToFalse);
255 }
256
257 ~SmtEngineStatistics() {
258 StatisticsRegistry::unregisterStat(&d_definitionExpansionTime);
259 StatisticsRegistry::unregisterStat(&d_rewriteBooleanTermsTime);
260 StatisticsRegistry::unregisterStat(&d_nonclausalSimplificationTime);
261 StatisticsRegistry::unregisterStat(&d_miplibPassTime);
262 StatisticsRegistry::unregisterStat(&d_numMiplibAssertionsRemoved);
263 StatisticsRegistry::unregisterStat(&d_numConstantProps);
264 StatisticsRegistry::unregisterStat(&d_staticLearningTime);
265 StatisticsRegistry::unregisterStat(&d_simpITETime);
266 StatisticsRegistry::unregisterStat(&d_unconstrainedSimpTime);
267 StatisticsRegistry::unregisterStat(&d_iteRemovalTime);
268 StatisticsRegistry::unregisterStat(&d_theoryPreprocessTime);
269 StatisticsRegistry::unregisterStat(&d_rewriteApplyToConstTime);
270 StatisticsRegistry::unregisterStat(&d_cnfConversionTime);
271 StatisticsRegistry::unregisterStat(&d_numAssertionsPre);
272 StatisticsRegistry::unregisterStat(&d_numAssertionsPost);
273 StatisticsRegistry::unregisterStat(&d_checkModelTime);
274 StatisticsRegistry::unregisterStat(&d_checkProofTime);
275 StatisticsRegistry::unregisterStat(&d_solveTime);
276 StatisticsRegistry::unregisterStat(&d_pushPopTime);
277 StatisticsRegistry::unregisterStat(&d_processAssertionsTime);
278 StatisticsRegistry::unregisterStat(&d_simplifiedToFalse);
279 }
280 };/* struct SmtEngineStatistics */
281
282 /**
283 * This is an inelegant solution, but for the present, it will work.
284 * The point of this is to separate the public and private portions of
285 * the SmtEngine class, so that smt_engine.h doesn't
286 * include "expr/node.h", which is a private CVC4 header (and can lead
287 * to linking errors due to the improper inlining of non-visible symbols
288 * into user code!).
289 *
290 * The "real" solution (that which is usually implemented) is to move
291 * ALL the implementation to SmtEnginePrivate and maintain a
292 * heap-allocated instance of it in SmtEngine. SmtEngine (the public
293 * one) becomes an "interface shell" which simply acts as a forwarder
294 * of method calls.
295 */
296 class SmtEnginePrivate : public NodeManagerListener {
297 SmtEngine& d_smt;
298
299 /** Learned literals */
300 vector<Node> d_nonClausalLearnedLiterals;
301
302 /** Size of assertions array when preprocessing starts */
303 unsigned d_realAssertionsEnd;
304
305 /** The converter for Boolean terms -> BITVECTOR(1). */
306 BooleanTermConverter* d_booleanTermConverter;
307
308 /** A circuit propagator for non-clausal propositional deduction */
309 booleans::CircuitPropagator d_propagator;
310 bool d_propagatorNeedsFinish;
311 std::vector<Node> d_boolVars;
312
313 /** Assertions in the preprocessing pipeline */
314 AssertionPipeline d_assertions;
315
316 /** Whether any assertions have been processed */
317 CDO<bool> d_assertionsProcessed;
318
319 /** Index for where to store substitutions */
320 CDO<unsigned> d_substitutionsIndex;
321
322 // Cached true value
323 Node d_true;
324
325 /**
326 * A context that never pushes/pops, for use by CD structures (like
327 * SubstitutionMaps) that should be "global".
328 */
329 context::Context d_fakeContext;
330
331 /**
332 * A map of AbsractValues to their actual constants. Only used if
333 * options::abstractValues() is on.
334 */
335 SubstitutionMap d_abstractValueMap;
336
337 /**
338 * A mapping of all abstract values (actual value |-> abstract) that
339 * we've handed out. This is necessary to ensure that we give the
340 * same AbstractValues for the same real constants. Only used if
341 * options::abstractValues() is on.
342 */
343 hash_map<Node, Node, NodeHashFunction> d_abstractValues;
344
345 /** Number of calls of simplify assertions active.
346 */
347 unsigned d_simplifyAssertionsDepth;
348
349 public:
350 /**
351 * Map from skolem variables to index in d_assertions containing
352 * corresponding introduced Boolean ite
353 */
354 IteSkolemMap d_iteSkolemMap;
355
356 /** Instance of the ITE remover */
357 RemoveITE d_iteRemover;
358
359 private:
360
361 theory::arith::PseudoBooleanProcessor d_pbsProcessor;
362
363 /** The top level substitutions */
364 SubstitutionMap d_topLevelSubstitutions;
365
366 static const bool d_doConstantProp = true;
367
368 /**
369 * Runs the nonclausal solver and tries to solve all the assigned
370 * theory literals.
371 *
372 * Returns false if the formula simplifies to "false"
373 */
374 bool nonClausalSimplify();
375
376 /**
377 * Performs static learning on the assertions.
378 */
379 void staticLearning();
380
381 /**
382 * Remove ITEs from the assertions.
383 */
384 void removeITEs();
385
386 /**
387 * Helper function to fix up assertion list to restore invariants needed after ite removal
388 */
389 void collectSkolems(TNode n, set<TNode>& skolemSet, hash_map<Node, bool, NodeHashFunction>& cache);
390
391 /**
392 * Helper function to fix up assertion list to restore invariants needed after ite removal
393 */
394 bool checkForBadSkolems(TNode n, TNode skolem, hash_map<Node, bool, NodeHashFunction>& cache);
395
396 // Lift bit-vectors of size 1 to booleans
397 void bvToBool();
398
399 // Abstract common structure over small domains to UF
400 // return true if changes were made.
401 void bvAbstraction();
402
403 // Simplify ITE structure
404 bool simpITE();
405
406 // Simplify based on unconstrained values
407 void unconstrainedSimp();
408
409 // Ensures the assertions asserted after before now
410 // effectively come before d_realAssertionsEnd
411 void compressBeforeRealAssertions(size_t before);
412
413 /**
414 * Any variable in an assertion that is declared as a subtype type
415 * (predicate subtype or integer subrange type) must be constrained
416 * to be in that type.
417 */
418 void constrainSubtypes(TNode n, AssertionPipeline& assertions)
419 throw();
420
421 // trace nodes back to their assertions using CircuitPropagator's BackEdgesMap
422 void traceBackToAssertions(const std::vector<Node>& nodes, std::vector<TNode>& assertions);
423 // remove conjuncts in toRemove from conjunction n; return # of removed conjuncts
424 size_t removeFromConjunction(Node& n, const std::hash_set<unsigned long>& toRemove);
425
426 // scrub miplib encodings
427 void doMiplibTrick();
428
429 /**
430 * Perform non-clausal simplification of a Node. This involves
431 * Theory implementations, but does NOT involve the SAT solver in
432 * any way.
433 *
434 * Returns false if the formula simplifies to "false"
435 */
436 bool simplifyAssertions() throw(TypeCheckingException, LogicException);
437
438 public:
439
440 SmtEnginePrivate(SmtEngine& smt) :
441 d_smt(smt),
442 d_nonClausalLearnedLiterals(),
443 d_realAssertionsEnd(0),
444 d_booleanTermConverter(NULL),
445 d_propagator(d_nonClausalLearnedLiterals, true, true),
446 d_propagatorNeedsFinish(false),
447 d_assertions(),
448 d_assertionsProcessed(smt.d_userContext, false),
449 d_substitutionsIndex(smt.d_userContext, 0),
450 d_fakeContext(),
451 d_abstractValueMap(&d_fakeContext),
452 d_abstractValues(),
453 d_simplifyAssertionsDepth(0),
454 d_iteSkolemMap(),
455 d_iteRemover(smt.d_userContext),
456 d_pbsProcessor(smt.d_userContext),
457 d_topLevelSubstitutions(smt.d_userContext)
458 {
459 d_smt.d_nodeManager->subscribeEvents(this);
460 d_true = NodeManager::currentNM()->mkConst(true);
461 }
462
463 ~SmtEnginePrivate() {
464 if(d_propagatorNeedsFinish) {
465 d_propagator.finish();
466 d_propagatorNeedsFinish = false;
467 }
468 if(d_booleanTermConverter != NULL) {
469 delete d_booleanTermConverter;
470 d_booleanTermConverter = NULL;
471 }
472 d_smt.d_nodeManager->unsubscribeEvents(this);
473 }
474
475 void nmNotifyNewSort(TypeNode tn, uint32_t flags) {
476 DeclareTypeCommand c(tn.getAttribute(expr::VarNameAttr()),
477 0,
478 tn.toType());
479 if((flags & ExprManager::SORT_FLAG_PLACEHOLDER) == 0) {
480 d_smt.addToModelCommandAndDump(c, flags);
481 }
482 }
483
484 void nmNotifyNewSortConstructor(TypeNode tn) {
485 DeclareTypeCommand c(tn.getAttribute(expr::VarNameAttr()),
486 tn.getAttribute(expr::SortArityAttr()),
487 tn.toType());
488 d_smt.addToModelCommandAndDump(c);
489 }
490
491 void nmNotifyNewDatatypes(const std::vector<DatatypeType>& dtts) {
492 DatatypeDeclarationCommand c(dtts);
493 d_smt.addToModelCommandAndDump(c);
494 }
495
496 void nmNotifyNewVar(TNode n, uint32_t flags) {
497 DeclareFunctionCommand c(n.getAttribute(expr::VarNameAttr()),
498 n.toExpr(),
499 n.getType().toType());
500 if((flags & ExprManager::VAR_FLAG_DEFINED) == 0) {
501 d_smt.addToModelCommandAndDump(c, flags);
502 }
503 if(n.getType().isBoolean() && !options::incrementalSolving()) {
504 d_boolVars.push_back(n);
505 }
506 }
507
508 void nmNotifyNewSkolem(TNode n, const std::string& comment, uint32_t flags) {
509 string id = n.getAttribute(expr::VarNameAttr());
510 DeclareFunctionCommand c(id,
511 n.toExpr(),
512 n.getType().toType());
513 if(Dump.isOn("skolems") && comment != "") {
514 Dump("skolems") << CommentCommand(id + " is " + comment);
515 }
516 if((flags & ExprManager::VAR_FLAG_DEFINED) == 0) {
517 d_smt.addToModelCommandAndDump(c, flags, false, "skolems");
518 }
519 if(n.getType().isBoolean() && !options::incrementalSolving()) {
520 d_boolVars.push_back(n);
521 }
522 }
523
524 Node applySubstitutions(TNode node) const {
525 return Rewriter::rewrite(d_topLevelSubstitutions.apply(node));
526 }
527
528 /**
529 * Process the assertions that have been asserted.
530 */
531 void processAssertions();
532
533 /**
534 * Process a user pop. Clears out the non-context-dependent stuff in this
535 * SmtEnginePrivate. Necessary to clear out our assertion vectors in case
536 * someone does a push-assert-pop without a check-sat.
537 */
538 void notifyPop() {
539 d_assertions.clear();
540 d_nonClausalLearnedLiterals.clear();
541 d_realAssertionsEnd = 0;
542 d_iteSkolemMap.clear();
543 }
544
545 /**
546 * Adds a formula to the current context. Action here depends on
547 * the SimplificationMode (in the current Options scope); the
548 * formula might be pushed out to the propositional layer
549 * immediately, or it might be simplified and kept, or it might not
550 * even be simplified.
551 */
552 void addFormula(TNode n)
553 throw(TypeCheckingException, LogicException);
554
555 /**
556 * Expand definitions in n.
557 */
558 Node expandDefinitions(TNode n, hash_map<Node, Node, NodeHashFunction>& cache, bool expandOnly = false)
559 throw(TypeCheckingException, LogicException);
560
561 /**
562 * Rewrite Boolean terms in a Node.
563 */
564 Node rewriteBooleanTerms(TNode n);
565
566 /**
567 * Simplify node "in" by expanding definitions and applying any
568 * substitutions learned from preprocessing.
569 */
570 Node simplify(TNode in) {
571 // Substitute out any abstract values in ex.
572 // Expand definitions.
573 hash_map<Node, Node, NodeHashFunction> cache;
574 Node n = expandDefinitions(in, cache).toExpr();
575 // Make sure we've done all preprocessing, etc.
576 Assert(d_assertions.size() == 0);
577 return applySubstitutions(n).toExpr();
578 }
579
580 /**
581 * Substitute away all AbstractValues in a node.
582 */
583 Node substituteAbstractValues(TNode n) {
584 // We need to do this even if options::abstractValues() is off,
585 // since the setting might have changed after we already gave out
586 // some abstract values.
587 return d_abstractValueMap.apply(n);
588 }
589
590 /**
591 * Make a new (or return an existing) abstract value for a node.
592 * Can only use this if options::abstractValues() is on.
593 */
594 Node mkAbstractValue(TNode n) {
595 Assert(options::abstractValues());
596 Node& val = d_abstractValues[n];
597 if(val.isNull()) {
598 val = d_smt.d_nodeManager->mkAbstractValue(n.getType());
599 d_abstractValueMap.addSubstitution(val, n);
600 }
601 return val;
602 }
603
604 std::hash_map<Node, Node, NodeHashFunction> rewriteApplyToConstCache;
605 Node rewriteApplyToConst(TNode n) {
606 Trace("rewriteApplyToConst") << "rewriteApplyToConst :: " << n << std::endl;
607
608 if(n.getMetaKind() == kind::metakind::CONSTANT || n.getMetaKind() == kind::metakind::VARIABLE) {
609 return n;
610 }
611
612 if(rewriteApplyToConstCache.find(n) != rewriteApplyToConstCache.end()) {
613 Trace("rewriteApplyToConst") << "in cache :: " << rewriteApplyToConstCache[n] << std::endl;
614 return rewriteApplyToConstCache[n];
615 }
616 if(n.getKind() == kind::APPLY_UF) {
617 if(n.getNumChildren() == 1 && n[0].isConst() && n[0].getType().isInteger()) {
618 stringstream ss;
619 ss << n.getOperator() << "_";
620 if(n[0].getConst<Rational>() < 0) {
621 ss << "m" << -n[0].getConst<Rational>();
622 } else {
623 ss << n[0];
624 }
625 Node newvar = NodeManager::currentNM()->mkSkolem(ss.str(), n.getType(), "rewriteApplyToConst skolem", NodeManager::SKOLEM_EXACT_NAME);
626 rewriteApplyToConstCache[n] = newvar;
627 Trace("rewriteApplyToConst") << "made :: " << newvar << std::endl;
628 return newvar;
629 } else {
630 stringstream ss;
631 ss << "The rewrite-apply-to-const preprocessor is currently limited;\n"
632 << "it only works if all function symbols are unary and with Integer\n"
633 << "domain, and all applications are to integer values.\n"
634 << "Found application: " << n;
635 Unhandled(ss.str());
636 }
637 }
638
639 NodeBuilder<> builder(n.getKind());
640 if(n.getMetaKind() == kind::metakind::PARAMETERIZED) {
641 builder << n.getOperator();
642 }
643 for(unsigned i = 0; i < n.getNumChildren(); ++i) {
644 builder << rewriteApplyToConst(n[i]);
645 }
646 Node rewr = builder;
647 rewriteApplyToConstCache[n] = rewr;
648 Trace("rewriteApplyToConst") << "built :: " << rewr << std::endl;
649 return rewr;
650 }
651
652 };/* class SmtEnginePrivate */
653
654 }/* namespace CVC4::smt */
655
656 SmtEngine::SmtEngine(ExprManager* em) throw() :
657 d_context(em->getContext()),
658 d_userLevels(),
659 d_userContext(new UserContext()),
660 d_exprManager(em),
661 d_nodeManager(d_exprManager->getNodeManager()),
662 d_decisionEngine(NULL),
663 d_theoryEngine(NULL),
664 d_propEngine(NULL),
665 d_proofManager(NULL),
666 d_definedFunctions(NULL),
667 d_assertionList(NULL),
668 d_assignments(NULL),
669 d_modelGlobalCommands(),
670 d_modelCommands(NULL),
671 d_dumpCommands(),
672 d_logic(),
673 d_pendingPops(0),
674 d_fullyInited(false),
675 d_problemExtended(false),
676 d_queryMade(false),
677 d_needPostsolve(false),
678 d_earlyTheoryPP(true),
679 d_timeBudgetCumulative(0),
680 d_timeBudgetPerCall(0),
681 d_resourceBudgetCumulative(0),
682 d_resourceBudgetPerCall(0),
683 d_cumulativeTimeUsed(0),
684 d_cumulativeResourceUsed(0),
685 d_status(),
686 d_private(NULL),
687 d_statisticsRegistry(NULL),
688 d_stats(NULL) {
689
690 SmtScope smts(this);
691 d_private = new smt::SmtEnginePrivate(*this);
692 d_statisticsRegistry = new StatisticsRegistry();
693 d_stats = new SmtEngineStatistics();
694
695 PROOF( d_proofManager = new ProofManager(); );
696
697 // We have mutual dependency here, so we add the prop engine to the theory
698 // engine later (it is non-essential there)
699 d_theoryEngine = new TheoryEngine(d_context, d_userContext, d_private->d_iteRemover, const_cast<const LogicInfo&>(d_logic));
700
701 // Add the theories
702 for(TheoryId id = theory::THEORY_FIRST; id < theory::THEORY_LAST; ++id) {
703 TheoryConstructor::addTheory(d_theoryEngine, id);
704 }
705
706 // global push/pop around everything, to ensure proper destruction
707 // of context-dependent data structures
708 d_userContext->push();
709 d_context->push();
710
711 d_definedFunctions = new(true) DefinedFunctionMap(d_userContext);
712 d_modelCommands = new(true) smt::CommandList(d_userContext);
713 }
714
715 void SmtEngine::finishInit() {
716 // ensure that our heuristics are properly set up
717 setDefaults();
718
719 d_decisionEngine = new DecisionEngine(d_context, d_userContext);
720 d_decisionEngine->init(); // enable appropriate strategies
721
722 d_propEngine = new PropEngine(d_theoryEngine, d_decisionEngine, d_context, d_userContext);
723
724 d_theoryEngine->setPropEngine(d_propEngine);
725 d_theoryEngine->setDecisionEngine(d_decisionEngine);
726 d_theoryEngine->finishInit();
727
728 // [MGD 10/20/2011] keep around in incremental mode, due to a
729 // cleanup ordering issue and Nodes/TNodes. If SAT is popped
730 // first, some user-context-dependent TNodes might still exist
731 // with rc == 0.
732 if(options::interactive() ||
733 options::incrementalSolving()) {
734 // In the case of incremental solving, we appear to need these to
735 // ensure the relevant Nodes remain live.
736 d_assertionList = new(true) AssertionList(d_userContext);
737 }
738
739 // dump out a set-logic command
740 if(Dump.isOn("benchmark")) {
741 // Dump("benchmark") << SetBenchmarkLogicCommand(logic.getLogicString());
742 LogicInfo everything;
743 everything.lock();
744 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.")
745 << SetBenchmarkLogicCommand(everything.getLogicString());
746 }
747
748 // dump out any pending declaration commands
749 for(unsigned i = 0; i < d_dumpCommands.size(); ++i) {
750 Dump("declarations") << *d_dumpCommands[i];
751 delete d_dumpCommands[i];
752 }
753 d_dumpCommands.clear();
754
755 if(options::perCallResourceLimit() != 0) {
756 setResourceLimit(options::perCallResourceLimit(), false);
757 }
758 if(options::cumulativeResourceLimit() != 0) {
759 setResourceLimit(options::cumulativeResourceLimit(), true);
760 }
761 if(options::perCallMillisecondLimit() != 0) {
762 setTimeLimit(options::perCallMillisecondLimit(), false);
763 }
764 if(options::cumulativeMillisecondLimit() != 0) {
765 setTimeLimit(options::cumulativeMillisecondLimit(), true);
766 }
767
768 PROOF( ProofManager::currentPM()->setLogic(d_logic.getLogicString()); );
769 }
770
771 void SmtEngine::finalOptionsAreSet() {
772 if(d_fullyInited) {
773 return;
774 }
775
776 if(! d_logic.isLocked()) {
777 setLogicInternal();
778 }
779
780 // finish initialization, create the prop engine, etc.
781 finishInit();
782
783 AlwaysAssert( d_propEngine->getAssertionLevel() == 0,
784 "The PropEngine has pushed but the SmtEngine "
785 "hasn't finished initializing!" );
786
787 d_fullyInited = true;
788 Assert(d_logic.isLocked());
789
790 d_propEngine->assertFormula(NodeManager::currentNM()->mkConst<bool>(true));
791 d_propEngine->assertFormula(NodeManager::currentNM()->mkConst<bool>(false).notNode());
792 }
793
794 void SmtEngine::shutdown() {
795 doPendingPops();
796
797 while(options::incrementalSolving() && d_userContext->getLevel() > 1) {
798 internalPop(true);
799 }
800
801 // check to see if a postsolve() is pending
802 if(d_needPostsolve) {
803 d_theoryEngine->postsolve();
804 d_needPostsolve = false;
805 }
806
807 if(d_propEngine != NULL) {
808 d_propEngine->shutdown();
809 }
810 if(d_theoryEngine != NULL) {
811 d_theoryEngine->shutdown();
812 }
813 if(d_decisionEngine != NULL) {
814 d_decisionEngine->shutdown();
815 }
816 }
817
818 SmtEngine::~SmtEngine() throw() {
819 SmtScope smts(this);
820
821 try {
822 shutdown();
823
824 // global push/pop around everything, to ensure proper destruction
825 // of context-dependent data structures
826 d_context->popto(0);
827 d_userContext->popto(0);
828
829 if(d_assignments != NULL) {
830 d_assignments->deleteSelf();
831 }
832
833 if(d_assertionList != NULL) {
834 d_assertionList->deleteSelf();
835 }
836
837 for(unsigned i = 0; i < d_dumpCommands.size(); ++i) {
838 delete d_dumpCommands[i];
839 }
840 d_dumpCommands.clear();
841
842 if(d_modelCommands != NULL) {
843 d_modelCommands->deleteSelf();
844 }
845
846 d_definedFunctions->deleteSelf();
847
848 delete d_theoryEngine;
849 delete d_propEngine;
850 delete d_decisionEngine;
851
852 delete d_stats;
853 delete d_statisticsRegistry;
854
855 delete d_private;
856
857 delete d_userContext;
858
859 } catch(Exception& e) {
860 Warning() << "CVC4 threw an exception during cleanup." << endl
861 << e << endl;
862 }
863 }
864
865 void SmtEngine::setLogic(const LogicInfo& logic) throw(ModalException) {
866 SmtScope smts(this);
867 if(d_fullyInited) {
868 throw ModalException("Cannot set logic in SmtEngine after the engine has finished initializing");
869 }
870 d_logic = logic;
871 setLogicInternal();
872 }
873
874 void SmtEngine::setLogic(const std::string& s) throw(ModalException, LogicException) {
875 SmtScope smts(this);
876 try {
877 setLogic(LogicInfo(s));
878 } catch(IllegalArgumentException& e) {
879 throw LogicException(e.what());
880 }
881 }
882
883 void SmtEngine::setLogic(const char* logic) throw(ModalException, LogicException) {
884 setLogic(string(logic));
885 }
886
887 LogicInfo SmtEngine::getLogicInfo() const {
888 return d_logic;
889 }
890
891 void SmtEngine::setLogicInternal() throw() {
892 Assert(!d_fullyInited, "setting logic in SmtEngine but the engine has already finished initializing for this run");
893 d_logic.lock();
894 }
895
896 void SmtEngine::setDefaults() {
897 if(options::forceLogic.wasSetByUser()) {
898 d_logic = options::forceLogic();
899 }
900
901 // set strings-exp
902 /* - disabled for 1.4 release [MGD 2014.06.25]
903 if(!d_logic.hasEverything() && d_logic.isTheoryEnabled(THEORY_STRINGS) ) {
904 if(! options::stringExp.wasSetByUser()) {
905 options::stringExp.set( true );
906 Trace("smt") << "turning on strings-exp, for the theory of strings" << std::endl;
907 }
908 }
909 */
910 // for strings
911 if(options::stringExp()) {
912 if( !d_logic.isQuantified() ) {
913 d_logic = d_logic.getUnlockedCopy();
914 d_logic.enableQuantifiers();
915 d_logic.lock();
916 Trace("smt") << "turning on quantifier logic, for strings-exp" << std::endl;
917 }
918 if(! options::finiteModelFind.wasSetByUser()) {
919 options::finiteModelFind.set( true );
920 Trace("smt") << "turning on finite-model-find, for strings-exp" << std::endl;
921 }
922 if(! options::fmfBoundInt.wasSetByUser()) {
923 if(! options::fmfBoundIntLazy.wasSetByUser()) {
924 options::fmfBoundIntLazy.set( true );
925 }
926 options::fmfBoundInt.set( true );
927 Trace("smt") << "turning on fmf-bound-int, for strings-exp" << std::endl;
928 }
929 /*
930 if(! options::rewriteDivk.wasSetByUser()) {
931 options::rewriteDivk.set( true );
932 Trace("smt") << "turning on rewrite-divk, for strings-exp" << std::endl;
933 }*/
934 /*
935 if(! options::stringFMF.wasSetByUser()) {
936 options::stringFMF.set( true );
937 Trace("smt") << "turning on strings-fmf, for strings-exp" << std::endl;
938 }
939 */
940 }
941
942 if(options::checkModels()) {
943 if(! options::interactive()) {
944 Notice() << "SmtEngine: turning on interactive-mode to support check-models" << endl;
945 setOption("interactive-mode", SExpr("true"));
946 }
947 }
948
949 if(options::unsatCores()) {
950 if(options::simplificationMode() != SIMPLIFICATION_MODE_NONE) {
951 if(options::simplificationMode.wasSetByUser()) {
952 throw OptionException("simplification not supported with unsat cores");
953 }
954 Notice() << "SmtEngine: turning off simplification to support unsat-cores" << endl;
955 options::simplificationMode.set(SIMPLIFICATION_MODE_NONE);
956 }
957
958 if(options::unconstrainedSimp()) {
959 if(options::unconstrainedSimp.wasSetByUser()) {
960 throw OptionException("unconstrained simplification not supported with unsat cores");
961 }
962 Notice() << "SmtEngine: turning off unconstrained simplification to support unsat-cores" << endl;
963 options::unconstrainedSimp.set(false);
964 }
965
966 if(options::pbRewrites()) {
967 if(options::pbRewrites.wasSetByUser()) {
968 throw OptionException("pseudoboolean rewrites not supported with unsat cores");
969 }
970 Notice() << "SmtEngine: turning off pseudoboolean rewrites to support unsat-cores" << endl;
971 setOption("pb-rewrites", false);
972 }
973
974 if(options::sortInference()) {
975 if(options::sortInference.wasSetByUser()) {
976 throw OptionException("sort inference not supported with unsat cores");
977 }
978 Notice() << "SmtEngine: turning off sort inference to support unsat-cores" << endl;
979 options::sortInference.set(false);
980 }
981
982 if(options::preSkolemQuant()) {
983 if(options::preSkolemQuant.wasSetByUser()) {
984 throw OptionException("pre-skolemization not supported with unsat cores");
985 }
986 Notice() << "SmtEngine: turning off pre-skolemization to support unsat-cores" << endl;
987 options::preSkolemQuant.set(false);
988 }
989
990 if(options::bitvectorToBool()) {
991 if(options::bitvectorToBool.wasSetByUser()) {
992 throw OptionException("bv-to-bool not supported with unsat cores");
993 }
994 Notice() << "SmtEngine: turning off bitvector-to-bool support unsat-cores" << endl;
995 options::bitvectorToBool.set(false);
996 }
997
998 if(options::bvIntroducePow2()) {
999 if(options::bvIntroducePow2.wasSetByUser()) {
1000 throw OptionException("bv-intro-pow2 not supported with unsat cores");
1001 }
1002 Notice() << "SmtEngine: turning off bv-introduce-pow2 to support unsat-cores" << endl;
1003 setOption("bv-intro-pow2", false);
1004 }
1005 }
1006
1007 if(options::produceAssignments() && !options::produceModels()) {
1008 Notice() << "SmtEngine: turning on produce-models to support produce-assignments" << endl;
1009 setOption("produce-models", SExpr("true"));
1010 }
1011
1012 // Set the options for the theoryOf
1013 if(!options::theoryOfMode.wasSetByUser()) {
1014 if(d_logic.isSharingEnabled() && !d_logic.isTheoryEnabled(THEORY_BV) && !d_logic.isTheoryEnabled(THEORY_STRINGS)) {
1015 Trace("smt") << "setting theoryof-mode to term-based" << endl;
1016 options::theoryOfMode.set(THEORY_OF_TERM_BASED);
1017 }
1018 }
1019
1020 // by default, symmetry breaker is on only for QF_UF
1021 if(! options::ufSymmetryBreaker.wasSetByUser()) {
1022 bool qf_uf = d_logic.isPure(THEORY_UF) && !d_logic.isQuantified();
1023 Trace("smt") << "setting uf symmetry breaker to " << qf_uf << endl;
1024 options::ufSymmetryBreaker.set(qf_uf);
1025 }
1026 // by default, nonclausal simplification is off for QF_SAT
1027 if(! options::simplificationMode.wasSetByUser()) {
1028 bool qf_sat = d_logic.isPure(THEORY_BOOL) && !d_logic.isQuantified();
1029 Trace("smt") << "setting simplification mode to <" << d_logic.getLogicString() << "> " << (!qf_sat) << endl;
1030 //simplification=none works better for SMT LIB benchmarks with quantifiers, not others
1031 //options::simplificationMode.set(qf_sat || quantifiers ? SIMPLIFICATION_MODE_NONE : SIMPLIFICATION_MODE_BATCH);
1032 options::simplificationMode.set(qf_sat ? SIMPLIFICATION_MODE_NONE : SIMPLIFICATION_MODE_BATCH);
1033 }
1034
1035 // If in arrays, set the UF handler to arrays
1036 if(d_logic.isTheoryEnabled(THEORY_ARRAY) && ( !d_logic.isQuantified() ||
1037 (d_logic.isQuantified() && !d_logic.isTheoryEnabled(THEORY_UF)))) {
1038 Theory::setUninterpretedSortOwner(THEORY_ARRAY);
1039 } else {
1040 Theory::setUninterpretedSortOwner(THEORY_UF);
1041 }
1042 // Turn on ite simplification for QF_LIA and QF_AUFBV
1043 if(! options::doITESimp.wasSetByUser()) {
1044 bool qf_aufbv = !d_logic.isQuantified() &&
1045 d_logic.isTheoryEnabled(THEORY_ARRAY) &&
1046 d_logic.isTheoryEnabled(THEORY_UF) &&
1047 d_logic.isTheoryEnabled(THEORY_BV);
1048 bool qf_lia = !d_logic.isQuantified() &&
1049 d_logic.isPure(THEORY_ARITH) &&
1050 d_logic.isLinear() &&
1051 !d_logic.isDifferenceLogic() &&
1052 !d_logic.areRealsUsed();
1053
1054 bool iteSimp = (qf_aufbv || qf_lia);
1055 Trace("smt") << "setting ite simplification to " << iteSimp << endl;
1056 options::doITESimp.set(iteSimp);
1057 }
1058 if(! options::compressItes.wasSetByUser() ){
1059 bool qf_lia = !d_logic.isQuantified() &&
1060 d_logic.isPure(THEORY_ARITH) &&
1061 d_logic.isLinear() &&
1062 !d_logic.isDifferenceLogic() &&
1063 !d_logic.areRealsUsed();
1064
1065 bool compressIte = qf_lia;
1066 Trace("smt") << "setting ite compression to " << compressIte << endl;
1067 options::compressItes.set(compressIte);
1068 }
1069 if(! options::simplifyWithCareEnabled.wasSetByUser() ){
1070 bool qf_aufbv = !d_logic.isQuantified() &&
1071 d_logic.isTheoryEnabled(THEORY_ARRAY) &&
1072 d_logic.isTheoryEnabled(THEORY_UF) &&
1073 d_logic.isTheoryEnabled(THEORY_BV);
1074
1075 bool withCare = qf_aufbv;
1076 Trace("smt") << "setting ite simplify with care to " << withCare << endl;
1077 options::simplifyWithCareEnabled.set(withCare);
1078 }
1079 // Turn off array eager index splitting for QF_AUFLIA
1080 if(! options::arraysEagerIndexSplitting.wasSetByUser()) {
1081 if (not d_logic.isQuantified() &&
1082 d_logic.isTheoryEnabled(THEORY_ARRAY) &&
1083 d_logic.isTheoryEnabled(THEORY_UF) &&
1084 d_logic.isTheoryEnabled(THEORY_ARITH)) {
1085 Trace("smt") << "setting array eager index splitting to false" << endl;
1086 options::arraysEagerIndexSplitting.set(false);
1087 }
1088 }
1089 // Turn on model-based arrays for QF_AX (unless models are enabled)
1090 // if(! options::arraysModelBased.wasSetByUser()) {
1091 // if (not d_logic.isQuantified() &&
1092 // d_logic.isTheoryEnabled(THEORY_ARRAY) &&
1093 // d_logic.isPure(THEORY_ARRAY) &&
1094 // !options::produceModels() &&
1095 // !options::checkModels()) {
1096 // Trace("smt") << "turning on model-based array solver" << endl;
1097 // options::arraysModelBased.set(true);
1098 // }
1099 // }
1100 // Turn on multiple-pass non-clausal simplification for QF_AUFBV
1101 if(! options::repeatSimp.wasSetByUser()) {
1102 bool repeatSimp = !d_logic.isQuantified() &&
1103 (d_logic.isTheoryEnabled(THEORY_ARRAY) && d_logic.isTheoryEnabled(THEORY_UF) && d_logic.isTheoryEnabled(THEORY_BV));
1104 Trace("smt") << "setting repeat simplification to " << repeatSimp << endl;
1105 options::repeatSimp.set(repeatSimp);
1106 }
1107 // Turn on unconstrained simplification for QF_AUFBV
1108 if(! options::unconstrainedSimp.wasSetByUser() || options::incrementalSolving()) {
1109 // bool qf_sat = d_logic.isPure(THEORY_BOOL) && !d_logic.isQuantified();
1110 // bool uncSimp = false && !qf_sat && !options::incrementalSolving();
1111 bool uncSimp = !options::incrementalSolving() && !d_logic.isQuantified() && !options::produceModels() && !options::produceAssignments() && !options::checkModels() &&
1112 (d_logic.isTheoryEnabled(THEORY_ARRAY) && d_logic.isTheoryEnabled(THEORY_BV));
1113 Trace("smt") << "setting unconstrained simplification to " << uncSimp << endl;
1114 options::unconstrainedSimp.set(uncSimp);
1115 }
1116 // Unconstrained simp currently does *not* support model generation
1117 if (options::unconstrainedSimp.wasSetByUser() && options::unconstrainedSimp()) {
1118 if (options::produceModels()) {
1119 if (options::produceModels.wasSetByUser()) {
1120 throw OptionException("Cannot use unconstrained-simp with model generation.");
1121 }
1122 Notice() << "SmtEngine: turning off produce-models to support unconstrainedSimp" << endl;
1123 setOption("produce-models", SExpr("false"));
1124 }
1125 if (options::produceAssignments()) {
1126 if (options::produceAssignments.wasSetByUser()) {
1127 throw OptionException("Cannot use unconstrained-simp with model generation (produce-assignments).");
1128 }
1129 Notice() << "SmtEngine: turning off produce-assignments to support unconstrainedSimp" << endl;
1130 setOption("produce-assignments", SExpr("false"));
1131 }
1132 if (options::checkModels()) {
1133 if (options::checkModels.wasSetByUser()) {
1134 throw OptionException("Cannot use unconstrained-simp with model generation (check-models).");
1135 }
1136 Notice() << "SmtEngine: turning off check-models to support unconstrainedSimp" << endl;
1137 setOption("check-models", SExpr("false"));
1138 }
1139 }
1140
1141
1142 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER &&
1143 options::incrementalSolving()) {
1144 if (options::incrementalSolving.wasSetByUser()) {
1145 throw OptionException(std::string("Eager bit-blasting does not currently support incremental mode. \n\
1146 Try --bitblast=lazy"));
1147 }
1148 Notice() << "SmtEngine: turning off incremental to support eager bit-blasting" << endl;
1149 setOption("incremental", SExpr("false"));
1150 }
1151
1152 if (! options::bvEagerExplanations.wasSetByUser() &&
1153 d_logic.isTheoryEnabled(THEORY_ARRAY) &&
1154 d_logic.isTheoryEnabled(THEORY_BV)) {
1155 Trace("smt") << "enabling eager bit-vector explanations " << endl;
1156 options::bvEagerExplanations.set(true);
1157 }
1158
1159 // Turn on arith rewrite equalities only for pure arithmetic
1160 if(! options::arithRewriteEq.wasSetByUser()) {
1161 bool arithRewriteEq = d_logic.isPure(THEORY_ARITH) && !d_logic.isQuantified();
1162 Trace("smt") << "setting arith rewrite equalities " << arithRewriteEq << endl;
1163 options::arithRewriteEq.set(arithRewriteEq);
1164 }
1165 if(! options::arithHeuristicPivots.wasSetByUser()) {
1166 int16_t heuristicPivots = 5;
1167 if(d_logic.isPure(THEORY_ARITH) && !d_logic.isQuantified()) {
1168 if(d_logic.isDifferenceLogic()) {
1169 heuristicPivots = -1;
1170 } else if(!d_logic.areIntegersUsed()) {
1171 heuristicPivots = 0;
1172 }
1173 }
1174 Trace("smt") << "setting arithHeuristicPivots " << heuristicPivots << endl;
1175 options::arithHeuristicPivots.set(heuristicPivots);
1176 }
1177 if(! options::arithPivotThreshold.wasSetByUser()){
1178 uint16_t pivotThreshold = 2;
1179 if(d_logic.isPure(THEORY_ARITH) && !d_logic.isQuantified()){
1180 if(d_logic.isDifferenceLogic()){
1181 pivotThreshold = 16;
1182 }
1183 }
1184 Trace("smt") << "setting arith arithPivotThreshold " << pivotThreshold << endl;
1185 options::arithPivotThreshold.set(pivotThreshold);
1186 }
1187 if(! options::arithStandardCheckVarOrderPivots.wasSetByUser()){
1188 int16_t varOrderPivots = -1;
1189 if(d_logic.isPure(THEORY_ARITH) && !d_logic.isQuantified()){
1190 varOrderPivots = 200;
1191 }
1192 Trace("smt") << "setting arithStandardCheckVarOrderPivots " << varOrderPivots << endl;
1193 options::arithStandardCheckVarOrderPivots.set(varOrderPivots);
1194 }
1195 // Turn off early theory preprocessing if arithRewriteEq is on
1196 if (options::arithRewriteEq()) {
1197 d_earlyTheoryPP = false;
1198 }
1199
1200 // Set decision mode based on logic (if not set by user)
1201 if(!options::decisionMode.wasSetByUser()) {
1202 decision::DecisionMode decMode =
1203 // ALL_SUPPORTED
1204 d_logic.hasEverything() ? decision::DECISION_STRATEGY_JUSTIFICATION :
1205 ( // QF_BV
1206 (not d_logic.isQuantified() &&
1207 d_logic.isPure(THEORY_BV)
1208 ) ||
1209 // QF_AUFBV or QF_ABV or QF_UFBV
1210 (not d_logic.isQuantified() &&
1211 (d_logic.isTheoryEnabled(THEORY_ARRAY) ||
1212 d_logic.isTheoryEnabled(THEORY_UF)) &&
1213 d_logic.isTheoryEnabled(THEORY_BV)
1214 ) ||
1215 // QF_AUFLIA (and may be ends up enabling QF_AUFLRA?)
1216 (not d_logic.isQuantified() &&
1217 d_logic.isTheoryEnabled(THEORY_ARRAY) &&
1218 d_logic.isTheoryEnabled(THEORY_UF) &&
1219 d_logic.isTheoryEnabled(THEORY_ARITH)
1220 ) ||
1221 // QF_LRA
1222 (not d_logic.isQuantified() &&
1223 d_logic.isPure(THEORY_ARITH) && d_logic.isLinear() && !d_logic.isDifferenceLogic() && !d_logic.areIntegersUsed()
1224 ) ||
1225 // Quantifiers
1226 d_logic.isQuantified() ||
1227 // Strings
1228 d_logic.isTheoryEnabled(THEORY_STRINGS)
1229 ? decision::DECISION_STRATEGY_JUSTIFICATION
1230 : decision::DECISION_STRATEGY_INTERNAL
1231 );
1232
1233 bool stoponly =
1234 // ALL_SUPPORTED
1235 d_logic.hasEverything() || d_logic.isTheoryEnabled(THEORY_STRINGS) ? false :
1236 ( // QF_AUFLIA
1237 (not d_logic.isQuantified() &&
1238 d_logic.isTheoryEnabled(THEORY_ARRAY) &&
1239 d_logic.isTheoryEnabled(THEORY_UF) &&
1240 d_logic.isTheoryEnabled(THEORY_ARITH)
1241 ) ||
1242 // QF_LRA
1243 (not d_logic.isQuantified() &&
1244 d_logic.isPure(THEORY_ARITH) && d_logic.isLinear() && !d_logic.isDifferenceLogic() && !d_logic.areIntegersUsed()
1245 )
1246 ? true : false
1247 );
1248
1249 Trace("smt") << "setting decision mode to " << decMode << endl;
1250 options::decisionMode.set(decMode);
1251 options::decisionStopOnly.set(stoponly);
1252 }
1253
1254 //for finite model finding
1255 if( ! options::instWhenMode.wasSetByUser()){
1256 //instantiate only on last call
1257 if( options::fmfInstEngine() ){
1258 Trace("smt") << "setting inst when mode to LAST_CALL" << endl;
1259 options::instWhenMode.set( quantifiers::INST_WHEN_LAST_CALL );
1260 }
1261 }
1262 if( d_logic.hasCardinalityConstraints() ){
1263 //must have finite model finding on
1264 options::finiteModelFind.set( true );
1265 }
1266 if( options::recurseCbqi() ){
1267 options::cbqi.set( true );
1268 }
1269 if(options::fmfBoundIntLazy.wasSetByUser() && options::fmfBoundIntLazy()) {
1270 options::fmfBoundInt.set( true );
1271 }
1272 if( options::fmfBoundInt() ){
1273 //must have finite model finding on
1274 options::finiteModelFind.set( true );
1275 if( ! options::mbqiMode.wasSetByUser() ||
1276 ( options::mbqiMode()!=quantifiers::MBQI_NONE &&
1277 options::mbqiMode()!=quantifiers::MBQI_FMC &&
1278 options::mbqiMode()!=quantifiers::MBQI_FMC_INTERVAL ) ){
1279 //if bounded integers are set, use no MBQI by default
1280 options::mbqiMode.set( quantifiers::MBQI_NONE );
1281 }
1282 }
1283 if( options::mbqiMode()==quantifiers::MBQI_INTERVAL ){
1284 //must do pre-skolemization
1285 options::preSkolemQuant.set( true );
1286 }
1287 if( options::ufssSymBreak() ){
1288 options::sortInference.set( true );
1289 }
1290 if( options::qcfMode.wasSetByUser() || options::qcfTConstraint() ){
1291 options::quantConflictFind.set( true );
1292 }
1293 //for induction techniques
1294 if( options::quantInduction() ){
1295 if( !options::dtStcInduction.wasSetByUser() ){
1296 options::dtStcInduction.set( true );
1297 }
1298 if( !options::intWfInduction.wasSetByUser() ){
1299 options::intWfInduction.set( true );
1300 }
1301 }
1302 if( options::dtStcInduction() ){
1303 if( !options::dtForceAssignment.wasSetByUser() ){
1304 options::dtForceAssignment.set( true );
1305 }
1306 }
1307 if( options::intWfInduction() ){
1308 if( !options::purifyTriggers.wasSetByUser() ){
1309 options::purifyTriggers.set( true );
1310 }
1311 }
1312
1313 //until bugs 371,431 are fixed
1314 if( ! options::minisatUseElim.wasSetByUser()){
1315 if( d_logic.isQuantified() || options::produceModels() || options::produceAssignments() || options::checkModels() ){
1316 options::minisatUseElim.set( false );
1317 }
1318 }
1319 else if (options::minisatUseElim()) {
1320 if (options::produceModels()) {
1321 Notice() << "SmtEngine: turning off produce-models to support minisatUseElim" << endl;
1322 setOption("produce-models", SExpr("false"));
1323 }
1324 if (options::produceAssignments()) {
1325 Notice() << "SmtEngine: turning off produce-assignments to support minisatUseElim" << endl;
1326 setOption("produce-assignments", SExpr("false"));
1327 }
1328 if (options::checkModels()) {
1329 Notice() << "SmtEngine: turning off check-models to support minisatUseElim" << endl;
1330 setOption("check-models", SExpr("false"));
1331 }
1332 }
1333
1334 // For now, these array theory optimizations do not support model-building
1335 if (options::produceModels() || options::produceAssignments() || options::checkModels()) {
1336 options::arraysOptimizeLinear.set(false);
1337 options::arraysLazyRIntro1.set(false);
1338 }
1339
1340 // Non-linear arithmetic does not support models
1341 if (d_logic.isTheoryEnabled(THEORY_ARITH) &&
1342 !d_logic.isLinear()) {
1343 if (options::produceModels()) {
1344 Warning() << "SmtEngine: turning off produce-models because unsupported for nonlinear arith" << endl;
1345 setOption("produce-models", SExpr("false"));
1346 }
1347 if (options::produceAssignments()) {
1348 Warning() << "SmtEngine: turning off produce-assignments because unsupported for nonlinear arith" << endl;
1349 setOption("produce-assignments", SExpr("false"));
1350 }
1351 if (options::checkModels()) {
1352 Warning() << "SmtEngine: turning off check-models because unsupported for nonlinear arith" << endl;
1353 setOption("check-models", SExpr("false"));
1354 }
1355 }
1356
1357 if (options::incrementalSolving() && options::proof()) {
1358 Warning() << "SmtEngine: turning off incremental solving mode (not yet supported with --proof" << endl;
1359 setOption("incremental", SExpr("false"));
1360 }
1361 }
1362
1363 void SmtEngine::setInfo(const std::string& key, const CVC4::SExpr& value)
1364 throw(OptionException, ModalException) {
1365
1366 SmtScope smts(this);
1367
1368 Trace("smt") << "SMT setInfo(" << key << ", " << value << ")" << endl;
1369 if(Dump.isOn("benchmark")) {
1370 if(key == "status") {
1371 string s = value.getValue();
1372 BenchmarkStatus status =
1373 (s == "sat") ? SMT_SATISFIABLE :
1374 ((s == "unsat") ? SMT_UNSATISFIABLE : SMT_UNKNOWN);
1375 Dump("benchmark") << SetBenchmarkStatusCommand(status);
1376 } else {
1377 Dump("benchmark") << SetInfoCommand(key, value);
1378 }
1379 }
1380
1381 // Check for CVC4-specific info keys (prefixed with "cvc4-" or "cvc4_")
1382 if(key.length() > 5) {
1383 string prefix = key.substr(0, 5);
1384 if(prefix == "cvc4-" || prefix == "cvc4_") {
1385 string cvc4key = key.substr(5);
1386 if(cvc4key == "logic") {
1387 if(! value.isAtom()) {
1388 throw OptionException("argument to (set-info :cvc4-logic ..) must be a string");
1389 }
1390 SmtScope smts(this);
1391 d_logic = value.getValue();
1392 setLogicInternal();
1393 return;
1394 } else {
1395 throw UnrecognizedOptionException();
1396 }
1397 }
1398 }
1399
1400 // Check for standard info keys (SMT-LIB v1, SMT-LIB v2, ...)
1401 if(key == "source" ||
1402 key == "category" ||
1403 key == "difficulty" ||
1404 key == "notes") {
1405 // ignore these
1406 return;
1407 } else if(key == "name") {
1408 d_filename = value.getValue();
1409 return;
1410 } else if(key == "smt-lib-version") {
1411 if( (value.isInteger() && value.getIntegerValue() == Integer(2)) ||
1412 (value.isRational() && value.getRationalValue() == Rational(2)) ||
1413 (value.getValue() == "2") ) {
1414 // supported SMT-LIB version
1415 return;
1416 }
1417 Warning() << "Warning: unsupported smt-lib-version: " << value << endl;
1418 throw UnrecognizedOptionException();
1419 } else if(key == "status") {
1420 string s;
1421 if(value.isAtom()) {
1422 s = value.getValue();
1423 }
1424 if(s != "sat" && s != "unsat" && s != "unknown") {
1425 throw OptionException("argument to (set-info :status ..) must be "
1426 "`sat' or `unsat' or `unknown'");
1427 }
1428 d_status = Result(s, d_filename);
1429 return;
1430 }
1431 throw UnrecognizedOptionException();
1432 }
1433
1434 CVC4::SExpr SmtEngine::getInfo(const std::string& key) const
1435 throw(OptionException, ModalException) {
1436
1437 SmtScope smts(this);
1438
1439 Trace("smt") << "SMT getInfo(" << key << ")" << endl;
1440 if(key == "all-statistics") {
1441 vector<SExpr> stats;
1442 for(StatisticsRegistry::const_iterator i = NodeManager::fromExprManager(d_exprManager)->getStatisticsRegistry()->begin();
1443 i != NodeManager::fromExprManager(d_exprManager)->getStatisticsRegistry()->end();
1444 ++i) {
1445 vector<SExpr> v;
1446 v.push_back((*i).first);
1447 v.push_back((*i).second);
1448 stats.push_back(v);
1449 }
1450 for(StatisticsRegistry::const_iterator i = d_statisticsRegistry->begin();
1451 i != d_statisticsRegistry->end();
1452 ++i) {
1453 vector<SExpr> v;
1454 v.push_back((*i).first);
1455 v.push_back((*i).second);
1456 stats.push_back(v);
1457 }
1458 return stats;
1459 } else if(key == "error-behavior") {
1460 // immediate-exit | continued-execution
1461 if( options::continuedExecution() || options::interactive() ) {
1462 return SExpr::Keyword("continued-execution");
1463 } else {
1464 return SExpr::Keyword("immediate-exit");
1465 }
1466 } else if(key == "name") {
1467 return Configuration::getName();
1468 } else if(key == "version") {
1469 return Configuration::getVersionString();
1470 } else if(key == "authors") {
1471 return Configuration::about();
1472 } else if(key == "status") {
1473 // sat | unsat | unknown
1474 switch(d_status.asSatisfiabilityResult().isSat()) {
1475 case Result::SAT:
1476 return SExpr::Keyword("sat");
1477 case Result::UNSAT:
1478 return SExpr::Keyword("unsat");
1479 default:
1480 return SExpr::Keyword("unknown");
1481 }
1482 } else if(key == "reason-unknown") {
1483 if(!d_status.isNull() && d_status.isUnknown()) {
1484 stringstream ss;
1485 ss << d_status.whyUnknown();
1486 string s = ss.str();
1487 transform(s.begin(), s.end(), s.begin(), ::tolower);
1488 return SExpr::Keyword(s);
1489 } else {
1490 throw ModalException("Can't get-info :reason-unknown when the "
1491 "last result wasn't unknown!");
1492 }
1493 } else if(key == "all-options") {
1494 // get the options, like all-statistics
1495 return Options::current().getOptions();
1496 } else {
1497 throw UnrecognizedOptionException();
1498 }
1499 }
1500
1501 void SmtEngine::defineFunction(Expr func,
1502 const std::vector<Expr>& formals,
1503 Expr formula) {
1504 Trace("smt") << "SMT defineFunction(" << func << ")" << endl;
1505 for(std::vector<Expr>::const_iterator i = formals.begin(); i != formals.end(); ++i) {
1506 if((*i).getKind() != kind::BOUND_VARIABLE) {
1507 stringstream ss;
1508 ss << "All formal arguments to defined functions must be BOUND_VARIABLEs, but in the\n"
1509 << "definition of function " << func << ", formal\n"
1510 << " " << *i << "\n"
1511 << "has kind " << (*i).getKind();
1512 throw TypeCheckingException(func, ss.str());
1513 }
1514 }
1515
1516 stringstream ss;
1517 ss << Expr::setlanguage(Expr::setlanguage::getLanguage(Dump.getStream()))
1518 << func;
1519 DefineFunctionCommand c(ss.str(), func, formals, formula);
1520 addToModelCommandAndDump(c, ExprManager::VAR_FLAG_DEFINED, true, "declarations");
1521
1522 SmtScope smts(this);
1523
1524 // Substitute out any abstract values in formula
1525 Expr form = d_private->substituteAbstractValues(Node::fromExpr(formula)).toExpr();
1526
1527 // type check body
1528 Type formulaType = form.getType(options::typeChecking());
1529
1530 Type funcType = func.getType();
1531 // We distinguish here between definitions of constants and functions,
1532 // because the type checking for them is subtly different. Perhaps we
1533 // should instead have SmtEngine::defineFunction() and
1534 // SmtEngine::defineConstant() for better clarity, although then that
1535 // doesn't match the SMT-LIBv2 standard...
1536 if(formals.size() > 0) {
1537 Type rangeType = FunctionType(funcType).getRangeType();
1538 if(! formulaType.isComparableTo(rangeType)) {
1539 stringstream ss;
1540 ss << "Type of defined function does not match its declaration\n"
1541 << "The function : " << func << "\n"
1542 << "Declared type : " << rangeType << "\n"
1543 << "The body : " << formula << "\n"
1544 << "Body type : " << formulaType;
1545 throw TypeCheckingException(func, ss.str());
1546 }
1547 } else {
1548 if(! formulaType.isComparableTo(funcType)) {
1549 stringstream ss;
1550 ss << "Declared type of defined constant does not match its definition\n"
1551 << "The constant : " << func << "\n"
1552 << "Declared type : " << funcType << " " << Type::getTypeNode(funcType)->getId() << "\n"
1553 << "The definition : " << formula << "\n"
1554 << "Definition type: " << formulaType << " " << Type::getTypeNode(formulaType)->getId();
1555 throw TypeCheckingException(func, ss.str());
1556 }
1557 }
1558 TNode funcNode = func.getTNode();
1559 vector<Node> formalsNodes;
1560 for(vector<Expr>::const_iterator i = formals.begin(),
1561 iend = formals.end();
1562 i != iend;
1563 ++i) {
1564 formalsNodes.push_back((*i).getNode());
1565 }
1566 TNode formNode = form.getTNode();
1567 DefinedFunction def(funcNode, formalsNodes, formNode);
1568 // Permit (check-sat) (define-fun ...) (get-value ...) sequences.
1569 // Otherwise, (check-sat) (get-value ((! foo :named bar))) breaks
1570 // d_haveAdditions = true;
1571 Debug("smt") << "definedFunctions insert " << funcNode << " " << formNode << endl;
1572 d_definedFunctions->insert(funcNode, def);
1573 }
1574
1575 Node SmtEnginePrivate::expandDefinitions(TNode n, hash_map<Node, Node, NodeHashFunction>& cache, bool expandOnly)
1576 throw(TypeCheckingException, LogicException) {
1577
1578 stack< triple<Node, Node, bool> > worklist;
1579 stack<Node> result;
1580 worklist.push(make_triple(Node(n), Node(n), false));
1581 // The worklist is made of triples, each is input / original node then the output / rewritten node
1582 // and finally a flag tracking whether the children have been explored (i.e. if this is a downward
1583 // or upward pass).
1584
1585 do {
1586 n = worklist.top().first; // n is the input / original
1587 Node node = worklist.top().second; // node is the output / result
1588 bool childrenPushed = worklist.top().third;
1589 worklist.pop();
1590
1591 // Working downwards
1592 if(!childrenPushed) {
1593 Kind k = n.getKind();
1594
1595 // Apart from apply, we can short circuit leaves
1596 if(k != kind::APPLY && n.getNumChildren() == 0) {
1597 SmtEngine::DefinedFunctionMap::const_iterator i = d_smt.d_definedFunctions->find(n);
1598 if(i != d_smt.d_definedFunctions->end()) {
1599 // replacement must be closed
1600 if((*i).second.getFormals().size() > 0) {
1601 result.push(d_smt.d_nodeManager->mkNode(kind::LAMBDA, d_smt.d_nodeManager->mkNode(kind::BOUND_VAR_LIST, (*i).second.getFormals()), (*i).second.getFormula()));
1602 continue;
1603 }
1604 // don't bother putting in the cache
1605 result.push((*i).second.getFormula());
1606 continue;
1607 }
1608 // don't bother putting in the cache
1609 result.push(n);
1610 continue;
1611 }
1612
1613 // maybe it's in the cache
1614 hash_map<Node, Node, NodeHashFunction>::iterator cacheHit = cache.find(n);
1615 if(cacheHit != cache.end()) {
1616 TNode ret = (*cacheHit).second;
1617 result.push(ret.isNull() ? n : ret);
1618 continue;
1619 }
1620
1621 // otherwise expand it
1622 if (k == kind::APPLY) {
1623 // application of a user-defined symbol
1624 TNode func = n.getOperator();
1625 SmtEngine::DefinedFunctionMap::const_iterator i =
1626 d_smt.d_definedFunctions->find(func);
1627 DefinedFunction def = (*i).second;
1628 vector<Node> formals = def.getFormals();
1629
1630 if(Debug.isOn("expand")) {
1631 Debug("expand") << "found: " << n << endl;
1632 Debug("expand") << " func: " << func << endl;
1633 string name = func.getAttribute(expr::VarNameAttr());
1634 Debug("expand") << " : \"" << name << "\"" << endl;
1635 }
1636 if(i == d_smt.d_definedFunctions->end()) {
1637 throw TypeCheckingException(n.toExpr(), string("Undefined function: `") + func.toString() + "'");
1638 }
1639 if(Debug.isOn("expand")) {
1640 Debug("expand") << " defn: " << def.getFunction() << endl
1641 << " [";
1642 if(formals.size() > 0) {
1643 copy( formals.begin(), formals.end() - 1,
1644 ostream_iterator<Node>(Debug("expand"), ", ") );
1645 Debug("expand") << formals.back();
1646 }
1647 Debug("expand") << "]" << endl
1648 << " " << def.getFunction().getType() << endl
1649 << " " << def.getFormula() << endl;
1650 }
1651
1652 TNode fm = def.getFormula();
1653 Node instance = fm.substitute(formals.begin(), formals.end(),
1654 n.begin(), n.end());
1655 Debug("expand") << "made : " << instance << endl;
1656
1657 Node expanded = expandDefinitions(instance, cache, expandOnly);
1658 cache[n] = (n == expanded ? Node::null() : expanded);
1659 result.push(expanded);
1660 continue;
1661
1662 } else if(! expandOnly) {
1663 // do not do any theory stuff if expandOnly is true
1664
1665 theory::Theory* t = d_smt.d_theoryEngine->theoryOf(node);
1666
1667 Assert(t != NULL);
1668 LogicRequest req(d_smt);
1669 node = t->expandDefinition(req, n);
1670 }
1671
1672 // there should be children here, otherwise we short-circuited a result-push/continue, above
1673 if (node.getNumChildren() == 0) {
1674 Debug("expand") << "Unexpectedly no children..." << node << endl;
1675 }
1676 // This invariant holds at the moment but it is concievable that a new theory
1677 // might introduce a kind which can have children before definition expansion but doesn't
1678 // afterwards. If this happens, remove this assertion.
1679 Assert(node.getNumChildren() > 0);
1680
1681 // the partial functions can fall through, in which case we still
1682 // consider their children
1683 worklist.push(make_triple(Node(n), node, true)); // Original and rewritten result
1684
1685 for(size_t i = 0; i < node.getNumChildren(); ++i) {
1686 worklist.push(make_triple(node[i], node[i], false)); // Rewrite the children of the result only
1687 }
1688
1689 } else {
1690 // Working upwards
1691 // Reconstruct the node from it's (now rewritten) children on the stack
1692
1693 Debug("expand") << "cons : " << node << endl;
1694 //cout << "cons : " << node << endl;
1695 NodeBuilder<> nb(node.getKind());
1696 if(node.getMetaKind() == kind::metakind::PARAMETERIZED) {
1697 Debug("expand") << "op : " << node.getOperator() << endl;
1698 //cout << "op : " << node.getOperator() << endl;
1699 nb << node.getOperator();
1700 }
1701 for(size_t i = 0; i < node.getNumChildren(); ++i) {
1702 Assert(!result.empty());
1703 Node expanded = result.top();
1704 result.pop();
1705 //cout << "exchld : " << expanded << endl;
1706 Debug("expand") << "exchld : " << expanded << endl;
1707 nb << expanded;
1708 }
1709 node = nb;
1710 cache[n] = n == node ? Node::null() : node; // Only cache once all subterms are expanded
1711 result.push(node);
1712 }
1713 } while(!worklist.empty());
1714
1715 AlwaysAssert(result.size() == 1);
1716
1717 return result.top();
1718 }
1719
1720 void SmtEnginePrivate::removeITEs() {
1721 d_smt.finalOptionsAreSet();
1722
1723 Trace("simplify") << "SmtEnginePrivate::removeITEs()" << endl;
1724
1725 // Remove all of the ITE occurrences and normalize
1726 d_iteRemover.run(d_assertions.ref(), d_iteSkolemMap, true);
1727 for (unsigned i = 0; i < d_assertions.size(); ++ i) {
1728 d_assertions.replace(i, Rewriter::rewrite(d_assertions[i]));
1729 }
1730 }
1731
1732 void SmtEnginePrivate::staticLearning() {
1733 d_smt.finalOptionsAreSet();
1734
1735 TimerStat::CodeTimer staticLearningTimer(d_smt.d_stats->d_staticLearningTime);
1736
1737 Trace("simplify") << "SmtEnginePrivate::staticLearning()" << endl;
1738
1739 for (unsigned i = 0; i < d_assertions.size(); ++ i) {
1740
1741 NodeBuilder<> learned(kind::AND);
1742 learned << d_assertions[i];
1743 d_smt.d_theoryEngine->ppStaticLearn(d_assertions[i], learned);
1744 if(learned.getNumChildren() == 1) {
1745 learned.clear();
1746 } else {
1747 d_assertions.replace(i, learned);
1748 }
1749 }
1750 }
1751
1752 // do dumping (before/after any preprocessing pass)
1753 static void dumpAssertions(const char* key, const AssertionPipeline& assertionList) {
1754 if( Dump.isOn("assertions") &&
1755 Dump.isOn(string("assertions:") + key) ) {
1756 // Push the simplified assertions to the dump output stream
1757 for(unsigned i = 0; i < assertionList.size(); ++ i) {
1758 TNode n = assertionList[i];
1759 Dump("assertions") << AssertCommand(Expr(n.toExpr()));
1760 }
1761 }
1762 }
1763
1764 // returns false if it learns a conflict
1765 bool SmtEnginePrivate::nonClausalSimplify() {
1766 d_smt.finalOptionsAreSet();
1767
1768 if(options::unsatCores()) {
1769 return true;
1770 }
1771
1772 TimerStat::CodeTimer nonclausalTimer(d_smt.d_stats->d_nonclausalSimplificationTime);
1773
1774 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify()" << endl;
1775
1776 if(d_propagatorNeedsFinish) {
1777 d_propagator.finish();
1778 d_propagatorNeedsFinish = false;
1779 }
1780 d_propagator.initialize();
1781
1782 // Assert all the assertions to the propagator
1783 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
1784 << "asserting to propagator" << endl;
1785 for (unsigned i = 0; i < d_assertions.size(); ++ i) {
1786 Assert(Rewriter::rewrite(d_assertions[i]) == d_assertions[i]);
1787 // Don't reprocess substitutions
1788 if (d_substitutionsIndex > 0 && i == d_substitutionsIndex) {
1789 continue;
1790 }
1791 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): asserting " << d_assertions[i] << endl;
1792 Debug("cores") << "d_propagator assertTrue: " << d_assertions[i] << std::endl;
1793 d_propagator.assertTrue(d_assertions[i]);
1794 }
1795
1796 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
1797 << "propagating" << endl;
1798 if (d_propagator.propagate()) {
1799 // If in conflict, just return false
1800 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
1801 << "conflict in non-clausal propagation" << endl;
1802 Node falseNode = NodeManager::currentNM()->mkConst<bool>(false);
1803 Assert(!options::unsatCores());
1804 d_assertions.clear();
1805 d_assertions.push_back(falseNode);
1806 d_propagatorNeedsFinish = true;
1807 return false;
1808 }
1809
1810 // No conflict, go through the literals and solve them
1811 SubstitutionMap constantPropagations(d_smt.d_context);
1812 SubstitutionMap newSubstitutions(d_smt.d_context);
1813 SubstitutionMap::iterator pos;
1814 unsigned j = 0;
1815 for(unsigned i = 0, i_end = d_nonClausalLearnedLiterals.size(); i < i_end; ++ i) {
1816 // Simplify the literal we learned wrt previous substitutions
1817 Node learnedLiteral = d_nonClausalLearnedLiterals[i];
1818 Assert(Rewriter::rewrite(learnedLiteral) == learnedLiteral);
1819 Assert(d_topLevelSubstitutions.apply(learnedLiteral) == learnedLiteral);
1820 Node learnedLiteralNew = newSubstitutions.apply(learnedLiteral);
1821 if (learnedLiteral != learnedLiteralNew) {
1822 learnedLiteral = Rewriter::rewrite(learnedLiteralNew);
1823 }
1824 for (;;) {
1825 learnedLiteralNew = constantPropagations.apply(learnedLiteral);
1826 if (learnedLiteralNew == learnedLiteral) {
1827 break;
1828 }
1829 ++d_smt.d_stats->d_numConstantProps;
1830 learnedLiteral = Rewriter::rewrite(learnedLiteralNew);
1831 }
1832 // It might just simplify to a constant
1833 if (learnedLiteral.isConst()) {
1834 if (learnedLiteral.getConst<bool>()) {
1835 // If the learned literal simplifies to true, it's redundant
1836 continue;
1837 } else {
1838 // If the learned literal simplifies to false, we're in conflict
1839 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
1840 << "conflict with "
1841 << d_nonClausalLearnedLiterals[i] << endl;
1842 Assert(!options::unsatCores());
1843 d_assertions.clear();
1844 d_assertions.push_back(NodeManager::currentNM()->mkConst<bool>(false));
1845 d_propagatorNeedsFinish = true;
1846 return false;
1847 }
1848 }
1849
1850 // Solve it with the corresponding theory, possibly adding new
1851 // substitutions to newSubstitutions
1852 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
1853 << "solving " << learnedLiteral << endl;
1854
1855 Theory::PPAssertStatus solveStatus =
1856 d_smt.d_theoryEngine->solve(learnedLiteral, newSubstitutions);
1857
1858 switch (solveStatus) {
1859 case Theory::PP_ASSERT_STATUS_SOLVED: {
1860 // The literal should rewrite to true
1861 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
1862 << "solved " << learnedLiteral << endl;
1863 Assert(Rewriter::rewrite(newSubstitutions.apply(learnedLiteral)).isConst());
1864 // vector<pair<Node, Node> > equations;
1865 // constantPropagations.simplifyLHS(d_topLevelSubstitutions, equations, true);
1866 // if (equations.empty()) {
1867 // break;
1868 // }
1869 // Assert(equations[0].first.isConst() && equations[0].second.isConst() && equations[0].first != equations[0].second);
1870 // else fall through
1871 break;
1872 }
1873 case Theory::PP_ASSERT_STATUS_CONFLICT:
1874 // If in conflict, we return false
1875 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
1876 << "conflict while solving "
1877 << learnedLiteral << endl;
1878 Assert(!options::unsatCores());
1879 d_assertions.clear();
1880 d_assertions.push_back(NodeManager::currentNM()->mkConst<bool>(false));
1881 d_propagatorNeedsFinish = true;
1882 return false;
1883 default:
1884 if (d_doConstantProp && learnedLiteral.getKind() == kind::EQUAL && (learnedLiteral[0].isConst() || learnedLiteral[1].isConst())) {
1885 // constant propagation
1886 TNode t;
1887 TNode c;
1888 if (learnedLiteral[0].isConst()) {
1889 t = learnedLiteral[1];
1890 c = learnedLiteral[0];
1891 }
1892 else {
1893 t = learnedLiteral[0];
1894 c = learnedLiteral[1];
1895 }
1896 Assert(!t.isConst());
1897 Assert(constantPropagations.apply(t) == t);
1898 Assert(d_topLevelSubstitutions.apply(t) == t);
1899 Assert(newSubstitutions.apply(t) == t);
1900 constantPropagations.addSubstitution(t, c);
1901 // vector<pair<Node,Node> > equations;
1902 // constantPropagations.simplifyLHS(t, c, equations, true);
1903 // if (!equations.empty()) {
1904 // Assert(equations[0].first.isConst() && equations[0].second.isConst() && equations[0].first != equations[0].second);
1905 // d_assertions.clear();
1906 // d_assertions.push_back(NodeManager::currentNM()->mkConst<bool>(false));
1907 // return;
1908 // }
1909 // d_topLevelSubstitutions.simplifyRHS(constantPropagations);
1910 }
1911 else {
1912 // Keep the literal
1913 d_nonClausalLearnedLiterals[j++] = d_nonClausalLearnedLiterals[i];
1914 }
1915 break;
1916 }
1917
1918 #ifdef CVC4_ASSERTIONS
1919 // Check data structure invariants:
1920 // 1. for each lhs of d_topLevelSubstitutions, does not appear anywhere in rhs of d_topLevelSubstitutions or anywhere in constantPropagations
1921 // 2. each lhs of constantPropagations rewrites to itself
1922 // 3. if l -> r is a constant propagation and l is a subterm of l' with l' -> r' another constant propagation, then l'[l/r] -> r' should be a
1923 // constant propagation too
1924 // 4. each lhs of constantPropagations is different from each rhs
1925 for (pos = newSubstitutions.begin(); pos != newSubstitutions.end(); ++pos) {
1926 Assert((*pos).first.isVar());
1927 Assert(d_topLevelSubstitutions.apply((*pos).first) == (*pos).first);
1928 Assert(d_topLevelSubstitutions.apply((*pos).second) == (*pos).second);
1929 Assert(newSubstitutions.apply(newSubstitutions.apply((*pos).second)) == newSubstitutions.apply((*pos).second));
1930 }
1931 for (pos = constantPropagations.begin(); pos != constantPropagations.end(); ++pos) {
1932 Assert((*pos).second.isConst());
1933 Assert(Rewriter::rewrite((*pos).first) == (*pos).first);
1934 // Node newLeft = d_topLevelSubstitutions.apply((*pos).first);
1935 // if (newLeft != (*pos).first) {
1936 // newLeft = Rewriter::rewrite(newLeft);
1937 // Assert(newLeft == (*pos).second ||
1938 // (constantPropagations.hasSubstitution(newLeft) && constantPropagations.apply(newLeft) == (*pos).second));
1939 // }
1940 // newLeft = constantPropagations.apply((*pos).first);
1941 // if (newLeft != (*pos).first) {
1942 // newLeft = Rewriter::rewrite(newLeft);
1943 // Assert(newLeft == (*pos).second ||
1944 // (constantPropagations.hasSubstitution(newLeft) && constantPropagations.apply(newLeft) == (*pos).second));
1945 // }
1946 Assert(constantPropagations.apply((*pos).second) == (*pos).second);
1947 }
1948 #endif /* CVC4_ASSERTIONS */
1949 }
1950 // Resize the learnt
1951 d_nonClausalLearnedLiterals.resize(j);
1952
1953 hash_set<TNode, TNodeHashFunction> s;
1954 Trace("debugging") << "NonClausal simplify pre-preprocess\n";
1955 for (unsigned i = 0; i < d_assertions.size(); ++ i) {
1956 Node assertion = d_assertions[i];
1957 Node assertionNew = newSubstitutions.apply(assertion);
1958 Trace("debugging") << "assertion = " << assertion << endl;
1959 Trace("debugging") << "assertionNew = " << assertionNew << endl;
1960 if (assertion != assertionNew) {
1961 assertion = Rewriter::rewrite(assertionNew);
1962 Trace("debugging") << "rewrite(assertion) = " << assertion << endl;
1963 }
1964 Assert(Rewriter::rewrite(assertion) == assertion);
1965 for (;;) {
1966 assertionNew = constantPropagations.apply(assertion);
1967 if (assertionNew == assertion) {
1968 break;
1969 }
1970 ++d_smt.d_stats->d_numConstantProps;
1971 Trace("debugging") << "assertionNew = " << assertionNew << endl;
1972 assertion = Rewriter::rewrite(assertionNew);
1973 Trace("debugging") << "assertionNew = " << assertionNew << endl;
1974 }
1975 Trace("debugging") << "\n";
1976 s.insert(assertion);
1977 d_assertions.replace(i, assertion);
1978 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
1979 << "non-clausal preprocessed: "
1980 << assertion << endl;
1981 }
1982
1983 // If in incremental mode, add substitutions to the list of assertions
1984 if (d_substitutionsIndex > 0) {
1985 NodeBuilder<> substitutionsBuilder(kind::AND);
1986 substitutionsBuilder << d_assertions[d_substitutionsIndex];
1987 pos = newSubstitutions.begin();
1988 for (; pos != newSubstitutions.end(); ++pos) {
1989 // Add back this substitution as an assertion
1990 TNode lhs = (*pos).first, rhs = newSubstitutions.apply((*pos).second);
1991 Node n = NodeManager::currentNM()->mkNode(lhs.getType().isBoolean() ? kind::IFF : kind::EQUAL, lhs, rhs);
1992 substitutionsBuilder << n;
1993 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): will notify SAT layer of substitution: " << n << endl;
1994 }
1995 if (substitutionsBuilder.getNumChildren() > 1) {
1996 d_assertions.replace(d_substitutionsIndex,
1997 Rewriter::rewrite(Node(substitutionsBuilder)));
1998 }
1999 } else {
2000 // If not in incremental mode, must add substitutions to model
2001 TheoryModel* m = d_smt.d_theoryEngine->getModel();
2002 if(m != NULL) {
2003 for(pos = newSubstitutions.begin(); pos != newSubstitutions.end(); ++pos) {
2004 Node n = (*pos).first;
2005 Node v = newSubstitutions.apply((*pos).second);
2006 Trace("model") << "Add substitution : " << n << " " << v << endl;
2007 m->addSubstitution( n, v );
2008 }
2009 }
2010 }
2011
2012 NodeBuilder<> learnedBuilder(kind::AND);
2013 Assert(d_realAssertionsEnd <= d_assertions.size());
2014 learnedBuilder << d_assertions[d_realAssertionsEnd - 1];
2015
2016 for (unsigned i = 0; i < d_nonClausalLearnedLiterals.size(); ++ i) {
2017 Node learned = d_nonClausalLearnedLiterals[i];
2018 Assert(d_topLevelSubstitutions.apply(learned) == learned);
2019 Node learnedNew = newSubstitutions.apply(learned);
2020 if (learned != learnedNew) {
2021 learned = Rewriter::rewrite(learnedNew);
2022 }
2023 Assert(Rewriter::rewrite(learned) == learned);
2024 for (;;) {
2025 learnedNew = constantPropagations.apply(learned);
2026 if (learnedNew == learned) {
2027 break;
2028 }
2029 ++d_smt.d_stats->d_numConstantProps;
2030 learned = Rewriter::rewrite(learnedNew);
2031 }
2032 if (s.find(learned) != s.end()) {
2033 continue;
2034 }
2035 s.insert(learned);
2036 learnedBuilder << learned;
2037 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
2038 << "non-clausal learned : "
2039 << learned << endl;
2040 }
2041 d_nonClausalLearnedLiterals.clear();
2042
2043 for (pos = constantPropagations.begin(); pos != constantPropagations.end(); ++pos) {
2044 Node cProp = (*pos).first.eqNode((*pos).second);
2045 Assert(d_topLevelSubstitutions.apply(cProp) == cProp);
2046 Node cPropNew = newSubstitutions.apply(cProp);
2047 if (cProp != cPropNew) {
2048 cProp = Rewriter::rewrite(cPropNew);
2049 Assert(Rewriter::rewrite(cProp) == cProp);
2050 }
2051 if (s.find(cProp) != s.end()) {
2052 continue;
2053 }
2054 s.insert(cProp);
2055 learnedBuilder << cProp;
2056 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
2057 << "non-clausal constant propagation : "
2058 << cProp << endl;
2059 }
2060
2061 // Add new substitutions to topLevelSubstitutions
2062 // Note that we don't have to keep rhs's in full solved form
2063 // because SubstitutionMap::apply does a fixed-point iteration when substituting
2064 d_topLevelSubstitutions.addSubstitutions(newSubstitutions);
2065
2066 if(learnedBuilder.getNumChildren() > 1) {
2067 d_assertions.replace(d_realAssertionsEnd - 1,
2068 Rewriter::rewrite(Node(learnedBuilder)));
2069 }
2070
2071 d_propagatorNeedsFinish = true;
2072 return true;
2073 }
2074
2075 void SmtEnginePrivate::bvAbstraction() {
2076 Trace("bv-abstraction") << "SmtEnginePrivate::bvAbstraction()" << endl;
2077 std::vector<Node> new_assertions;
2078 bool changed = d_smt.d_theoryEngine->ppBvAbstraction(d_assertions.ref(), new_assertions);
2079 for (unsigned i = 0; i < d_assertions.size(); ++ i) {
2080 d_assertions.replace(i, Rewriter::rewrite(new_assertions[i]));
2081 }
2082 // if we are using the lazy solver and the abstraction
2083 // applies, then UF symbols were introduced
2084 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_LAZY &&
2085 changed) {
2086 LogicRequest req(d_smt);
2087 req.widenLogic(THEORY_UF);
2088 }
2089 }
2090
2091
2092 void SmtEnginePrivate::bvToBool() {
2093 Trace("bv-to-bool") << "SmtEnginePrivate::bvToBool()" << endl;
2094 std::vector<Node> new_assertions;
2095 d_smt.d_theoryEngine->ppBvToBool(d_assertions.ref(), new_assertions);
2096 for (unsigned i = 0; i < d_assertions.size(); ++ i) {
2097 d_assertions.replace(i, Rewriter::rewrite(new_assertions[i]));
2098 }
2099 }
2100
2101 bool SmtEnginePrivate::simpITE() {
2102 TimerStat::CodeTimer simpITETimer(d_smt.d_stats->d_simpITETime);
2103
2104 Trace("simplify") << "SmtEnginePrivate::simpITE()" << endl;
2105
2106 unsigned numAssertionOnEntry = d_assertions.size();
2107 for (unsigned i = 0; i < d_assertions.size(); ++i) {
2108 Node result = d_smt.d_theoryEngine->ppSimpITE(d_assertions[i]);
2109 d_assertions.replace(i, result);
2110 if(result.isConst() && !result.getConst<bool>()){
2111 return false;
2112 }
2113 }
2114 bool result = d_smt.d_theoryEngine->donePPSimpITE(d_assertions.ref());
2115 if(numAssertionOnEntry < d_assertions.size()){
2116 compressBeforeRealAssertions(numAssertionOnEntry);
2117 }
2118 return result;
2119 }
2120
2121 void SmtEnginePrivate::compressBeforeRealAssertions(size_t before){
2122 size_t curr = d_assertions.size();
2123 if(before >= curr ||
2124 d_realAssertionsEnd <= 0 ||
2125 d_realAssertionsEnd >= curr){
2126 return;
2127 }
2128
2129 // assertions
2130 // original: [0 ... d_realAssertionsEnd)
2131 // can be modified
2132 // ites skolems [d_realAssertionsEnd, before)
2133 // cannot be moved
2134 // added [before, curr)
2135 // can be modified
2136 Assert(0 < d_realAssertionsEnd);
2137 Assert(d_realAssertionsEnd <= before);
2138 Assert(before < curr);
2139
2140 std::vector<Node> intoConjunction;
2141 for(size_t i = before; i<curr; ++i){
2142 intoConjunction.push_back(d_assertions[i]);
2143 }
2144 d_assertions.resize(before);
2145 size_t lastBeforeItes = d_realAssertionsEnd - 1;
2146 intoConjunction.push_back(d_assertions[lastBeforeItes]);
2147 Node newLast = util::NaryBuilder::mkAssoc(kind::AND, intoConjunction);
2148 d_assertions.replace(lastBeforeItes, newLast);
2149 Assert(d_assertions.size() == before);
2150 }
2151
2152 void SmtEnginePrivate::unconstrainedSimp() {
2153 TimerStat::CodeTimer unconstrainedSimpTimer(d_smt.d_stats->d_unconstrainedSimpTime);
2154 Trace("simplify") << "SmtEnginePrivate::unconstrainedSimp()" << endl;
2155 d_smt.d_theoryEngine->ppUnconstrainedSimp(d_assertions.ref());
2156 }
2157
2158
2159 void SmtEnginePrivate::constrainSubtypes(TNode top, AssertionPipeline& assertions)
2160 throw() {
2161
2162 Trace("constrainSubtypes") << "constrainSubtypes(): looking at " << top << endl;
2163
2164 set<TNode> done;
2165 stack<TNode> worklist;
2166 worklist.push(top);
2167 done.insert(top);
2168
2169 do {
2170 TNode n = worklist.top();
2171 worklist.pop();
2172
2173 TypeNode t = n.getType();
2174 if(t.isPredicateSubtype()) {
2175 WarningOnce() << "Warning: CVC4 doesn't yet do checking that predicate subtypes are nonempty domains" << endl;
2176 Node pred = t.getSubtypePredicate();
2177 Kind k;
2178 // pred can be a LAMBDA, a function constant, or a datatype tester
2179 Trace("constrainSubtypes") << "constrainSubtypes(): pred.getType() == " << pred.getType() << endl;
2180 if(d_smt.d_definedFunctions->find(pred) != d_smt.d_definedFunctions->end()) {
2181 k = kind::APPLY;
2182 } else if(pred.getType().isTester()) {
2183 k = kind::APPLY_TESTER;
2184 } else {
2185 k = kind::APPLY_UF;
2186 }
2187 Node app = NodeManager::currentNM()->mkNode(k, pred, n);
2188 Trace("constrainSubtypes") << "constrainSubtypes(): assert(" << k << ") " << app << endl;
2189 assertions.push_back(app);
2190 } else if(t.isSubrange()) {
2191 SubrangeBounds bounds = t.getSubrangeBounds();
2192 Trace("constrainSubtypes") << "constrainSubtypes(): got bounds " << bounds << endl;
2193 if(bounds.lower.hasBound()) {
2194 Node c = NodeManager::currentNM()->mkConst(Rational(bounds.lower.getBound()));
2195 Node lb = NodeManager::currentNM()->mkNode(kind::LEQ, c, n);
2196 Trace("constrainSubtypes") << "constrainSubtypes(): assert " << lb << endl;
2197 assertions.push_back(lb);
2198 }
2199 if(bounds.upper.hasBound()) {
2200 Node c = NodeManager::currentNM()->mkConst(Rational(bounds.upper.getBound()));
2201 Node ub = NodeManager::currentNM()->mkNode(kind::LEQ, n, c);
2202 Trace("constrainSubtypes") << "constrainSubtypes(): assert " << ub << endl;
2203 assertions.push_back(ub);
2204 }
2205 }
2206
2207 for(TNode::iterator i = n.begin(); i != n.end(); ++i) {
2208 if(done.find(*i) == done.end()) {
2209 worklist.push(*i);
2210 done.insert(*i);
2211 }
2212 }
2213 } while(! worklist.empty());
2214 }
2215
2216 void SmtEnginePrivate::traceBackToAssertions(const std::vector<Node>& nodes, std::vector<TNode>& assertions) {
2217 const booleans::CircuitPropagator::BackEdgesMap& backEdges = d_propagator.getBackEdges();
2218 for(vector<Node>::const_iterator i = nodes.begin(); i != nodes.end(); ++i) {
2219 booleans::CircuitPropagator::BackEdgesMap::const_iterator j = backEdges.find(*i);
2220 // term must appear in map, otherwise how did we get here?!
2221 Assert(j != backEdges.end());
2222 // if term maps to empty, that means it's a top-level assertion
2223 if(!(*j).second.empty()) {
2224 traceBackToAssertions((*j).second, assertions);
2225 } else {
2226 assertions.push_back(*i);
2227 }
2228 }
2229 }
2230
2231 size_t SmtEnginePrivate::removeFromConjunction(Node& n, const std::hash_set<unsigned long>& toRemove) {
2232 Assert(n.getKind() == kind::AND);
2233 size_t removals = 0;
2234 for(Node::iterator j = n.begin(); j != n.end(); ++j) {
2235 size_t subremovals = 0;
2236 Node sub = *j;
2237 if(toRemove.find(sub.getId()) != toRemove.end() ||
2238 (sub.getKind() == kind::AND && (subremovals = removeFromConjunction(sub, toRemove)) > 0)) {
2239 NodeBuilder<> b(kind::AND);
2240 b.append(n.begin(), j);
2241 if(subremovals > 0) {
2242 removals += subremovals;
2243 b << sub;
2244 } else {
2245 ++removals;
2246 }
2247 for(++j; j != n.end(); ++j) {
2248 if(toRemove.find((*j).getId()) != toRemove.end()) {
2249 ++removals;
2250 } else if((*j).getKind() == kind::AND) {
2251 sub = *j;
2252 if((subremovals = removeFromConjunction(sub, toRemove)) > 0) {
2253 removals += subremovals;
2254 b << sub;
2255 } else {
2256 b << *j;
2257 }
2258 } else {
2259 b << *j;
2260 }
2261 }
2262 if(b.getNumChildren() == 0) {
2263 n = d_true;
2264 b.clear();
2265 } else if(b.getNumChildren() == 1) {
2266 n = b[0];
2267 b.clear();
2268 } else {
2269 n = b;
2270 }
2271 n = Rewriter::rewrite(n);
2272 return removals;
2273 }
2274 }
2275
2276 Assert(removals == 0);
2277 return 0;
2278 }
2279
2280 void SmtEnginePrivate::doMiplibTrick() {
2281 Assert(d_realAssertionsEnd == d_assertions.size());
2282 Assert(!options::incrementalSolving());
2283
2284 const booleans::CircuitPropagator::BackEdgesMap& backEdges = d_propagator.getBackEdges();
2285 hash_set<unsigned long> removeAssertions;
2286
2287 NodeManager* nm = NodeManager::currentNM();
2288 Node zero = nm->mkConst(Rational(0)), one = nm->mkConst(Rational(1));
2289
2290 hash_map<TNode, Node, TNodeHashFunction> intVars;
2291 for(vector<Node>::const_iterator i = d_boolVars.begin(); i != d_boolVars.end(); ++i) {
2292 if(d_propagator.isAssigned(*i)) {
2293 Debug("miplib") << "ineligible: " << *i << " because assigned " << d_propagator.getAssignment(*i) << endl;
2294 continue;
2295 }
2296
2297 vector<TNode> assertions;
2298 booleans::CircuitPropagator::BackEdgesMap::const_iterator j = backEdges.find(*i);
2299 // if not in back edges map, the bool var is unconstrained, showing up in no assertions.
2300 // if maps to an empty vector, that means the bool var was asserted itself.
2301 if(j != backEdges.end()) {
2302 if(!(*j).second.empty()) {
2303 traceBackToAssertions((*j).second, assertions);
2304 } else {
2305 assertions.push_back(*i);
2306 }
2307 }
2308 Debug("miplib") << "for " << *i << endl;
2309 bool eligible = true;
2310 map<pair<Node, Node>, uint64_t> marks;
2311 map<pair<Node, Node>, vector<Rational> > coef;
2312 map<pair<Node, Node>, vector<Rational> > checks;
2313 map<pair<Node, Node>, vector<TNode> > asserts;
2314 for(vector<TNode>::const_iterator j = assertions.begin(); j != assertions.end(); ++j) {
2315 Debug("miplib") << " found: " << *j << endl;
2316 if((*j).getKind() != kind::IMPLIES) {
2317 eligible = false;
2318 Debug("miplib") << " -- INELIGIBLE -- (not =>)" << endl;
2319 break;
2320 }
2321 Node conj = BooleanSimplification::simplify((*j)[0]);
2322 if(conj.getKind() == kind::AND && conj.getNumChildren() > 6) {
2323 eligible = false;
2324 Debug("miplib") << " -- INELIGIBLE -- (N-ary /\\ too big)" << endl;
2325 break;
2326 }
2327 if(conj.getKind() != kind::AND && !conj.isVar() && !(conj.getKind() == kind::NOT && conj[0].isVar())) {
2328 eligible = false;
2329 Debug("miplib") << " -- INELIGIBLE -- (not /\\ or literal)" << endl;
2330 break;
2331 }
2332 if((*j)[1].getKind() != kind::EQUAL ||
2333 !( ( (*j)[1][0].isVar() &&
2334 (*j)[1][1].getKind() == kind::CONST_RATIONAL ) ||
2335 ( (*j)[1][0].getKind() == kind::CONST_RATIONAL &&
2336 (*j)[1][1].isVar() ) )) {
2337 eligible = false;
2338 Debug("miplib") << " -- INELIGIBLE -- (=> (and X X) X)" << endl;
2339 break;
2340 }
2341 if(conj.getKind() == kind::AND) {
2342 vector<Node> posv;
2343 bool found_x = false;
2344 map<TNode, bool> neg;
2345 for(Node::iterator ii = conj.begin(); ii != conj.end(); ++ii) {
2346 if((*ii).isVar()) {
2347 posv.push_back(*ii);
2348 neg[*ii] = false;
2349 found_x = found_x || *i == *ii;
2350 } else if((*ii).getKind() == kind::NOT && (*ii)[0].isVar()) {
2351 posv.push_back((*ii)[0]);
2352 neg[(*ii)[0]] = true;
2353 found_x = found_x || *i == (*ii)[0];
2354 } else {
2355 eligible = false;
2356 Debug("miplib") << " -- INELIGIBLE -- (non-var: " << *ii << ")" << endl;
2357 break;
2358 }
2359 if(d_propagator.isAssigned(posv.back())) {
2360 eligible = false;
2361 Debug("miplib") << " -- INELIGIBLE -- (" << posv.back() << " asserted)" << endl;
2362 break;
2363 }
2364 }
2365 if(!eligible) {
2366 break;
2367 }
2368 if(!found_x) {
2369 eligible = false;
2370 Debug("miplib") << " --INELIGIBLE -- (couldn't find " << *i << " in conjunction)" << endl;
2371 break;
2372 }
2373 sort(posv.begin(), posv.end());
2374 const Node pos = NodeManager::currentNM()->mkNode(kind::AND, posv);
2375 const TNode var = ((*j)[1][0].getKind() == kind::CONST_RATIONAL) ? (*j)[1][1] : (*j)[1][0];
2376 const pair<Node, Node> pos_var(pos, var);
2377 const Rational& constant = ((*j)[1][0].getKind() == kind::CONST_RATIONAL) ? (*j)[1][0].getConst<Rational>() : (*j)[1][1].getConst<Rational>();
2378 uint64_t mark = 0;
2379 unsigned countneg = 0, thepos = 0;
2380 for(unsigned ii = 0; ii < pos.getNumChildren(); ++ii) {
2381 if(neg[pos[ii]]) {
2382 ++countneg;
2383 } else {
2384 thepos = ii;
2385 mark |= (0x1 << ii);
2386 }
2387 }
2388 if((marks[pos_var] & (1lu << mark)) != 0) {
2389 eligible = false;
2390 Debug("miplib") << " -- INELIGIBLE -- (remarked)" << endl;
2391 break;
2392 }
2393 Debug("miplib") << "mark is " << mark << " -- " << (1lu << mark) << endl;
2394 marks[pos_var] |= (1lu << mark);
2395 Debug("miplib") << "marks[" << pos << "," << var << "] now " << marks[pos_var] << endl;
2396 if(countneg == pos.getNumChildren()) {
2397 if(constant != 0) {
2398 eligible = false;
2399 Debug("miplib") << " -- INELIGIBLE -- (nonzero constant)" << endl;
2400 break;
2401 }
2402 } else if(countneg == pos.getNumChildren() - 1) {
2403 Assert(coef[pos_var].size() <= 6 && thepos < 6);
2404 if(coef[pos_var].size() <= thepos) {
2405 coef[pos_var].resize(thepos + 1);
2406 }
2407 coef[pos_var][thepos] = constant;
2408 } else {
2409 if(checks[pos_var].size() <= mark) {
2410 checks[pos_var].resize(mark + 1);
2411 }
2412 checks[pos_var][mark] = constant;
2413 }
2414 asserts[pos_var].push_back(*j);
2415 } else {
2416 TNode x = conj;
2417 if(x != *i && x != (*i).notNode()) {
2418 eligible = false;
2419 Debug("miplib") << " -- INELIGIBLE -- (x not present where I expect it)" << endl;
2420 break;
2421 }
2422 const bool xneg = (x.getKind() == kind::NOT);
2423 x = xneg ? x[0] : x;
2424 Debug("miplib") << " x:" << x << " " << xneg << endl;
2425 const TNode var = ((*j)[1][0].getKind() == kind::CONST_RATIONAL) ? (*j)[1][1] : (*j)[1][0];
2426 const pair<Node, Node> x_var(x, var);
2427 const Rational& constant = ((*j)[1][0].getKind() == kind::CONST_RATIONAL) ? (*j)[1][0].getConst<Rational>() : (*j)[1][1].getConst<Rational>();
2428 unsigned mark = (xneg ? 0 : 1);
2429 if((marks[x_var] & (1u << mark)) != 0) {
2430 eligible = false;
2431 Debug("miplib") << " -- INELIGIBLE -- (remarked)" << endl;
2432 break;
2433 }
2434 marks[x_var] |= (1u << mark);
2435 if(xneg) {
2436 if(constant != 0) {
2437 eligible = false;
2438 Debug("miplib") << " -- INELIGIBLE -- (nonzero constant)" << endl;
2439 break;
2440 }
2441 } else {
2442 Assert(coef[x_var].size() <= 6);
2443 coef[x_var].resize(6);
2444 coef[x_var][0] = constant;
2445 }
2446 asserts[x_var].push_back(*j);
2447 }
2448 }
2449 if(eligible) {
2450 for(map<pair<Node, Node>, uint64_t>::const_iterator j = marks.begin(); j != marks.end(); ++j) {
2451 const TNode pos = (*j).first.first;
2452 const TNode var = (*j).first.second;
2453 const pair<Node, Node>& pos_var = (*j).first;
2454 const uint64_t mark = (*j).second;
2455 const unsigned numVars = pos.getKind() == kind::AND ? pos.getNumChildren() : 1;
2456 uint64_t expected = (uint64_t(1) << (1 << numVars)) - 1;
2457 expected = (expected == 0) ? -1 : expected; // fix for overflow
2458 Debug("miplib") << "[" << pos << "] => " << hex << mark << " expect " << expected << dec << endl;
2459 Assert(pos.getKind() == kind::AND || pos.isVar());
2460 if(mark != expected) {
2461 Debug("miplib") << " -- INELIGIBLE " << pos << " -- (insufficiently marked, got " << mark << " for " << numVars << " vars, expected " << expected << endl;
2462 } else {
2463 if(mark != 3) { // exclude single-var case; nothing to check there
2464 uint64_t sz = (uint64_t(1) << checks[pos_var].size()) - 1;
2465 sz = (sz == 0) ? -1 : sz; // fix for overflow
2466 Assert(sz == mark, "expected size %u == mark %u", sz, mark);
2467 for(size_t k = 0; k < checks[pos_var].size(); ++k) {
2468 if((k & (k - 1)) != 0) {
2469 Rational sum = 0;
2470 Debug("miplib") << k << " => " << checks[pos_var][k] << endl;
2471 for(size_t v = 1, kk = k; kk != 0; ++v, kk >>= 1) {
2472 if((kk & 0x1) == 1) {
2473 Assert(pos.getKind() == kind::AND);
2474 Debug("miplib") << "var " << v << " : " << pos[v - 1] << " coef:" << coef[pos_var][v - 1] << endl;
2475 sum += coef[pos_var][v - 1];
2476 }
2477 }
2478 Debug("miplib") << "checkSum is " << sum << " input says " << checks[pos_var][k] << endl;
2479 if(sum != checks[pos_var][k]) {
2480 eligible = false;
2481 Debug("miplib") << " -- INELIGIBLE " << pos << " -- (nonlinear combination)" << endl;
2482 break;
2483 }
2484 } else {
2485 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
2486 }
2487 }
2488 }
2489 if(!eligible) {
2490 eligible = true; // next is still eligible
2491 continue;
2492 }
2493
2494 Debug("miplib") << " -- ELIGIBLE " << *i << " , " << pos << " --" << endl;
2495 vector<Node> newVars;
2496 expr::NodeSelfIterator ii, iiend;
2497 if(pos.getKind() == kind::AND) {
2498 ii = pos.begin();
2499 iiend = pos.end();
2500 } else {
2501 ii = expr::NodeSelfIterator::self(pos);
2502 iiend = expr::NodeSelfIterator::selfEnd(pos);
2503 }
2504 for(; ii != iiend; ++ii) {
2505 Node& varRef = intVars[*ii];
2506 if(varRef.isNull()) {
2507 stringstream ss;
2508 ss << "mipvar_" << *ii;
2509 Node newVar = nm->mkSkolem(ss.str(), nm->integerType(), "a variable introduced due to scrubbing a miplib encoding", NodeManager::SKOLEM_EXACT_NAME);
2510 Node geq = Rewriter::rewrite(nm->mkNode(kind::GEQ, newVar, zero));
2511 Node leq = Rewriter::rewrite(nm->mkNode(kind::LEQ, newVar, one));
2512 d_assertions.push_back(Rewriter::rewrite(geq.andNode(leq)));
2513 SubstitutionMap nullMap(&d_fakeContext);
2514 Theory::PPAssertStatus status CVC4_UNUSED; // just for assertions
2515 status = d_smt.d_theoryEngine->solve(geq, nullMap);
2516 Assert(status == Theory::PP_ASSERT_STATUS_UNSOLVED,
2517 "unexpected solution from arith's ppAssert()");
2518 Assert(nullMap.empty(),
2519 "unexpected substitution from arith's ppAssert()");
2520 status = d_smt.d_theoryEngine->solve(leq, nullMap);
2521 Assert(status == Theory::PP_ASSERT_STATUS_UNSOLVED,
2522 "unexpected solution from arith's ppAssert()");
2523 Assert(nullMap.empty(),
2524 "unexpected substitution from arith's ppAssert()");
2525 d_smt.d_theoryEngine->getModel()->addSubstitution(*ii, newVar.eqNode(one));
2526 newVars.push_back(newVar);
2527 varRef = newVar;
2528 } else {
2529 newVars.push_back(varRef);
2530 }
2531 if(!d_smt.d_logic.areIntegersUsed()) {
2532 d_smt.d_logic = d_smt.d_logic.getUnlockedCopy();
2533 d_smt.d_logic.enableIntegers();
2534 d_smt.d_logic.lock();
2535 }
2536 }
2537 Node sum;
2538 if(pos.getKind() == kind::AND) {
2539 NodeBuilder<> sumb(kind::PLUS);
2540 for(size_t ii = 0; ii < pos.getNumChildren(); ++ii) {
2541 sumb << nm->mkNode(kind::MULT, nm->mkConst(coef[pos_var][ii]), newVars[ii]);
2542 }
2543 sum = sumb;
2544 } else {
2545 sum = nm->mkNode(kind::MULT, nm->mkConst(coef[pos_var][0]), newVars[0]);
2546 }
2547 Debug("miplib") << "vars[] " << var << endl
2548 << " eq " << Rewriter::rewrite(sum) << endl;
2549 Node newAssertion = var.eqNode(Rewriter::rewrite(sum));
2550 if(d_topLevelSubstitutions.hasSubstitution(newAssertion[0])) {
2551 //Warning() << "RE-SUBSTITUTION " << newAssertion[0] << endl;
2552 //Warning() << "REPLACE " << newAssertion[1] << endl;
2553 //Warning() << "ORIG " << d_topLevelSubstitutions.getSubstitution(newAssertion[0]) << endl;
2554 Assert(d_topLevelSubstitutions.getSubstitution(newAssertion[0]) == newAssertion[1]);
2555 } else if(pos.getNumChildren() <= options::arithMLTrickSubstitutions()) {
2556 d_topLevelSubstitutions.addSubstitution(newAssertion[0], newAssertion[1]);
2557 Debug("miplib") << "addSubs: " << newAssertion[0] << " to " << newAssertion[1] << endl;
2558 } else {
2559 Debug("miplib") << "skipSubs: " << newAssertion[0] << " to " << newAssertion[1] << " (threshold is " << options::arithMLTrickSubstitutions() << ")" << endl;
2560 }
2561 newAssertion = Rewriter::rewrite(newAssertion);
2562 Debug("miplib") << " " << newAssertion << endl;
2563 d_assertions.push_back(newAssertion);
2564 Debug("miplib") << " assertions to remove: " << endl;
2565 for(vector<TNode>::const_iterator k = asserts[pos_var].begin(), k_end = asserts[pos_var].end(); k != k_end; ++k) {
2566 Debug("miplib") << " " << *k << endl;
2567 removeAssertions.insert((*k).getId());
2568 }
2569 }
2570 }
2571 }
2572 }
2573 if(!removeAssertions.empty()) {
2574 Debug("miplib") << "SmtEnginePrivate::simplify(): scrubbing miplib encoding..." << endl;
2575 for(size_t i = 0; i < d_realAssertionsEnd; ++i) {
2576 if(removeAssertions.find(d_assertions[i].getId()) != removeAssertions.end()) {
2577 Debug("miplib") << "SmtEnginePrivate::simplify(): - removing " << d_assertions[i] << endl;
2578 d_assertions[i] = d_true;
2579 ++d_smt.d_stats->d_numMiplibAssertionsRemoved;
2580 } else if(d_assertions[i].getKind() == kind::AND) {
2581 size_t removals = removeFromConjunction(d_assertions[i], removeAssertions);
2582 if(removals > 0) {
2583 Debug("miplib") << "SmtEnginePrivate::simplify(): - reduced " << d_assertions[i] << endl;
2584 Debug("miplib") << "SmtEnginePrivate::simplify(): - by " << removals << " conjuncts" << endl;
2585 d_smt.d_stats->d_numMiplibAssertionsRemoved += removals;
2586 }
2587 }
2588 Debug("miplib") << "had: " << d_assertions[i] << endl;
2589 d_assertions[i] = Rewriter::rewrite(d_topLevelSubstitutions.apply(d_assertions[i]));
2590 Debug("miplib") << "now: " << d_assertions[i] << endl;
2591 }
2592 } else {
2593 Debug("miplib") << "SmtEnginePrivate::simplify(): miplib pass found nothing." << endl;
2594 }
2595 d_realAssertionsEnd = d_assertions.size();
2596 }
2597
2598
2599 // returns false if simplification led to "false"
2600 bool SmtEnginePrivate::simplifyAssertions()
2601 throw(TypeCheckingException, LogicException) {
2602 Assert(d_smt.d_pendingPops == 0);
2603 try {
2604 ScopeCounter depth(d_simplifyAssertionsDepth);
2605
2606 Trace("simplify") << "SmtEnginePrivate::simplify()" << endl;
2607
2608 if(options::simplificationMode() != SIMPLIFICATION_MODE_NONE) {
2609 // Perform non-clausal simplification
2610 Chat() << "...performing nonclausal simplification..." << endl;
2611 Trace("simplify") << "SmtEnginePrivate::simplify(): "
2612 << "performing non-clausal simplification" << endl;
2613 bool noConflict = nonClausalSimplify();
2614 if(!noConflict) {
2615 return false;
2616 }
2617
2618 // We piggy-back off of the BackEdgesMap in the CircuitPropagator to
2619 // do the miplib trick.
2620 if( // check that option is on
2621 options::arithMLTrick() &&
2622 // miplib rewrites aren't safe in incremental mode
2623 ! options::incrementalSolving() &&
2624 // only useful in arith
2625 d_smt.d_logic.isTheoryEnabled(THEORY_ARITH) &&
2626 // we add new assertions and need this (in practice, this
2627 // restriction only disables miplib processing during
2628 // re-simplification, which we don't expect to be useful anyway)
2629 d_realAssertionsEnd == d_assertions.size() ) {
2630 Chat() << "...fixing miplib encodings..." << endl;
2631 Trace("simplify") << "SmtEnginePrivate::simplify(): "
2632 << "looking for miplib pseudobooleans..." << endl;
2633
2634 TimerStat::CodeTimer miplibTimer(d_smt.d_stats->d_miplibPassTime);
2635
2636 doMiplibTrick();
2637 } else {
2638 Trace("simplify") << "SmtEnginePrivate::simplify(): "
2639 << "skipping miplib pseudobooleans pass (either incrementalSolving is on, or miplib pbs are turned off)..." << endl;
2640 }
2641 }
2642
2643 dumpAssertions("post-nonclausal", d_assertions);
2644 Trace("smt") << "POST nonClausalSimplify" << endl;
2645 Debug("smt") << " d_assertions : " << d_assertions.size() << endl;
2646
2647 // before ppRewrite check if only core theory for BV theory
2648 d_smt.d_theoryEngine->staticInitializeBVOptions(d_assertions.ref());
2649
2650 dumpAssertions("pre-theorypp", d_assertions);
2651
2652 // Theory preprocessing
2653 if (d_smt.d_earlyTheoryPP) {
2654 Chat() << "...doing early theory preprocessing..." << endl;
2655 TimerStat::CodeTimer codeTimer(d_smt.d_stats->d_theoryPreprocessTime);
2656 // Call the theory preprocessors
2657 d_smt.d_theoryEngine->preprocessStart();
2658 for (unsigned i = 0; i < d_assertions.size(); ++ i) {
2659 Assert(Rewriter::rewrite(d_assertions[i]) == d_assertions[i]);
2660 d_assertions.replace(i, d_smt.d_theoryEngine->preprocess(d_assertions[i]));
2661 Assert(Rewriter::rewrite(d_assertions[i]) == d_assertions[i]);
2662 }
2663 }
2664
2665 dumpAssertions("post-theorypp", d_assertions);
2666 Trace("smt") << "POST theoryPP" << endl;
2667 Debug("smt") << " d_assertions : " << d_assertions.size() << endl;
2668
2669 // ITE simplification
2670 if(options::doITESimp() &&
2671 (d_simplifyAssertionsDepth <= 1 || options::doITESimpOnRepeat())) {
2672 Chat() << "...doing ITE simplification..." << endl;
2673 bool noConflict = simpITE();
2674 if(!noConflict){
2675 Chat() << "...ITE simplification found unsat..." << endl;
2676 return false;
2677 }
2678 }
2679
2680 dumpAssertions("post-itesimp", d_assertions);
2681 Trace("smt") << "POST iteSimp" << endl;
2682 Debug("smt") << " d_assertions : " << d_assertions.size() << endl;
2683
2684 // Unconstrained simplification
2685 if(options::unconstrainedSimp()) {
2686 Chat() << "...doing unconstrained simplification..." << endl;
2687 unconstrainedSimp();
2688 }
2689
2690 dumpAssertions("post-unconstrained", d_assertions);
2691 Trace("smt") << "POST unconstrainedSimp" << endl;
2692 Debug("smt") << " d_assertions : " << d_assertions.size() << endl;
2693
2694 if(options::repeatSimp() && options::simplificationMode() != SIMPLIFICATION_MODE_NONE) {
2695 Chat() << "...doing another round of nonclausal simplification..." << endl;
2696 Trace("simplify") << "SmtEnginePrivate::simplify(): "
2697 << " doing repeated simplification" << endl;
2698 bool noConflict = nonClausalSimplify();
2699 if(!noConflict) {
2700 return false;
2701 }
2702 }
2703
2704 dumpAssertions("post-repeatsimp", d_assertions);
2705 Trace("smt") << "POST repeatSimp" << endl;
2706 Debug("smt") << " d_assertions : " << d_assertions.size() << endl;
2707
2708 } catch(TypeCheckingExceptionPrivate& tcep) {
2709 // Calls to this function should have already weeded out any
2710 // typechecking exceptions via (e.g.) ensureBoolean(). But a
2711 // theory could still create a new expression that isn't
2712 // well-typed, and we don't want the C++ runtime to abort our
2713 // process without any error notice.
2714 stringstream ss;
2715 ss << "A bad expression was produced. Original exception follows:\n"
2716 << tcep;
2717 InternalError(ss.str().c_str());
2718 }
2719 return true;
2720 }
2721
2722 Result SmtEngine::check() {
2723 Assert(d_fullyInited);
2724 Assert(d_pendingPops == 0);
2725
2726 Trace("smt") << "SmtEngine::check()" << endl;
2727
2728 // Make sure the prop layer has all of the assertions
2729 Trace("smt") << "SmtEngine::check(): processing assertions" << endl;
2730 d_private->processAssertions();
2731
2732 // Turn off stop only for QF_LRA
2733 // TODO: Bring up in a meeting where to put this
2734 if(options::decisionStopOnly() && !options::decisionMode.wasSetByUser() ){
2735 if( // QF_LRA
2736 (not d_logic.isQuantified() &&
2737 d_logic.isPure(THEORY_ARITH) && d_logic.isLinear() && !d_logic.isDifferenceLogic() && !d_logic.areIntegersUsed()
2738 )){
2739 if(d_private->d_iteSkolemMap.empty()){
2740 options::decisionStopOnly.set(false);
2741 d_decisionEngine->clearStrategies();
2742 Trace("smt") << "SmtEngine::check(): turning off stop only" << endl;
2743 }
2744 }
2745 }
2746
2747 unsigned long millis = 0;
2748 if(d_timeBudgetCumulative != 0) {
2749 millis = getTimeRemaining();
2750 if(millis == 0) {
2751 return Result(Result::VALIDITY_UNKNOWN, Result::TIMEOUT, d_filename);
2752 }
2753 }
2754 if(d_timeBudgetPerCall != 0 && (millis == 0 || d_timeBudgetPerCall < millis)) {
2755 millis = d_timeBudgetPerCall;
2756 }
2757
2758 unsigned long resource = 0;
2759 if(d_resourceBudgetCumulative != 0) {
2760 resource = getResourceRemaining();
2761 if(resource == 0) {
2762 return Result(Result::VALIDITY_UNKNOWN, Result::RESOURCEOUT, d_filename);
2763 }
2764 }
2765 if(d_resourceBudgetPerCall != 0 && (resource == 0 || d_resourceBudgetPerCall < resource)) {
2766 resource = d_resourceBudgetPerCall;
2767 }
2768
2769 TimerStat::CodeTimer solveTimer(d_stats->d_solveTime);
2770
2771 Chat() << "solving..." << endl;
2772 Trace("smt") << "SmtEngine::check(): running check" << endl;
2773 Result result = d_propEngine->checkSat(millis, resource);
2774
2775 // PropEngine::checkSat() returns the actual amount used in these
2776 // variables.
2777 d_cumulativeTimeUsed += millis;
2778 d_cumulativeResourceUsed += resource;
2779
2780 Trace("limit") << "SmtEngine::check(): cumulative millis " << d_cumulativeTimeUsed
2781 << ", conflicts " << d_cumulativeResourceUsed << endl;
2782
2783 return Result(result, d_filename);
2784 }
2785
2786 Result SmtEngine::quickCheck() {
2787 Assert(d_fullyInited);
2788 Trace("smt") << "SMT quickCheck()" << endl;
2789 return Result(Result::VALIDITY_UNKNOWN, Result::REQUIRES_FULL_CHECK, d_filename);
2790 }
2791
2792
2793 void SmtEnginePrivate::collectSkolems(TNode n, set<TNode>& skolemSet, hash_map<Node, bool, NodeHashFunction>& cache)
2794 {
2795 hash_map<Node, bool, NodeHashFunction>::iterator it;
2796 it = cache.find(n);
2797 if (it != cache.end()) {
2798 return;
2799 }
2800
2801 size_t sz = n.getNumChildren();
2802 if (sz == 0) {
2803 IteSkolemMap::iterator it = d_iteSkolemMap.find(n);
2804 if (it != d_iteSkolemMap.end()) {
2805 skolemSet.insert(n);
2806 }
2807 cache[n] = true;
2808 return;
2809 }
2810
2811 size_t k = 0;
2812 for (; k < sz; ++k) {
2813 collectSkolems(n[k], skolemSet, cache);
2814 }
2815 cache[n] = true;
2816 }
2817
2818
2819 bool SmtEnginePrivate::checkForBadSkolems(TNode n, TNode skolem, hash_map<Node, bool, NodeHashFunction>& cache)
2820 {
2821 hash_map<Node, bool, NodeHashFunction>::iterator it;
2822 it = cache.find(n);
2823 if (it != cache.end()) {
2824 return (*it).second;
2825 }
2826
2827 size_t sz = n.getNumChildren();
2828 if (sz == 0) {
2829 IteSkolemMap::iterator it = d_iteSkolemMap.find(n);
2830 bool bad = false;
2831 if (it != d_iteSkolemMap.end()) {
2832 if (!((*it).first < n)) {
2833 bad = true;
2834 }
2835 }
2836 cache[n] = bad;
2837 return bad;
2838 }
2839
2840 size_t k = 0;
2841 for (; k < sz; ++k) {
2842 if (checkForBadSkolems(n[k], skolem, cache)) {
2843 cache[n] = true;
2844 return true;
2845 }
2846 }
2847
2848 cache[n] = false;
2849 return false;
2850 }
2851
2852 Node SmtEnginePrivate::rewriteBooleanTerms(TNode n) {
2853 TimerStat::CodeTimer codeTimer(d_smt.d_stats->d_rewriteBooleanTermsTime);
2854 if(d_booleanTermConverter == NULL) {
2855 // This needs to be initialized _after_ the whole SMT framework is in place, subscribed
2856 // to ExprManager notifications, etc. Otherwise we might miss the "BooleanTerm" datatype
2857 // definition, and not dump it properly.
2858 d_booleanTermConverter = new BooleanTermConverter(d_smt);
2859 }
2860 Node retval = d_booleanTermConverter->rewriteBooleanTerms(n);
2861 if(retval != n) {
2862 switch(booleans::BooleanTermConversionMode mode = options::booleanTermConversionMode()) {
2863 case booleans::BOOLEAN_TERM_CONVERT_TO_BITVECTORS:
2864 case booleans::BOOLEAN_TERM_CONVERT_NATIVE:
2865 if(!d_smt.d_logic.isTheoryEnabled(THEORY_BV)) {
2866 d_smt.d_logic = d_smt.d_logic.getUnlockedCopy();
2867 d_smt.d_logic.enableTheory(THEORY_BV);
2868 d_smt.d_logic.lock();
2869 }
2870 break;
2871 case booleans::BOOLEAN_TERM_CONVERT_TO_DATATYPES:
2872 if(!d_smt.d_logic.isTheoryEnabled(THEORY_DATATYPES)) {
2873 d_smt.d_logic = d_smt.d_logic.getUnlockedCopy();
2874 d_smt.d_logic.enableTheory(THEORY_DATATYPES);
2875 d_smt.d_logic.lock();
2876 }
2877 break;
2878 default:
2879 Unhandled(mode);
2880 }
2881 }
2882 return retval;
2883 }
2884
2885 void SmtEnginePrivate::processAssertions() {
2886 TimerStat::CodeTimer paTimer(d_smt.d_stats->d_processAssertionsTime);
2887
2888 Assert(d_smt.d_fullyInited);
2889 Assert(d_smt.d_pendingPops == 0);
2890
2891 // Dump the assertions
2892 dumpAssertions("pre-everything", d_assertions);
2893
2894 Trace("smt") << "SmtEnginePrivate::processAssertions()" << endl;
2895
2896 Debug("smt") << " d_assertions : " << d_assertions.size() << endl;
2897
2898 if (d_assertions.size() == 0) {
2899 // nothing to do
2900 return;
2901 }
2902
2903 if (d_assertionsProcessed && options::incrementalSolving()) {
2904 // Placeholder for storing substitutions
2905 d_substitutionsIndex = d_assertions.size();
2906 d_assertions.push_back(NodeManager::currentNM()->mkConst<bool>(true));
2907 }
2908
2909 // Add dummy assertion in last position - to be used as a
2910 // placeholder for any new assertions to get added
2911 d_assertions.push_back(NodeManager::currentNM()->mkConst<bool>(true));
2912 // any assertions added beyond realAssertionsEnd must NOT affect the
2913 // equisatisfiability
2914 d_realAssertionsEnd = d_assertions.size();
2915
2916 // Assertions are NOT guaranteed to be rewritten by this point
2917
2918 dumpAssertions("pre-definition-expansion", d_assertions);
2919 {
2920 Chat() << "expanding definitions..." << endl;
2921 Trace("simplify") << "SmtEnginePrivate::simplify(): expanding definitions" << endl;
2922 TimerStat::CodeTimer codeTimer(d_smt.d_stats->d_definitionExpansionTime);
2923 hash_map<Node, Node, NodeHashFunction> cache;
2924 for(unsigned i = 0; i < d_assertions.size(); ++ i) {
2925 d_assertions.replace(i, expandDefinitions(d_assertions[i], cache));
2926 }
2927 }
2928 dumpAssertions("post-definition-expansion", d_assertions);
2929
2930 Debug("smt") << " d_assertions : " << d_assertions.size() << endl;
2931
2932 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER &&
2933 !d_smt.d_logic.isPure(THEORY_BV)) {
2934 throw ModalException("Eager bit-blasting does not currently support theory combination. "
2935 "Note that in a QF_BV problem UF symbols can be introduced for division. "
2936 "Try --bv-div-zero-const to interpret division by zero as a constant.");
2937 }
2938
2939 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER) {
2940 d_smt.d_theoryEngine->mkAckermanizationAsssertions(d_assertions.ref());
2941 }
2942
2943 if ( options::bvAbstraction() &&
2944 !options::incrementalSolving()) {
2945 dumpAssertions("pre-bv-abstraction", d_assertions);
2946 bvAbstraction();
2947 dumpAssertions("post-bv-abstraction", d_assertions);
2948 }
2949
2950 dumpAssertions("pre-boolean-terms", d_assertions);
2951 {
2952 Chat() << "rewriting Boolean terms..." << endl;
2953 for(unsigned i = 0, i_end = d_assertions.size(); i != i_end; ++i) {
2954 d_assertions.replace(i, rewriteBooleanTerms(d_assertions[i]));
2955 }
2956 }
2957 dumpAssertions("post-boolean-terms", d_assertions);
2958
2959 Debug("smt") << " d_assertions : " << d_assertions.size() << endl;
2960
2961 dumpAssertions("pre-constrain-subtypes", d_assertions);
2962 {
2963 // Any variables of subtype types need to be constrained properly.
2964 // Careful, here: constrainSubtypes() adds to the back of
2965 // d_assertions, but we don't need to reprocess those.
2966 // We also can't use an iterator, because the vector may be moved in
2967 // memory during this loop.
2968 Chat() << "constraining subtypes..." << endl;
2969 for(unsigned i = 0, i_end = d_assertions.size(); i != i_end; ++i) {
2970 constrainSubtypes(d_assertions[i], d_assertions);
2971 }
2972 }
2973 dumpAssertions("post-constrain-subtypes", d_assertions);
2974
2975 Debug("smt") << " d_assertions : " << d_assertions.size() << endl;
2976
2977 bool noConflict = true;
2978
2979 // Unconstrained simplification
2980 if(options::unconstrainedSimp()) {
2981 dumpAssertions("pre-unconstrained-simp", d_assertions);
2982 Chat() << "...doing unconstrained simplification..." << endl;
2983 unconstrainedSimp();
2984 dumpAssertions("post-unconstrained-simp", d_assertions);
2985 }
2986
2987 if(options::bvIntroducePow2()){
2988 theory::bv::BVIntroducePow2::pow2Rewrite(d_assertions.ref());
2989 }
2990
2991 dumpAssertions("pre-substitution", d_assertions);
2992
2993 if(options::unsatCores()) {
2994 // special rewriting pass for unsat cores, since many of the passes below are skipped
2995 for (unsigned i = 0; i < d_assertions.size(); ++ i) {
2996 d_assertions.replace(i, Rewriter::rewrite(d_assertions[i]));
2997 }
2998 } else {
2999 // Apply the substitutions we already have, and normalize
3000 if(!options::unsatCores()) {
3001 Chat() << "applying substitutions..." << endl;
3002 Trace("simplify") << "SmtEnginePrivate::nonClausalSimplify(): "
3003 << "applying substitutions" << endl;
3004 for (unsigned i = 0; i < d_assertions.size(); ++ i) {
3005 Trace("simplify") << "applying to " << d_assertions[i] << endl;
3006 d_assertions.replace(i, Rewriter::rewrite(d_topLevelSubstitutions.apply(d_assertions[i])));
3007 Trace("simplify") << " got " << d_assertions[i] << endl;
3008 }
3009 }
3010 }
3011
3012 dumpAssertions("post-substitution", d_assertions);
3013
3014 // Assertions ARE guaranteed to be rewritten by this point
3015
3016 // Lift bit-vectors of size 1 to bool
3017 if(options::bitvectorToBool()) {
3018 dumpAssertions("pre-bv-to-bool", d_assertions);
3019 Chat() << "...doing bvToBool..." << endl;
3020 bvToBool();
3021 dumpAssertions("post-bv-to-bool", d_assertions);
3022 }
3023
3024 if( d_smt.d_logic.isTheoryEnabled(THEORY_STRINGS) ) {
3025 dumpAssertions("pre-strings-pp", d_assertions);
3026 CVC4::theory::strings::StringsPreprocess sp;
3027 std::vector<Node> newNodes;
3028 newNodes.push_back(d_assertions[d_realAssertionsEnd - 1]);
3029 sp.simplify( d_assertions.ref(), newNodes );
3030 if(newNodes.size() > 1) {
3031 d_assertions[d_realAssertionsEnd - 1] = NodeManager::currentNM()->mkNode(kind::AND, newNodes);
3032 }
3033 for (unsigned i = 0; i < d_assertions.size(); ++ i) {
3034 d_assertions[i] = Rewriter::rewrite( d_assertions[i] );
3035 }
3036 dumpAssertions("post-strings-pp", d_assertions);
3037 }
3038 if( d_smt.d_logic.isQuantified() ){
3039 //remove rewrite rules
3040 for( unsigned i=0; i < d_assertions.size(); i++ ) {
3041 if( d_assertions[i].getKind() == kind::REWRITE_RULE ){
3042 Node prev = d_assertions[i];
3043 Trace("quantifiers-rewrite-debug") << "Rewrite rewrite rule " << prev << "..." << std::endl;
3044 d_assertions[i] = Rewriter::rewrite( quantifiers::QuantifiersRewriter::rewriteRewriteRule( d_assertions[i] ) );
3045 Trace("quantifiers-rewrite") << "*** rr-rewrite " << prev << endl;
3046 Trace("quantifiers-rewrite") << " ...got " << d_assertions[i] << endl;
3047 }
3048 }
3049
3050 dumpAssertions("pre-skolem-quant", d_assertions);
3051 if( options::preSkolemQuant() ){
3052 //apply pre-skolemization to existential quantifiers
3053 for (unsigned i = 0; i < d_assertions.size(); ++ i) {
3054 Node prev = d_assertions[i];
3055 Trace("quantifiers-rewrite-debug") << "Pre-skolemize " << prev << "..." << std::endl;
3056 vector< TypeNode > fvTypes;
3057 vector< TNode > fvs;
3058 d_assertions.replace(i, quantifiers::QuantifiersRewriter::preSkolemizeQuantifiers( prev, true, fvTypes, fvs ));
3059 if( prev!=d_assertions[i] ){
3060 d_assertions.replace(i, Rewriter::rewrite( d_assertions[i] ));
3061 Trace("quantifiers-rewrite") << "*** Pre-skolemize " << prev << endl;
3062 Trace("quantifiers-rewrite") << " ...got " << d_assertions[i] << endl;
3063 }
3064 }
3065 }
3066 dumpAssertions("post-skolem-quant", d_assertions);
3067 if( options::macrosQuant() ){
3068 //quantifiers macro expansion
3069 bool success;
3070 do{
3071 quantifiers::QuantifierMacros qm;
3072 success = qm.simplify( d_assertions.ref(), true );
3073 }while( success );
3074 }
3075
3076 Trace("fo-rsn-enable") << std::endl;
3077 if( options::foPropQuant() ){
3078 quantifiers::FirstOrderPropagation fop;
3079 fop.simplify( d_assertions.ref() );
3080 }
3081 }
3082
3083 if( options::sortInference() ){
3084 //sort inference technique
3085 SortInference * si = d_smt.d_theoryEngine->getSortInference();
3086 si->simplify( d_assertions.ref() );
3087 for( std::map< Node, Node >::iterator it = si->d_model_replace_f.begin(); it != si->d_model_replace_f.end(); ++it ){
3088 d_smt.setPrintFuncInModel( it->first.toExpr(), false );
3089 d_smt.setPrintFuncInModel( it->second.toExpr(), true );
3090 }
3091 }
3092
3093 //if( options::quantConflictFind() ){
3094 // d_smt.d_theoryEngine->getQuantConflictFind()->registerAssertions( d_assertions );
3095 //}
3096
3097 if( options::pbRewrites() ){
3098 d_pbsProcessor.learn(d_assertions.ref());
3099 if(d_pbsProcessor.likelyToHelp()){
3100 d_pbsProcessor.applyReplacements(d_assertions.ref());
3101 }
3102 }
3103
3104 dumpAssertions("pre-simplify", d_assertions);
3105 Chat() << "simplifying assertions..." << endl;
3106 noConflict = simplifyAssertions();
3107 if(!noConflict){
3108 ++(d_smt.d_stats->d_simplifiedToFalse);
3109 }
3110 dumpAssertions("post-simplify", d_assertions);
3111
3112 dumpAssertions("pre-static-learning", d_assertions);
3113 if(options::doStaticLearning()) {
3114 // Perform static learning
3115 Chat() << "doing static learning..." << endl;
3116 Trace("simplify") << "SmtEnginePrivate::simplify(): "
3117 << "performing static learning" << endl;
3118 staticLearning();
3119 }
3120 dumpAssertions("post-static-learning", d_assertions);
3121
3122 Trace("smt") << "POST bvToBool" << endl;
3123 Debug("smt") << " d_assertions : " << d_assertions.size() << endl;
3124
3125
3126 dumpAssertions("pre-ite-removal", d_assertions);
3127 {
3128 Chat() << "removing term ITEs..." << endl;
3129 TimerStat::CodeTimer codeTimer(d_smt.d_stats->d_iteRemovalTime);
3130 // Remove ITEs, updating d_iteSkolemMap
3131 d_smt.d_stats->d_numAssertionsPre += d_assertions.size();
3132 removeITEs();
3133 d_smt.d_stats->d_numAssertionsPost += d_assertions.size();
3134 }
3135 dumpAssertions("post-ite-removal", d_assertions);
3136
3137 dumpAssertions("pre-repeat-simplify", d_assertions);
3138 if(options::repeatSimp()) {
3139 Chat() << "re-simplifying assertions..." << endl;
3140 ScopeCounter depth(d_simplifyAssertionsDepth);
3141 noConflict &= simplifyAssertions();
3142 if (noConflict) {
3143 // Need to fix up assertion list to maintain invariants:
3144 // Let Sk be the set of Skolem variables introduced by ITE's. Let <_sk be the order in which these variables were introduced
3145 // during ite removal.
3146 // For each skolem variable sk, let iteExpr = iteMap(sk) be the ite expr mapped to by sk.
3147
3148 // cache for expression traversal
3149 hash_map<Node, bool, NodeHashFunction> cache;
3150
3151 // First, find all skolems that appear in the substitution map - their associated iteExpr will need
3152 // to be moved to the main assertion set
3153 set<TNode> skolemSet;
3154 SubstitutionMap::iterator pos = d_topLevelSubstitutions.begin();
3155 for (; pos != d_topLevelSubstitutions.end(); ++pos) {
3156 collectSkolems((*pos).first, skolemSet, cache);
3157 collectSkolems((*pos).second, skolemSet, cache);
3158 }
3159
3160 // We need to ensure:
3161 // 1. iteExpr has the form (ite cond (sk = t) (sk = e))
3162 // 2. if some sk' in Sk appears in cond, t, or e, then sk' <_sk sk
3163 // If either of these is violated, we must add iteExpr as a proper assertion
3164 IteSkolemMap::iterator it = d_iteSkolemMap.begin();
3165 IteSkolemMap::iterator iend = d_iteSkolemMap.end();
3166 NodeBuilder<> builder(kind::AND);
3167 builder << d_assertions[d_realAssertionsEnd - 1];
3168 vector<TNode> toErase;
3169 for (; it != iend; ++it) {
3170 if (skolemSet.find((*it).first) == skolemSet.end()) {
3171 TNode iteExpr = d_assertions[(*it).second];
3172 if (iteExpr.getKind() == kind::ITE &&
3173 iteExpr[1].getKind() == kind::EQUAL &&
3174 iteExpr[1][0] == (*it).first &&
3175 iteExpr[2].getKind() == kind::EQUAL &&
3176 iteExpr[2][0] == (*it).first) {
3177 cache.clear();
3178 bool bad = checkForBadSkolems(iteExpr[0], (*it).first, cache);
3179 bad = bad || checkForBadSkolems(iteExpr[1][1], (*it).first, cache);
3180 bad = bad || checkForBadSkolems(iteExpr[2][1], (*it).first, cache);
3181 if (!bad) {
3182 continue;
3183 }
3184 }
3185 }
3186 // Move this iteExpr into the main assertions
3187 builder << d_assertions[(*it).second];
3188 d_assertions[(*it).second] = NodeManager::currentNM()->mkConst<bool>(true);
3189 toErase.push_back((*it).first);
3190 }
3191 if(builder.getNumChildren() > 1) {
3192 while (!toErase.empty()) {
3193 d_iteSkolemMap.erase(toErase.back());
3194 toErase.pop_back();
3195 }
3196 d_assertions[d_realAssertionsEnd - 1] =
3197 Rewriter::rewrite(Node(builder));
3198 }
3199 // For some reason this is needed for some benchmarks, such as
3200 // http://cvc4.cs.nyu.edu/benchmarks/smtlib2/QF_AUFBV/dwp_formulas/try5_small_difret_functions_dwp_tac.re_node_set_remove_at.il.dwp.smt2
3201 // Figure it out later
3202 removeITEs();
3203 // Assert(iteRewriteAssertionsEnd == d_assertions.size());
3204 }
3205 }
3206 dumpAssertions("post-repeat-simplify", d_assertions);
3207
3208 dumpAssertions("pre-rewrite-apply-to-const", d_assertions);
3209 if(options::rewriteApplyToConst()) {
3210 Chat() << "Rewriting applies to constants..." << endl;
3211 TimerStat::CodeTimer codeTimer(d_smt.d_stats->d_rewriteApplyToConstTime);
3212 for (unsigned i = 0; i < d_assertions.size(); ++ i) {
3213 d_assertions[i] = Rewriter::rewrite(rewriteApplyToConst(d_assertions[i]));
3214 }
3215 }
3216 dumpAssertions("post-rewrite-apply-to-const", d_assertions);
3217
3218 // begin: INVARIANT to maintain: no reordering of assertions or
3219 // introducing new ones
3220 #ifdef CVC4_ASSERTIONS
3221 unsigned iteRewriteAssertionsEnd = d_assertions.size();
3222 #endif
3223
3224 Debug("smt") << " d_assertions : " << d_assertions.size() << endl;
3225
3226 Debug("smt") << "SmtEnginePrivate::processAssertions() POST SIMPLIFICATION" << endl;
3227 Debug("smt") << " d_assertions : " << d_assertions.size() << endl;
3228
3229 dumpAssertions("pre-theory-preprocessing", d_assertions);
3230 {
3231 Chat() << "theory preprocessing..." << endl;
3232 TimerStat::CodeTimer codeTimer(d_smt.d_stats->d_theoryPreprocessTime);
3233 // Call the theory preprocessors
3234 d_smt.d_theoryEngine->preprocessStart();
3235 for (unsigned i = 0; i < d_assertions.size(); ++ i) {
3236 d_assertions.replace(i, d_smt.d_theoryEngine->preprocess(d_assertions[i]));
3237 }
3238 }
3239 dumpAssertions("post-theory-preprocessing", d_assertions);
3240
3241 // If we are using eager bit-blasting wrap assertions in fake atom so that
3242 // everything gets bit-blasted to internal SAT solver
3243 if (options::bitblastMode() == theory::bv::BITBLAST_MODE_EAGER) {
3244 for (unsigned i = 0; i < d_assertions.size(); ++i) {
3245 TNode atom = d_assertions[i];
3246 Node eager_atom = NodeManager::currentNM()->mkNode(kind::BITVECTOR_EAGER_ATOM, atom);
3247 d_assertions.replace(i, eager_atom);
3248 TheoryModel* m = d_smt.d_theoryEngine->getModel();
3249 m->addSubstitution(eager_atom, atom);
3250 }
3251 }
3252
3253 // Push the formula to decision engine
3254 if(noConflict) {
3255 Chat() << "pushing to decision engine..." << endl;
3256 Assert(iteRewriteAssertionsEnd == d_assertions.size());
3257 d_smt.d_decisionEngine->addAssertions
3258 (d_assertions.ref(), d_realAssertionsEnd, d_iteSkolemMap);
3259 }
3260
3261 // end: INVARIANT to maintain: no reordering of assertions or
3262 // introducing new ones
3263
3264 dumpAssertions("post-everything", d_assertions);
3265
3266 //set instantiation level of everything to zero
3267 if( options::instLevelInputOnly() && options::instMaxLevel()!=-1 ){
3268 for( unsigned i=0; i < d_assertions.size(); i++ ) {
3269 theory::QuantifiersEngine::setInstantiationLevelAttr( d_assertions[i], 0 );
3270 }
3271 }
3272
3273 // Push the formula to SAT
3274 {
3275 Chat() << "converting to CNF..." << endl;
3276 TimerStat::CodeTimer codeTimer(d_smt.d_stats->d_cnfConversionTime);
3277 for (unsigned i = 0; i < d_assertions.size(); ++ i) {
3278 Chat() << "+ " << d_assertions[i] << std::endl;
3279 d_smt.d_propEngine->assertFormula(d_assertions[i]);
3280 }
3281 }
3282
3283 d_assertionsProcessed = true;
3284
3285 d_assertions.clear();
3286 d_iteSkolemMap.clear();
3287 }
3288
3289 void SmtEnginePrivate::addFormula(TNode n)
3290 throw(TypeCheckingException, LogicException) {
3291
3292 if (n == d_true) {
3293 // nothing to do
3294 return;
3295 }
3296
3297 Trace("smt") << "SmtEnginePrivate::addFormula(" << n << ")" << endl;
3298
3299 // Add the normalized formula to the queue
3300 d_assertions.push_back(n);
3301 //d_assertions.push_back(Rewriter::rewrite(n));
3302 }
3303
3304 void SmtEngine::ensureBoolean(const Expr& e) throw(TypeCheckingException) {
3305 Type type = e.getType(options::typeChecking());
3306 Type boolType = d_exprManager->booleanType();
3307 if(type != boolType) {
3308 stringstream ss;
3309 ss << "Expected " << boolType << "\n"
3310 << "The assertion : " << e << "\n"
3311 << "Its type : " << type;
3312 throw TypeCheckingException(e, ss.str());
3313 }
3314 }
3315
3316 Result SmtEngine::checkSat(const Expr& ex, bool inUnsatCore) throw(TypeCheckingException, ModalException, LogicException) {
3317 Assert(ex.isNull() || ex.getExprManager() == d_exprManager);
3318 SmtScope smts(this);
3319 finalOptionsAreSet();
3320 doPendingPops();
3321
3322 Trace("smt") << "SmtEngine::checkSat(" << ex << ")" << endl;
3323
3324 if(d_queryMade && !options::incrementalSolving()) {
3325 throw ModalException("Cannot make multiple queries unless "
3326 "incremental solving is enabled "
3327 "(try --incremental)");
3328 }
3329
3330 Expr e;
3331 if(!ex.isNull()) {
3332 // Substitute out any abstract values in ex.
3333 e = d_private->substituteAbstractValues(Node::fromExpr(ex)).toExpr();
3334 // Ensure expr is type-checked at this point.
3335 ensureBoolean(e);
3336 // Give it to proof manager
3337 PROOF( ProofManager::currentPM()->addAssertion(e, inUnsatCore); );
3338 }
3339
3340 // check to see if a postsolve() is pending
3341 if(d_needPostsolve) {
3342 d_theoryEngine->postsolve();
3343 d_needPostsolve = false;
3344 }
3345
3346 // Push the context
3347 internalPush();
3348
3349 // Note that a query has been made
3350 d_queryMade = true;
3351
3352 // Add the formula
3353 if(!e.isNull()) {
3354 d_problemExtended = true;
3355 if(d_assertionList != NULL) {
3356 d_assertionList->push_back(e);
3357 }
3358 d_private->addFormula(e.getNode());
3359 }
3360
3361 // Run the check
3362 Result r = check().asSatisfiabilityResult();
3363 d_needPostsolve = true;
3364
3365 // Dump the query if requested
3366 if(Dump.isOn("benchmark")) {
3367 // the expr already got dumped out if assertion-dumping is on
3368 Dump("benchmark") << CheckSatCommand();
3369 }
3370
3371 // Pop the context
3372 internalPop();
3373
3374 // Remember the status
3375 d_status = r;
3376
3377 d_problemExtended = false;
3378
3379 Trace("smt") << "SmtEngine::checkSat(" << e << ") => " << r << endl;
3380
3381 // Check that SAT results generate a model correctly.
3382 if(options::checkModels()) {
3383 if(r.asSatisfiabilityResult().isSat() == Result::SAT ||
3384 (r.isUnknown() && r.whyUnknown() == Result::INCOMPLETE) ){
3385 checkModel(/* hard failure iff */ ! r.isUnknown());
3386 }
3387 }
3388 // Check that UNSAT results generate a proof correctly.
3389 if(options::checkProofs()) {
3390 if(r.asSatisfiabilityResult().isSat() == Result::UNSAT) {
3391 TimerStat::CodeTimer checkProofTimer(d_stats->d_checkProofTime);
3392 checkProof();
3393 }
3394 }
3395
3396 return r;
3397 }/* SmtEngine::checkSat() */
3398
3399 Result SmtEngine::query(const Expr& ex, bool inUnsatCore) throw(TypeCheckingException, ModalException, LogicException) {
3400 Assert(!ex.isNull());
3401 Assert(ex.getExprManager() == d_exprManager);
3402 SmtScope smts(this);
3403 finalOptionsAreSet();
3404 doPendingPops();
3405 Trace("smt") << "SMT query(" << ex << ")" << endl;
3406
3407 if(d_queryMade && !options::incrementalSolving()) {
3408 throw ModalException("Cannot make multiple queries unless "
3409 "incremental solving is enabled "
3410 "(try --incremental)");
3411 }
3412
3413 // Substitute out any abstract values in ex
3414 Expr e = d_private->substituteAbstractValues(Node::fromExpr(ex)).toExpr();
3415 // Ensure that the expression is type-checked at this point, and Boolean
3416 ensureBoolean(e);
3417 // Give it to proof manager
3418 PROOF( ProofManager::currentPM()->addAssertion(e.notExpr(), inUnsatCore); );
3419
3420 // check to see if a postsolve() is pending
3421 if(d_needPostsolve) {
3422 d_theoryEngine->postsolve();
3423 d_needPostsolve = false;
3424 }
3425
3426 // Push the context
3427 internalPush();
3428
3429 // Note that a query has been made
3430 d_queryMade = true;
3431
3432 // Add the formula
3433 d_problemExtended = true;
3434 if(d_assertionList != NULL) {
3435 d_assertionList->push_back(e.notExpr());
3436 }
3437 d_private->addFormula(e.getNode().notNode());
3438
3439 // Run the check
3440 Result r = check().asValidityResult();
3441 d_needPostsolve = true;
3442
3443 // Dump the query if requested
3444 if(Dump.isOn("benchmark")) {
3445 // the expr already got dumped out if assertion-dumping is on
3446 Dump("benchmark") << CheckSatCommand();
3447 }
3448
3449 // Pop the context
3450 internalPop();
3451
3452 // Remember the status
3453 d_status = r;
3454
3455 d_problemExtended = false;
3456
3457 Trace("smt") << "SMT query(" << e << ") ==> " << r << endl;
3458
3459 // Check that SAT results generate a model correctly.
3460 if(options::checkModels()) {
3461 if(r.asSatisfiabilityResult().isSat() == Result::SAT ||
3462 (r.isUnknown() && r.whyUnknown() == Result::INCOMPLETE) ){
3463 checkModel(/* hard failure iff */ ! r.isUnknown());
3464 }
3465 }
3466 // Check that UNSAT results generate a proof correctly.
3467 if(options::checkProofs()) {
3468 if(r.asSatisfiabilityResult().isSat() == Result::UNSAT) {
3469 TimerStat::CodeTimer checkProofTimer(d_stats->d_checkProofTime);
3470 checkProof();
3471 }
3472 }
3473
3474 return r;
3475 }/* SmtEngine::query() */
3476
3477 Result SmtEngine::assertFormula(const Expr& ex, bool inUnsatCore) throw(TypeCheckingException, LogicException) {
3478 Assert(ex.getExprManager() == d_exprManager);
3479 SmtScope smts(this);
3480 finalOptionsAreSet();
3481 doPendingPops();
3482
3483 PROOF( ProofManager::currentPM()->addAssertion(ex, inUnsatCore); );
3484
3485 Trace("smt") << "SmtEngine::assertFormula(" << ex << ")" << endl;
3486
3487 // Substitute out any abstract values in ex
3488 Expr e = d_private->substituteAbstractValues(Node::fromExpr(ex)).toExpr();
3489
3490 ensureBoolean(e);
3491 if(d_assertionList != NULL) {
3492 d_assertionList->push_back(e);
3493 }
3494 d_private->addFormula(e.getNode());
3495 return quickCheck().asValidityResult();
3496 }/* SmtEngine::assertFormula() */
3497
3498 Node SmtEngine::postprocess(TNode node, TypeNode expectedType) const {
3499 ModelPostprocessor mpost;
3500 NodeVisitor<ModelPostprocessor> visitor;
3501 Node value = visitor.run(mpost, node);
3502 Debug("boolean-terms") << "postproc: got " << value << " expect type " << expectedType << endl;
3503 Node realValue = mpost.rewriteAs(value, expectedType);
3504 Debug("boolean-terms") << "postproc: realval " << realValue << " expect type " << expectedType << endl;
3505 return realValue;
3506 }
3507
3508 Expr SmtEngine::simplify(const Expr& ex) throw(TypeCheckingException, LogicException) {
3509 Assert(ex.getExprManager() == d_exprManager);
3510 SmtScope smts(this);
3511 finalOptionsAreSet();
3512 doPendingPops();
3513 Trace("smt") << "SMT simplify(" << ex << ")" << endl;
3514
3515 if(Dump.isOn("benchmark")) {
3516 Dump("benchmark") << SimplifyCommand(ex);
3517 }
3518
3519 Expr e = d_private->substituteAbstractValues(Node::fromExpr(ex)).toExpr();
3520 if( options::typeChecking() ) {
3521 e.getType(true); // ensure expr is type-checked at this point
3522 }
3523
3524 // Make sure all preprocessing is done
3525 d_private->processAssertions();
3526 Node n = d_private->simplify(Node::fromExpr(e));
3527 n = postprocess(n, TypeNode::fromType(e.getType()));
3528 return n.toExpr();
3529 }
3530
3531 Expr SmtEngine::expandDefinitions(const Expr& ex) throw(TypeCheckingException, LogicException) {
3532 Assert(ex.getExprManager() == d_exprManager);
3533 SmtScope smts(this);
3534 finalOptionsAreSet();
3535 doPendingPops();
3536 Trace("smt") << "SMT expandDefinitions(" << ex << ")" << endl;
3537
3538 // Substitute out any abstract values in ex.
3539 Expr e = d_private->substituteAbstractValues(Node::fromExpr(ex)).toExpr();
3540 if(options::typeChecking()) {
3541 // Ensure expr is type-checked at this point.
3542 e.getType(true);
3543 }
3544 if(Dump.isOn("benchmark")) {
3545 Dump("benchmark") << ExpandDefinitionsCommand(e);
3546 }
3547 hash_map<Node, Node, NodeHashFunction> cache;
3548 Node n = d_private->expandDefinitions(Node::fromExpr(e), cache, /* expandOnly = */ true);
3549 n = postprocess(n, TypeNode::fromType(e.getType()));
3550
3551 return n.toExpr();
3552 }
3553
3554 Expr SmtEngine::getValue(const Expr& ex) const throw(ModalException, TypeCheckingException, LogicException) {
3555 Assert(ex.getExprManager() == d_exprManager);
3556 SmtScope smts(this);
3557
3558 Trace("smt") << "SMT getValue(" << ex << ")" << endl;
3559 if(Dump.isOn("benchmark")) {
3560 Dump("benchmark") << GetValueCommand(ex);
3561 }
3562
3563 if(!options::produceModels()) {
3564 const char* msg =
3565 "Cannot get value when produce-models options is off.";
3566 throw ModalException(msg);
3567 }
3568 if(d_status.isNull() ||
3569 d_status.asSatisfiabilityResult() == Result::UNSAT ||
3570 d_problemExtended) {
3571 const char* msg =
3572 "Cannot get value unless immediately preceded by SAT/INVALID or UNKNOWN response.";
3573 throw ModalException(msg);
3574 }
3575
3576 // Substitute out any abstract values in ex.
3577 Expr e = d_private->substituteAbstractValues(Node::fromExpr(ex)).toExpr();
3578
3579 // Ensure expr is type-checked at this point.
3580 e.getType(options::typeChecking());
3581
3582 // do not need to apply preprocessing substitutions (should be recorded
3583 // in model already)
3584
3585 Node n = Node::fromExpr(e);
3586 Trace("smt") << "--- getting value of " << n << endl;
3587 TypeNode expectedType = n.getType();
3588
3589 // Expand, then normalize
3590 hash_map<Node, Node, NodeHashFunction> cache;
3591 n = d_private->expandDefinitions(n, cache);
3592 // There are two ways model values for terms are computed (for historical
3593 // reasons). One way is that used in check-model; the other is that
3594 // used by the Model classes. It's not clear to me exactly how these
3595 // two are different, but they need to be unified. This ugly hack here
3596 // is to fix bug 554 until we can revamp boolean-terms and models [MGD]
3597 if(!n.getType().isFunction()) {
3598 n = d_private->rewriteBooleanTerms(n);
3599 n = Rewriter::rewrite(n);
3600 }
3601
3602 Trace("smt") << "--- getting value of " << n << endl;
3603 TheoryModel* m = d_theoryEngine->getModel();
3604 Node resultNode;
3605 if(m != NULL) {
3606 resultNode = m->getValue(n);
3607 }
3608 Trace("smt") << "--- got value " << n << " = " << resultNode << endl;
3609 resultNode = postprocess(resultNode, expectedType);
3610 Trace("smt") << "--- model-post returned " << resultNode << endl;
3611 Trace("smt") << "--- model-post returned " << resultNode.getType() << endl;
3612 Trace("smt") << "--- model-post expected " << expectedType << endl;
3613
3614 // type-check the result we got
3615 Assert(resultNode.isNull() || resultNode.getType().isSubtypeOf(expectedType),
3616 "Run with -t smt for details.");
3617
3618 // ensure it's a constant
3619 Assert(resultNode.getKind() == kind::LAMBDA || resultNode.isConst());
3620
3621 if(options::abstractValues() && resultNode.getType().isArray()) {
3622 resultNode = d_private->mkAbstractValue(resultNode);
3623 }
3624
3625 return resultNode.toExpr();
3626 }
3627
3628 bool SmtEngine::addToAssignment(const Expr& ex) throw() {
3629 SmtScope smts(this);
3630 finalOptionsAreSet();
3631 doPendingPops();
3632 // Substitute out any abstract values in ex
3633 Expr e = d_private->substituteAbstractValues(Node::fromExpr(ex)).toExpr();
3634 Type type = e.getType(options::typeChecking());
3635 // must be Boolean
3636 CheckArgument( type.isBoolean(), e,
3637 "expected Boolean-typed variable or function application "
3638 "in addToAssignment()" );
3639 Node n = e.getNode();
3640 // must be an APPLY of a zero-ary defined function, or a variable
3641 CheckArgument( ( ( n.getKind() == kind::APPLY &&
3642 ( d_definedFunctions->find(n.getOperator()) !=
3643 d_definedFunctions->end() ) &&
3644 n.getNumChildren() == 0 ) ||
3645 n.isVar() ), e,
3646 "expected variable or defined-function application "
3647 "in addToAssignment(),\ngot %s", e.toString().c_str() );
3648 if(!options::produceAssignments()) {
3649 return false;
3650 }
3651 if(d_assignments == NULL) {
3652 d_assignments = new(true) AssignmentSet(d_context);
3653 }
3654 d_assignments->insert(n);
3655
3656 return true;
3657 }
3658
3659 CVC4::SExpr SmtEngine::getAssignment() throw(ModalException) {
3660 Trace("smt") << "SMT getAssignment()" << endl;
3661 SmtScope smts(this);
3662 finalOptionsAreSet();
3663 if(Dump.isOn("benchmark")) {
3664 Dump("benchmark") << GetAssignmentCommand();
3665 }
3666 if(!options::produceAssignments()) {
3667 const char* msg =
3668 "Cannot get the current assignment when "
3669 "produce-assignments option is off.";
3670 throw ModalException(msg);
3671 }
3672 if(d_status.isNull() ||
3673 d_status.asSatisfiabilityResult() == Result::UNSAT ||
3674 d_problemExtended) {
3675 const char* msg =
3676 "Cannot get the current assignment unless immediately "
3677 "preceded by SAT/INVALID or UNKNOWN response.";
3678 throw ModalException(msg);
3679 }
3680
3681 if(d_assignments == NULL) {
3682 return SExpr(vector<SExpr>());
3683 }
3684
3685 vector<SExpr> sexprs;
3686 TypeNode boolType = d_nodeManager->booleanType();
3687 TheoryModel* m = d_theoryEngine->getModel();
3688 for(AssignmentSet::const_iterator i = d_assignments->begin(),
3689 iend = d_assignments->end();
3690 i != iend;
3691 ++i) {
3692 Assert((*i).getType() == boolType);
3693
3694 Trace("smt") << "--- getting value of " << *i << endl;
3695
3696 // Expand, then normalize
3697 hash_map<Node, Node, NodeHashFunction> cache;
3698 Node n = d_private->expandDefinitions(*i, cache);
3699 n = d_private->rewriteBooleanTerms(n);
3700 n = Rewriter::rewrite(n);
3701
3702 Trace("smt") << "--- getting value of " << n << endl;
3703 Node resultNode;
3704 if(m != NULL) {
3705 resultNode = m->getValue(n);
3706 }
3707
3708 // type-check the result we got
3709 Assert(resultNode.isNull() || resultNode.getType() == boolType);
3710
3711 // ensure it's a constant
3712 Assert(resultNode.isConst());
3713
3714 vector<SExpr> v;
3715 if((*i).getKind() == kind::APPLY) {
3716 Assert((*i).getNumChildren() == 0);
3717 v.push_back(SExpr::Keyword((*i).getOperator().toString()));
3718 } else {
3719 Assert((*i).isVar());
3720 v.push_back(SExpr::Keyword((*i).toString()));
3721 }
3722 v.push_back(SExpr::Keyword(resultNode.toString()));
3723 sexprs.push_back(v);
3724 }
3725 return SExpr(sexprs);
3726 }
3727
3728 void SmtEngine::addToModelCommandAndDump(const Command& c, uint32_t flags, bool userVisible, const char* dumpTag) {
3729 Trace("smt") << "SMT addToModelCommandAndDump(" << c << ")" << endl;
3730 SmtScope smts(this);
3731 // If we aren't yet fully inited, the user might still turn on
3732 // produce-models. So let's keep any commands around just in
3733 // case. This is useful in two cases: (1) SMT-LIBv1 auto-declares
3734 // sort "U" in QF_UF before setLogic() is run and we still want to
3735 // support finding card(U) with --finite-model-find, and (2) to
3736 // decouple SmtEngine and ExprManager if the user does a few
3737 // ExprManager::mkSort() before SmtEngine::setOption("produce-models")
3738 // and expects to find their cardinalities in the model.
3739 if(/* userVisible && */
3740 (!d_fullyInited || options::produceModels()) &&
3741 (flags & ExprManager::VAR_FLAG_DEFINED) == 0) {
3742 doPendingPops();
3743 if(flags & ExprManager::VAR_FLAG_GLOBAL) {
3744 d_modelGlobalCommands.push_back(c.clone());
3745 } else {
3746 d_modelCommands->push_back(c.clone());
3747 }
3748 }
3749 if(Dump.isOn(dumpTag)) {
3750 if(d_fullyInited) {
3751 Dump(dumpTag) << c;
3752 } else {
3753 d_dumpCommands.push_back(c.clone());
3754 }
3755 }
3756 }
3757
3758 Model* SmtEngine::getModel() throw(ModalException) {
3759 Trace("smt") << "SMT getModel()" << endl;
3760 SmtScope smts(this);
3761
3762 finalOptionsAreSet();
3763
3764 if(Dump.isOn("benchmark")) {
3765 Dump("benchmark") << GetModelCommand();
3766 }
3767
3768 if(d_status.isNull() ||
3769 d_status.asSatisfiabilityResult() == Result::UNSAT ||
3770 d_problemExtended) {
3771 const char* msg =
3772 "Cannot get the current model unless immediately "
3773 "preceded by SAT/INVALID or UNKNOWN response.";
3774 throw ModalException(msg);
3775 }
3776 if(!options::produceModels()) {
3777 const char* msg =
3778 "Cannot get model when produce-models options is off.";
3779 throw ModalException(msg);
3780 }
3781 TheoryModel* m = d_theoryEngine->getModel();
3782 m->d_inputName = d_filename;
3783 return m;
3784 }
3785
3786 void SmtEngine::checkModel(bool hardFailure) {
3787 // --check-model implies --interactive, which enables the assertion list,
3788 // so we should be ok.
3789 Assert(d_assertionList != NULL, "don't have an assertion list to check in SmtEngine::checkModel()");
3790
3791 TimerStat::CodeTimer checkModelTimer(d_stats->d_checkModelTime);
3792
3793 // Throughout, we use Notice() to give diagnostic output.
3794 //
3795 // If this function is running, the user gave --check-model (or equivalent),
3796 // and if Notice() is on, the user gave --verbose (or equivalent).
3797
3798 Notice() << "SmtEngine::checkModel(): generating model" << endl;
3799 TheoryModel* m = d_theoryEngine->getModel();
3800
3801 // Check individual theory assertions
3802 d_theoryEngine->checkTheoryAssertionsWithModel();
3803
3804 // Output the model
3805 Notice() << *m;
3806
3807 // We have a "fake context" for the substitution map (we don't need it
3808 // to be context-dependent)
3809 context::Context fakeContext;
3810 SubstitutionMap substitutions(&fakeContext, /* substituteUnderQuantifiers = */ false);
3811
3812 for(size_t k = 0; k < m->getNumCommands(); ++k) {
3813 const DeclareFunctionCommand* c = dynamic_cast<const DeclareFunctionCommand*>(m->getCommand(k));
3814 Notice() << "SmtEngine::checkModel(): model command " << k << " : " << m->getCommand(k) << endl;
3815 if(c == NULL) {
3816 // we don't care about DECLARE-DATATYPES, DECLARE-SORT, ...
3817 Notice() << "SmtEngine::checkModel(): skipping..." << endl;
3818 } else {
3819 // We have a DECLARE-FUN:
3820 //
3821 // We'll first do some checks, then add to our substitution map
3822 // the mapping: function symbol |-> value
3823
3824 Expr func = c->getFunction();
3825 Node val = m->getValue(func);
3826
3827 Notice() << "SmtEngine::checkModel(): adding substitution: " << func << " |-> " << val << endl;
3828
3829 // (1) if the value is a lambda, ensure the lambda doesn't contain the
3830 // function symbol (since then the definition is recursive)
3831 if (val.getKind() == kind::LAMBDA) {
3832 // first apply the model substitutions we have so far
3833 Debug("boolean-terms") << "applying subses to " << val[1] << endl;
3834 Node n = substitutions.apply(val[1]);
3835 Debug("boolean-terms") << "++ got " << n << endl;
3836 // now check if n contains func by doing a substitution
3837 // [func->func2] and checking equality of the Nodes.
3838 // (this just a way to check if func is in n.)
3839 SubstitutionMap subs(&fakeContext);
3840 Node func2 = NodeManager::currentNM()->mkSkolem("", TypeNode::fromType(func.getType()), "", NodeManager::SKOLEM_NO_NOTIFY);
3841 subs.addSubstitution(func, func2);
3842 if(subs.apply(n) != n) {
3843 Notice() << "SmtEngine::checkModel(): *** PROBLEM: MODEL VALUE DEFINED IN TERMS OF ITSELF ***" << endl;
3844 stringstream ss;
3845 ss << "SmtEngine::checkModel(): ERRORS SATISFYING ASSERTIONS WITH MODEL:" << endl
3846 << "considering model value for " << func << endl
3847 << "body of lambda is: " << val << endl;
3848 if(n != val[1]) {
3849 ss << "body substitutes to: " << n << endl;
3850 }
3851 ss << "so " << func << " is defined in terms of itself." << endl
3852 << "Run with `--check-models -v' for additional diagnostics.";
3853 InternalError(ss.str());
3854 }
3855 }
3856
3857 // (2) check that the value is actually a value
3858 else if (!val.isConst()) {
3859 Notice() << "SmtEngine::checkModel(): *** PROBLEM: MODEL VALUE NOT A CONSTANT ***" << endl;
3860 stringstream ss;
3861 ss << "SmtEngine::checkModel(): ERRORS SATISFYING ASSERTIONS WITH MODEL:" << endl
3862 << "model value for " << func << endl
3863 << " is " << val << endl
3864 << "and that is not a constant (.isConst() == false)." << endl
3865 << "Run with `--check-models -v' for additional diagnostics.";
3866 InternalError(ss.str());
3867 }
3868
3869 // (3) check that it's the correct (sub)type
3870 // This was intended to be a more general check, but for now we can't do that because
3871 // e.g. "1" is an INT, which isn't a subrange type [1..10] (etc.).
3872 else if(func.getType().isInteger() && !val.getType().isInteger()) {
3873 Notice() << "SmtEngine::checkModel(): *** PROBLEM: MODEL VALUE NOT CORRECT TYPE ***" << endl;
3874 stringstream ss;
3875 ss << "SmtEngine::checkModel(): ERRORS SATISFYING ASSERTIONS WITH MODEL:" << endl
3876 << "model value for " << func << endl
3877 << " is " << val << endl
3878 << "value type is " << val.getType() << endl
3879 << "should be of type " << func.getType() << endl
3880 << "Run with `--check-models -v' for additional diagnostics.";
3881 InternalError(ss.str());
3882 }
3883
3884 // (4) checks complete, add the substitution
3885 Debug("boolean-terms") << "cm: adding subs " << func << " :=> " << val << endl;
3886 substitutions.addSubstitution(func, val);
3887 }
3888 }
3889
3890 // Now go through all our user assertions checking if they're satisfied.
3891 for(AssertionList::const_iterator i = d_assertionList->begin(); i != d_assertionList->end(); ++i) {
3892 Notice() << "SmtEngine::checkModel(): checking assertion " << *i << endl;
3893 Node n = Node::fromExpr(*i);
3894
3895 // Apply any define-funs from the problem.
3896 {
3897 hash_map<Node, Node, NodeHashFunction> cache;
3898 n = d_private->expandDefinitions(n, cache);
3899 }
3900 Notice() << "SmtEngine::checkModel(): -- expands to " << n << endl;
3901
3902 // Apply our model value substitutions.
3903 Debug("boolean-terms") << "applying subses to " << n << endl;
3904 n = substitutions.apply(n);
3905 Debug("boolean-terms") << "++ got " << n << endl;
3906 Notice() << "SmtEngine::checkModel(): -- substitutes to " << n << endl;
3907
3908 //AJR : FIXME need to ignore quantifiers too?
3909 if( n.getKind() != kind::REWRITE_RULE ){
3910 // In case it's a quantifier (or contains one), look up its value before
3911 // simplifying, or the quantifier might be irreparably altered.
3912 n = m->getValue(n);
3913 } else {
3914 // Note this "skip" is done here, rather than above. This is
3915 // because (1) the quantifier could in principle simplify to false,
3916 // which should be reported, and (2) checking for the quantifier
3917 // above, before simplification, doesn't catch buried quantifiers
3918 // anyway (those not at the top-level).
3919 Notice() << "SmtEngine::checkModel(): -- skipping quantifiers/rewrite-rules assertion"
3920 << endl;
3921 continue;
3922 }
3923
3924 // Simplify the result.
3925 n = d_private->simplify(n);
3926 Notice() << "SmtEngine::checkModel(): -- simplifies to " << n << endl;
3927
3928 // Replace the already-known ITEs (this is important for ground ITEs under quantifiers).
3929 n = d_private->d_iteRemover.replace(n);
3930 Notice() << "SmtEngine::checkModel(): -- ite replacement gives " << n << endl;
3931
3932 // Apply our model value substitutions (again), as things may have been simplified.
3933 Debug("boolean-terms") << "applying subses to " << n << endl;
3934 n = substitutions.apply(n);
3935 Debug("boolean-terms") << "++ got " << n << endl;
3936 Notice() << "SmtEngine::checkModel(): -- re-substitutes to " << n << endl;
3937
3938 // As a last-ditch effort, ask model to simplify it.
3939 // Presently, this is only an issue for quantifiers, which can have a value
3940 // but don't show up in our substitution map above.
3941 n = m->getValue(n);
3942 Notice() << "SmtEngine::checkModel(): -- model-substitutes to " << n << endl;
3943 AlwaysAssert(!hardFailure || n.isConst() || n.getKind() == kind::LAMBDA);
3944
3945 // The result should be == true.
3946 if(n != NodeManager::currentNM()->mkConst(true)) {
3947 Notice() << "SmtEngine::checkModel(): *** PROBLEM: EXPECTED `TRUE' ***"
3948 << endl;
3949 stringstream ss;
3950 ss << "SmtEngine::checkModel(): "
3951 << "ERRORS SATISFYING ASSERTIONS WITH MODEL:" << endl
3952 << "assertion: " << *i << endl
3953 << "simplifies to: " << n << endl
3954 << "expected `true'." << endl
3955 << "Run with `--check-models -v' for additional diagnostics.";
3956 if(hardFailure) {
3957 InternalError(ss.str());
3958 } else {
3959 Warning() << ss.str() << endl;
3960 }
3961 }
3962 }
3963 Notice() << "SmtEngine::checkModel(): all assertions checked out OK !" << endl;
3964 }
3965
3966 UnsatCore SmtEngine::getUnsatCore() throw(ModalException) {
3967 Trace("smt") << "SMT getUnsatCore()" << endl;
3968 SmtScope smts(this);
3969 finalOptionsAreSet();
3970 if(Dump.isOn("benchmark")) {
3971 Dump("benchmark") << GetUnsatCoreCommand();
3972 }
3973 #ifdef CVC4_PROOF
3974 if(!options::unsatCores()) {
3975 throw ModalException("Cannot get an unsat core when produce-unsat-cores option is off.");
3976 }
3977 if(d_status.isNull() ||
3978 d_status.asSatisfiabilityResult() != Result::UNSAT ||
3979 d_problemExtended) {
3980 throw ModalException("Cannot get an unsat core unless immediately preceded by UNSAT/VALID response.");
3981 }
3982
3983 d_proofManager->getProof(this);// just to trigger core creation
3984 return UnsatCore(this, d_proofManager->begin_unsat_core(), d_proofManager->end_unsat_core());
3985 #else /* CVC4_PROOF */
3986 throw ModalException("This build of CVC4 doesn't have proof support (required for unsat cores).");
3987 #endif /* CVC4_PROOF */
3988 }
3989
3990 Proof* SmtEngine::getProof() throw(ModalException) {
3991 Trace("smt") << "SMT getProof()" << endl;
3992 SmtScope smts(this);
3993 finalOptionsAreSet();
3994 if(Dump.isOn("benchmark")) {
3995 Dump("benchmark") << GetProofCommand();
3996 }
3997 #ifdef CVC4_PROOF
3998 if(!options::proof()) {
3999 throw ModalException("Cannot get a proof when produce-proofs option is off.");
4000 }
4001 if(d_status.isNull() ||
4002 d_status.asSatisfiabilityResult() != Result::UNSAT ||
4003 d_problemExtended) {
4004 throw ModalException("Cannot get a proof unless immediately preceded by UNSAT/VALID response.");
4005 }
4006
4007 return ProofManager::getProof(this);
4008 #else /* CVC4_PROOF */
4009 throw ModalException("This build of CVC4 doesn't have proof support.");
4010 #endif /* CVC4_PROOF */
4011 }
4012
4013 void SmtEngine::printInstantiations( std::ostream& out ) {
4014 SmtScope smts(this);
4015 if( options::instFormatMode()==INST_FORMAT_MODE_SZS ){
4016 out << "% SZS output start Proof for " << d_filename.c_str() << std::endl;
4017 }
4018 if( d_theoryEngine ){
4019 d_theoryEngine->printInstantiations( out );
4020 }
4021 if( options::instFormatMode()==INST_FORMAT_MODE_SZS ){
4022 out << "% SZS output end Proof for " << d_filename.c_str() << std::endl;
4023 }
4024 }
4025
4026 vector<Expr> SmtEngine::getAssertions() throw(ModalException) {
4027 SmtScope smts(this);
4028 finalOptionsAreSet();
4029 if(Dump.isOn("benchmark")) {
4030 Dump("benchmark") << GetAssertionsCommand();
4031 }
4032 Trace("smt") << "SMT getAssertions()" << endl;
4033 if(!options::interactive()) {
4034 const char* msg =
4035 "Cannot query the current assertion list when not in interactive mode.";
4036 throw ModalException(msg);
4037 }
4038 Assert(d_assertionList != NULL);
4039 // copy the result out
4040 return vector<Expr>(d_assertionList->begin(), d_assertionList->end());
4041 }
4042
4043 void SmtEngine::push() throw(ModalException, LogicException) {
4044 SmtScope smts(this);
4045 finalOptionsAreSet();
4046 doPendingPops();
4047 Trace("smt") << "SMT push()" << endl;
4048 d_private->processAssertions();
4049 if(Dump.isOn("benchmark")) {
4050 Dump("benchmark") << PushCommand();
4051 }
4052 if(!options::incrementalSolving()) {
4053 throw ModalException("Cannot push when not solving incrementally (use --incremental)");
4054 }
4055
4056 // check to see if a postsolve() is pending
4057 if(d_needPostsolve) {
4058 d_theoryEngine->postsolve();
4059 d_needPostsolve = false;
4060 }
4061
4062 // The problem isn't really "extended" yet, but this disallows
4063 // get-model after a push, simplifying our lives somewhat and
4064 // staying symmtric with pop.
4065 d_problemExtended = true;
4066
4067 d_userLevels.push_back(d_userContext->getLevel());
4068 internalPush();
4069 Trace("userpushpop") << "SmtEngine: pushed to level "
4070 << d_userContext->getLevel() << endl;
4071 }
4072
4073 void SmtEngine::pop() throw(ModalException) {
4074 SmtScope smts(this);
4075 finalOptionsAreSet();
4076 Trace("smt") << "SMT pop()" << endl;
4077 if(Dump.isOn("benchmark")) {
4078 Dump("benchmark") << PopCommand();
4079 }
4080 if(!options::incrementalSolving()) {
4081 throw ModalException("Cannot pop when not solving incrementally (use --incremental)");
4082 }
4083 if(d_userLevels.size() == 0) {
4084 throw ModalException("Cannot pop beyond the first user frame");
4085 }
4086
4087 // check to see if a postsolve() is pending
4088 if(d_needPostsolve) {
4089 d_theoryEngine->postsolve();
4090 d_needPostsolve = false;
4091 }
4092
4093 // The problem isn't really "extended" yet, but this disallows
4094 // get-model after a pop, simplifying our lives somewhat. It might
4095 // not be strictly necessary to do so, since the pops occur lazily,
4096 // but also it would be weird to have a legally-executed (get-model)
4097 // that only returns a subset of the assignment (because the rest
4098 // is no longer in scope!).
4099 d_problemExtended = true;
4100
4101 AlwaysAssert(d_userContext->getLevel() > 0);
4102 AlwaysAssert(d_userLevels.back() < d_userContext->getLevel());
4103 while (d_userLevels.back() < d_userContext->getLevel()) {
4104 internalPop(true);
4105 }
4106 d_userLevels.pop_back();
4107
4108 // Clear out assertion queues etc., in case anything is still in there
4109 d_private->notifyPop();
4110
4111 Trace("userpushpop") << "SmtEngine: popped to level "
4112 << d_userContext->getLevel() << endl;
4113 // FIXME: should we reset d_status here?
4114 // SMT-LIBv2 spec seems to imply no, but it would make sense to..
4115 // Still, we want the right exit status after any final sequence
4116 // of pops... hm.
4117 }
4118
4119 void SmtEngine::internalPush() {
4120 Assert(d_fullyInited);
4121 Trace("smt") << "SmtEngine::internalPush()" << endl;
4122 doPendingPops();
4123 if(options::incrementalSolving()) {
4124 d_private->processAssertions();
4125 TimerStat::CodeTimer pushPopTimer(d_stats->d_pushPopTime);
4126 d_userContext->push();
4127 // the d_context push is done inside of the SAT solver
4128 d_propEngine->push();
4129 }
4130 }
4131
4132 void SmtEngine::internalPop(bool immediate) {
4133 Assert(d_fullyInited);
4134 Trace("smt") << "SmtEngine::internalPop()" << endl;
4135 if(options::incrementalSolving()) {
4136 ++d_pendingPops;
4137 }
4138 if(immediate) {
4139 doPendingPops();
4140 }
4141 }
4142
4143 void SmtEngine::doPendingPops() {
4144 Assert(d_pendingPops == 0 || options::incrementalSolving());
4145 while(d_pendingPops > 0) {
4146 TimerStat::CodeTimer pushPopTimer(d_stats->d_pushPopTime);
4147 d_propEngine->pop();
4148 // the d_context pop is done inside of the SAT solver
4149 d_userContext->pop();
4150 --d_pendingPops;
4151 }
4152 }
4153
4154 void SmtEngine::interrupt() throw(ModalException) {
4155 if(!d_fullyInited) {
4156 return;
4157 }
4158 d_propEngine->interrupt();
4159 d_theoryEngine->interrupt();
4160 }
4161
4162 void SmtEngine::setResourceLimit(unsigned long units, bool cumulative) {
4163 if(cumulative) {
4164 Trace("limit") << "SmtEngine: setting cumulative resource limit to " << units << endl;
4165 d_resourceBudgetCumulative = (units == 0) ? 0 : (d_cumulativeResourceUsed + units);
4166 } else {
4167 Trace("limit") << "SmtEngine: setting per-call resource limit to " << units << endl;
4168 d_resourceBudgetPerCall = units;
4169 }
4170 }
4171
4172 void SmtEngine::setTimeLimit(unsigned long millis, bool cumulative) {
4173 if(cumulative) {
4174 Trace("limit") << "SmtEngine: setting cumulative time limit to " << millis << " ms" << endl;
4175 d_timeBudgetCumulative = (millis == 0) ? 0 : (d_cumulativeTimeUsed + millis);
4176 } else {
4177 Trace("limit") << "SmtEngine: setting per-call time limit to " << millis << " ms" << endl;
4178 d_timeBudgetPerCall = millis;
4179 }
4180 }
4181
4182 unsigned long SmtEngine::getResourceUsage() const {
4183 return d_cumulativeResourceUsed;
4184 }
4185
4186 unsigned long SmtEngine::getTimeUsage() const {
4187 return d_cumulativeTimeUsed;
4188 }
4189
4190 unsigned long SmtEngine::getResourceRemaining() const throw(ModalException) {
4191 if(d_resourceBudgetCumulative == 0) {
4192 throw ModalException("No cumulative resource limit is currently set");
4193 }
4194
4195 return d_resourceBudgetCumulative <= d_cumulativeResourceUsed ? 0 :
4196 d_resourceBudgetCumulative - d_cumulativeResourceUsed;
4197 }
4198
4199 unsigned long SmtEngine::getTimeRemaining() const throw(ModalException) {
4200 if(d_timeBudgetCumulative == 0) {
4201 throw ModalException("No cumulative time limit is currently set");
4202 }
4203
4204 return d_timeBudgetCumulative <= d_cumulativeTimeUsed ? 0 :
4205 d_timeBudgetCumulative - d_cumulativeTimeUsed;
4206 }
4207
4208 Statistics SmtEngine::getStatistics() const throw() {
4209 return Statistics(*d_statisticsRegistry);
4210 }
4211
4212 SExpr SmtEngine::getStatistic(std::string name) const throw() {
4213 return d_statisticsRegistry->getStatistic(name);
4214 }
4215
4216 void SmtEngine::setUserAttribute(const std::string& attr, Expr expr, std::vector<Expr> expr_values, std::string str_value) {
4217 SmtScope smts(this);
4218 std::vector<Node> node_values;
4219 for( unsigned i=0; i<expr_values.size(); i++ ){
4220 node_values.push_back( expr_values[i].getNode() );
4221 }
4222 d_theoryEngine->setUserAttribute(attr, expr.getNode(), node_values, str_value);
4223 }
4224
4225 void SmtEngine::setPrintFuncInModel(Expr f, bool p) {
4226 Trace("setp-model") << "Set printInModel " << f << " to " << p << std::endl;
4227 for( unsigned i=0; i<d_modelGlobalCommands.size(); i++ ){
4228 Command * c = d_modelGlobalCommands[i];
4229 DeclareFunctionCommand* dfc = dynamic_cast<DeclareFunctionCommand*>(c);
4230 if(dfc != NULL) {
4231 if( dfc->getFunction()==f ){
4232 dfc->setPrintInModel( p );
4233 }
4234 }
4235 }
4236 for( unsigned i=0; i<d_modelCommands->size(); i++ ){
4237 Command * c = (*d_modelCommands)[i];
4238 DeclareFunctionCommand* dfc = dynamic_cast<DeclareFunctionCommand*>(c);
4239 if(dfc != NULL) {
4240 if( dfc->getFunction()==f ){
4241 dfc->setPrintInModel( p );
4242 }
4243 }
4244 }
4245 }
4246
4247 }/* CVC4 namespace */