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