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