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