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