Bug fix for printing ...
[satune.git] / src / csolver.cc
1 #include "csolver.h"
2 #include "set.h"
3 #include "mutableset.h"
4 #include "element.h"
5 #include "boolean.h"
6 #include "predicate.h"
7 #include "order.h"
8 #include "table.h"
9 #include "function.h"
10 #include "satencoder.h"
11 #include "sattranslator.h"
12 #include "tunable.h"
13 #include "polarityassignment.h"
14 #include "decomposeordertransform.h"
15 #include "autotuner.h"
16 #include "astops.h"
17 #include "structs.h"
18 #include "orderresolver.h"
19 #include "integerencoding.h"
20 #include "qsort.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 <time.h>
30 #include <stdarg.h>
31
32 CSolver::CSolver() :
33         boolTrue(BooleanEdge(new BooleanConst(true))),
34         boolFalse(boolTrue.negate()),
35         unsat(false),
36         tuner(NULL),
37         elapsedTime(0)
38 {
39         satEncoder = new SATEncoder(this);
40 }
41
42 /** This function tears down the solver and the entire AST */
43
44 CSolver::~CSolver() {
45         //serialize();
46         uint size = allBooleans.getSize();
47         for (uint i = 0; i < size; i++) {
48                 delete allBooleans.get(i);
49         }
50
51         size = allSets.getSize();
52         for (uint i = 0; i < size; i++) {
53                 delete allSets.get(i);
54         }
55
56         size = allElements.getSize();
57         for (uint i = 0; i < size; i++) {
58                 Element *el = allElements.get(i);
59                 delete el;
60         }
61
62         size = allTables.getSize();
63         for (uint i = 0; i < size; i++) {
64                 delete allTables.get(i);
65         }
66
67         size = allPredicates.getSize();
68         for (uint i = 0; i < size; i++) {
69                 delete allPredicates.get(i);
70         }
71
72         size = allOrders.getSize();
73         for (uint i = 0; i < size; i++) {
74                 delete allOrders.get(i);
75         }
76         size = allFunctions.getSize();
77         for (uint i = 0; i < size; i++) {
78                 delete allFunctions.get(i);
79         }
80
81         delete boolTrue.getBoolean();
82         delete satEncoder;
83 }
84
85 void CSolver::resetSolver() {
86         //serialize();
87         uint size = allBooleans.getSize();
88         for (uint i = 0; i < size; i++) {
89                 delete allBooleans.get(i);
90         }
91
92         size = allSets.getSize();
93         for (uint i = 0; i < size; i++) {
94                 delete allSets.get(i);
95         }
96
97         size = allElements.getSize();
98         for (uint i = 0; i < size; i++) {
99                 Element *el = allElements.get(i);
100                 delete el;
101         }
102
103         size = allTables.getSize();
104         for (uint i = 0; i < size; i++) {
105                 delete allTables.get(i);
106         }
107
108         size = allPredicates.getSize();
109         for (uint i = 0; i < size; i++) {
110                 delete allPredicates.get(i);
111         }
112
113         size = allOrders.getSize();
114         for (uint i = 0; i < size; i++) {
115                 delete allOrders.get(i);
116         }
117         size = allFunctions.getSize();
118         for (uint i = 0; i < size; i++) {
119                 delete allFunctions.get(i);
120         }
121         delete boolTrue.getBoolean();
122         allBooleans.clear();
123         allSets.clear();
124         allElements.clear();
125         allTables.clear();
126         allPredicates.clear();
127         allOrders.clear();
128         allFunctions.clear();
129         constraints.reset();
130         activeOrders.reset();
131         boolMap.reset();
132         elemMap.reset();
133
134         boolTrue = BooleanEdge(new BooleanConst(true));
135         boolFalse = boolTrue.negate();
136         unsat = false;
137         elapsedTime = 0;
138         tuner = NULL;
139         satEncoder->resetSATEncoder();
140
141 }
142
143 CSolver *CSolver::clone() {
144         CSolver *copy = new CSolver();
145         CloneMap map;
146         SetIteratorBooleanEdge *it = getConstraints();
147         while (it->hasNext()) {
148                 BooleanEdge b = it->next();
149                 copy->addConstraint(cloneEdge(copy, &map, b));
150         }
151         delete it;
152         return copy;
153 }
154
155 CSolver *CSolver::deserialize(const char *file) {
156         model_print("deserializing ...\n");
157         Deserializer deserializer(file);
158         return deserializer.deserialize();
159 }
160
161 void CSolver::serialize() {
162         model_print("serializing ...\n");
163         char buffer[255];
164         long long nanotime = getTimeNano();
165         int numchars = sprintf(buffer, "DUMP%llu", nanotime);
166         Serializer serializer(buffer);
167         SetIteratorBooleanEdge *it = getConstraints();
168         while (it->hasNext()) {
169                 BooleanEdge b = it->next();
170                 serializeBooleanEdge(&serializer, b, true);
171         }
172         delete it;
173 }
174
175 Set *CSolver::createSet(VarType type, uint64_t *elements, uint numelements) {
176         Set *set = new Set(type, elements, numelements);
177         allSets.push(set);
178         return set;
179 }
180
181 Set *CSolver::createRangeSet(VarType type, uint64_t lowrange, uint64_t highrange) {
182         Set *set = new Set(type, lowrange, highrange);
183         allSets.push(set);
184         return set;
185 }
186
187 bool CSolver::itemExistInSet(Set *set, uint64_t item){
188         return set->exists(item);
189 }
190
191 VarType CSolver::getSetVarType(Set *set) {
192         return set->getType();
193 }
194
195 Element *CSolver::createRangeVar(VarType type, uint64_t lowrange, uint64_t highrange) {
196         Set *s = createRangeSet(type, lowrange, highrange);
197         return getElementVar(s);
198 }
199
200 MutableSet *CSolver::createMutableSet(VarType type) {
201         MutableSet *set = new MutableSet(type);
202         allSets.push(set);
203         return set;
204 }
205
206 void CSolver::addItem(MutableSet *set, uint64_t element) {
207         set->addElementMSet(element);
208 }
209
210 uint64_t CSolver::createUniqueItem(MutableSet *set) {
211         uint64_t element = set->getNewUniqueItem();
212         set->addElementMSet(element);
213         return element;
214 }
215
216 void CSolver::finalizeMutableSet(MutableSet *set) {
217         set->finalize();
218 }
219
220 Element *CSolver::getElementVar(Set *set) {
221         Element *element = new ElementSet(set);
222         allElements.push(element);
223         return element;
224 }
225
226 void CSolver::mustHaveValue(Element *element){
227         element->getElementEncoding()->anyValue = true;
228 }
229
230 Set *CSolver::getElementRange (Element *element) {
231         return element->getRange();
232 }
233
234
235 Element *CSolver::getElementConst(VarType type, uint64_t value) {
236         uint64_t array[] = {value};
237         Set *set = new Set(type, array, 1);
238         Element *element = new ElementConst(value, set);
239         Element *e = elemMap.get(element);
240         if (e == NULL) {
241                 allSets.push(set);
242                 allElements.push(element);
243                 elemMap.put(element, element);
244                 return element;
245         } else {
246                 delete set;
247                 delete element;
248                 return e;
249         }
250 }
251
252
253 Element *CSolver::applyFunction(Function *function, Element **array, uint numArrays, BooleanEdge overflowstatus) {
254         Element *element = new ElementFunction(function,array,numArrays,overflowstatus);
255         Element *e = elemMap.get(element);
256         if (e == NULL) {
257                 element->updateParents();
258                 allElements.push(element);
259                 elemMap.put(element, element);
260                 return element;
261         } else {
262                 delete element;
263                 return e;
264         }
265 }
266
267 Function *CSolver::createFunctionOperator(ArithOp op, Set *range, OverFlowBehavior overflowbehavior) {
268         Function *function = new FunctionOperator(op, range, overflowbehavior);
269         allFunctions.push(function);
270         return function;
271 }
272
273 Predicate *CSolver::createPredicateOperator(CompOp op) {
274         Predicate *predicate = new PredicateOperator(op);
275         allPredicates.push(predicate);
276         return predicate;
277 }
278
279 Predicate *CSolver::createPredicateTable(Table *table, UndefinedBehavior behavior) {
280         Predicate *predicate = new PredicateTable(table, behavior);
281         allPredicates.push(predicate);
282         return predicate;
283 }
284
285 Table *CSolver::createTable(Set *range) {
286         Table *table = new Table(range);
287         allTables.push(table);
288         return table;
289 }
290
291 Table *CSolver::createTableForPredicate() {
292         return createTable(NULL);
293 }
294
295 void CSolver::addTableEntry(Table *table, uint64_t *inputs, uint inputSize, uint64_t result) {
296         table->addNewTableEntry(inputs, inputSize, result);
297 }
298
299 Function *CSolver::completeTable(Table *table, UndefinedBehavior behavior) {
300         Function *function = new FunctionTable(table, behavior);
301         allFunctions.push(function);
302         return function;
303 }
304
305 BooleanEdge CSolver::getBooleanVar(VarType type) {
306         Boolean *boolean = new BooleanVar(type);
307         allBooleans.push(boolean);
308         return BooleanEdge(boolean);
309 }
310
311 BooleanEdge CSolver::getBooleanTrue() {
312         return boolTrue;
313 }
314
315 BooleanEdge CSolver::getBooleanFalse() {
316         return boolFalse;
317 }
318
319 BooleanEdge CSolver::applyPredicate(Predicate *predicate, Element **inputs, uint numInputs) {
320         return applyPredicateTable(predicate, inputs, numInputs, BooleanEdge(NULL));
321 }
322
323 BooleanEdge CSolver::applyPredicateTable(Predicate *predicate, Element **inputs, uint numInputs, BooleanEdge undefinedStatus) {
324         BooleanPredicate *boolean = new BooleanPredicate(predicate, inputs, numInputs, undefinedStatus);
325         Boolean *b = boolMap.get(boolean);
326         if (b == NULL) {
327                 boolean->updateParents();
328                 boolMap.put(boolean, boolean);
329                 allBooleans.push(boolean);
330                 return BooleanEdge(boolean);
331         } else {
332                 delete boolean;
333                 return BooleanEdge(b);
334         }
335 }
336
337 bool CSolver::isTrue(BooleanEdge b) {
338         return b.isNegated() ? b->isFalse() : b->isTrue();
339 }
340
341 bool CSolver::isFalse(BooleanEdge b) {
342         return b.isNegated() ? b->isTrue() : b->isFalse();
343 }
344
345 BooleanEdge CSolver::applyLogicalOperation(LogicOp op, BooleanEdge arg1, BooleanEdge arg2) {
346         BooleanEdge array[] = {arg1, arg2};
347         return applyLogicalOperation(op, array, 2);
348 }
349
350 BooleanEdge CSolver::applyLogicalOperation(LogicOp op, BooleanEdge arg) {
351         BooleanEdge array[] = {arg};
352         return applyLogicalOperation(op, array, 1);
353 }
354
355 static int booleanEdgeCompares(const void *p1, const void *p2) {
356         BooleanEdge be1 = *(BooleanEdge const *) p1;
357         BooleanEdge be2 = *(BooleanEdge const *) p2;
358         uint64_t b1 = be1->id;
359         uint64_t b2 = be2->id;
360         if (b1 < b2)
361                 return -1;
362         else if (b1 == b2)
363                 return 0;
364         else
365                 return 1;
366 }
367
368 BooleanEdge CSolver::rewriteLogicalOperation(LogicOp op, BooleanEdge *array, uint asize) {
369         BooleanEdge newarray[asize];
370         memcpy(newarray, array, asize * sizeof(BooleanEdge));
371         for (uint i = 0; i < asize; i++) {
372                 BooleanEdge b = newarray[i];
373                 if (b->type == LOGICOP) {
374                         if (((BooleanLogic *) b.getBoolean())->replaced) {
375                                 newarray[i] = doRewrite(newarray[i]);
376                                 i--;//Check again
377                         }
378                 }
379         }
380         return applyLogicalOperation(op, newarray, asize);
381 }
382
383 BooleanEdge CSolver::applyLogicalOperation(LogicOp op, BooleanEdge *array, uint asize) {
384         BooleanEdge newarray[asize];
385         switch (op) {
386         case SATC_NOT: {
387                 return array[0].negate();
388         }
389         case SATC_IFF: {
390                 for (uint i = 0; i < 2; i++) {
391                         if (isTrue(array[i])) { // It can be undefined
392                                 return array[1 - i];
393                         } else if (isFalse(array[i])) {
394                                 newarray[0] = array[1 - i];
395                                 return applyLogicalOperation(SATC_NOT, newarray, 1);
396                         } else if (array[i]->type == LOGICOP) {
397                                 BooleanLogic *b = (BooleanLogic *)array[i].getBoolean();
398                                 if (b->replaced) {
399                                         return rewriteLogicalOperation(op, array, asize);
400                                 }
401                         }
402                 }
403                 break;
404         }
405         case SATC_OR: {
406                 for (uint i = 0; i < asize; i++) {
407                         newarray[i] = applyLogicalOperation(SATC_NOT, array[i]);
408                 }
409                 return applyLogicalOperation(SATC_NOT, applyLogicalOperation(SATC_AND, newarray, asize));
410         }
411         case SATC_AND: {
412                 uint newindex = 0;
413                 for (uint i = 0; i < asize; i++) {
414                         BooleanEdge b = array[i];
415                         if (b->type == LOGICOP) {
416                                 if (((BooleanLogic *)b.getBoolean())->replaced)
417                                         return rewriteLogicalOperation(op, array, asize);
418                         }
419                         if (isTrue(b))
420                                 continue;
421                         else if (isFalse(b)) {
422                                 return boolFalse;
423                         } else
424                                 newarray[newindex++] = b;
425                 }
426                 if (newindex == 0) {
427                         return boolTrue;
428                 } else if (newindex == 1) {
429                         return newarray[0];
430                 } else {
431                         bsdqsort(newarray, newindex, sizeof(BooleanEdge), booleanEdgeCompares);
432                         array = newarray;
433                         asize = newindex;
434                 }
435                 break;
436         }
437         case SATC_XOR: {
438                 //handle by translation
439                 return applyLogicalOperation(SATC_NOT, applyLogicalOperation(SATC_IFF, array, asize));
440         }
441         case SATC_IMPLIES: {
442                 //handle by translation
443                 return applyLogicalOperation(SATC_OR, applyLogicalOperation(SATC_NOT, array[0]), array[1]);
444         }
445         }
446
447         ASSERT(asize != 0);
448         Boolean *boolean = new BooleanLogic(this, op, array, asize);
449         Boolean *b = boolMap.get(boolean);
450         if (b == NULL) {
451                 boolean->updateParents();
452                 boolMap.put(boolean, boolean);
453                 allBooleans.push(boolean);
454                 return BooleanEdge(boolean);
455         } else {
456                 delete boolean;
457                 return BooleanEdge(b);
458         }
459 }
460
461 BooleanEdge CSolver::orderConstraint(Order *order, uint64_t first, uint64_t second) {
462         //      ASSERT(first != second);
463         if (first == second)
464                 return getBooleanFalse();
465
466         bool negate = false;
467         if (order->type == SATC_TOTAL) {
468                 if (first > second) {
469                         uint64_t tmp = first;
470                         first = second;
471                         second = tmp;
472                         negate = true;
473                 }
474         }
475         Boolean *constraint = new BooleanOrder(order, first, second);
476         Boolean *b = boolMap.get(constraint);
477
478         if (b == NULL) {
479                 allBooleans.push(constraint);
480                 boolMap.put(constraint, constraint);
481                 constraint->updateParents();
482                 if (order->graph != NULL) {
483                         OrderGraph *graph = order->graph;
484                         OrderNode *from = graph->lookupOrderNodeFromOrderGraph(first);
485                         if (from != NULL) {
486                                 OrderNode *to = graph->lookupOrderNodeFromOrderGraph(second);
487                                 if (to != NULL) {
488                                         OrderEdge *edge = graph->lookupOrderEdgeFromOrderGraph(from, to);
489                                         OrderEdge *invedge;
490
491                                         if (edge != NULL && edge->mustPos) {
492                                                 replaceBooleanWithTrueNoRemove(constraint);
493                                         } else if (edge != NULL && edge->mustNeg) {
494                                                 replaceBooleanWithFalseNoRemove(constraint);
495                                         } else if ((invedge = graph->lookupOrderEdgeFromOrderGraph(to, from)) != NULL
496                                                                                  && invedge->mustPos) {
497                                                 replaceBooleanWithFalseNoRemove(constraint);
498                                         }
499                                 }
500                         }
501                 }
502         } else {
503                 delete constraint;
504                 constraint = b;
505         }
506
507         BooleanEdge be = BooleanEdge(constraint);
508         return negate ? be.negate() : be;
509 }
510
511 void CSolver::addConstraint(BooleanEdge constraint) {
512         if (isTrue(constraint))
513                 return;
514         else if (isFalse(constraint)) {
515                 setUnSAT();
516         }
517         else {
518                 if (constraint->type == LOGICOP) {
519                         BooleanLogic *b = (BooleanLogic *) constraint.getBoolean();
520                         if (!constraint.isNegated()) {
521                                 if (b->op == SATC_AND) {
522                                         uint size = b->inputs.getSize();
523                                         //Handle potential concurrent modification
524                                         BooleanEdge array[size];
525                                         for (uint i = 0; i < size; i++) {
526                                                 array[i] = b->inputs.get(i);
527                                         }
528                                         for (uint i = 0; i < size; i++) {
529                                                 addConstraint(array[i]);
530                                         }
531                                         return;
532                                 }
533                         }
534                         if (b->replaced) {
535                                 addConstraint(doRewrite(constraint));
536                                 return;
537                         }
538                 }
539                 constraints.add(constraint);
540                 Boolean *ptr = constraint.getBoolean();
541
542                 if (ptr->boolVal == BV_UNSAT) {
543                         setUnSAT();
544                 }
545
546                 replaceBooleanWithTrueNoRemove(constraint);
547                 constraint->parents.clear();
548         }
549 }
550
551 Order *CSolver::createOrder(OrderType type, Set *set) {
552         Order *order = new Order(type, set);
553         allOrders.push(order);
554         activeOrders.add(order);
555         return order;
556 }
557
558 /** Computes static ordering information to allow isTrue/isFalse
559     queries on newly created orders to work. */
560
561 void CSolver::inferFixedOrder(Order *order) {
562         if (order->graph != NULL) {
563                 delete order->graph;
564         }
565         order->graph = buildMustOrderGraph(order);
566         reachMustAnalysis(this, order->graph, true);
567 }
568
569 void CSolver::inferFixedOrders() {
570         SetIteratorOrder *orderit = activeOrders.iterator();
571         while (orderit->hasNext()) {
572                 Order *order = orderit->next();
573                 inferFixedOrder(order);
574         }
575 }
576
577 #define NANOSEC 1000000000.0
578 int CSolver::solve() {
579         long long starttime = getTimeNano();
580         bool deleteTuner = false;
581         if (tuner == NULL) {
582                 tuner = new DefaultTuner();
583                 deleteTuner = true;
584         }
585
586
587         {
588                 SetIteratorOrder *orderit = activeOrders.iterator();
589                 while (orderit->hasNext()) {
590                         Order *order = orderit->next();
591                         if (order->graph != NULL) {
592                                 delete order->graph;
593                                 order->graph = NULL;
594                         }
595                 }
596                 delete orderit;
597         }
598         computePolarities(this);
599         long long time2 = getTimeNano();
600         model_print("Polarity time: %f\n", (time2 - starttime) / NANOSEC);
601         Preprocess pp(this);
602         pp.doTransform();
603         long long time3 = getTimeNano();
604         model_print("Preprocess time: %f\n", (time3 - time2) / NANOSEC);
605
606         DecomposeOrderTransform dot(this);
607         dot.doTransform();
608         long long time4 = getTimeNano();
609         model_print("Decompose Order: %f\n", (time4 - time3) / NANOSEC);
610
611         IntegerEncodingTransform iet(this);
612         iet.doTransform();
613
614         ElementOpt eop(this);
615         eop.doTransform();
616
617         EncodingGraph eg(this);
618         eg.buildGraph();
619         eg.encode();
620
621         naiveEncodingDecision(this);
622         long long time5 = getTimeNano();
623         model_print("Encoding Graph Time: %f\n", (time5 - time4) / NANOSEC);
624
625         long long startTime = getTimeNano();
626         satEncoder->encodeAllSATEncoder(this);
627         long long endTime = getTimeNano();
628
629         elapsedTime = endTime - startTime;
630         model_print("Elapse Encode time: %f\n", elapsedTime / NANOSEC);
631
632         model_print("Is problem UNSAT after encoding: %d\n", unsat);
633         int result = unsat ? IS_UNSAT : satEncoder->solve();
634         model_print("Result Computed in SAT solver: %d\n", result);
635
636         if (deleteTuner) {
637                 delete tuner;
638                 tuner = NULL;
639         }
640         return result;
641 }
642
643 void CSolver::printConstraints() {
644         SetIteratorBooleanEdge *it = getConstraints();
645         while (it->hasNext()) {
646                 BooleanEdge b = it->next();
647                 b.print();
648         }
649         delete it;
650 }
651
652 void CSolver::printConstraint(BooleanEdge b) {
653         b.print();
654 }
655
656 uint64_t CSolver::getElementValue(Element *element) {
657         switch (element->type) {
658         case ELEMSET:
659         case ELEMCONST:
660         case ELEMFUNCRETURN:
661                 return getElementValueSATTranslator(this, element);
662         default:
663                 ASSERT(0);
664         }
665         exit(-1);
666 }
667
668 bool CSolver::getBooleanValue(BooleanEdge bedge) {
669         Boolean *boolean = bedge.getBoolean();
670         switch (boolean->type) {
671         case BOOLEANVAR:
672                 return getBooleanVariableValueSATTranslator(this, boolean);
673         default:
674                 ASSERT(0);
675         }
676         exit(-1);
677 }
678
679 bool CSolver::getOrderConstraintValue(Order *order, uint64_t first, uint64_t second) {
680         return order->encoding.resolver->resolveOrder(first, second);
681 }
682
683 long long CSolver::getEncodeTime() { return satEncoder->getEncodeTime(); }
684
685 long long CSolver::getSolveTime() { return satEncoder->getSolveTime(); }
686
687 void CSolver::autoTune(uint budget) {
688         AutoTuner *autotuner = new AutoTuner(budget);
689         autotuner->addProblem(this);
690         autotuner->tune();
691         delete autotuner;
692 }
693
694