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