(de)serializer: BooleanOrder + BooleanVar
[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
25 CSolver::CSolver() :
26         boolTrue(BooleanEdge(new BooleanConst(true))),
27         boolFalse(boolTrue.negate()),
28         unsat(false),
29         tuner(NULL),
30         elapsedTime(0)
31 {
32         satEncoder = new SATEncoder(this);
33 }
34
35 /** This function tears down the solver and the entire AST */
36
37 CSolver::~CSolver() {
38         uint size = allBooleans.getSize();
39         for (uint i = 0; i < size; i++) {
40                 delete allBooleans.get(i);
41         }
42
43         size = allSets.getSize();
44         for (uint i = 0; i < size; i++) {
45                 delete allSets.get(i);
46         }
47
48         size = allElements.getSize();
49         for (uint i = 0; i < size; i++) {
50                 delete allElements.get(i);
51         }
52
53         size = allTables.getSize();
54         for (uint i = 0; i < size; i++) {
55                 delete allTables.get(i);
56         }
57
58         size = allPredicates.getSize();
59         for (uint i = 0; i < size; i++) {
60                 delete allPredicates.get(i);
61         }
62
63         size = allOrders.getSize();
64         for (uint i = 0; i < size; i++) {
65                 delete allOrders.get(i);
66         }
67
68         size = allFunctions.getSize();
69         for (uint i = 0; i < size; i++) {
70                 delete allFunctions.get(i);
71         }
72
73         delete boolTrue.getBoolean();
74         delete satEncoder;
75 }
76
77 CSolver *CSolver::clone() {
78         CSolver *copy = new CSolver();
79         CloneMap map;
80         SetIteratorBooleanEdge *it = getConstraints();
81         while (it->hasNext()) {
82                 BooleanEdge b = it->next();
83                 copy->addConstraint(cloneEdge(copy, &map, b));
84         }
85         delete it;
86         return copy;
87 }
88
89 void CSolver::serialize() {
90         {
91                 Serializer serializer("dump");
92                 SetIteratorBooleanEdge *it = getConstraints();
93                 while (it->hasNext()) {
94                         BooleanEdge b = it->next();
95                         serializeBooleanEdge(&serializer, b);
96                 }
97                 delete it;
98         }
99         model_print("deserializing ...\n");
100         {
101                 Deserializer deserializer("dump");
102                 deserializer.deserialize();
103         }
104         
105 }
106
107 Set *CSolver::createSet(VarType type, uint64_t *elements, uint numelements) {
108         Set *set = new Set(type, elements, numelements);
109         allSets.push(set);
110         return set;
111 }
112
113 Set *CSolver::createRangeSet(VarType type, uint64_t lowrange, uint64_t highrange) {
114         Set *set = new Set(type, lowrange, highrange);
115         allSets.push(set);
116         return set;
117 }
118
119 Element *CSolver::createRangeVar(VarType type, uint64_t lowrange, uint64_t highrange) {
120         Set *s = createRangeSet(type, lowrange, highrange);
121         return getElementVar(s);
122 }
123
124 MutableSet *CSolver::createMutableSet(VarType type) {
125         MutableSet *set = new MutableSet(type);
126         allSets.push(set);
127         return set;
128 }
129
130 void CSolver::addItem(MutableSet *set, uint64_t element) {
131         set->addElementMSet(element);
132 }
133
134 uint64_t CSolver::createUniqueItem(MutableSet *set) {
135         uint64_t element = set->getNewUniqueItem();
136         set->addElementMSet(element);
137         return element;
138 }
139
140 Element *CSolver::getElementVar(Set *set) {
141         Element *element = new ElementSet(set);
142         allElements.push(element);
143         return element;
144 }
145
146 Element *CSolver::getElementConst(VarType type, uint64_t value) {
147         uint64_t array[] = {value};
148         Set *set = new Set(type, array, 1);
149         Element *element = new ElementConst(value, type, set);
150         Element *e = elemMap.get(element);
151         if (e == NULL) {
152                 allSets.push(set);
153                 allElements.push(element);
154                 elemMap.put(element, element);
155                 return element;
156         } else {
157                 delete set;
158                 delete element;
159                 return e;
160         }
161 }
162
163 Element *CSolver::applyFunction(Function *function, Element **array, uint numArrays, BooleanEdge overflowstatus) {
164         Element *element = new ElementFunction(function,array,numArrays,overflowstatus);
165         Element *e = elemMap.get(element);
166         if (e == NULL) {
167                 element->updateParents();
168                 allElements.push(element);
169                 elemMap.put(element, element);
170                 return element;
171         } else {
172                 delete element;
173                 return e;
174         }
175 }
176
177 Function *CSolver::createFunctionOperator(ArithOp op, Set **domain, uint numDomain, Set *range,OverFlowBehavior overflowbehavior) {
178         Function *function = new FunctionOperator(op, domain, numDomain, range, overflowbehavior);
179         allFunctions.push(function);
180         return function;
181 }
182
183 Predicate *CSolver::createPredicateOperator(CompOp op, Set **domain, uint numDomain) {
184         Predicate *predicate = new PredicateOperator(op, domain,numDomain);
185         allPredicates.push(predicate);
186         return predicate;
187 }
188
189 Predicate *CSolver::createPredicateTable(Table *table, UndefinedBehavior behavior) {
190         Predicate *predicate = new PredicateTable(table, behavior);
191         allPredicates.push(predicate);
192         return predicate;
193 }
194
195 Table *CSolver::createTable(Set **domains, uint numDomain, Set *range) {
196         Table *table = new Table(domains,numDomain,range);
197         allTables.push(table);
198         return table;
199 }
200
201 Table *CSolver::createTableForPredicate(Set **domains, uint numDomain) {
202         return createTable(domains, numDomain, NULL);
203 }
204
205 void CSolver::addTableEntry(Table *table, uint64_t *inputs, uint inputSize, uint64_t result) {
206         table->addNewTableEntry(inputs, inputSize, result);
207 }
208
209 Function *CSolver::completeTable(Table *table, UndefinedBehavior behavior) {
210         Function *function = new FunctionTable(table, behavior);
211         allFunctions.push(function);
212         return function;
213 }
214
215 BooleanEdge CSolver::getBooleanVar(VarType type) {
216         Boolean *boolean = new BooleanVar(type);
217         allBooleans.push(boolean);
218         return BooleanEdge(boolean);
219 }
220
221 BooleanEdge CSolver::getBooleanTrue() {
222         return boolTrue;
223 }
224
225 BooleanEdge CSolver::getBooleanFalse() {
226         return boolFalse;
227 }
228
229 BooleanEdge CSolver::applyPredicate(Predicate *predicate, Element **inputs, uint numInputs) {
230         return applyPredicateTable(predicate, inputs, numInputs, NULL);
231 }
232
233 BooleanEdge CSolver::applyPredicateTable(Predicate *predicate, Element **inputs, uint numInputs, BooleanEdge undefinedStatus) {
234         BooleanPredicate *boolean = new BooleanPredicate(predicate, inputs, numInputs, undefinedStatus);
235         Boolean *b = boolMap.get(boolean);
236         if (b == NULL) {
237                 boolean->updateParents();
238                 boolMap.put(boolean, boolean);
239                 allBooleans.push(boolean);
240                 return BooleanEdge(boolean);
241         } else {
242                 delete boolean;
243                 return BooleanEdge(b);
244         }
245 }
246
247 bool CSolver::isTrue(BooleanEdge b) {
248         return b.isNegated()?b->isFalse():b->isTrue();
249 }
250
251 bool CSolver::isFalse(BooleanEdge b) {
252         return b.isNegated()?b->isTrue():b->isFalse();
253 }
254
255 BooleanEdge CSolver::applyLogicalOperation(LogicOp op, BooleanEdge arg1, BooleanEdge arg2) {
256         BooleanEdge array[] = {arg1, arg2};
257         return applyLogicalOperation(op, array, 2);
258 }
259
260 BooleanEdge CSolver::applyLogicalOperation(LogicOp op, BooleanEdge arg) {
261         BooleanEdge array[] = {arg};
262         return applyLogicalOperation(op, array, 1);
263 }
264
265 static int ptrcompares(const void *p1, const void *p2) {
266         uintptr_t b1 = *(uintptr_t const *) p1;
267   uintptr_t b2 = *(uintptr_t const *) p2;
268         if (b1 < b2)
269                 return -1;
270         else if (b1 == b2)
271                 return 0;
272         else
273                 return 1;
274 }
275
276 BooleanEdge CSolver::rewriteLogicalOperation(LogicOp op, BooleanEdge * array, uint asize) {
277         BooleanEdge newarray[asize];
278         memcpy(newarray, array, asize * sizeof(BooleanEdge));
279         for(uint i=0; i < asize; i++) {
280                 BooleanEdge b=newarray[i];
281                 if (b->type == LOGICOP) {
282                         if (((BooleanLogic *) b.getBoolean())->replaced) {
283                                 newarray[i] = doRewrite(newarray[i]);
284                                 i--;//Check again
285                         }
286                 }
287         }
288         return applyLogicalOperation(op, newarray, asize);
289 }
290
291 BooleanEdge CSolver::applyLogicalOperation(LogicOp op, BooleanEdge *array, uint asize) {
292         BooleanEdge newarray[asize];
293         switch (op) {
294         case SATC_NOT: {
295                 return array[0].negate();
296         }
297         case SATC_IFF: {
298                 for (uint i = 0; i < 2; i++) {
299                         if (array[i]->type == BOOLCONST) {
300                                 if (array[i]->isTrue()) {
301                                         return array[1 - i];
302                                 } else {
303                                         newarray[0] = array[1 - i];
304                                         return applyLogicalOperation(SATC_NOT, newarray, 1);
305                                 }
306                         } else if (array[i]->type == LOGICOP) {
307                                 BooleanLogic *b =(BooleanLogic *)array[i].getBoolean();
308                                 if (b->replaced) {
309                                         return rewriteLogicalOperation(op, array, asize);
310                                 }
311                         }
312                 }
313                 break;
314         }
315         case SATC_OR: {
316                 for (uint i =0; i <asize; i++) {
317                         newarray[i] = applyLogicalOperation(SATC_NOT, array[i]);
318                 }
319                 return applyLogicalOperation(SATC_NOT, applyLogicalOperation(SATC_AND, newarray, asize));
320         }
321         case SATC_AND: {
322                 uint newindex = 0;
323                 for (uint i = 0; i < asize; i++) {
324                         BooleanEdge b = array[i];
325                         if (b->type == LOGICOP) {
326                                 if (((BooleanLogic *)b.getBoolean())->replaced)
327                                         return rewriteLogicalOperation(op, array, asize);
328                         }
329                         if (b->type == BOOLCONST) {
330                                 if (b->isTrue())
331                                         continue;
332                                 else
333                                         return boolFalse;
334                         } else
335                                 newarray[newindex++] = b;
336                 }
337                 if (newindex == 0) {
338                         return boolTrue;
339                 } else if (newindex == 1) {
340                         return newarray[0];
341                 } else {
342                         bsdqsort(newarray, newindex, sizeof(BooleanEdge), ptrcompares);
343                         array = newarray;
344                         asize = newindex;
345                 }
346                 break;
347         }
348         case SATC_XOR: {
349                 //handle by translation
350                 return applyLogicalOperation(SATC_NOT, applyLogicalOperation(SATC_IFF, array, asize));
351         }
352         case SATC_IMPLIES: {
353                 //handle by translation
354                 return applyLogicalOperation(SATC_OR, applyLogicalOperation(SATC_NOT, array[0]), array[1]);
355         }
356         }
357
358         ASSERT(asize != 0);
359         Boolean *boolean = new BooleanLogic(this, op, array, asize);
360         Boolean *b = boolMap.get(boolean);
361         if (b == NULL) {
362                 boolean->updateParents();
363                 boolMap.put(boolean, boolean);
364                 allBooleans.push(boolean);
365                 return BooleanEdge(boolean);
366         } else {
367                 delete boolean;
368                 return BooleanEdge(b);
369         }
370 }
371
372 BooleanEdge CSolver::orderConstraint(Order *order, uint64_t first, uint64_t second) {
373         Boolean *constraint = new BooleanOrder(order, first, second);
374         allBooleans.push(constraint);
375         return BooleanEdge(constraint);
376 }
377
378 void CSolver::addConstraint(BooleanEdge constraint) {
379         if (isTrue(constraint))
380                 return;
381         else if (isFalse(constraint))
382                 setUnSAT();
383         else {
384                 if (constraint->type == LOGICOP) {
385                         BooleanLogic *b=(BooleanLogic *) constraint.getBoolean();
386                         if (!constraint.isNegated()) {
387                                 if (b->op==SATC_AND) {
388                                         for(uint i=0;i<b->inputs.getSize();i++) {
389                                                 addConstraint(b->inputs.get(i));
390                                         }
391                                         return;
392                                 }
393                         }
394                         if (b->replaced) {
395                                 addConstraint(doRewrite(constraint));
396                                 return;
397                         }
398                 }
399                 constraints.add(constraint);
400                 Boolean *ptr=constraint.getBoolean();
401                 
402                 if (ptr->boolVal == BV_UNSAT)
403                         setUnSAT();
404                 
405                 replaceBooleanWithTrueNoRemove(constraint);
406                 constraint->parents.clear();
407         }
408 }
409
410 Order *CSolver::createOrder(OrderType type, Set *set) {
411         Order *order = new Order(type, set);
412         allOrders.push(order);
413         activeOrders.add(order);
414         return order;
415 }
416
417 int CSolver::solve() {
418         bool deleteTuner = false;
419         if (tuner == NULL) {
420                 tuner = new DefaultTuner();
421                 deleteTuner = true;
422         }
423
424         long long startTime = getTimeNano();
425         computePolarities(this);
426
427         Preprocess pp(this);
428         pp.doTransform();
429         
430         DecomposeOrderTransform dot(this);
431         dot.doTransform();
432
433         IntegerEncodingTransform iet(this);
434         iet.doTransform();
435
436         naiveEncodingDecision(this);
437         satEncoder->encodeAllSATEncoder(this);
438         int result = unsat ? IS_UNSAT : satEncoder->solve();
439         long long finishTime = getTimeNano();
440         elapsedTime = finishTime - startTime;
441         if (deleteTuner) {
442                 delete tuner;
443                 tuner = NULL;
444         }
445         return result;
446 }
447
448 uint64_t CSolver::getElementValue(Element *element) {
449         switch (element->type) {
450         case ELEMSET:
451         case ELEMCONST:
452         case ELEMFUNCRETURN:
453                 return getElementValueSATTranslator(this, element);
454         default:
455                 ASSERT(0);
456         }
457         exit(-1);
458 }
459
460 bool CSolver::getBooleanValue(BooleanEdge bedge) {
461         Boolean *boolean=bedge.getBoolean();
462         switch (boolean->type) {
463         case BOOLEANVAR:
464                 return getBooleanVariableValueSATTranslator(this, boolean);
465         default:
466                 ASSERT(0);
467         }
468         exit(-1);
469 }
470
471 bool CSolver::getOrderConstraintValue(Order *order, uint64_t first, uint64_t second) {
472         return order->encoding.resolver->resolveOrder(first, second);
473 }
474
475 long long CSolver::getEncodeTime() { return satEncoder->getEncodeTime(); }
476
477 long long CSolver::getSolveTime() { return satEncoder->getSolveTime(); }
478
479 void CSolver::autoTune(uint budget) {
480         AutoTuner *autotuner = new AutoTuner(budget);
481         autotuner->addProblem(this);
482         autotuner->tune();
483         delete autotuner;
484 }