3 #include "mutableset.h"
10 #include "satencoder.h"
11 #include "sattranslator.h"
13 #include "polarityassignment.h"
14 #include "decomposeordertransform.h"
15 #include "autotuner.h"
18 #include "orderresolver.h"
19 #include "integerencoding.h"
21 #include "preprocess.h"
22 #include "serializer.h"
23 #include "deserializer.h"
24 #include "encodinggraph.h"
25 #include "ordergraph.h"
26 #include "orderedge.h"
27 #include "orderanalysis.h"
28 #include "elementopt.h"
29 #include "varorderingopt.h"
34 boolTrue(BooleanEdge(new BooleanConst(true))),
35 boolFalse(boolTrue.negate()),
37 booleanVarUsed(false),
40 satsolverTimeout(NOTIMEOUT)
42 satEncoder = new SATEncoder(this);
45 /** This function tears down the solver and the entire AST */
49 uint size = allBooleans.getSize();
50 for (uint i = 0; i < size; i++) {
51 delete allBooleans.get(i);
54 size = allSets.getSize();
55 for (uint i = 0; i < size; i++) {
56 delete allSets.get(i);
59 size = allElements.getSize();
60 for (uint i = 0; i < size; i++) {
61 Element *el = allElements.get(i);
65 size = allTables.getSize();
66 for (uint i = 0; i < size; i++) {
67 delete allTables.get(i);
70 size = allPredicates.getSize();
71 for (uint i = 0; i < size; i++) {
72 delete allPredicates.get(i);
75 size = allOrders.getSize();
76 for (uint i = 0; i < size; i++) {
77 delete allOrders.get(i);
79 size = allFunctions.getSize();
80 for (uint i = 0; i < size; i++) {
81 delete allFunctions.get(i);
84 delete boolTrue.getBoolean();
88 void CSolver::resetSolver() {
90 uint size = allBooleans.getSize();
91 for (uint i = 0; i < size; i++) {
92 delete allBooleans.get(i);
95 size = allSets.getSize();
96 for (uint i = 0; i < size; i++) {
97 delete allSets.get(i);
100 size = allElements.getSize();
101 for (uint i = 0; i < size; i++) {
102 Element *el = allElements.get(i);
106 size = allTables.getSize();
107 for (uint i = 0; i < size; i++) {
108 delete allTables.get(i);
111 size = allPredicates.getSize();
112 for (uint i = 0; i < size; i++) {
113 delete allPredicates.get(i);
116 size = allOrders.getSize();
117 for (uint i = 0; i < size; i++) {
118 delete allOrders.get(i);
120 size = allFunctions.getSize();
121 for (uint i = 0; i < size; i++) {
122 delete allFunctions.get(i);
124 delete boolTrue.getBoolean();
129 allPredicates.clear();
131 allFunctions.clear();
133 activeOrders.reset();
137 boolTrue = BooleanEdge(new BooleanConst(true));
138 boolFalse = boolTrue.negate();
140 booleanVarUsed = false;
143 satEncoder->resetSATEncoder();
147 CSolver *CSolver::clone() {
148 CSolver *copy = new CSolver();
150 SetIteratorBooleanEdge *it = getConstraints();
151 while (it->hasNext()) {
152 BooleanEdge b = it->next();
153 copy->addConstraint(cloneEdge(copy, &map, b));
159 CSolver *CSolver::deserialize(const char *file) {
160 model_print("deserializing %s ...\n", file);
161 Deserializer deserializer(file);
162 return deserializer.deserialize();
165 void CSolver::serialize() {
166 model_print("serializing ...\n");
168 long long nanotime = getTimeNano();
169 int numchars = sprintf(buffer, "DUMP%llu", nanotime);
170 Serializer serializer(buffer);
171 SetIteratorBooleanEdge *it = getConstraints();
172 while (it->hasNext()) {
173 BooleanEdge b = it->next();
174 serializeBooleanEdge(&serializer, b, true);
179 Set *CSolver::createSet(VarType type, uint64_t *elements, uint numelements) {
180 Set *set = new Set(type, elements, numelements);
185 Set *CSolver::createRangeSet(VarType type, uint64_t lowrange, uint64_t highrange) {
186 Set *set = new Set(type, lowrange, highrange);
191 bool CSolver::itemExistInSet(Set *set, uint64_t item) {
192 return set->exists(item);
195 VarType CSolver::getSetVarType(Set *set) {
196 return set->getType();
199 Element *CSolver::createRangeVar(VarType type, uint64_t lowrange, uint64_t highrange) {
200 Set *s = createRangeSet(type, lowrange, highrange);
201 return getElementVar(s);
204 MutableSet *CSolver::createMutableSet(VarType type) {
205 MutableSet *set = new MutableSet(type);
210 void CSolver::addItem(MutableSet *set, uint64_t element) {
211 set->addElementMSet(element);
214 uint64_t CSolver::createUniqueItem(MutableSet *set) {
215 uint64_t element = set->getNewUniqueItem();
216 set->addElementMSet(element);
220 void CSolver::finalizeMutableSet(MutableSet *set) {
224 Element *CSolver::getElementVar(Set *set) {
225 Element *element = new ElementSet(set);
226 allElements.push(element);
230 void CSolver::mustHaveValue(Element *element) {
231 element->anyValue = true;
234 Set *CSolver::getElementRange (Element *element) {
235 return element->getRange();
239 Element *CSolver::getElementConst(VarType type, uint64_t value) {
240 uint64_t array[] = {value};
241 Set *set = new Set(type, array, 1);
242 Element *element = new ElementConst(value, set);
243 Element *e = elemMap.get(element);
246 allElements.push(element);
247 elemMap.put(element, element);
257 Element *CSolver::applyFunction(Function *function, Element **array, uint numArrays, BooleanEdge overflowstatus) {
258 ASSERT(numArrays == 2);
259 Element *element = new ElementFunction(function,array,numArrays,overflowstatus);
260 Element *e = elemMap.get(element);
262 element->updateParents();
263 allElements.push(element);
264 elemMap.put(element, element);
272 Function *CSolver::createFunctionOperator(ArithOp op, Set *range, OverFlowBehavior overflowbehavior) {
273 Function *function = new FunctionOperator(op, range, overflowbehavior);
274 allFunctions.push(function);
278 Predicate *CSolver::createPredicateOperator(CompOp op) {
279 Predicate *predicate = new PredicateOperator(op);
280 allPredicates.push(predicate);
284 Predicate *CSolver::createPredicateTable(Table *table, UndefinedBehavior behavior) {
285 Predicate *predicate = new PredicateTable(table, behavior);
286 allPredicates.push(predicate);
290 Table *CSolver::createTable(Set *range) {
291 Table *table = new Table(range);
292 allTables.push(table);
296 Table *CSolver::createTableForPredicate() {
297 return createTable(NULL);
300 void CSolver::addTableEntry(Table *table, uint64_t *inputs, uint inputSize, uint64_t result) {
301 table->addNewTableEntry(inputs, inputSize, result);
304 Function *CSolver::completeTable(Table *table, UndefinedBehavior behavior) {
305 Function *function = new FunctionTable(table, behavior);
306 allFunctions.push(function);
310 BooleanEdge CSolver::getBooleanVar(VarType type) {
311 Boolean *boolean = new BooleanVar(type);
312 allBooleans.push(boolean);
314 booleanVarUsed = true;
315 return BooleanEdge(boolean);
318 BooleanEdge CSolver::getBooleanTrue() {
322 BooleanEdge CSolver::getBooleanFalse() {
326 BooleanEdge CSolver::applyPredicate(Predicate *predicate, Element **inputs, uint numInputs) {
327 return applyPredicateTable(predicate, inputs, numInputs, BooleanEdge(NULL));
330 BooleanEdge CSolver::applyPredicateTable(Predicate *predicate, Element **inputs, uint numInputs, BooleanEdge undefinedStatus) {
331 BooleanPredicate *boolean = new BooleanPredicate(predicate, inputs, numInputs, undefinedStatus);
332 Boolean *b = boolMap.get(boolean);
334 boolean->updateParents();
335 boolMap.put(boolean, boolean);
336 allBooleans.push(boolean);
337 return BooleanEdge(boolean);
340 return BooleanEdge(b);
344 bool CSolver::isTrue(BooleanEdge b) {
345 return b.isNegated() ? b->isFalse() : b->isTrue();
348 bool CSolver::isFalse(BooleanEdge b) {
349 return b.isNegated() ? b->isTrue() : b->isFalse();
352 BooleanEdge CSolver::applyLogicalOperation(LogicOp op, BooleanEdge arg1, BooleanEdge arg2) {
353 BooleanEdge array[] = {arg1, arg2};
354 return applyLogicalOperation(op, array, 2);
357 BooleanEdge CSolver::applyLogicalOperation(LogicOp op, BooleanEdge arg) {
358 BooleanEdge array[] = {arg};
359 return applyLogicalOperation(op, array, 1);
362 static int booleanEdgeCompares(const void *p1, const void *p2) {
363 BooleanEdge be1 = *(BooleanEdge const *) p1;
364 BooleanEdge be2 = *(BooleanEdge const *) p2;
365 uint64_t b1 = be1->id;
366 uint64_t b2 = be2->id;
375 BooleanEdge CSolver::rewriteLogicalOperation(LogicOp op, BooleanEdge *array, uint asize) {
376 BooleanEdge newarray[asize];
377 memcpy(newarray, array, asize * sizeof(BooleanEdge));
378 for (uint i = 0; i < asize; i++) {
379 BooleanEdge b = newarray[i];
380 if (b->type == LOGICOP) {
381 if (((BooleanLogic *) b.getBoolean())->replaced) {
382 newarray[i] = doRewrite(newarray[i]);
387 return applyLogicalOperation(op, newarray, asize);
390 BooleanEdge CSolver::applyLogicalOperation(LogicOp op, BooleanEdge *array, uint asize) {
391 BooleanEdge newarray[asize];
394 return array[0].negate();
397 for (uint i = 0; i < 2; i++) {
398 if (isTrue(array[i])) { // It can be undefined
400 } else if (isFalse(array[i])) {
401 newarray[0] = array[1 - i];
402 return applyLogicalOperation(SATC_NOT, newarray, 1);
403 } else if (array[i]->type == LOGICOP) {
404 BooleanLogic *b = (BooleanLogic *)array[i].getBoolean();
406 return rewriteLogicalOperation(op, array, asize);
413 for (uint i = 0; i < asize; i++) {
414 newarray[i] = applyLogicalOperation(SATC_NOT, array[i]);
416 return applyLogicalOperation(SATC_NOT, applyLogicalOperation(SATC_AND, newarray, asize));
420 for (uint i = 0; i < asize; i++) {
421 BooleanEdge b = array[i];
422 if (b->type == LOGICOP) {
423 if (((BooleanLogic *)b.getBoolean())->replaced)
424 return rewriteLogicalOperation(op, array, asize);
428 else if (isFalse(b)) {
431 newarray[newindex++] = b;
435 } else if (newindex == 1) {
438 bsdqsort(newarray, newindex, sizeof(BooleanEdge), booleanEdgeCompares);
445 //handle by translation
446 return applyLogicalOperation(SATC_NOT, applyLogicalOperation(SATC_IFF, array, asize));
449 //handle by translation
450 return applyLogicalOperation(SATC_OR, applyLogicalOperation(SATC_NOT, array[0]), array[1]);
455 Boolean *boolean = new BooleanLogic(this, op, array, asize);
456 Boolean *b = boolMap.get(boolean);
458 boolean->updateParents();
459 boolMap.put(boolean, boolean);
460 allBooleans.push(boolean);
461 return BooleanEdge(boolean);
464 return BooleanEdge(b);
468 BooleanEdge CSolver::orderConstraint(Order *order, uint64_t first, uint64_t second) {
469 // ASSERT(first != second);
471 return getBooleanFalse();
474 if (order->type == SATC_TOTAL) {
475 if (first > second) {
476 uint64_t tmp = first;
482 Boolean *constraint = new BooleanOrder(order, first, second);
483 Boolean *b = boolMap.get(constraint);
486 allBooleans.push(constraint);
487 boolMap.put(constraint, constraint);
488 constraint->updateParents();
489 if (order->graph != NULL) {
490 OrderGraph *graph = order->graph;
491 OrderNode *from = graph->lookupOrderNodeFromOrderGraph(first);
493 OrderNode *to = graph->lookupOrderNodeFromOrderGraph(second);
495 OrderEdge *edge = graph->lookupOrderEdgeFromOrderGraph(from, to);
498 if (edge != NULL && edge->mustPos) {
499 replaceBooleanWithTrueNoRemove(constraint);
500 } else if (edge != NULL && edge->mustNeg) {
501 replaceBooleanWithFalseNoRemove(constraint);
502 } else if ((invedge = graph->lookupOrderEdgeFromOrderGraph(to, from)) != NULL
503 && invedge->mustPos) {
504 replaceBooleanWithFalseNoRemove(constraint);
514 BooleanEdge be = BooleanEdge(constraint);
515 return negate ? be.negate() : be;
518 void CSolver::addConstraint(BooleanEdge constraint) {
519 if (isTrue(constraint))
521 else if (isFalse(constraint)) {
525 if (constraint->type == LOGICOP) {
526 BooleanLogic *b = (BooleanLogic *) constraint.getBoolean();
527 if (!constraint.isNegated()) {
528 if (b->op == SATC_AND) {
529 uint size = b->inputs.getSize();
530 //Handle potential concurrent modification
531 BooleanEdge array[size];
532 for (uint i = 0; i < size; i++) {
533 array[i] = b->inputs.get(i);
535 for (uint i = 0; i < size; i++) {
536 addConstraint(array[i]);
542 addConstraint(doRewrite(constraint));
546 constraints.add(constraint);
547 Boolean *ptr = constraint.getBoolean();
549 if (ptr->boolVal == BV_UNSAT) {
553 replaceBooleanWithTrueNoRemove(constraint);
554 constraint->parents.clear();
558 Order *CSolver::createOrder(OrderType type, Set *set) {
559 Order *order = new Order(type, set);
560 allOrders.push(order);
561 activeOrders.add(order);
565 /** Computes static ordering information to allow isTrue/isFalse
566 queries on newly created orders to work. */
568 void CSolver::inferFixedOrder(Order *order) {
569 if (order->graph != NULL) {
572 order->graph = buildMustOrderGraph(order);
573 reachMustAnalysis(this, order->graph, true);
576 void CSolver::inferFixedOrders() {
577 SetIteratorOrder *orderit = activeOrders.iterator();
578 while (orderit->hasNext()) {
579 Order *order = orderit->next();
580 inferFixedOrder(order);
584 int CSolver::solve() {
585 long long startTime = getTimeNano();
586 bool deleteTuner = false;
588 tuner = new DefaultTuner();
594 SetIteratorOrder *orderit = activeOrders.iterator();
595 while (orderit->hasNext()) {
596 Order *order = orderit->next();
597 if (order->graph != NULL) {
604 computePolarities(this);
605 long long time1 = getTimeNano();
606 model_print("Polarity time: %f\n", (time1 - startTime) / NANOSEC);
609 long long time2 = getTimeNano();
610 model_print("Preprocess time: %f\n", (time2 - time1) / NANOSEC);
612 DecomposeOrderTransform dot(this);
614 time1 = getTimeNano();
615 model_print("Decompose Order: %f\n", (time1 - time2) / NANOSEC);
617 IntegerEncodingTransform iet(this);
620 ElementOpt eop(this);
623 EncodingGraph eg(this);
626 naiveEncodingDecision(this);
629 VarOrderingOpt bor(this, satEncoder);
632 time2 = getTimeNano();
633 model_print("Encoding Graph Time: %f\n", (time2 - time1) / NANOSEC);
635 satEncoder->encodeAllSATEncoder(this);
636 time1 = getTimeNano();
638 model_print("Elapse Encode time: %f\n", (time1 - startTime) / NANOSEC);
640 model_print("Is problem UNSAT after encoding: %d\n", unsat);
641 int result = unsat ? IS_UNSAT : satEncoder->solve(satsolverTimeout);
642 model_print("Result Computed in SAT solver:\t%s\n", result == IS_SAT ? "SAT" : result == IS_INDETER ? "INDETERMINATE" : " UNSAT");
643 time2 = getTimeNano();
644 elapsedTime = time2 - startTime;
645 model_print("CSOLVER solve time: %f\n", elapsedTime / NANOSEC);
653 void CSolver::printConstraints() {
654 SetIteratorBooleanEdge *it = getConstraints();
655 while (it->hasNext()) {
656 BooleanEdge b = it->next();
662 void CSolver::printConstraint(BooleanEdge b) {
666 uint64_t CSolver::getElementValue(Element *element) {
667 switch (element->type) {
671 return getElementValueSATTranslator(this, element);
678 bool CSolver::getBooleanValue(BooleanEdge bedge) {
679 Boolean *boolean = bedge.getBoolean();
680 switch (boolean->type) {
682 return getBooleanVariableValueSATTranslator(this, boolean);
689 bool CSolver::getOrderConstraintValue(Order *order, uint64_t first, uint64_t second) {
690 return order->encoding.resolver->resolveOrder(first, second);
693 long long CSolver::getEncodeTime() { return satEncoder->getEncodeTime(); }
695 long long CSolver::getSolveTime() { return satEncoder->getSolveTime(); }
697 void CSolver::autoTune(uint budget) {
698 AutoTuner *autotuner = new AutoTuner(budget);
699 autotuner->addProblem(this);