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