58177a55647a3fe0f7f344955ccfbacf3efe2757
[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                 int t = 0;
516                 setUnSAT();
517         }
518         else {
519                 if (constraint->type == LOGICOP) {
520                         BooleanLogic *b = (BooleanLogic *) constraint.getBoolean();
521                         if (!constraint.isNegated()) {
522                                 if (b->op == SATC_AND) {
523                                         uint size = b->inputs.getSize();
524                                         //Handle potential concurrent modification
525                                         BooleanEdge array[size];
526                                         for (uint i = 0; i < size; i++) {
527                                                 array[i] = b->inputs.get(i);
528                                         }
529                                         for (uint i = 0; i < size; i++) {
530                                                 addConstraint(array[i]);
531                                         }
532                                         return;
533                                 }
534                         }
535                         if (b->replaced) {
536                                 addConstraint(doRewrite(constraint));
537                                 return;
538                         }
539                 }
540                 constraints.add(constraint);
541                 Boolean *ptr = constraint.getBoolean();
542
543                 if (ptr->boolVal == BV_UNSAT) {
544                         setUnSAT();
545                 }
546
547                 replaceBooleanWithTrueNoRemove(constraint);
548                 constraint->parents.clear();
549         }
550 }
551
552 Order *CSolver::createOrder(OrderType type, Set *set) {
553         Order *order = new Order(type, set);
554         allOrders.push(order);
555         activeOrders.add(order);
556         return order;
557 }
558
559 /** Computes static ordering information to allow isTrue/isFalse
560     queries on newly created orders to work. */
561
562 void CSolver::inferFixedOrder(Order *order) {
563         if (order->graph != NULL) {
564                 delete order->graph;
565         }
566         order->graph = buildMustOrderGraph(order);
567         reachMustAnalysis(this, order->graph, true);
568 }
569
570 void CSolver::inferFixedOrders() {
571         SetIteratorOrder *orderit = activeOrders.iterator();
572         while (orderit->hasNext()) {
573                 Order *order = orderit->next();
574                 inferFixedOrder(order);
575         }
576 }
577
578 #define NANOSEC 1000000000.0
579 int CSolver::solve() {
580         long long starttime = getTimeNano();
581         bool deleteTuner = false;
582         if (tuner == NULL) {
583                 tuner = new DefaultTuner();
584                 deleteTuner = true;
585         }
586
587
588         {
589                 SetIteratorOrder *orderit = activeOrders.iterator();
590                 while (orderit->hasNext()) {
591                         Order *order = orderit->next();
592                         if (order->graph != NULL) {
593                                 delete order->graph;
594                                 order->graph = NULL;
595                         }
596                 }
597                 delete orderit;
598         }
599         computePolarities(this);
600         long long time2 = getTimeNano();
601         model_print("Polarity time: %f\n", (time2 - starttime) / NANOSEC);
602         Preprocess pp(this);
603         pp.doTransform();
604         long long time3 = getTimeNano();
605         model_print("Preprocess time: %f\n", (time3 - time2) / NANOSEC);
606
607         DecomposeOrderTransform dot(this);
608         dot.doTransform();
609         long long time4 = getTimeNano();
610         model_print("Decompose Order: %f\n", (time4 - time3) / NANOSEC);
611
612         IntegerEncodingTransform iet(this);
613         iet.doTransform();
614
615         ElementOpt eop(this);
616         eop.doTransform();
617         
618         EncodingGraph eg(this);
619         eg.buildGraph();
620         eg.encode();
621
622         naiveEncodingDecision(this);
623         long long time5 = getTimeNano();
624         model_print("Encoding Graph Time: %f\n", (time5 - time4) / NANOSEC);
625
626         long long startTime = getTimeNano();
627         satEncoder->encodeAllSATEncoder(this);
628         long long endTime = getTimeNano();
629
630         elapsedTime = endTime - startTime;
631         model_print("Elapse Encode time: %f\n", elapsedTime / NANOSEC);
632
633         model_print("Is problem UNSAT after encoding: %d\n", unsat);
634         int result = unsat ? IS_UNSAT : satEncoder->solve();
635         model_print("Result Computed in SAT solver: %d\n", result);
636
637         if (deleteTuner) {
638                 delete tuner;
639                 tuner = NULL;
640         }
641         return result;
642 }
643
644 void CSolver::printConstraints() {
645         SetIteratorBooleanEdge *it = getConstraints();
646         while (it->hasNext()) {
647                 BooleanEdge b = it->next();
648                 if (b.isNegated())
649                         model_print("!");
650                 b->print();
651                 model_print("\n");
652         }
653         delete it;
654 }
655
656 void CSolver::printConstraint(BooleanEdge b) {
657         if (b.isNegated())
658                 model_print("!");
659         b->print();
660         model_print("\n");
661 }
662
663 uint64_t CSolver::getElementValue(Element *element) {
664         switch (element->type) {
665         case ELEMSET:
666         case ELEMCONST:
667         case ELEMFUNCRETURN:
668                 return getElementValueSATTranslator(this, element);
669         default:
670                 ASSERT(0);
671         }
672         exit(-1);
673 }
674
675 bool CSolver::getBooleanValue(BooleanEdge bedge) {
676         Boolean *boolean = bedge.getBoolean();
677         switch (boolean->type) {
678         case BOOLEANVAR:
679                 return getBooleanVariableValueSATTranslator(this, boolean);
680         default:
681                 ASSERT(0);
682         }
683         exit(-1);
684 }
685
686 bool CSolver::getOrderConstraintValue(Order *order, uint64_t first, uint64_t second) {
687         return order->encoding.resolver->resolveOrder(first, second);
688 }
689
690 long long CSolver::getEncodeTime() { return satEncoder->getEncodeTime(); }
691
692 long long CSolver::getSolveTime() { return satEncoder->getSolveTime(); }
693
694 void CSolver::autoTune(uint budget) {
695         AutoTuner *autotuner = new AutoTuner(budget);
696         autotuner->addProblem(this);
697         autotuner->tune();
698         delete autotuner;
699 }
700
701 //Set* CSolver::addItemsToRange(Element* element, uint num, ...){
702 //        va_list args;
703 //        va_start(args, num);
704 //        element->getRange()
705 //        uint setSize = set->getSize();
706 //        uint newSize = setSize+ num;
707 //        uint64_t members[newSize];
708 //        for(uint i=0; i<setSize; i++){
709 //                members[i] = set->getElement(i);
710 //        }
711 //        for( uint i=0; i< num; i++){
712 //                uint64_t arg = va_arg(args, uint64_t);
713 //                members[setSize+i] = arg;
714 //        }
715 //        va_end(args);
716 //        return createSet(set->getType(), members, newSize);
717 //}