Fix <strings.h> includes
[platform/upstream/isl.git] / isl_map_simplify.c
1 /*
2  * Copyright 2008-2009 Katholieke Universiteit Leuven
3  *
4  * Use of this software is governed by the GNU LGPLv2.1 license
5  *
6  * Written by Sven Verdoolaege, K.U.Leuven, Departement
7  * Computerwetenschappen, Celestijnenlaan 200A, B-3001 Leuven, Belgium
8  */
9
10 #include <strings.h>
11 #include <isl_ctx_private.h>
12 #include <isl_map_private.h>
13 #include "isl_equalities.h"
14 #include <isl/map.h>
15 #include <isl/seq.h>
16 #include "isl_tab.h"
17 #include <isl_dim_private.h>
18 #include <isl_mat_private.h>
19
20 static void swap_equality(struct isl_basic_map *bmap, int a, int b)
21 {
22         isl_int *t = bmap->eq[a];
23         bmap->eq[a] = bmap->eq[b];
24         bmap->eq[b] = t;
25 }
26
27 static void swap_inequality(struct isl_basic_map *bmap, int a, int b)
28 {
29         if (a != b) {
30                 isl_int *t = bmap->ineq[a];
31                 bmap->ineq[a] = bmap->ineq[b];
32                 bmap->ineq[b] = t;
33         }
34 }
35
36 static void constraint_drop_vars(isl_int *c, unsigned n, unsigned rem)
37 {
38         isl_seq_cpy(c, c + n, rem);
39         isl_seq_clr(c + rem, n);
40 }
41
42 /* Drop n dimensions starting at first.
43  *
44  * In principle, this frees up some extra variables as the number
45  * of columns remains constant, but we would have to extend
46  * the div array too as the number of rows in this array is assumed
47  * to be equal to extra.
48  */
49 struct isl_basic_set *isl_basic_set_drop_dims(
50                 struct isl_basic_set *bset, unsigned first, unsigned n)
51 {
52         int i;
53
54         if (!bset)
55                 goto error;
56
57         isl_assert(bset->ctx, first + n <= bset->dim->n_out, goto error);
58
59         if (n == 0 && !isl_dim_get_tuple_name(bset->dim, isl_dim_set))
60                 return bset;
61
62         bset = isl_basic_set_cow(bset);
63         if (!bset)
64                 return NULL;
65
66         for (i = 0; i < bset->n_eq; ++i)
67                 constraint_drop_vars(bset->eq[i]+1+bset->dim->nparam+first, n,
68                                      (bset->dim->n_out-first-n)+bset->extra);
69
70         for (i = 0; i < bset->n_ineq; ++i)
71                 constraint_drop_vars(bset->ineq[i]+1+bset->dim->nparam+first, n,
72                                      (bset->dim->n_out-first-n)+bset->extra);
73
74         for (i = 0; i < bset->n_div; ++i)
75                 constraint_drop_vars(bset->div[i]+1+1+bset->dim->nparam+first, n,
76                                      (bset->dim->n_out-first-n)+bset->extra);
77
78         bset->dim = isl_dim_drop_outputs(bset->dim, first, n);
79         if (!bset->dim)
80                 goto error;
81
82         ISL_F_CLR(bset, ISL_BASIC_SET_NORMALIZED);
83         bset = isl_basic_set_simplify(bset);
84         return isl_basic_set_finalize(bset);
85 error:
86         isl_basic_set_free(bset);
87         return NULL;
88 }
89
90 struct isl_set *isl_set_drop_dims(
91                 struct isl_set *set, unsigned first, unsigned n)
92 {
93         int i;
94
95         if (!set)
96                 goto error;
97
98         isl_assert(set->ctx, first + n <= set->dim->n_out, goto error);
99
100         if (n == 0 && !isl_dim_get_tuple_name(set->dim, isl_dim_set))
101                 return set;
102         set = isl_set_cow(set);
103         if (!set)
104                 goto error;
105         set->dim = isl_dim_drop_outputs(set->dim, first, n);
106         if (!set->dim)
107                 goto error;
108
109         for (i = 0; i < set->n; ++i) {
110                 set->p[i] = isl_basic_set_drop_dims(set->p[i], first, n);
111                 if (!set->p[i])
112                         goto error;
113         }
114
115         ISL_F_CLR(set, ISL_SET_NORMALIZED);
116         return set;
117 error:
118         isl_set_free(set);
119         return NULL;
120 }
121
122 /* Move "n" divs starting at "first" to the end of the list of divs.
123  */
124 static struct isl_basic_map *move_divs_last(struct isl_basic_map *bmap,
125         unsigned first, unsigned n)
126 {
127         isl_int **div;
128         int i;
129
130         if (first + n == bmap->n_div)
131                 return bmap;
132
133         div = isl_alloc_array(bmap->ctx, isl_int *, n);
134         if (!div)
135                 goto error;
136         for (i = 0; i < n; ++i)
137                 div[i] = bmap->div[first + i];
138         for (i = 0; i < bmap->n_div - first - n; ++i)
139                 bmap->div[first + i] = bmap->div[first + n + i];
140         for (i = 0; i < n; ++i)
141                 bmap->div[bmap->n_div - n + i] = div[i];
142         free(div);
143         return bmap;
144 error:
145         isl_basic_map_free(bmap);
146         return NULL;
147 }
148
149 /* Drop "n" dimensions of type "type" starting at "first".
150  *
151  * In principle, this frees up some extra variables as the number
152  * of columns remains constant, but we would have to extend
153  * the div array too as the number of rows in this array is assumed
154  * to be equal to extra.
155  */
156 struct isl_basic_map *isl_basic_map_drop(struct isl_basic_map *bmap,
157         enum isl_dim_type type, unsigned first, unsigned n)
158 {
159         int i;
160         unsigned dim;
161         unsigned offset;
162         unsigned left;
163
164         if (!bmap)
165                 goto error;
166
167         dim = isl_basic_map_dim(bmap, type);
168         isl_assert(bmap->ctx, first + n <= dim, goto error);
169
170         if (n == 0 && !isl_dim_get_tuple_name(bmap->dim, type))
171                 return bmap;
172
173         bmap = isl_basic_map_cow(bmap);
174         if (!bmap)
175                 return NULL;
176
177         offset = isl_basic_map_offset(bmap, type) + first;
178         left = isl_basic_map_total_dim(bmap) - (offset - 1) - n;
179         for (i = 0; i < bmap->n_eq; ++i)
180                 constraint_drop_vars(bmap->eq[i]+offset, n, left);
181
182         for (i = 0; i < bmap->n_ineq; ++i)
183                 constraint_drop_vars(bmap->ineq[i]+offset, n, left);
184
185         for (i = 0; i < bmap->n_div; ++i)
186                 constraint_drop_vars(bmap->div[i]+1+offset, n, left);
187
188         if (type == isl_dim_div) {
189                 bmap = move_divs_last(bmap, first, n);
190                 if (!bmap)
191                         goto error;
192                 isl_basic_map_free_div(bmap, n);
193         } else
194                 bmap->dim = isl_dim_drop(bmap->dim, type, first, n);
195         if (!bmap->dim)
196                 goto error;
197
198         ISL_F_CLR(bmap, ISL_BASIC_MAP_NORMALIZED);
199         bmap = isl_basic_map_simplify(bmap);
200         return isl_basic_map_finalize(bmap);
201 error:
202         isl_basic_map_free(bmap);
203         return NULL;
204 }
205
206 __isl_give isl_basic_set *isl_basic_set_drop(__isl_take isl_basic_set *bset,
207         enum isl_dim_type type, unsigned first, unsigned n)
208 {
209         return (isl_basic_set *)isl_basic_map_drop((isl_basic_map *)bset,
210                                                         type, first, n);
211 }
212
213 struct isl_basic_map *isl_basic_map_drop_inputs(
214                 struct isl_basic_map *bmap, unsigned first, unsigned n)
215 {
216         return isl_basic_map_drop(bmap, isl_dim_in, first, n);
217 }
218
219 struct isl_map *isl_map_drop(struct isl_map *map,
220         enum isl_dim_type type, unsigned first, unsigned n)
221 {
222         int i;
223
224         if (!map)
225                 goto error;
226
227         isl_assert(map->ctx, first + n <= isl_map_dim(map, type), goto error);
228
229         if (n == 0 && !isl_dim_get_tuple_name(map->dim, type))
230                 return map;
231         map = isl_map_cow(map);
232         if (!map)
233                 goto error;
234         map->dim = isl_dim_drop(map->dim, type, first, n);
235         if (!map->dim)
236                 goto error;
237
238         for (i = 0; i < map->n; ++i) {
239                 map->p[i] = isl_basic_map_drop(map->p[i], type, first, n);
240                 if (!map->p[i])
241                         goto error;
242         }
243         ISL_F_CLR(map, ISL_MAP_NORMALIZED);
244
245         return map;
246 error:
247         isl_map_free(map);
248         return NULL;
249 }
250
251 struct isl_set *isl_set_drop(struct isl_set *set,
252         enum isl_dim_type type, unsigned first, unsigned n)
253 {
254         return (isl_set *)isl_map_drop((isl_map *)set, type, first, n);
255 }
256
257 struct isl_map *isl_map_drop_inputs(
258                 struct isl_map *map, unsigned first, unsigned n)
259 {
260         return isl_map_drop(map, isl_dim_in, first, n);
261 }
262
263 /*
264  * We don't cow, as the div is assumed to be redundant.
265  */
266 static struct isl_basic_map *isl_basic_map_drop_div(
267                 struct isl_basic_map *bmap, unsigned div)
268 {
269         int i;
270         unsigned pos;
271
272         if (!bmap)
273                 goto error;
274
275         pos = 1 + isl_dim_total(bmap->dim) + div;
276
277         isl_assert(bmap->ctx, div < bmap->n_div, goto error);
278
279         for (i = 0; i < bmap->n_eq; ++i)
280                 constraint_drop_vars(bmap->eq[i]+pos, 1, bmap->extra-div-1);
281
282         for (i = 0; i < bmap->n_ineq; ++i) {
283                 if (!isl_int_is_zero(bmap->ineq[i][pos])) {
284                         isl_basic_map_drop_inequality(bmap, i);
285                         --i;
286                         continue;
287                 }
288                 constraint_drop_vars(bmap->ineq[i]+pos, 1, bmap->extra-div-1);
289         }
290
291         for (i = 0; i < bmap->n_div; ++i)
292                 constraint_drop_vars(bmap->div[i]+1+pos, 1, bmap->extra-div-1);
293
294         if (div != bmap->n_div - 1) {
295                 int j;
296                 isl_int *t = bmap->div[div];
297
298                 for (j = div; j < bmap->n_div - 1; ++j)
299                         bmap->div[j] = bmap->div[j+1];
300
301                 bmap->div[bmap->n_div - 1] = t;
302         }
303         ISL_F_CLR(bmap, ISL_BASIC_MAP_NORMALIZED);
304         isl_basic_map_free_div(bmap, 1);
305
306         return bmap;
307 error:
308         isl_basic_map_free(bmap);
309         return NULL;
310 }
311
312 struct isl_basic_map *isl_basic_map_normalize_constraints(
313         struct isl_basic_map *bmap)
314 {
315         int i;
316         isl_int gcd;
317         unsigned total = isl_basic_map_total_dim(bmap);
318
319         if (!bmap)
320                 return NULL;
321
322         isl_int_init(gcd);
323         for (i = bmap->n_eq - 1; i >= 0; --i) {
324                 isl_seq_gcd(bmap->eq[i]+1, total, &gcd);
325                 if (isl_int_is_zero(gcd)) {
326                         if (!isl_int_is_zero(bmap->eq[i][0])) {
327                                 bmap = isl_basic_map_set_to_empty(bmap);
328                                 break;
329                         }
330                         isl_basic_map_drop_equality(bmap, i);
331                         continue;
332                 }
333                 if (ISL_F_ISSET(bmap, ISL_BASIC_MAP_RATIONAL))
334                         isl_int_gcd(gcd, gcd, bmap->eq[i][0]);
335                 if (isl_int_is_one(gcd))
336                         continue;
337                 if (!isl_int_is_divisible_by(bmap->eq[i][0], gcd)) {
338                         bmap = isl_basic_map_set_to_empty(bmap);
339                         break;
340                 }
341                 isl_seq_scale_down(bmap->eq[i], bmap->eq[i], gcd, 1+total);
342         }
343
344         for (i = bmap->n_ineq - 1; i >= 0; --i) {
345                 isl_seq_gcd(bmap->ineq[i]+1, total, &gcd);
346                 if (isl_int_is_zero(gcd)) {
347                         if (isl_int_is_neg(bmap->ineq[i][0])) {
348                                 bmap = isl_basic_map_set_to_empty(bmap);
349                                 break;
350                         }
351                         isl_basic_map_drop_inequality(bmap, i);
352                         continue;
353                 }
354                 if (ISL_F_ISSET(bmap, ISL_BASIC_MAP_RATIONAL))
355                         isl_int_gcd(gcd, gcd, bmap->ineq[i][0]);
356                 if (isl_int_is_one(gcd))
357                         continue;
358                 isl_int_fdiv_q(bmap->ineq[i][0], bmap->ineq[i][0], gcd);
359                 isl_seq_scale_down(bmap->ineq[i]+1, bmap->ineq[i]+1, gcd, total);
360         }
361         isl_int_clear(gcd);
362
363         return bmap;
364 }
365
366 struct isl_basic_set *isl_basic_set_normalize_constraints(
367         struct isl_basic_set *bset)
368 {
369         return (struct isl_basic_set *)isl_basic_map_normalize_constraints(
370                 (struct isl_basic_map *)bset);
371 }
372
373 /* Assumes divs have been ordered if keep_divs is set.
374  */
375 static void eliminate_var_using_equality(struct isl_basic_map *bmap,
376         unsigned pos, isl_int *eq, int keep_divs, int *progress)
377 {
378         unsigned total;
379         int k;
380         int last_div;
381
382         total = isl_basic_map_total_dim(bmap);
383         last_div = isl_seq_last_non_zero(eq + 1 + isl_dim_total(bmap->dim),
384                                                 bmap->n_div);
385         for (k = 0; k < bmap->n_eq; ++k) {
386                 if (bmap->eq[k] == eq)
387                         continue;
388                 if (isl_int_is_zero(bmap->eq[k][1+pos]))
389                         continue;
390                 if (progress)
391                         *progress = 1;
392                 isl_seq_elim(bmap->eq[k], eq, 1+pos, 1+total, NULL);
393                 isl_seq_normalize(bmap->ctx, bmap->eq[k], 1 + total);
394         }
395
396         for (k = 0; k < bmap->n_ineq; ++k) {
397                 if (isl_int_is_zero(bmap->ineq[k][1+pos]))
398                         continue;
399                 if (progress)
400                         *progress = 1;
401                 isl_seq_elim(bmap->ineq[k], eq, 1+pos, 1+total, NULL);
402                 isl_seq_normalize(bmap->ctx, bmap->ineq[k], 1 + total);
403                 ISL_F_CLR(bmap, ISL_BASIC_MAP_NORMALIZED);
404         }
405
406         for (k = 0; k < bmap->n_div; ++k) {
407                 if (isl_int_is_zero(bmap->div[k][0]))
408                         continue;
409                 if (isl_int_is_zero(bmap->div[k][1+1+pos]))
410                         continue;
411                 if (progress)
412                         *progress = 1;
413                 /* We need to be careful about circular definitions,
414                  * so for now we just remove the definition of div k
415                  * if the equality contains any divs.
416                  * If keep_divs is set, then the divs have been ordered
417                  * and we can keep the definition as long as the result
418                  * is still ordered.
419                  */
420                 if (last_div == -1 || (keep_divs && last_div < k))
421                         isl_seq_elim(bmap->div[k]+1, eq,
422                                         1+pos, 1+total, &bmap->div[k][0]);
423                 else
424                         isl_seq_clr(bmap->div[k], 1 + total);
425                 ISL_F_CLR(bmap, ISL_BASIC_MAP_NORMALIZED);
426         }
427 }
428
429 /* Assumes divs have been ordered if keep_divs is set.
430  */
431 static void eliminate_div(struct isl_basic_map *bmap, isl_int *eq,
432         unsigned div, int keep_divs)
433 {
434         unsigned pos = isl_dim_total(bmap->dim) + div;
435
436         eliminate_var_using_equality(bmap, pos, eq, keep_divs, NULL);
437
438         isl_basic_map_drop_div(bmap, div);
439 }
440
441 /* Check if elimination of div "div" using equality "eq" would not
442  * result in a div depending on a later div.
443  */
444 static int ok_to_eliminate_div(struct isl_basic_map *bmap, isl_int *eq,
445         unsigned div)
446 {
447         int k;
448         int last_div;
449         unsigned pos = isl_dim_total(bmap->dim) + div;
450
451         last_div = isl_seq_last_non_zero(eq + 1 + isl_dim_total(bmap->dim),
452                                                 bmap->n_div);
453         if (last_div < 0 || last_div <= div)
454                 return 1;
455
456         for (k = 0; k <= last_div; ++k) {
457                 if (isl_int_is_zero(bmap->div[k][0]))
458                         return 1;
459                 if (!isl_int_is_zero(bmap->div[k][1 + 1 + pos]))
460                         return 0;
461         }
462
463         return 1;
464 }
465
466 /* Elimininate divs based on equalities
467  */
468 static struct isl_basic_map *eliminate_divs_eq(
469                 struct isl_basic_map *bmap, int *progress)
470 {
471         int d;
472         int i;
473         int modified = 0;
474         unsigned off;
475
476         bmap = isl_basic_map_order_divs(bmap);
477
478         if (!bmap)
479                 return NULL;
480
481         off = 1 + isl_dim_total(bmap->dim);
482
483         for (d = bmap->n_div - 1; d >= 0 ; --d) {
484                 for (i = 0; i < bmap->n_eq; ++i) {
485                         if (!isl_int_is_one(bmap->eq[i][off + d]) &&
486                             !isl_int_is_negone(bmap->eq[i][off + d]))
487                                 continue;
488                         if (!ok_to_eliminate_div(bmap, bmap->eq[i], d))
489                                 continue;
490                         modified = 1;
491                         *progress = 1;
492                         eliminate_div(bmap, bmap->eq[i], d, 1);
493                         isl_basic_map_drop_equality(bmap, i);
494                         break;
495                 }
496         }
497         if (modified)
498                 return eliminate_divs_eq(bmap, progress);
499         return bmap;
500 }
501
502 /* Elimininate divs based on inequalities
503  */
504 static struct isl_basic_map *eliminate_divs_ineq(
505                 struct isl_basic_map *bmap, int *progress)
506 {
507         int d;
508         int i;
509         unsigned off;
510         struct isl_ctx *ctx;
511
512         if (!bmap)
513                 return NULL;
514
515         ctx = bmap->ctx;
516         off = 1 + isl_dim_total(bmap->dim);
517
518         for (d = bmap->n_div - 1; d >= 0 ; --d) {
519                 for (i = 0; i < bmap->n_eq; ++i)
520                         if (!isl_int_is_zero(bmap->eq[i][off + d]))
521                                 break;
522                 if (i < bmap->n_eq)
523                         continue;
524                 for (i = 0; i < bmap->n_ineq; ++i)
525                         if (isl_int_abs_gt(bmap->ineq[i][off + d], ctx->one))
526                                 break;
527                 if (i < bmap->n_ineq)
528                         continue;
529                 *progress = 1;
530                 bmap = isl_basic_map_eliminate_vars(bmap, (off-1)+d, 1);
531                 if (!bmap || ISL_F_ISSET(bmap, ISL_BASIC_MAP_EMPTY))
532                         break;
533                 bmap = isl_basic_map_drop_div(bmap, d);
534                 if (!bmap)
535                         break;
536         }
537         return bmap;
538 }
539
540 struct isl_basic_map *isl_basic_map_gauss(
541         struct isl_basic_map *bmap, int *progress)
542 {
543         int k;
544         int done;
545         int last_var;
546         unsigned total_var;
547         unsigned total;
548
549         bmap = isl_basic_map_order_divs(bmap);
550
551         if (!bmap)
552                 return NULL;
553
554         total = isl_basic_map_total_dim(bmap);
555         total_var = total - bmap->n_div;
556
557         last_var = total - 1;
558         for (done = 0; done < bmap->n_eq; ++done) {
559                 for (; last_var >= 0; --last_var) {
560                         for (k = done; k < bmap->n_eq; ++k)
561                                 if (!isl_int_is_zero(bmap->eq[k][1+last_var]))
562                                         break;
563                         if (k < bmap->n_eq)
564                                 break;
565                 }
566                 if (last_var < 0)
567                         break;
568                 if (k != done)
569                         swap_equality(bmap, k, done);
570                 if (isl_int_is_neg(bmap->eq[done][1+last_var]))
571                         isl_seq_neg(bmap->eq[done], bmap->eq[done], 1+total);
572
573                 eliminate_var_using_equality(bmap, last_var, bmap->eq[done], 1,
574                                                 progress);
575
576                 if (last_var >= total_var &&
577                     isl_int_is_zero(bmap->div[last_var - total_var][0])) {
578                         unsigned div = last_var - total_var;
579                         isl_seq_neg(bmap->div[div]+1, bmap->eq[done], 1+total);
580                         isl_int_set_si(bmap->div[div][1+1+last_var], 0);
581                         isl_int_set(bmap->div[div][0],
582                                     bmap->eq[done][1+last_var]);
583                         ISL_F_CLR(bmap, ISL_BASIC_MAP_NORMALIZED);
584                 }
585         }
586         if (done == bmap->n_eq)
587                 return bmap;
588         for (k = done; k < bmap->n_eq; ++k) {
589                 if (isl_int_is_zero(bmap->eq[k][0]))
590                         continue;
591                 return isl_basic_map_set_to_empty(bmap);
592         }
593         isl_basic_map_free_equality(bmap, bmap->n_eq-done);
594         return bmap;
595 }
596
597 struct isl_basic_set *isl_basic_set_gauss(
598         struct isl_basic_set *bset, int *progress)
599 {
600         return (struct isl_basic_set*)isl_basic_map_gauss(
601                         (struct isl_basic_map *)bset, progress);
602 }
603
604
605 static unsigned int round_up(unsigned int v)
606 {
607         int old_v = v;
608
609         while (v) {
610                 old_v = v;
611                 v ^= v & -v;
612         }
613         return old_v << 1;
614 }
615
616 static int hash_index(isl_int ***index, unsigned int size, int bits,
617                         struct isl_basic_map *bmap, int k)
618 {
619         int h;
620         unsigned total = isl_basic_map_total_dim(bmap);
621         uint32_t hash = isl_seq_get_hash_bits(bmap->ineq[k]+1, total, bits);
622         for (h = hash; index[h]; h = (h+1) % size)
623                 if (&bmap->ineq[k] != index[h] &&
624                     isl_seq_eq(bmap->ineq[k]+1, index[h][0]+1, total))
625                         break;
626         return h;
627 }
628
629 static int set_hash_index(isl_int ***index, unsigned int size, int bits,
630                           struct isl_basic_set *bset, int k)
631 {
632         return hash_index(index, size, bits, (struct isl_basic_map *)bset, k);
633 }
634
635 /* If we can eliminate more than one div, then we need to make
636  * sure we do it from last div to first div, in order not to
637  * change the position of the other divs that still need to
638  * be removed.
639  */
640 static struct isl_basic_map *remove_duplicate_divs(
641         struct isl_basic_map *bmap, int *progress)
642 {
643         unsigned int size;
644         int *index;
645         int *elim_for;
646         int k, l, h;
647         int bits;
648         struct isl_blk eq;
649         unsigned total_var;
650         unsigned total;
651         struct isl_ctx *ctx;
652
653         if (!bmap || bmap->n_div <= 1)
654                 return bmap;
655
656         total_var = isl_dim_total(bmap->dim);
657         total = total_var + bmap->n_div;
658
659         ctx = bmap->ctx;
660         for (k = bmap->n_div - 1; k >= 0; --k)
661                 if (!isl_int_is_zero(bmap->div[k][0]))
662                         break;
663         if (k <= 0)
664                 return bmap;
665
666         elim_for = isl_calloc_array(ctx, int, bmap->n_div);
667         size = round_up(4 * bmap->n_div / 3 - 1);
668         bits = ffs(size) - 1;
669         index = isl_calloc_array(ctx, int, size);
670         if (!index)
671                 return bmap;
672         eq = isl_blk_alloc(ctx, 1+total);
673         if (isl_blk_is_error(eq))
674                 goto out;
675
676         isl_seq_clr(eq.data, 1+total);
677         index[isl_seq_get_hash_bits(bmap->div[k], 2+total, bits)] = k + 1;
678         for (--k; k >= 0; --k) {
679                 uint32_t hash;
680
681                 if (isl_int_is_zero(bmap->div[k][0]))
682                         continue;
683
684                 hash = isl_seq_get_hash_bits(bmap->div[k], 2+total, bits);
685                 for (h = hash; index[h]; h = (h+1) % size)
686                         if (isl_seq_eq(bmap->div[k],
687                                        bmap->div[index[h]-1], 2+total))
688                                 break;
689                 if (index[h]) {
690                         *progress = 1;
691                         l = index[h] - 1;
692                         elim_for[l] = k + 1;
693                 }
694                 index[h] = k+1;
695         }
696         for (l = bmap->n_div - 1; l >= 0; --l) {
697                 if (!elim_for[l])
698                         continue;
699                 k = elim_for[l] - 1;
700                 isl_int_set_si(eq.data[1+total_var+k], -1);
701                 isl_int_set_si(eq.data[1+total_var+l], 1);
702                 eliminate_div(bmap, eq.data, l, 0);
703                 isl_int_set_si(eq.data[1+total_var+k], 0);
704                 isl_int_set_si(eq.data[1+total_var+l], 0);
705         }
706
707         isl_blk_free(ctx, eq);
708 out:
709         free(index);
710         free(elim_for);
711         return bmap;
712 }
713
714 static int n_pure_div_eq(struct isl_basic_map *bmap)
715 {
716         int i, j;
717         unsigned total;
718
719         total = isl_dim_total(bmap->dim);
720         for (i = 0, j = bmap->n_div-1; i < bmap->n_eq; ++i) {
721                 while (j >= 0 && isl_int_is_zero(bmap->eq[i][1 + total + j]))
722                         --j;
723                 if (j < 0)
724                         break;
725                 if (isl_seq_first_non_zero(bmap->eq[i] + 1 + total, j) != -1)
726                         return 0;
727         }
728         return i;
729 }
730
731 /* Normalize divs that appear in equalities.
732  *
733  * In particular, we assume that bmap contains some equalities
734  * of the form
735  *
736  *      a x = m * e_i
737  *
738  * and we want to replace the set of e_i by a minimal set and
739  * such that the new e_i have a canonical representation in terms
740  * of the vector x.
741  * If any of the equalities involves more than one divs, then
742  * we currently simply bail out.
743  *
744  * Let us first additionally assume that all equalities involve
745  * a div.  The equalities then express modulo constraints on the
746  * remaining variables and we can use "parameter compression"
747  * to find a minimal set of constraints.  The result is a transformation
748  *
749  *      x = T(x') = x_0 + G x'
750  *
751  * with G a lower-triangular matrix with all elements below the diagonal
752  * non-negative and smaller than the diagonal element on the same row.
753  * We first normalize x_0 by making the same property hold in the affine
754  * T matrix.
755  * The rows i of G with a 1 on the diagonal do not impose any modulo
756  * constraint and simply express x_i = x'_i.
757  * For each of the remaining rows i, we introduce a div and a corresponding
758  * equality.  In particular
759  *
760  *      g_ii e_j = x_i - g_i(x')
761  *
762  * where each x'_k is replaced either by x_k (if g_kk = 1) or the
763  * corresponding div (if g_kk != 1).
764  *
765  * If there are any equalities not involving any div, then we
766  * first apply a variable compression on the variables x:
767  *
768  *      x = C x''       x'' = C_2 x
769  *
770  * and perform the above parameter compression on A C instead of on A.
771  * The resulting compression is then of the form
772  *
773  *      x'' = T(x') = x_0 + G x'
774  *
775  * and in constructing the new divs and the corresponding equalities,
776  * we have to replace each x'', i.e., the x'_k with (g_kk = 1),
777  * by the corresponding row from C_2.
778  */
779 static struct isl_basic_map *normalize_divs(
780         struct isl_basic_map *bmap, int *progress)
781 {
782         int i, j, k;
783         int total;
784         int div_eq;
785         struct isl_mat *B;
786         struct isl_vec *d;
787         struct isl_mat *T = NULL;
788         struct isl_mat *C = NULL;
789         struct isl_mat *C2 = NULL;
790         isl_int v;
791         int *pos;
792         int dropped, needed;
793
794         if (!bmap)
795                 return NULL;
796
797         if (bmap->n_div == 0)
798                 return bmap;
799
800         if (bmap->n_eq == 0)
801                 return bmap;
802
803         if (ISL_F_ISSET(bmap, ISL_BASIC_MAP_NORMALIZED_DIVS))
804                 return bmap;
805
806         total = isl_dim_total(bmap->dim);
807         div_eq = n_pure_div_eq(bmap);
808         if (div_eq == 0)
809                 return bmap;
810
811         if (div_eq < bmap->n_eq) {
812                 B = isl_mat_sub_alloc6(bmap->ctx, bmap->eq, div_eq,
813                                         bmap->n_eq - div_eq, 0, 1 + total);
814                 C = isl_mat_variable_compression(B, &C2);
815                 if (!C || !C2)
816                         goto error;
817                 if (C->n_col == 0) {
818                         bmap = isl_basic_map_set_to_empty(bmap);
819                         isl_mat_free(C);
820                         isl_mat_free(C2);
821                         goto done;
822                 }
823         }
824
825         d = isl_vec_alloc(bmap->ctx, div_eq);
826         if (!d)
827                 goto error;
828         for (i = 0, j = bmap->n_div-1; i < div_eq; ++i) {
829                 while (j >= 0 && isl_int_is_zero(bmap->eq[i][1 + total + j]))
830                         --j;
831                 isl_int_set(d->block.data[i], bmap->eq[i][1 + total + j]);
832         }
833         B = isl_mat_sub_alloc6(bmap->ctx, bmap->eq, 0, div_eq, 0, 1 + total);
834
835         if (C) {
836                 B = isl_mat_product(B, C);
837                 C = NULL;
838         }
839
840         T = isl_mat_parameter_compression(B, d);
841         if (!T)
842                 goto error;
843         if (T->n_col == 0) {
844                 bmap = isl_basic_map_set_to_empty(bmap);
845                 isl_mat_free(C2);
846                 isl_mat_free(T);
847                 goto done;
848         }
849         isl_int_init(v);
850         for (i = 0; i < T->n_row - 1; ++i) {
851                 isl_int_fdiv_q(v, T->row[1 + i][0], T->row[1 + i][1 + i]);
852                 if (isl_int_is_zero(v))
853                         continue;
854                 isl_mat_col_submul(T, 0, v, 1 + i);
855         }
856         isl_int_clear(v);
857         pos = isl_alloc_array(bmap->ctx, int, T->n_row);
858         if (!pos)
859                 goto error;
860         /* We have to be careful because dropping equalities may reorder them */
861         dropped = 0;
862         for (j = bmap->n_div - 1; j >= 0; --j) {
863                 for (i = 0; i < bmap->n_eq; ++i)
864                         if (!isl_int_is_zero(bmap->eq[i][1 + total + j]))
865                                 break;
866                 if (i < bmap->n_eq) {
867                         bmap = isl_basic_map_drop_div(bmap, j);
868                         isl_basic_map_drop_equality(bmap, i);
869                         ++dropped;
870                 }
871         }
872         pos[0] = 0;
873         needed = 0;
874         for (i = 1; i < T->n_row; ++i) {
875                 if (isl_int_is_one(T->row[i][i]))
876                         pos[i] = i;
877                 else
878                         needed++;
879         }
880         if (needed > dropped) {
881                 bmap = isl_basic_map_extend_dim(bmap, isl_dim_copy(bmap->dim),
882                                 needed, needed, 0);
883                 if (!bmap)
884                         goto error;
885         }
886         for (i = 1; i < T->n_row; ++i) {
887                 if (isl_int_is_one(T->row[i][i]))
888                         continue;
889                 k = isl_basic_map_alloc_div(bmap);
890                 pos[i] = 1 + total + k;
891                 isl_seq_clr(bmap->div[k] + 1, 1 + total + bmap->n_div);
892                 isl_int_set(bmap->div[k][0], T->row[i][i]);
893                 if (C2)
894                         isl_seq_cpy(bmap->div[k] + 1, C2->row[i], 1 + total);
895                 else
896                         isl_int_set_si(bmap->div[k][1 + i], 1);
897                 for (j = 0; j < i; ++j) {
898                         if (isl_int_is_zero(T->row[i][j]))
899                                 continue;
900                         if (pos[j] < T->n_row && C2)
901                                 isl_seq_submul(bmap->div[k] + 1, T->row[i][j],
902                                                 C2->row[pos[j]], 1 + total);
903                         else
904                                 isl_int_neg(bmap->div[k][1 + pos[j]],
905                                                                 T->row[i][j]);
906                 }
907                 j = isl_basic_map_alloc_equality(bmap);
908                 isl_seq_neg(bmap->eq[j], bmap->div[k]+1, 1+total+bmap->n_div);
909                 isl_int_set(bmap->eq[j][pos[i]], bmap->div[k][0]);
910         }
911         free(pos);
912         isl_mat_free(C2);
913         isl_mat_free(T);
914
915         if (progress)
916                 *progress = 1;
917 done:
918         ISL_F_SET(bmap, ISL_BASIC_MAP_NORMALIZED_DIVS);
919
920         return bmap;
921 error:
922         isl_mat_free(C);
923         isl_mat_free(C2);
924         isl_mat_free(T);
925         return bmap;
926 }
927
928 static struct isl_basic_map *set_div_from_lower_bound(
929         struct isl_basic_map *bmap, int div, int ineq)
930 {
931         unsigned total = 1 + isl_dim_total(bmap->dim);
932
933         isl_seq_neg(bmap->div[div] + 1, bmap->ineq[ineq], total + bmap->n_div);
934         isl_int_set(bmap->div[div][0], bmap->ineq[ineq][total + div]);
935         isl_int_add(bmap->div[div][1], bmap->div[div][1], bmap->div[div][0]);
936         isl_int_sub_ui(bmap->div[div][1], bmap->div[div][1], 1);
937         isl_int_set_si(bmap->div[div][1 + total + div], 0);
938
939         return bmap;
940 }
941
942 /* Check whether it is ok to define a div based on an inequality.
943  * To avoid the introduction of circular definitions of divs, we
944  * do not allow such a definition if the resulting expression would refer to
945  * any other undefined divs or if any known div is defined in
946  * terms of the unknown div.
947  */
948 static int ok_to_set_div_from_bound(struct isl_basic_map *bmap,
949         int div, int ineq)
950 {
951         int j;
952         unsigned total = 1 + isl_dim_total(bmap->dim);
953
954         /* Not defined in terms of unknown divs */
955         for (j = 0; j < bmap->n_div; ++j) {
956                 if (div == j)
957                         continue;
958                 if (isl_int_is_zero(bmap->ineq[ineq][total + j]))
959                         continue;
960                 if (isl_int_is_zero(bmap->div[j][0]))
961                         return 0;
962         }
963
964         /* No other div defined in terms of this one => avoid loops */
965         for (j = 0; j < bmap->n_div; ++j) {
966                 if (div == j)
967                         continue;
968                 if (isl_int_is_zero(bmap->div[j][0]))
969                         continue;
970                 if (!isl_int_is_zero(bmap->div[j][1 + total + div]))
971                         return 0;
972         }
973
974         return 1;
975 }
976
977 /* Given two constraints "k" and "l" that are opposite to each other,
978  * except for the constant term, check if we can use them
979  * to obtain an expression for one of the hitherto unknown divs.
980  * "sum" is the sum of the constant terms of the constraints.
981  * If this sum is strictly smaller than the coefficient of one
982  * of the divs, then this pair can be used define the div.
983  * To avoid the introduction of circular definitions of divs, we
984  * do not use the pair if the resulting expression would refer to
985  * any other undefined divs or if any known div is defined in
986  * terms of the unknown div.
987  */
988 static struct isl_basic_map *check_for_div_constraints(
989         struct isl_basic_map *bmap, int k, int l, isl_int sum, int *progress)
990 {
991         int i;
992         unsigned total = 1 + isl_dim_total(bmap->dim);
993
994         for (i = 0; i < bmap->n_div; ++i) {
995                 if (!isl_int_is_zero(bmap->div[i][0]))
996                         continue;
997                 if (isl_int_is_zero(bmap->ineq[k][total + i]))
998                         continue;
999                 if (isl_int_abs_ge(sum, bmap->ineq[k][total + i]))
1000                         continue;
1001                 if (!ok_to_set_div_from_bound(bmap, i, k))
1002                         break;
1003                 if (isl_int_is_pos(bmap->ineq[k][total + i]))
1004                         bmap = set_div_from_lower_bound(bmap, i, k);
1005                 else
1006                         bmap = set_div_from_lower_bound(bmap, i, l);
1007                 if (progress)
1008                         *progress = 1;
1009                 break;
1010         }
1011         return bmap;
1012 }
1013
1014 static struct isl_basic_map *remove_duplicate_constraints(
1015         struct isl_basic_map *bmap, int *progress, int detect_divs)
1016 {
1017         unsigned int size;
1018         isl_int ***index;
1019         int k, l, h;
1020         int bits;
1021         unsigned total = isl_basic_map_total_dim(bmap);
1022         isl_int sum;
1023
1024         if (!bmap || bmap->n_ineq <= 1)
1025                 return bmap;
1026
1027         size = round_up(4 * (bmap->n_ineq+1) / 3 - 1);
1028         bits = ffs(size) - 1;
1029         index = isl_calloc_array(ctx, isl_int **, size);
1030         if (!index)
1031                 return bmap;
1032
1033         index[isl_seq_get_hash_bits(bmap->ineq[0]+1, total, bits)] = &bmap->ineq[0];
1034         for (k = 1; k < bmap->n_ineq; ++k) {
1035                 h = hash_index(index, size, bits, bmap, k);
1036                 if (!index[h]) {
1037                         index[h] = &bmap->ineq[k];
1038                         continue;
1039                 }
1040                 if (progress)
1041                         *progress = 1;
1042                 l = index[h] - &bmap->ineq[0];
1043                 if (isl_int_lt(bmap->ineq[k][0], bmap->ineq[l][0]))
1044                         swap_inequality(bmap, k, l);
1045                 isl_basic_map_drop_inequality(bmap, k);
1046                 --k;
1047         }
1048         isl_int_init(sum);
1049         for (k = 0; k < bmap->n_ineq-1; ++k) {
1050                 isl_seq_neg(bmap->ineq[k]+1, bmap->ineq[k]+1, total);
1051                 h = hash_index(index, size, bits, bmap, k);
1052                 isl_seq_neg(bmap->ineq[k]+1, bmap->ineq[k]+1, total);
1053                 if (!index[h])
1054                         continue;
1055                 l = index[h] - &bmap->ineq[0];
1056                 isl_int_add(sum, bmap->ineq[k][0], bmap->ineq[l][0]);
1057                 if (isl_int_is_pos(sum)) {
1058                         if (detect_divs)
1059                                 bmap = check_for_div_constraints(bmap, k, l,
1060                                                                  sum, progress);
1061                         continue;
1062                 }
1063                 if (isl_int_is_zero(sum)) {
1064                         /* We need to break out of the loop after these
1065                          * changes since the contents of the hash
1066                          * will no longer be valid.
1067                          * Plus, we probably we want to regauss first.
1068                          */
1069                         if (progress)
1070                                 *progress = 1;
1071                         isl_basic_map_drop_inequality(bmap, l);
1072                         isl_basic_map_inequality_to_equality(bmap, k);
1073                 } else
1074                         bmap = isl_basic_map_set_to_empty(bmap);
1075                 break;
1076         }
1077         isl_int_clear(sum);
1078
1079         free(index);
1080         return bmap;
1081 }
1082
1083
1084 struct isl_basic_map *isl_basic_map_simplify(struct isl_basic_map *bmap)
1085 {
1086         int progress = 1;
1087         if (!bmap)
1088                 return NULL;
1089         while (progress) {
1090                 progress = 0;
1091                 bmap = isl_basic_map_normalize_constraints(bmap);
1092                 bmap = remove_duplicate_divs(bmap, &progress);
1093                 bmap = eliminate_divs_eq(bmap, &progress);
1094                 bmap = eliminate_divs_ineq(bmap, &progress);
1095                 bmap = isl_basic_map_gauss(bmap, &progress);
1096                 /* requires equalities in normal form */
1097                 bmap = normalize_divs(bmap, &progress);
1098                 bmap = remove_duplicate_constraints(bmap, &progress, 1);
1099         }
1100         return bmap;
1101 }
1102
1103 struct isl_basic_set *isl_basic_set_simplify(struct isl_basic_set *bset)
1104 {
1105         return (struct isl_basic_set *)
1106                 isl_basic_map_simplify((struct isl_basic_map *)bset);
1107 }
1108
1109
1110 int isl_basic_map_is_div_constraint(__isl_keep isl_basic_map *bmap,
1111         isl_int *constraint, unsigned div)
1112 {
1113         unsigned pos;
1114
1115         if (!bmap)
1116                 return -1;
1117
1118         pos = 1 + isl_dim_total(bmap->dim) + div;
1119
1120         if (isl_int_eq(constraint[pos], bmap->div[div][0])) {
1121                 int neg;
1122                 isl_int_sub(bmap->div[div][1],
1123                                 bmap->div[div][1], bmap->div[div][0]);
1124                 isl_int_add_ui(bmap->div[div][1], bmap->div[div][1], 1);
1125                 neg = isl_seq_is_neg(constraint, bmap->div[div]+1, pos);
1126                 isl_int_sub_ui(bmap->div[div][1], bmap->div[div][1], 1);
1127                 isl_int_add(bmap->div[div][1],
1128                                 bmap->div[div][1], bmap->div[div][0]);
1129                 if (!neg)
1130                         return 0;
1131                 if (isl_seq_first_non_zero(constraint+pos+1,
1132                                             bmap->n_div-div-1) != -1)
1133                         return 0;
1134         } else if (isl_int_abs_eq(constraint[pos], bmap->div[div][0])) {
1135                 if (!isl_seq_eq(constraint, bmap->div[div]+1, pos))
1136                         return 0;
1137                 if (isl_seq_first_non_zero(constraint+pos+1,
1138                                             bmap->n_div-div-1) != -1)
1139                         return 0;
1140         } else
1141                 return 0;
1142
1143         return 1;
1144 }
1145
1146
1147 /* If the only constraints a div d=floor(f/m)
1148  * appears in are its two defining constraints
1149  *
1150  *      f - m d >=0
1151  *      -(f - (m - 1)) + m d >= 0
1152  *
1153  * then it can safely be removed.
1154  */
1155 static int div_is_redundant(struct isl_basic_map *bmap, int div)
1156 {
1157         int i;
1158         unsigned pos = 1 + isl_dim_total(bmap->dim) + div;
1159
1160         for (i = 0; i < bmap->n_eq; ++i)
1161                 if (!isl_int_is_zero(bmap->eq[i][pos]))
1162                         return 0;
1163
1164         for (i = 0; i < bmap->n_ineq; ++i) {
1165                 if (isl_int_is_zero(bmap->ineq[i][pos]))
1166                         continue;
1167                 if (!isl_basic_map_is_div_constraint(bmap, bmap->ineq[i], div))
1168                         return 0;
1169         }
1170
1171         for (i = 0; i < bmap->n_div; ++i)
1172                 if (!isl_int_is_zero(bmap->div[i][1+pos]))
1173                         return 0;
1174
1175         return 1;
1176 }
1177
1178 /*
1179  * Remove divs that don't occur in any of the constraints or other divs.
1180  * These can arise when dropping some of the variables in a quast
1181  * returned by piplib.
1182  */
1183 static struct isl_basic_map *remove_redundant_divs(struct isl_basic_map *bmap)
1184 {
1185         int i;
1186
1187         if (!bmap)
1188                 return NULL;
1189
1190         for (i = bmap->n_div-1; i >= 0; --i) {
1191                 if (!div_is_redundant(bmap, i))
1192                         continue;
1193                 bmap = isl_basic_map_drop_div(bmap, i);
1194         }
1195         return bmap;
1196 }
1197
1198 struct isl_basic_map *isl_basic_map_finalize(struct isl_basic_map *bmap)
1199 {
1200         bmap = remove_redundant_divs(bmap);
1201         if (!bmap)
1202                 return NULL;
1203         ISL_F_SET(bmap, ISL_BASIC_SET_FINAL);
1204         return bmap;
1205 }
1206
1207 struct isl_basic_set *isl_basic_set_finalize(struct isl_basic_set *bset)
1208 {
1209         return (struct isl_basic_set *)
1210                 isl_basic_map_finalize((struct isl_basic_map *)bset);
1211 }
1212
1213 struct isl_set *isl_set_finalize(struct isl_set *set)
1214 {
1215         int i;
1216
1217         if (!set)
1218                 return NULL;
1219         for (i = 0; i < set->n; ++i) {
1220                 set->p[i] = isl_basic_set_finalize(set->p[i]);
1221                 if (!set->p[i])
1222                         goto error;
1223         }
1224         return set;
1225 error:
1226         isl_set_free(set);
1227         return NULL;
1228 }
1229
1230 struct isl_map *isl_map_finalize(struct isl_map *map)
1231 {
1232         int i;
1233
1234         if (!map)
1235                 return NULL;
1236         for (i = 0; i < map->n; ++i) {
1237                 map->p[i] = isl_basic_map_finalize(map->p[i]);
1238                 if (!map->p[i])
1239                         goto error;
1240         }
1241         ISL_F_CLR(map, ISL_MAP_NORMALIZED);
1242         return map;
1243 error:
1244         isl_map_free(map);
1245         return NULL;
1246 }
1247
1248
1249 /* Remove definition of any div that is defined in terms of the given variable.
1250  * The div itself is not removed.  Functions such as
1251  * eliminate_divs_ineq depend on the other divs remaining in place.
1252  */
1253 static struct isl_basic_map *remove_dependent_vars(struct isl_basic_map *bmap,
1254                                                                         int pos)
1255 {
1256         int i;
1257
1258         for (i = 0; i < bmap->n_div; ++i) {
1259                 if (isl_int_is_zero(bmap->div[i][0]))
1260                         continue;
1261                 if (isl_int_is_zero(bmap->div[i][1+1+pos]))
1262                         continue;
1263                 isl_int_set_si(bmap->div[i][0], 0);
1264         }
1265         return bmap;
1266 }
1267
1268 /* Eliminate the specified variables from the constraints using
1269  * Fourier-Motzkin.  The variables themselves are not removed.
1270  */
1271 struct isl_basic_map *isl_basic_map_eliminate_vars(
1272         struct isl_basic_map *bmap, unsigned pos, unsigned n)
1273 {
1274         int d;
1275         int i, j, k;
1276         unsigned total;
1277
1278         if (n == 0)
1279                 return bmap;
1280         if (!bmap)
1281                 return NULL;
1282         total = isl_basic_map_total_dim(bmap);
1283
1284         bmap = isl_basic_map_cow(bmap);
1285         for (d = pos + n - 1; d >= 0 && d >= pos; --d)
1286                 bmap = remove_dependent_vars(bmap, d);
1287
1288         for (d = pos + n - 1;
1289              d >= 0 && d >= total - bmap->n_div && d >= pos; --d)
1290                 isl_seq_clr(bmap->div[d-(total-bmap->n_div)], 2+total);
1291         for (d = pos + n - 1; d >= 0 && d >= pos; --d) {
1292                 int n_lower, n_upper;
1293                 if (!bmap)
1294                         return NULL;
1295                 for (i = 0; i < bmap->n_eq; ++i) {
1296                         if (isl_int_is_zero(bmap->eq[i][1+d]))
1297                                 continue;
1298                         eliminate_var_using_equality(bmap, d, bmap->eq[i], 0, NULL);
1299                         isl_basic_map_drop_equality(bmap, i);
1300                         break;
1301                 }
1302                 if (i < bmap->n_eq)
1303                         continue;
1304                 n_lower = 0;
1305                 n_upper = 0;
1306                 for (i = 0; i < bmap->n_ineq; ++i) {
1307                         if (isl_int_is_pos(bmap->ineq[i][1+d]))
1308                                 n_lower++;
1309                         else if (isl_int_is_neg(bmap->ineq[i][1+d]))
1310                                 n_upper++;
1311                 }
1312                 bmap = isl_basic_map_extend_constraints(bmap,
1313                                 0, n_lower * n_upper);
1314                 if (!bmap)
1315                         goto error;
1316                 for (i = bmap->n_ineq - 1; i >= 0; --i) {
1317                         int last;
1318                         if (isl_int_is_zero(bmap->ineq[i][1+d]))
1319                                 continue;
1320                         last = -1;
1321                         for (j = 0; j < i; ++j) {
1322                                 if (isl_int_is_zero(bmap->ineq[j][1+d]))
1323                                         continue;
1324                                 last = j;
1325                                 if (isl_int_sgn(bmap->ineq[i][1+d]) ==
1326                                     isl_int_sgn(bmap->ineq[j][1+d]))
1327                                         continue;
1328                                 k = isl_basic_map_alloc_inequality(bmap);
1329                                 if (k < 0)
1330                                         goto error;
1331                                 isl_seq_cpy(bmap->ineq[k], bmap->ineq[i],
1332                                                 1+total);
1333                                 isl_seq_elim(bmap->ineq[k], bmap->ineq[j],
1334                                                 1+d, 1+total, NULL);
1335                         }
1336                         isl_basic_map_drop_inequality(bmap, i);
1337                         i = last + 1;
1338                 }
1339                 if (n_lower > 0 && n_upper > 0) {
1340                         bmap = isl_basic_map_normalize_constraints(bmap);
1341                         bmap = remove_duplicate_constraints(bmap, NULL, 0);
1342                         bmap = isl_basic_map_gauss(bmap, NULL);
1343                         bmap = isl_basic_map_remove_redundancies(bmap);
1344                         if (!bmap)
1345                                 goto error;
1346                         if (ISL_F_ISSET(bmap, ISL_BASIC_MAP_EMPTY))
1347                                 break;
1348                 }
1349         }
1350         ISL_F_CLR(bmap, ISL_BASIC_MAP_NORMALIZED);
1351         return bmap;
1352 error:
1353         isl_basic_map_free(bmap);
1354         return NULL;
1355 }
1356
1357 struct isl_basic_set *isl_basic_set_eliminate_vars(
1358         struct isl_basic_set *bset, unsigned pos, unsigned n)
1359 {
1360         return (struct isl_basic_set *)isl_basic_map_eliminate_vars(
1361                         (struct isl_basic_map *)bset, pos, n);
1362 }
1363
1364 /* Don't assume equalities are in order, because align_divs
1365  * may have changed the order of the divs.
1366  */
1367 static void compute_elimination_index(struct isl_basic_map *bmap, int *elim)
1368 {
1369         int d, i;
1370         unsigned total;
1371
1372         total = isl_dim_total(bmap->dim);
1373         for (d = 0; d < total; ++d)
1374                 elim[d] = -1;
1375         for (i = 0; i < bmap->n_eq; ++i) {
1376                 for (d = total - 1; d >= 0; --d) {
1377                         if (isl_int_is_zero(bmap->eq[i][1+d]))
1378                                 continue;
1379                         elim[d] = i;
1380                         break;
1381                 }
1382         }
1383 }
1384
1385 static void set_compute_elimination_index(struct isl_basic_set *bset, int *elim)
1386 {
1387         compute_elimination_index((struct isl_basic_map *)bset, elim);
1388 }
1389
1390 static int reduced_using_equalities(isl_int *dst, isl_int *src,
1391         struct isl_basic_map *bmap, int *elim)
1392 {
1393         int d;
1394         int copied = 0;
1395         unsigned total;
1396
1397         total = isl_dim_total(bmap->dim);
1398         for (d = total - 1; d >= 0; --d) {
1399                 if (isl_int_is_zero(src[1+d]))
1400                         continue;
1401                 if (elim[d] == -1)
1402                         continue;
1403                 if (!copied) {
1404                         isl_seq_cpy(dst, src, 1 + total);
1405                         copied = 1;
1406                 }
1407                 isl_seq_elim(dst, bmap->eq[elim[d]], 1 + d, 1 + total, NULL);
1408         }
1409         return copied;
1410 }
1411
1412 static int set_reduced_using_equalities(isl_int *dst, isl_int *src,
1413         struct isl_basic_set *bset, int *elim)
1414 {
1415         return reduced_using_equalities(dst, src,
1416                                         (struct isl_basic_map *)bset, elim);
1417 }
1418
1419 static struct isl_basic_set *isl_basic_set_reduce_using_equalities(
1420         struct isl_basic_set *bset, struct isl_basic_set *context)
1421 {
1422         int i;
1423         int *elim;
1424
1425         if (!bset || !context)
1426                 goto error;
1427
1428         if (context->n_eq == 0) {
1429                 isl_basic_set_free(context);
1430                 return bset;
1431         }
1432
1433         bset = isl_basic_set_cow(bset);
1434         if (!bset)
1435                 goto error;
1436
1437         elim = isl_alloc_array(bset->ctx, int, isl_basic_set_n_dim(bset));
1438         if (!elim)
1439                 goto error;
1440         set_compute_elimination_index(context, elim);
1441         for (i = 0; i < bset->n_eq; ++i)
1442                 set_reduced_using_equalities(bset->eq[i], bset->eq[i],
1443                                                         context, elim);
1444         for (i = 0; i < bset->n_ineq; ++i)
1445                 set_reduced_using_equalities(bset->ineq[i], bset->ineq[i],
1446                                                         context, elim);
1447         isl_basic_set_free(context);
1448         free(elim);
1449         bset = isl_basic_set_simplify(bset);
1450         bset = isl_basic_set_finalize(bset);
1451         return bset;
1452 error:
1453         isl_basic_set_free(bset);
1454         isl_basic_set_free(context);
1455         return NULL;
1456 }
1457
1458 static struct isl_basic_set *remove_shifted_constraints(
1459         struct isl_basic_set *bset, struct isl_basic_set *context)
1460 {
1461         unsigned int size;
1462         isl_int ***index;
1463         int bits;
1464         int k, h, l;
1465
1466         if (!bset)
1467                 return NULL;
1468
1469         size = round_up(4 * (context->n_ineq+1) / 3 - 1);
1470         bits = ffs(size) - 1;
1471         index = isl_calloc_array(ctx, isl_int **, size);
1472         if (!index)
1473                 return bset;
1474
1475         for (k = 0; k < context->n_ineq; ++k) {
1476                 h = set_hash_index(index, size, bits, context, k);
1477                 index[h] = &context->ineq[k];
1478         }
1479         for (k = 0; k < bset->n_ineq; ++k) {
1480                 h = set_hash_index(index, size, bits, bset, k);
1481                 if (!index[h])
1482                         continue;
1483                 l = index[h] - &context->ineq[0];
1484                 if (isl_int_lt(bset->ineq[k][0], context->ineq[l][0]))
1485                         continue;
1486                 bset = isl_basic_set_cow(bset);
1487                 if (!bset)
1488                         goto error;
1489                 isl_basic_set_drop_inequality(bset, k);
1490                 --k;
1491         }
1492         free(index);
1493         return bset;
1494 error:
1495         free(index);
1496         return bset;
1497 }
1498
1499 /* Remove all information from bset that is redundant in the context
1500  * of context.  Both bset and context are assumed to be full-dimensional.
1501  *
1502  * We first * remove the inequalities from "bset"
1503  * that are obviously redundant with respect to some inequality in "context".
1504  *
1505  * If there are any inequalities left, we construct a tableau for
1506  * the context and then add the inequalities of "bset".
1507  * Before adding these inequalities, we freeze all constraints such that
1508  * they won't be considered redundant in terms of the constraints of "bset".
1509  * Then we detect all redundant constraints (among the
1510  * constraints that weren't frozen), first by checking for redundancy in the
1511  * the tableau and then by checking if replacing a constraint by its negation
1512  * would lead to an empty set.  This last step is fairly expensive
1513  * and could be optimized by more reuse of the tableau.
1514  * Finally, we update bset according to the results.
1515  */
1516 static __isl_give isl_basic_set *uset_gist_full(__isl_take isl_basic_set *bset,
1517         __isl_take isl_basic_set *context)
1518 {
1519         int i, k;
1520         isl_basic_set *combined = NULL;
1521         struct isl_tab *tab = NULL;
1522         unsigned context_ineq;
1523         unsigned total;
1524
1525         if (!bset || !context)
1526                 goto error;
1527
1528         if (isl_basic_set_is_universe(bset)) {
1529                 isl_basic_set_free(context);
1530                 return bset;
1531         }
1532
1533         if (isl_basic_set_is_universe(context)) {
1534                 isl_basic_set_free(context);
1535                 return bset;
1536         }
1537
1538         bset = remove_shifted_constraints(bset, context);
1539         if (!bset)
1540                 goto error;
1541         if (bset->n_ineq == 0)
1542                 goto done;
1543
1544         context_ineq = context->n_ineq;
1545         combined = isl_basic_set_cow(isl_basic_set_copy(context));
1546         combined = isl_basic_set_extend_constraints(combined, 0, bset->n_ineq);
1547         tab = isl_tab_from_basic_set(combined);
1548         for (i = 0; i < context_ineq; ++i)
1549                 if (isl_tab_freeze_constraint(tab, i) < 0)
1550                         goto error;
1551         tab = isl_tab_extend(tab, bset->n_ineq);
1552         for (i = 0; i < bset->n_ineq; ++i)
1553                 if (isl_tab_add_ineq(tab, bset->ineq[i]) < 0)
1554                         goto error;
1555         bset = isl_basic_set_add_constraints(combined, bset, 0);
1556         combined = NULL;
1557         if (!bset)
1558                 goto error;
1559         if (isl_tab_detect_redundant(tab) < 0)
1560                 goto error;
1561         total = isl_basic_set_total_dim(bset);
1562         for (i = context_ineq; i < bset->n_ineq; ++i) {
1563                 int is_empty;
1564                 if (tab->con[i].is_redundant)
1565                         continue;
1566                 tab->con[i].is_redundant = 1;
1567                 combined = isl_basic_set_dup(bset);
1568                 combined = isl_basic_set_update_from_tab(combined, tab);
1569                 combined = isl_basic_set_extend_constraints(combined, 0, 1);
1570                 k = isl_basic_set_alloc_inequality(combined);
1571                 if (k < 0)
1572                         goto error;
1573                 isl_seq_neg(combined->ineq[k], bset->ineq[i], 1 + total);
1574                 isl_int_sub_ui(combined->ineq[k][0], combined->ineq[k][0], 1);
1575                 is_empty = isl_basic_set_is_empty(combined);
1576                 if (is_empty < 0)
1577                         goto error;
1578                 isl_basic_set_free(combined);
1579                 combined = NULL;
1580                 if (!is_empty)
1581                         tab->con[i].is_redundant = 0;
1582         }
1583         for (i = 0; i < context_ineq; ++i)
1584                 tab->con[i].is_redundant = 1;
1585         bset = isl_basic_set_update_from_tab(bset, tab);
1586         if (bset) {
1587                 ISL_F_SET(bset, ISL_BASIC_SET_NO_IMPLICIT);
1588                 ISL_F_SET(bset, ISL_BASIC_SET_NO_REDUNDANT);
1589         }
1590
1591         isl_tab_free(tab);
1592 done:
1593         bset = isl_basic_set_simplify(bset);
1594         bset = isl_basic_set_finalize(bset);
1595         isl_basic_set_free(context);
1596         return bset;
1597 error:
1598         isl_tab_free(tab);
1599         isl_basic_set_free(combined);
1600         isl_basic_set_free(context);
1601         isl_basic_set_free(bset);
1602         return NULL;
1603 }
1604
1605 /* Remove all information from bset that is redundant in the context
1606  * of context.  In particular, equalities that are linear combinations
1607  * of those in context are removed.  Then the inequalities that are
1608  * redundant in the context of the equalities and inequalities of
1609  * context are removed.
1610  *
1611  * We first compute the integer affine hull of the intersection,
1612  * compute the gist inside this affine hull and then add back
1613  * those equalities that are not implied by the context.
1614  *
1615  * If two constraints are mutually redundant, then uset_gist_full
1616  * will remove the second of those constraints.  We therefore first
1617  * sort the constraints so that constraints not involving existentially
1618  * quantified variables are given precedence over those that do.
1619  * We have to perform this sorting before the variable compression,
1620  * because that may effect the order of the variables.
1621  */
1622 static __isl_give isl_basic_set *uset_gist(__isl_take isl_basic_set *bset,
1623         __isl_take isl_basic_set *context)
1624 {
1625         isl_mat *eq;
1626         isl_mat *T, *T2;
1627         isl_basic_set *aff;
1628         isl_basic_set *aff_context;
1629         unsigned total;
1630
1631         if (!bset || !context)
1632                 goto error;
1633
1634         bset = isl_basic_set_intersect(bset, isl_basic_set_copy(context));
1635         if (isl_basic_set_plain_is_empty(bset)) {
1636                 isl_basic_set_free(context);
1637                 return bset;
1638         }
1639         bset = isl_basic_set_sort_constraints(bset);
1640         aff = isl_basic_set_affine_hull(isl_basic_set_copy(bset));
1641         if (!aff)
1642                 goto error;
1643         if (isl_basic_set_plain_is_empty(aff)) {
1644                 isl_basic_set_free(aff);
1645                 isl_basic_set_free(context);
1646                 return bset;
1647         }
1648         if (aff->n_eq == 0) {
1649                 isl_basic_set_free(aff);
1650                 return uset_gist_full(bset, context);
1651         }
1652         total = isl_basic_set_total_dim(bset);
1653         eq = isl_mat_sub_alloc6(bset->ctx, aff->eq, 0, aff->n_eq, 0, 1 + total);
1654         eq = isl_mat_cow(eq);
1655         T = isl_mat_variable_compression(eq, &T2);
1656         if (T && T->n_col == 0) {
1657                 isl_mat_free(T);
1658                 isl_mat_free(T2);
1659                 isl_basic_set_free(context);
1660                 isl_basic_set_free(aff);
1661                 return isl_basic_set_set_to_empty(bset);
1662         }
1663
1664         aff_context = isl_basic_set_affine_hull(isl_basic_set_copy(context));
1665
1666         bset = isl_basic_set_preimage(bset, isl_mat_copy(T));
1667         context = isl_basic_set_preimage(context, T);
1668
1669         bset = uset_gist_full(bset, context);
1670         bset = isl_basic_set_preimage(bset, T2);
1671         bset = isl_basic_set_intersect(bset, aff);
1672         bset = isl_basic_set_reduce_using_equalities(bset, aff_context);
1673
1674         if (bset) {
1675                 ISL_F_SET(bset, ISL_BASIC_SET_NO_IMPLICIT);
1676                 ISL_F_SET(bset, ISL_BASIC_SET_NO_REDUNDANT);
1677         }
1678
1679         return bset;
1680 error:
1681         isl_basic_set_free(bset);
1682         isl_basic_set_free(context);
1683         return NULL;
1684 }
1685
1686 /* Normalize the divs in "bmap" in the context of the equalities in "context".
1687  * We simply add the equalities in context to bmap and then do a regular
1688  * div normalizations.  Better results can be obtained by normalizing
1689  * only the divs in bmap than do not also appear in context.
1690  * We need to be careful to reduce the divs using the equalities
1691  * so that later calls to isl_basic_map_overlying_set wouldn't introduce
1692  * spurious constraints.
1693  */
1694 static struct isl_basic_map *normalize_divs_in_context(
1695         struct isl_basic_map *bmap, struct isl_basic_map *context)
1696 {
1697         int i;
1698         unsigned total_context;
1699         int div_eq;
1700
1701         div_eq = n_pure_div_eq(bmap);
1702         if (div_eq == 0)
1703                 return bmap;
1704
1705         if (context->n_div > 0)
1706                 bmap = isl_basic_map_align_divs(bmap, context);
1707
1708         total_context = isl_basic_map_total_dim(context);
1709         bmap = isl_basic_map_extend_constraints(bmap, context->n_eq, 0);
1710         for (i = 0; i < context->n_eq; ++i) {
1711                 int k;
1712                 k = isl_basic_map_alloc_equality(bmap);
1713                 isl_seq_cpy(bmap->eq[k], context->eq[i], 1 + total_context);
1714                 isl_seq_clr(bmap->eq[k] + 1 + total_context,
1715                                 isl_basic_map_total_dim(bmap) - total_context);
1716         }
1717         bmap = isl_basic_map_gauss(bmap, NULL);
1718         bmap = normalize_divs(bmap, NULL);
1719         bmap = isl_basic_map_gauss(bmap, NULL);
1720         return bmap;
1721 }
1722
1723 struct isl_basic_map *isl_basic_map_gist(struct isl_basic_map *bmap,
1724         struct isl_basic_map *context)
1725 {
1726         struct isl_basic_set *bset;
1727
1728         if (!bmap || !context)
1729                 goto error;
1730
1731         if (isl_basic_map_is_universe(bmap)) {
1732                 isl_basic_map_free(context);
1733                 return bmap;
1734         }
1735         if (isl_basic_map_plain_is_empty(context)) {
1736                 struct isl_dim *dim = isl_dim_copy(bmap->dim);
1737                 isl_basic_map_free(context);
1738                 isl_basic_map_free(bmap);
1739                 return isl_basic_map_universe(dim);
1740         }
1741         if (isl_basic_map_plain_is_empty(bmap)) {
1742                 isl_basic_map_free(context);
1743                 return bmap;
1744         }
1745
1746         bmap = isl_basic_map_remove_redundancies(bmap);
1747         context = isl_basic_map_remove_redundancies(context);
1748
1749         if (context->n_eq)
1750                 bmap = normalize_divs_in_context(bmap, context);
1751
1752         context = isl_basic_map_align_divs(context, bmap);
1753         bmap = isl_basic_map_align_divs(bmap, context);
1754
1755         bset = uset_gist(isl_basic_map_underlying_set(isl_basic_map_copy(bmap)),
1756                          isl_basic_map_underlying_set(context));
1757
1758         return isl_basic_map_overlying_set(bset, bmap);
1759 error:
1760         isl_basic_map_free(bmap);
1761         isl_basic_map_free(context);
1762         return NULL;
1763 }
1764
1765 /*
1766  * Assumes context has no implicit divs.
1767  */
1768 __isl_give isl_map *isl_map_gist_basic_map(__isl_take isl_map *map,
1769         __isl_take isl_basic_map *context)
1770 {
1771         int i;
1772
1773         if (!map || !context)
1774                 goto error;;
1775
1776         if (isl_basic_map_plain_is_empty(context)) {
1777                 struct isl_dim *dim = isl_dim_copy(map->dim);
1778                 isl_basic_map_free(context);
1779                 isl_map_free(map);
1780                 return isl_map_universe(dim);
1781         }
1782
1783         context = isl_basic_map_remove_redundancies(context);
1784         map = isl_map_cow(map);
1785         if (!map || !context)
1786                 goto error;;
1787         isl_assert(map->ctx, isl_dim_equal(map->dim, context->dim), goto error);
1788         map = isl_map_compute_divs(map);
1789         for (i = 0; i < map->n; ++i)
1790                 context = isl_basic_map_align_divs(context, map->p[i]);
1791         for (i = map->n - 1; i >= 0; --i) {
1792                 map->p[i] = isl_basic_map_gist(map->p[i],
1793                                                 isl_basic_map_copy(context));
1794                 if (!map->p[i])
1795                         goto error;
1796                 if (isl_basic_map_plain_is_empty(map->p[i])) {
1797                         isl_basic_map_free(map->p[i]);
1798                         if (i != map->n - 1)
1799                                 map->p[i] = map->p[map->n - 1];
1800                         map->n--;
1801                 }
1802         }
1803         isl_basic_map_free(context);
1804         ISL_F_CLR(map, ISL_MAP_NORMALIZED);
1805         return map;
1806 error:
1807         isl_map_free(map);
1808         isl_basic_map_free(context);
1809         return NULL;
1810 }
1811
1812 __isl_give isl_map *isl_map_gist(__isl_take isl_map *map,
1813         __isl_take isl_map *context)
1814 {
1815         context = isl_map_compute_divs(context);
1816         return isl_map_gist_basic_map(map, isl_map_simple_hull(context));
1817 }
1818
1819 struct isl_basic_set *isl_basic_set_gist(struct isl_basic_set *bset,
1820                                                 struct isl_basic_set *context)
1821 {
1822         return (struct isl_basic_set *)isl_basic_map_gist(
1823                 (struct isl_basic_map *)bset, (struct isl_basic_map *)context);
1824 }
1825
1826 __isl_give isl_set *isl_set_gist_basic_set(__isl_take isl_set *set,
1827         __isl_take isl_basic_set *context)
1828 {
1829         return (struct isl_set *)isl_map_gist_basic_map((struct isl_map *)set,
1830                                         (struct isl_basic_map *)context);
1831 }
1832
1833 __isl_give isl_set *isl_set_gist(__isl_take isl_set *set,
1834         __isl_take isl_set *context)
1835 {
1836         return (struct isl_set *)isl_map_gist((struct isl_map *)set,
1837                                         (struct isl_map *)context);
1838 }
1839
1840 /* Quick check to see if two basic maps are disjoint.
1841  * In particular, we reduce the equalities and inequalities of
1842  * one basic map in the context of the equalities of the other
1843  * basic map and check if we get a contradiction.
1844  */
1845 int isl_basic_map_plain_is_disjoint(__isl_keep isl_basic_map *bmap1,
1846         __isl_keep isl_basic_map *bmap2)
1847 {
1848         struct isl_vec *v = NULL;
1849         int *elim = NULL;
1850         unsigned total;
1851         int i;
1852
1853         if (!bmap1 || !bmap2)
1854                 return -1;
1855         isl_assert(bmap1->ctx, isl_dim_equal(bmap1->dim, bmap2->dim),
1856                         return -1);
1857         if (bmap1->n_div || bmap2->n_div)
1858                 return 0;
1859         if (!bmap1->n_eq && !bmap2->n_eq)
1860                 return 0;
1861
1862         total = isl_dim_total(bmap1->dim);
1863         if (total == 0)
1864                 return 0;
1865         v = isl_vec_alloc(bmap1->ctx, 1 + total);
1866         if (!v)
1867                 goto error;
1868         elim = isl_alloc_array(bmap1->ctx, int, total);
1869         if (!elim)
1870                 goto error;
1871         compute_elimination_index(bmap1, elim);
1872         for (i = 0; i < bmap2->n_eq; ++i) {
1873                 int reduced;
1874                 reduced = reduced_using_equalities(v->block.data, bmap2->eq[i],
1875                                                         bmap1, elim);
1876                 if (reduced && !isl_int_is_zero(v->block.data[0]) &&
1877                     isl_seq_first_non_zero(v->block.data + 1, total) == -1)
1878                         goto disjoint;
1879         }
1880         for (i = 0; i < bmap2->n_ineq; ++i) {
1881                 int reduced;
1882                 reduced = reduced_using_equalities(v->block.data,
1883                                                 bmap2->ineq[i], bmap1, elim);
1884                 if (reduced && isl_int_is_neg(v->block.data[0]) &&
1885                     isl_seq_first_non_zero(v->block.data + 1, total) == -1)
1886                         goto disjoint;
1887         }
1888         compute_elimination_index(bmap2, elim);
1889         for (i = 0; i < bmap1->n_ineq; ++i) {
1890                 int reduced;
1891                 reduced = reduced_using_equalities(v->block.data,
1892                                                 bmap1->ineq[i], bmap2, elim);
1893                 if (reduced && isl_int_is_neg(v->block.data[0]) &&
1894                     isl_seq_first_non_zero(v->block.data + 1, total) == -1)
1895                         goto disjoint;
1896         }
1897         isl_vec_free(v);
1898         free(elim);
1899         return 0;
1900 disjoint:
1901         isl_vec_free(v);
1902         free(elim);
1903         return 1;
1904 error:
1905         isl_vec_free(v);
1906         free(elim);
1907         return -1;
1908 }
1909
1910 int isl_basic_set_plain_is_disjoint(__isl_keep isl_basic_set *bset1,
1911         __isl_keep isl_basic_set *bset2)
1912 {
1913         return isl_basic_map_plain_is_disjoint((struct isl_basic_map *)bset1,
1914                                               (struct isl_basic_map *)bset2);
1915 }
1916
1917 int isl_map_plain_is_disjoint(__isl_keep isl_map *map1,
1918         __isl_keep isl_map *map2)
1919 {
1920         int i, j;
1921
1922         if (!map1 || !map2)
1923                 return -1;
1924
1925         if (isl_map_plain_is_equal(map1, map2))
1926                 return 0;
1927
1928         for (i = 0; i < map1->n; ++i) {
1929                 for (j = 0; j < map2->n; ++j) {
1930                         int d = isl_basic_map_plain_is_disjoint(map1->p[i],
1931                                                                map2->p[j]);
1932                         if (d != 1)
1933                                 return d;
1934                 }
1935         }
1936         return 1;
1937 }
1938
1939 int isl_set_plain_is_disjoint(__isl_keep isl_set *set1,
1940         __isl_keep isl_set *set2)
1941 {
1942         return isl_map_plain_is_disjoint((struct isl_map *)set1,
1943                                         (struct isl_map *)set2);
1944 }
1945
1946 int isl_set_fast_is_disjoint(__isl_keep isl_set *set1, __isl_keep isl_set *set2)
1947 {
1948         return isl_set_plain_is_disjoint(set1, set2);
1949 }
1950
1951 /* Check if we can combine a given div with lower bound l and upper
1952  * bound u with some other div and if so return that other div.
1953  * Otherwise return -1.
1954  *
1955  * We first check that
1956  *      - the bounds are opposites of each other (except for the constant
1957  *        term)
1958  *      - the bounds do not reference any other div
1959  *      - no div is defined in terms of this div
1960  *
1961  * Let m be the size of the range allowed on the div by the bounds.
1962  * That is, the bounds are of the form
1963  *
1964  *      e <= a <= e + m - 1
1965  *
1966  * with e some expression in the other variables.
1967  * We look for another div b such that no third div is defined in terms
1968  * of this second div b and such that in any constraint that contains
1969  * a (except for the given lower and upper bound), also contains b
1970  * with a coefficient that is m times that of b.
1971  * That is, all constraints (execpt for the lower and upper bound)
1972  * are of the form
1973  *
1974  *      e + f (a + m b) >= 0
1975  *
1976  * If so, we return b so that "a + m b" can be replaced by
1977  * a single div "c = a + m b".
1978  */
1979 static int div_find_coalesce(struct isl_basic_map *bmap, int *pairs,
1980         unsigned div, unsigned l, unsigned u)
1981 {
1982         int i, j;
1983         unsigned dim;
1984         int coalesce = -1;
1985
1986         if (bmap->n_div <= 1)
1987                 return -1;
1988         dim = isl_dim_total(bmap->dim);
1989         if (isl_seq_first_non_zero(bmap->ineq[l] + 1 + dim, div) != -1)
1990                 return -1;
1991         if (isl_seq_first_non_zero(bmap->ineq[l] + 1 + dim + div + 1,
1992                                    bmap->n_div - div - 1) != -1)
1993                 return -1;
1994         if (!isl_seq_is_neg(bmap->ineq[l] + 1, bmap->ineq[u] + 1,
1995                             dim + bmap->n_div))
1996                 return -1;
1997
1998         for (i = 0; i < bmap->n_div; ++i) {
1999                 if (isl_int_is_zero(bmap->div[i][0]))
2000                         continue;
2001                 if (!isl_int_is_zero(bmap->div[i][1 + 1 + dim + div]))
2002                         return -1;
2003         }
2004
2005         isl_int_add(bmap->ineq[l][0], bmap->ineq[l][0], bmap->ineq[u][0]);
2006         if (isl_int_is_neg(bmap->ineq[l][0])) {
2007                 isl_int_sub(bmap->ineq[l][0],
2008                             bmap->ineq[l][0], bmap->ineq[u][0]);
2009                 bmap = isl_basic_map_copy(bmap);
2010                 bmap = isl_basic_map_set_to_empty(bmap);
2011                 isl_basic_map_free(bmap);
2012                 return -1;
2013         }
2014         isl_int_add_ui(bmap->ineq[l][0], bmap->ineq[l][0], 1);
2015         for (i = 0; i < bmap->n_div; ++i) {
2016                 if (i == div)
2017                         continue;
2018                 if (!pairs[i])
2019                         continue;
2020                 for (j = 0; j < bmap->n_div; ++j) {
2021                         if (isl_int_is_zero(bmap->div[j][0]))
2022                                 continue;
2023                         if (!isl_int_is_zero(bmap->div[j][1 + 1 + dim + i]))
2024                                 break;
2025                 }
2026                 if (j < bmap->n_div)
2027                         continue;
2028                 for (j = 0; j < bmap->n_ineq; ++j) {
2029                         int valid;
2030                         if (j == l || j == u)
2031                                 continue;
2032                         if (isl_int_is_zero(bmap->ineq[j][1 + dim + div]))
2033                                 continue;
2034                         if (isl_int_is_zero(bmap->ineq[j][1 + dim + i]))
2035                                 break;
2036                         isl_int_mul(bmap->ineq[j][1 + dim + div],
2037                                     bmap->ineq[j][1 + dim + div],
2038                                     bmap->ineq[l][0]);
2039                         valid = isl_int_eq(bmap->ineq[j][1 + dim + div],
2040                                            bmap->ineq[j][1 + dim + i]);
2041                         isl_int_divexact(bmap->ineq[j][1 + dim + div],
2042                                          bmap->ineq[j][1 + dim + div],
2043                                          bmap->ineq[l][0]);
2044                         if (!valid)
2045                                 break;
2046                 }
2047                 if (j < bmap->n_ineq)
2048                         continue;
2049                 coalesce = i;
2050                 break;
2051         }
2052         isl_int_sub_ui(bmap->ineq[l][0], bmap->ineq[l][0], 1);
2053         isl_int_sub(bmap->ineq[l][0], bmap->ineq[l][0], bmap->ineq[u][0]);
2054         return coalesce;
2055 }
2056
2057 /* Given a lower and an upper bound on div i, construct an inequality
2058  * that when nonnegative ensures that this pair of bounds always allows
2059  * for an integer value of the given div.
2060  * The lower bound is inequality l, while the upper bound is inequality u.
2061  * The constructed inequality is stored in ineq.
2062  * g, fl, fu are temporary scalars.
2063  *
2064  * Let the upper bound be
2065  *
2066  *      -n_u a + e_u >= 0
2067  *
2068  * and the lower bound
2069  *
2070  *      n_l a + e_l >= 0
2071  *
2072  * Let n_u = f_u g and n_l = f_l g, with g = gcd(n_u, n_l).
2073  * We have
2074  *
2075  *      - f_u e_l <= f_u f_l g a <= f_l e_u
2076  *
2077  * Since all variables are integer valued, this is equivalent to
2078  *
2079  *      - f_u e_l - (f_u - 1) <= f_u f_l g a <= f_l e_u + (f_l - 1)
2080  *
2081  * If this interval is at least f_u f_l g, then it contains at least
2082  * one integer value for a.
2083  * That is, the test constraint is
2084  *
2085  *      f_l e_u + f_u e_l + f_l - 1 + f_u - 1 + 1 >= f_u f_l g
2086  */
2087 static void construct_test_ineq(struct isl_basic_map *bmap, int i,
2088         int l, int u, isl_int *ineq, isl_int g, isl_int fl, isl_int fu)
2089 {
2090         unsigned dim;
2091         dim = isl_dim_total(bmap->dim);
2092
2093         isl_int_gcd(g, bmap->ineq[l][1 + dim + i], bmap->ineq[u][1 + dim + i]);
2094         isl_int_divexact(fl, bmap->ineq[l][1 + dim + i], g);
2095         isl_int_divexact(fu, bmap->ineq[u][1 + dim + i], g);
2096         isl_int_neg(fu, fu);
2097         isl_seq_combine(ineq, fl, bmap->ineq[u], fu, bmap->ineq[l],
2098                         1 + dim + bmap->n_div);
2099         isl_int_add(ineq[0], ineq[0], fl);
2100         isl_int_add(ineq[0], ineq[0], fu);
2101         isl_int_sub_ui(ineq[0], ineq[0], 1);
2102         isl_int_mul(g, g, fl);
2103         isl_int_mul(g, g, fu);
2104         isl_int_sub(ineq[0], ineq[0], g);
2105 }
2106
2107 /* Remove more kinds of divs that are not strictly needed.
2108  * In particular, if all pairs of lower and upper bounds on a div
2109  * are such that they allow at least one integer value of the div,
2110  * the we can eliminate the div using Fourier-Motzkin without
2111  * introducing any spurious solutions.
2112  */
2113 static struct isl_basic_map *drop_more_redundant_divs(
2114         struct isl_basic_map *bmap, int *pairs, int n)
2115 {
2116         struct isl_tab *tab = NULL;
2117         struct isl_vec *vec = NULL;
2118         unsigned dim;
2119         int remove = -1;
2120         isl_int g, fl, fu;
2121
2122         isl_int_init(g);
2123         isl_int_init(fl);
2124         isl_int_init(fu);
2125
2126         if (!bmap)
2127                 goto error;
2128
2129         dim = isl_dim_total(bmap->dim);
2130         vec = isl_vec_alloc(bmap->ctx, 1 + dim + bmap->n_div);
2131         if (!vec)
2132                 goto error;
2133
2134         tab = isl_tab_from_basic_map(bmap);
2135
2136         while (n > 0) {
2137                 int i, l, u;
2138                 int best = -1;
2139                 enum isl_lp_result res;
2140
2141                 for (i = 0; i < bmap->n_div; ++i) {
2142                         if (!pairs[i])
2143                                 continue;
2144                         if (best >= 0 && pairs[best] <= pairs[i])
2145                                 continue;
2146                         best = i;
2147                 }
2148
2149                 i = best;
2150                 for (l = 0; l < bmap->n_ineq; ++l) {
2151                         if (!isl_int_is_pos(bmap->ineq[l][1 + dim + i]))
2152                                 continue;
2153                         for (u = 0; u < bmap->n_ineq; ++u) {
2154                                 if (!isl_int_is_neg(bmap->ineq[u][1 + dim + i]))
2155                                         continue;
2156                                 construct_test_ineq(bmap, i, l, u,
2157                                                     vec->el, g, fl, fu);
2158                                 res = isl_tab_min(tab, vec->el,
2159                                                   bmap->ctx->one, &g, NULL, 0);
2160                                 if (res == isl_lp_error)
2161                                         goto error;
2162                                 if (res == isl_lp_empty) {
2163                                         bmap = isl_basic_map_set_to_empty(bmap);
2164                                         break;
2165                                 }
2166                                 if (res != isl_lp_ok || isl_int_is_neg(g))
2167                                         break;
2168                         }
2169                         if (u < bmap->n_ineq)
2170                                 break;
2171                 }
2172                 if (l == bmap->n_ineq) {
2173                         remove = i;
2174                         break;
2175                 }
2176                 pairs[i] = 0;
2177                 --n;
2178         }
2179
2180         isl_tab_free(tab);
2181         isl_vec_free(vec);
2182
2183         isl_int_clear(g);
2184         isl_int_clear(fl);
2185         isl_int_clear(fu);
2186
2187         free(pairs);
2188
2189         if (remove < 0)
2190                 return bmap;
2191
2192         bmap = isl_basic_map_remove_dims(bmap, isl_dim_div, remove, 1);
2193         return isl_basic_map_drop_redundant_divs(bmap);
2194 error:
2195         free(pairs);
2196         isl_basic_map_free(bmap);
2197         isl_tab_free(tab);
2198         isl_vec_free(vec);
2199         isl_int_clear(g);
2200         isl_int_clear(fl);
2201         isl_int_clear(fu);
2202         return NULL;
2203 }
2204
2205 /* Given a pair of divs div1 and div2 such that, expect for the lower bound l
2206  * and the upper bound u, div1 always occurs together with div2 in the form 
2207  * (div1 + m div2), where m is the constant range on the variable div1
2208  * allowed by l and u, replace the pair div1 and div2 by a single
2209  * div that is equal to div1 + m div2.
2210  *
2211  * The new div will appear in the location that contains div2.
2212  * We need to modify all constraints that contain
2213  * div2 = (div - div1) / m
2214  * (If a constraint does not contain div2, it will also not contain div1.)
2215  * If the constraint also contains div1, then we know they appear
2216  * as f (div1 + m div2) and we can simply replace (div1 + m div2) by div,
2217  * i.e., the coefficient of div is f.
2218  *
2219  * Otherwise, we first need to introduce div1 into the constraint.
2220  * Let the l be
2221  *
2222  *      div1 + f >=0
2223  *
2224  * and u
2225  *
2226  *      -div1 + f' >= 0
2227  *
2228  * A lower bound on div2
2229  *
2230  *      n div2 + t >= 0
2231  *
2232  * can be replaced by
2233  *
2234  *      (n * (m div 2 + div1) + m t + n f)/g >= 0
2235  *
2236  * with g = gcd(m,n).
2237  * An upper bound
2238  *
2239  *      -n div2 + t >= 0
2240  *
2241  * can be replaced by
2242  *
2243  *      (-n * (m div2 + div1) + m t + n f')/g >= 0
2244  *
2245  * These constraint are those that we would obtain from eliminating
2246  * div1 using Fourier-Motzkin.
2247  *
2248  * After all constraints have been modified, we drop the lower and upper
2249  * bound and then drop div1.
2250  */
2251 static struct isl_basic_map *coalesce_divs(struct isl_basic_map *bmap,
2252         unsigned div1, unsigned div2, unsigned l, unsigned u)
2253 {
2254         isl_int a;
2255         isl_int b;
2256         isl_int m;
2257         unsigned dim, total;
2258         int i;
2259
2260         dim = isl_dim_total(bmap->dim);
2261         total = 1 + dim + bmap->n_div;
2262
2263         isl_int_init(a);
2264         isl_int_init(b);
2265         isl_int_init(m);
2266         isl_int_add(m, bmap->ineq[l][0], bmap->ineq[u][0]);
2267         isl_int_add_ui(m, m, 1);
2268
2269         for (i = 0; i < bmap->n_ineq; ++i) {
2270                 if (i == l || i == u)
2271                         continue;
2272                 if (isl_int_is_zero(bmap->ineq[i][1 + dim + div2]))
2273                         continue;
2274                 if (isl_int_is_zero(bmap->ineq[i][1 + dim + div1])) {
2275                         isl_int_gcd(b, m, bmap->ineq[i][1 + dim + div2]);
2276                         isl_int_divexact(a, m, b);
2277                         isl_int_divexact(b, bmap->ineq[i][1 + dim + div2], b);
2278                         if (isl_int_is_pos(b)) {
2279                                 isl_seq_combine(bmap->ineq[i], a, bmap->ineq[i],
2280                                                 b, bmap->ineq[l], total);
2281                         } else {
2282                                 isl_int_neg(b, b);
2283                                 isl_seq_combine(bmap->ineq[i], a, bmap->ineq[i],
2284                                                 b, bmap->ineq[u], total);
2285                         }
2286                 }
2287                 isl_int_set(bmap->ineq[i][1 + dim + div2],
2288                             bmap->ineq[i][1 + dim + div1]);
2289                 isl_int_set_si(bmap->ineq[i][1 + dim + div1], 0);
2290         }
2291
2292         isl_int_clear(a);
2293         isl_int_clear(b);
2294         isl_int_clear(m);
2295         if (l > u) {
2296                 isl_basic_map_drop_inequality(bmap, l);
2297                 isl_basic_map_drop_inequality(bmap, u);
2298         } else {
2299                 isl_basic_map_drop_inequality(bmap, u);
2300                 isl_basic_map_drop_inequality(bmap, l);
2301         }
2302         bmap = isl_basic_map_drop_div(bmap, div1);
2303         return bmap;
2304 }
2305
2306 /* First check if we can coalesce any pair of divs and
2307  * then continue with dropping more redundant divs.
2308  *
2309  * We loop over all pairs of lower and upper bounds on a div
2310  * with coefficient 1 and -1, respectively, check if there
2311  * is any other div "c" with which we can coalesce the div
2312  * and if so, perform the coalescing.
2313  */
2314 static struct isl_basic_map *coalesce_or_drop_more_redundant_divs(
2315         struct isl_basic_map *bmap, int *pairs, int n)
2316 {
2317         int i, l, u;
2318         unsigned dim;
2319
2320         dim = isl_dim_total(bmap->dim);
2321
2322         for (i = 0; i < bmap->n_div; ++i) {
2323                 if (!pairs[i])
2324                         continue;
2325                 for (l = 0; l < bmap->n_ineq; ++l) {
2326                         if (!isl_int_is_one(bmap->ineq[l][1 + dim + i]))
2327                                 continue;
2328                         for (u = 0; u < bmap->n_ineq; ++u) {
2329                                 int c;
2330
2331                                 if (!isl_int_is_negone(bmap->ineq[u][1+dim+i]))
2332                                         continue;
2333                                 c = div_find_coalesce(bmap, pairs, i, l, u);
2334                                 if (c < 0)
2335                                         continue;
2336                                 free(pairs);
2337                                 bmap = coalesce_divs(bmap, i, c, l, u);
2338                                 return isl_basic_map_drop_redundant_divs(bmap);
2339                         }
2340                 }
2341         }
2342
2343         if (ISL_F_ISSET(bmap, ISL_BASIC_MAP_EMPTY))
2344                 return bmap;
2345
2346         return drop_more_redundant_divs(bmap, pairs, n);
2347 }
2348
2349 /* Remove divs that are not strictly needed.
2350  * In particular, if a div only occurs positively (or negatively)
2351  * in constraints, then it can simply be dropped.
2352  * Also, if a div occurs only occurs in two constraints and if moreover
2353  * those two constraints are opposite to each other, except for the constant
2354  * term and if the sum of the constant terms is such that for any value
2355  * of the other values, there is always at least one integer value of the
2356  * div, i.e., if one plus this sum is greater than or equal to
2357  * the (absolute value) of the coefficent of the div in the constraints,
2358  * then we can also simply drop the div.
2359  *
2360  * If any divs are left after these simple checks then we move on
2361  * to more complicated cases in drop_more_redundant_divs.
2362  */
2363 struct isl_basic_map *isl_basic_map_drop_redundant_divs(
2364         struct isl_basic_map *bmap)
2365 {
2366         int i, j;
2367         unsigned off;
2368         int *pairs = NULL;
2369         int n = 0;
2370
2371         if (!bmap)
2372                 goto error;
2373
2374         off = isl_dim_total(bmap->dim);
2375         pairs = isl_calloc_array(bmap->ctx, int, bmap->n_div);
2376         if (!pairs)
2377                 goto error;
2378
2379         for (i = 0; i < bmap->n_div; ++i) {
2380                 int pos, neg;
2381                 int last_pos, last_neg;
2382                 int redundant;
2383                 int defined;
2384
2385                 defined = !isl_int_is_zero(bmap->div[i][0]);
2386                 for (j = 0; j < bmap->n_eq; ++j)
2387                         if (!isl_int_is_zero(bmap->eq[j][1 + off + i]))
2388                                 break;
2389                 if (j < bmap->n_eq)
2390                         continue;
2391                 ++n;
2392                 pos = neg = 0;
2393                 for (j = 0; j < bmap->n_ineq; ++j) {
2394                         if (isl_int_is_pos(bmap->ineq[j][1 + off + i])) {
2395                                 last_pos = j;
2396                                 ++pos;
2397                         }
2398                         if (isl_int_is_neg(bmap->ineq[j][1 + off + i])) {
2399                                 last_neg = j;
2400                                 ++neg;
2401                         }
2402                 }
2403                 pairs[i] = pos * neg;
2404                 if (pairs[i] == 0) {
2405                         for (j = bmap->n_ineq - 1; j >= 0; --j)
2406                                 if (!isl_int_is_zero(bmap->ineq[j][1+off+i]))
2407                                         isl_basic_map_drop_inequality(bmap, j);
2408                         bmap = isl_basic_map_drop_div(bmap, i);
2409                         free(pairs);
2410                         return isl_basic_map_drop_redundant_divs(bmap);
2411                 }
2412                 if (pairs[i] != 1)
2413                         continue;
2414                 if (!isl_seq_is_neg(bmap->ineq[last_pos] + 1,
2415                                     bmap->ineq[last_neg] + 1,
2416                                     off + bmap->n_div))
2417                         continue;
2418
2419                 isl_int_add(bmap->ineq[last_pos][0],
2420                             bmap->ineq[last_pos][0], bmap->ineq[last_neg][0]);
2421                 isl_int_add_ui(bmap->ineq[last_pos][0],
2422                                bmap->ineq[last_pos][0], 1);
2423                 redundant = isl_int_ge(bmap->ineq[last_pos][0],
2424                                 bmap->ineq[last_pos][1+off+i]);
2425                 isl_int_sub_ui(bmap->ineq[last_pos][0],
2426                                bmap->ineq[last_pos][0], 1);
2427                 isl_int_sub(bmap->ineq[last_pos][0],
2428                             bmap->ineq[last_pos][0], bmap->ineq[last_neg][0]);
2429                 if (!redundant) {
2430                         if (defined ||
2431                             !ok_to_set_div_from_bound(bmap, i, last_pos)) {
2432                                 pairs[i] = 0;
2433                                 --n;
2434                                 continue;
2435                         }
2436                         bmap = set_div_from_lower_bound(bmap, i, last_pos);
2437                         bmap = isl_basic_map_simplify(bmap);
2438                         free(pairs);
2439                         return isl_basic_map_drop_redundant_divs(bmap);
2440                 }
2441                 if (last_pos > last_neg) {
2442                         isl_basic_map_drop_inequality(bmap, last_pos);
2443                         isl_basic_map_drop_inequality(bmap, last_neg);
2444                 } else {
2445                         isl_basic_map_drop_inequality(bmap, last_neg);
2446                         isl_basic_map_drop_inequality(bmap, last_pos);
2447                 }
2448                 bmap = isl_basic_map_drop_div(bmap, i);
2449                 free(pairs);
2450                 return isl_basic_map_drop_redundant_divs(bmap);
2451         }
2452
2453         if (n > 0)
2454                 return coalesce_or_drop_more_redundant_divs(bmap, pairs, n);
2455
2456         free(pairs);
2457         return bmap;
2458 error:
2459         free(pairs);
2460         isl_basic_map_free(bmap);
2461         return NULL;
2462 }
2463
2464 struct isl_basic_set *isl_basic_set_drop_redundant_divs(
2465         struct isl_basic_set *bset)
2466 {
2467         return (struct isl_basic_set *)
2468             isl_basic_map_drop_redundant_divs((struct isl_basic_map *)bset);
2469 }
2470
2471 struct isl_map *isl_map_drop_redundant_divs(struct isl_map *map)
2472 {
2473         int i;
2474
2475         if (!map)
2476                 return NULL;
2477         for (i = 0; i < map->n; ++i) {
2478                 map->p[i] = isl_basic_map_drop_redundant_divs(map->p[i]);
2479                 if (!map->p[i])
2480                         goto error;
2481         }
2482         ISL_F_CLR(map, ISL_MAP_NORMALIZED);
2483         return map;
2484 error:
2485         isl_map_free(map);
2486         return NULL;
2487 }
2488
2489 struct isl_set *isl_set_drop_redundant_divs(struct isl_set *set)
2490 {
2491         return (struct isl_set *)
2492             isl_map_drop_redundant_divs((struct isl_map *)set);
2493 }