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()),
39 satsolverTimeout(NOTIMEOUT)
41 satEncoder = new SATEncoder(this);
44 /** This function tears down the solver and the entire AST */
48 uint size = allBooleans.getSize();
49 for (uint i = 0; i < size; i++) {
50 delete allBooleans.get(i);
53 size = allSets.getSize();
54 for (uint i = 0; i < size; i++) {
55 delete allSets.get(i);
58 size = allElements.getSize();
59 for (uint i = 0; i < size; i++) {
60 Element *el = allElements.get(i);
64 size = allTables.getSize();
65 for (uint i = 0; i < size; i++) {
66 delete allTables.get(i);
69 size = allPredicates.getSize();
70 for (uint i = 0; i < size; i++) {
71 delete allPredicates.get(i);
74 size = allOrders.getSize();
75 for (uint i = 0; i < size; i++) {
76 delete allOrders.get(i);
78 size = allFunctions.getSize();
79 for (uint i = 0; i < size; i++) {
80 delete allFunctions.get(i);
83 delete boolTrue.getBoolean();
87 void CSolver::resetSolver() {
89 uint size = allBooleans.getSize();
90 for (uint i = 0; i < size; i++) {
91 delete allBooleans.get(i);
94 size = allSets.getSize();
95 for (uint i = 0; i < size; i++) {
96 delete allSets.get(i);
99 size = allElements.getSize();
100 for (uint i = 0; i < size; i++) {
101 Element *el = allElements.get(i);
105 size = allTables.getSize();
106 for (uint i = 0; i < size; i++) {
107 delete allTables.get(i);
110 size = allPredicates.getSize();
111 for (uint i = 0; i < size; i++) {
112 delete allPredicates.get(i);
115 size = allOrders.getSize();
116 for (uint i = 0; i < size; i++) {
117 delete allOrders.get(i);
119 size = allFunctions.getSize();
120 for (uint i = 0; i < size; i++) {
121 delete allFunctions.get(i);
123 delete boolTrue.getBoolean();
128 allPredicates.clear();
130 allFunctions.clear();
132 activeOrders.reset();
136 boolTrue = BooleanEdge(new BooleanConst(true));
137 boolFalse = boolTrue.negate();
141 satEncoder->resetSATEncoder();
145 CSolver *CSolver::clone() {
146 CSolver *copy = new CSolver();
148 SetIteratorBooleanEdge *it = getConstraints();
149 while (it->hasNext()) {
150 BooleanEdge b = it->next();
151 copy->addConstraint(cloneEdge(copy, &map, b));
157 CSolver *CSolver::deserialize(const char *file) {
158 model_print("deserializing %s ...\n", file);
159 Deserializer deserializer(file);
160 return deserializer.deserialize();
163 void CSolver::serialize() {
164 model_print("serializing ...\n");
166 long long nanotime = getTimeNano();
167 int numchars = sprintf(buffer, "DUMP%llu", nanotime);
168 Serializer serializer(buffer);
169 SetIteratorBooleanEdge *it = getConstraints();
170 while (it->hasNext()) {
171 BooleanEdge b = it->next();
172 serializeBooleanEdge(&serializer, b, true);
177 Set *CSolver::createSet(VarType type, uint64_t *elements, uint numelements) {
178 Set *set = new Set(type, elements, numelements);
183 Set *CSolver::createRangeSet(VarType type, uint64_t lowrange, uint64_t highrange) {
184 Set *set = new Set(type, lowrange, highrange);
189 bool CSolver::itemExistInSet(Set *set, uint64_t item) {
190 return set->exists(item);
193 VarType CSolver::getSetVarType(Set *set) {
194 return set->getType();
197 Element *CSolver::createRangeVar(VarType type, uint64_t lowrange, uint64_t highrange) {
198 Set *s = createRangeSet(type, lowrange, highrange);
199 return getElementVar(s);
202 MutableSet *CSolver::createMutableSet(VarType type) {
203 MutableSet *set = new MutableSet(type);
208 void CSolver::addItem(MutableSet *set, uint64_t element) {
209 set->addElementMSet(element);
212 uint64_t CSolver::createUniqueItem(MutableSet *set) {
213 uint64_t element = set->getNewUniqueItem();
214 set->addElementMSet(element);
218 void CSolver::finalizeMutableSet(MutableSet *set) {
222 Element *CSolver::getElementVar(Set *set) {
223 Element *element = new ElementSet(set);
224 allElements.push(element);
228 void CSolver::mustHaveValue(Element *element) {
229 element->anyValue = true;
232 Set *CSolver::getElementRange (Element *element) {
233 return element->getRange();
237 Element *CSolver::getElementConst(VarType type, uint64_t value) {
238 uint64_t array[] = {value};
239 Set *set = new Set(type, array, 1);
240 Element *element = new ElementConst(value, set);
241 Element *e = elemMap.get(element);
244 allElements.push(element);
245 elemMap.put(element, element);
255 Element *CSolver::applyFunction(Function *function, Element **array, uint numArrays, BooleanEdge overflowstatus) {
256 ASSERT(numArrays == 2);
257 Element *element = new ElementFunction(function,array,numArrays,overflowstatus);
258 Element *e = elemMap.get(element);
260 element->updateParents();
261 allElements.push(element);
262 elemMap.put(element, element);
270 Function *CSolver::createFunctionOperator(ArithOp op, Set *range, OverFlowBehavior overflowbehavior) {
271 Function *function = new FunctionOperator(op, range, overflowbehavior);
272 allFunctions.push(function);
276 Predicate *CSolver::createPredicateOperator(CompOp op) {
277 Predicate *predicate = new PredicateOperator(op);
278 allPredicates.push(predicate);
282 Predicate *CSolver::createPredicateTable(Table *table, UndefinedBehavior behavior) {
283 Predicate *predicate = new PredicateTable(table, behavior);
284 allPredicates.push(predicate);
288 Table *CSolver::createTable(Set *range) {
289 Table *table = new Table(range);
290 allTables.push(table);
294 Table *CSolver::createTableForPredicate() {
295 return createTable(NULL);
298 void CSolver::addTableEntry(Table *table, uint64_t *inputs, uint inputSize, uint64_t result) {
299 table->addNewTableEntry(inputs, inputSize, result);
302 Function *CSolver::completeTable(Table *table, UndefinedBehavior behavior) {
303 Function *function = new FunctionTable(table, behavior);
304 allFunctions.push(function);
308 BooleanEdge CSolver::getBooleanVar(VarType type) {
309 Boolean *boolean = new BooleanVar(type);
310 allBooleans.push(boolean);
311 return BooleanEdge(boolean);
314 BooleanEdge CSolver::getBooleanTrue() {
318 BooleanEdge CSolver::getBooleanFalse() {
322 BooleanEdge CSolver::applyPredicate(Predicate *predicate, Element **inputs, uint numInputs) {
323 return applyPredicateTable(predicate, inputs, numInputs, BooleanEdge(NULL));
326 BooleanEdge CSolver::applyPredicateTable(Predicate *predicate, Element **inputs, uint numInputs, BooleanEdge undefinedStatus) {
327 BooleanPredicate *boolean = new BooleanPredicate(predicate, inputs, numInputs, undefinedStatus);
328 Boolean *b = boolMap.get(boolean);
330 boolean->updateParents();
331 boolMap.put(boolean, boolean);
332 allBooleans.push(boolean);
333 return BooleanEdge(boolean);
336 return BooleanEdge(b);
340 bool CSolver::isTrue(BooleanEdge b) {
341 return b.isNegated() ? b->isFalse() : b->isTrue();
344 bool CSolver::isFalse(BooleanEdge b) {
345 return b.isNegated() ? b->isTrue() : b->isFalse();
348 BooleanEdge CSolver::applyLogicalOperation(LogicOp op, BooleanEdge arg1, BooleanEdge arg2) {
349 BooleanEdge array[] = {arg1, arg2};
350 return applyLogicalOperation(op, array, 2);
353 BooleanEdge CSolver::applyLogicalOperation(LogicOp op, BooleanEdge arg) {
354 BooleanEdge array[] = {arg};
355 return applyLogicalOperation(op, array, 1);
358 static int booleanEdgeCompares(const void *p1, const void *p2) {
359 BooleanEdge be1 = *(BooleanEdge const *) p1;
360 BooleanEdge be2 = *(BooleanEdge const *) p2;
361 uint64_t b1 = be1->id;
362 uint64_t b2 = be2->id;
371 BooleanEdge CSolver::rewriteLogicalOperation(LogicOp op, BooleanEdge *array, uint asize) {
372 BooleanEdge newarray[asize];
373 memcpy(newarray, array, asize * sizeof(BooleanEdge));
374 for (uint i = 0; i < asize; i++) {
375 BooleanEdge b = newarray[i];
376 if (b->type == LOGICOP) {
377 if (((BooleanLogic *) b.getBoolean())->replaced) {
378 newarray[i] = doRewrite(newarray[i]);
383 return applyLogicalOperation(op, newarray, asize);
386 BooleanEdge CSolver::applyLogicalOperation(LogicOp op, BooleanEdge *array, uint asize) {
387 BooleanEdge newarray[asize];
390 return array[0].negate();
393 for (uint i = 0; i < 2; i++) {
394 if (isTrue(array[i])) { // It can be undefined
396 } else if (isFalse(array[i])) {
397 newarray[0] = array[1 - i];
398 return applyLogicalOperation(SATC_NOT, newarray, 1);
399 } else if (array[i]->type == LOGICOP) {
400 BooleanLogic *b = (BooleanLogic *)array[i].getBoolean();
402 return rewriteLogicalOperation(op, array, asize);
409 for (uint i = 0; i < asize; i++) {
410 newarray[i] = applyLogicalOperation(SATC_NOT, array[i]);
412 return applyLogicalOperation(SATC_NOT, applyLogicalOperation(SATC_AND, newarray, asize));
416 for (uint i = 0; i < asize; i++) {
417 BooleanEdge b = array[i];
418 if (b->type == LOGICOP) {
419 if (((BooleanLogic *)b.getBoolean())->replaced)
420 return rewriteLogicalOperation(op, array, asize);
424 else if (isFalse(b)) {
427 newarray[newindex++] = b;
431 } else if (newindex == 1) {
434 bsdqsort(newarray, newindex, sizeof(BooleanEdge), booleanEdgeCompares);
441 //handle by translation
442 return applyLogicalOperation(SATC_NOT, applyLogicalOperation(SATC_IFF, array, asize));
445 //handle by translation
446 return applyLogicalOperation(SATC_OR, applyLogicalOperation(SATC_NOT, array[0]), array[1]);
451 Boolean *boolean = new BooleanLogic(this, op, array, asize);
452 Boolean *b = boolMap.get(boolean);
454 boolean->updateParents();
455 boolMap.put(boolean, boolean);
456 allBooleans.push(boolean);
457 return BooleanEdge(boolean);
460 return BooleanEdge(b);
464 BooleanEdge CSolver::orderConstraint(Order *order, uint64_t first, uint64_t second) {
465 // ASSERT(first != second);
467 return getBooleanFalse();
470 if (order->type == SATC_TOTAL) {
471 if (first > second) {
472 uint64_t tmp = first;
478 Boolean *constraint = new BooleanOrder(order, first, second);
479 Boolean *b = boolMap.get(constraint);
482 allBooleans.push(constraint);
483 boolMap.put(constraint, constraint);
484 constraint->updateParents();
485 if (order->graph != NULL) {
486 OrderGraph *graph = order->graph;
487 OrderNode *from = graph->lookupOrderNodeFromOrderGraph(first);
489 OrderNode *to = graph->lookupOrderNodeFromOrderGraph(second);
491 OrderEdge *edge = graph->lookupOrderEdgeFromOrderGraph(from, to);
494 if (edge != NULL && edge->mustPos) {
495 replaceBooleanWithTrueNoRemove(constraint);
496 } else if (edge != NULL && edge->mustNeg) {
497 replaceBooleanWithFalseNoRemove(constraint);
498 } else if ((invedge = graph->lookupOrderEdgeFromOrderGraph(to, from)) != NULL
499 && invedge->mustPos) {
500 replaceBooleanWithFalseNoRemove(constraint);
510 BooleanEdge be = BooleanEdge(constraint);
511 return negate ? be.negate() : be;
514 void CSolver::addConstraint(BooleanEdge constraint) {
515 if (isTrue(constraint))
517 else if (isFalse(constraint)) {
521 if (constraint->type == LOGICOP) {
522 BooleanLogic *b = (BooleanLogic *) constraint.getBoolean();
523 if (!constraint.isNegated()) {
524 if (b->op == SATC_AND) {
525 uint size = b->inputs.getSize();
526 //Handle potential concurrent modification
527 BooleanEdge array[size];
528 for (uint i = 0; i < size; i++) {
529 array[i] = b->inputs.get(i);
531 for (uint i = 0; i < size; i++) {
532 addConstraint(array[i]);
538 addConstraint(doRewrite(constraint));
542 constraints.add(constraint);
543 Boolean *ptr = constraint.getBoolean();
545 if (ptr->boolVal == BV_UNSAT) {
549 replaceBooleanWithTrueNoRemove(constraint);
550 constraint->parents.clear();
554 Order *CSolver::createOrder(OrderType type, Set *set) {
555 Order *order = new Order(type, set);
556 allOrders.push(order);
557 activeOrders.add(order);
561 /** Computes static ordering information to allow isTrue/isFalse
562 queries on newly created orders to work. */
564 void CSolver::inferFixedOrder(Order *order) {
565 if (order->graph != NULL) {
568 order->graph = buildMustOrderGraph(order);
569 reachMustAnalysis(this, order->graph, true);
572 void CSolver::inferFixedOrders() {
573 SetIteratorOrder *orderit = activeOrders.iterator();
574 while (orderit->hasNext()) {
575 Order *order = orderit->next();
576 inferFixedOrder(order);
580 #define NANOSEC 1000000000.0
581 int CSolver::solve() {
582 long long startTime = getTimeNano();
583 bool deleteTuner = false;
585 tuner = new DefaultTuner();
591 SetIteratorOrder *orderit = activeOrders.iterator();
592 while (orderit->hasNext()) {
593 Order *order = orderit->next();
594 if (order->graph != NULL) {
601 computePolarities(this);
602 long long time1 = getTimeNano();
603 model_print("Polarity time: %f\n", (time1 - startTime) / NANOSEC);
606 long long time2 = getTimeNano();
607 model_print("Preprocess time: %f\n", (time2 - time1) / NANOSEC);
609 DecomposeOrderTransform dot(this);
611 time1 = getTimeNano();
612 model_print("Decompose Order: %f\n", (time1 - time2) / NANOSEC);
614 IntegerEncodingTransform iet(this);
617 ElementOpt eop(this);
620 EncodingGraph eg(this);
623 naiveEncodingDecision(this);
626 VarOrderingOpt bor(this, satEncoder);
629 time2 = getTimeNano();
630 model_print("Encoding Graph Time: %f\n", (time2 - time1) / NANOSEC);
632 satEncoder->encodeAllSATEncoder(this);
633 time1 = getTimeNano();
635 model_print("Elapse Encode time: %f\n", (time1 - startTime) / NANOSEC);
637 model_print("Is problem UNSAT after encoding: %d\n", unsat);
638 int result = unsat ? IS_UNSAT : satEncoder->solve(satsolverTimeout);
639 model_print("Result Computed in SAT solver:\t%s\n", result == IS_SAT ? "SAT" : result == IS_INDETER ? "INDETERMINATE" : " UNSAT");
640 time2 = getTimeNano();
641 elapsedTime = time2 - startTime;
642 model_print("CSOLVER solve time: %f\n", elapsedTime / NANOSEC);
650 void CSolver::printConstraints() {
651 SetIteratorBooleanEdge *it = getConstraints();
652 while (it->hasNext()) {
653 BooleanEdge b = it->next();
659 void CSolver::printConstraint(BooleanEdge b) {
663 uint64_t CSolver::getElementValue(Element *element) {
664 switch (element->type) {
668 return getElementValueSATTranslator(this, element);
675 bool CSolver::getBooleanValue(BooleanEdge bedge) {
676 Boolean *boolean = bedge.getBoolean();
677 switch (boolean->type) {
679 return getBooleanVariableValueSATTranslator(this, boolean);
686 bool CSolver::getOrderConstraintValue(Order *order, uint64_t first, uint64_t second) {
687 return order->encoding.resolver->resolveOrder(first, second);
690 long long CSolver::getEncodeTime() { return satEncoder->getEncodeTime(); }
692 long long CSolver::getSolveTime() { return satEncoder->getSolveTime(); }
694 void CSolver::autoTune(uint budget) {
695 AutoTuner *autotuner = new AutoTuner(budget);
696 autotuner->addProblem(this);