add isl_term_get_coefficient_val
[platform/upstream/isl.git] / isl_polynomial.c
1 /*
2  * Copyright 2010      INRIA Saclay
3  *
4  * Use of this software is governed by the MIT license
5  *
6  * Written by Sven Verdoolaege, INRIA Saclay - Ile-de-France,
7  * Parc Club Orsay Universite, ZAC des vignes, 4 rue Jacques Monod,
8  * 91893 Orsay, France 
9  */
10
11 #include <stdlib.h>
12 #define ISL_DIM_H
13 #include <isl_ctx_private.h>
14 #include <isl_map_private.h>
15 #include <isl_factorization.h>
16 #include <isl/lp.h>
17 #include <isl/seq.h>
18 #include <isl_union_map_private.h>
19 #include <isl_constraint_private.h>
20 #include <isl_polynomial_private.h>
21 #include <isl_point_private.h>
22 #include <isl_space_private.h>
23 #include <isl_mat_private.h>
24 #include <isl_range.h>
25 #include <isl_local_space_private.h>
26 #include <isl_aff_private.h>
27 #include <isl_val_private.h>
28 #include <isl_config.h>
29
30 static unsigned pos(__isl_keep isl_space *dim, enum isl_dim_type type)
31 {
32         switch (type) {
33         case isl_dim_param:     return 0;
34         case isl_dim_in:        return dim->nparam;
35         case isl_dim_out:       return dim->nparam + dim->n_in;
36         default:                return 0;
37         }
38 }
39
40 int isl_upoly_is_cst(__isl_keep struct isl_upoly *up)
41 {
42         if (!up)
43                 return -1;
44
45         return up->var < 0;
46 }
47
48 __isl_keep struct isl_upoly_cst *isl_upoly_as_cst(__isl_keep struct isl_upoly *up)
49 {
50         if (!up)
51                 return NULL;
52
53         isl_assert(up->ctx, up->var < 0, return NULL);
54
55         return (struct isl_upoly_cst *)up;
56 }
57
58 __isl_keep struct isl_upoly_rec *isl_upoly_as_rec(__isl_keep struct isl_upoly *up)
59 {
60         if (!up)
61                 return NULL;
62
63         isl_assert(up->ctx, up->var >= 0, return NULL);
64
65         return (struct isl_upoly_rec *)up;
66 }
67
68 int isl_upoly_is_equal(__isl_keep struct isl_upoly *up1,
69         __isl_keep struct isl_upoly *up2)
70 {
71         int i;
72         struct isl_upoly_rec *rec1, *rec2;
73
74         if (!up1 || !up2)
75                 return -1;
76         if (up1 == up2)
77                 return 1;
78         if (up1->var != up2->var)
79                 return 0;
80         if (isl_upoly_is_cst(up1)) {
81                 struct isl_upoly_cst *cst1, *cst2;
82                 cst1 = isl_upoly_as_cst(up1);
83                 cst2 = isl_upoly_as_cst(up2);
84                 if (!cst1 || !cst2)
85                         return -1;
86                 return isl_int_eq(cst1->n, cst2->n) &&
87                        isl_int_eq(cst1->d, cst2->d);
88         }
89
90         rec1 = isl_upoly_as_rec(up1);
91         rec2 = isl_upoly_as_rec(up2);
92         if (!rec1 || !rec2)
93                 return -1;
94
95         if (rec1->n != rec2->n)
96                 return 0;
97
98         for (i = 0; i < rec1->n; ++i) {
99                 int eq = isl_upoly_is_equal(rec1->p[i], rec2->p[i]);
100                 if (eq < 0 || !eq)
101                         return eq;
102         }
103
104         return 1;
105 }
106
107 int isl_upoly_is_zero(__isl_keep struct isl_upoly *up)
108 {
109         struct isl_upoly_cst *cst;
110
111         if (!up)
112                 return -1;
113         if (!isl_upoly_is_cst(up))
114                 return 0;
115
116         cst = isl_upoly_as_cst(up);
117         if (!cst)
118                 return -1;
119
120         return isl_int_is_zero(cst->n) && isl_int_is_pos(cst->d);
121 }
122
123 int isl_upoly_sgn(__isl_keep struct isl_upoly *up)
124 {
125         struct isl_upoly_cst *cst;
126
127         if (!up)
128                 return 0;
129         if (!isl_upoly_is_cst(up))
130                 return 0;
131
132         cst = isl_upoly_as_cst(up);
133         if (!cst)
134                 return 0;
135
136         return isl_int_sgn(cst->n);
137 }
138
139 int isl_upoly_is_nan(__isl_keep struct isl_upoly *up)
140 {
141         struct isl_upoly_cst *cst;
142
143         if (!up)
144                 return -1;
145         if (!isl_upoly_is_cst(up))
146                 return 0;
147
148         cst = isl_upoly_as_cst(up);
149         if (!cst)
150                 return -1;
151
152         return isl_int_is_zero(cst->n) && isl_int_is_zero(cst->d);
153 }
154
155 int isl_upoly_is_infty(__isl_keep struct isl_upoly *up)
156 {
157         struct isl_upoly_cst *cst;
158
159         if (!up)
160                 return -1;
161         if (!isl_upoly_is_cst(up))
162                 return 0;
163
164         cst = isl_upoly_as_cst(up);
165         if (!cst)
166                 return -1;
167
168         return isl_int_is_pos(cst->n) && isl_int_is_zero(cst->d);
169 }
170
171 int isl_upoly_is_neginfty(__isl_keep struct isl_upoly *up)
172 {
173         struct isl_upoly_cst *cst;
174
175         if (!up)
176                 return -1;
177         if (!isl_upoly_is_cst(up))
178                 return 0;
179
180         cst = isl_upoly_as_cst(up);
181         if (!cst)
182                 return -1;
183
184         return isl_int_is_neg(cst->n) && isl_int_is_zero(cst->d);
185 }
186
187 int isl_upoly_is_one(__isl_keep struct isl_upoly *up)
188 {
189         struct isl_upoly_cst *cst;
190
191         if (!up)
192                 return -1;
193         if (!isl_upoly_is_cst(up))
194                 return 0;
195
196         cst = isl_upoly_as_cst(up);
197         if (!cst)
198                 return -1;
199
200         return isl_int_eq(cst->n, cst->d) && isl_int_is_pos(cst->d);
201 }
202
203 int isl_upoly_is_negone(__isl_keep struct isl_upoly *up)
204 {
205         struct isl_upoly_cst *cst;
206
207         if (!up)
208                 return -1;
209         if (!isl_upoly_is_cst(up))
210                 return 0;
211
212         cst = isl_upoly_as_cst(up);
213         if (!cst)
214                 return -1;
215
216         return isl_int_is_negone(cst->n) && isl_int_is_one(cst->d);
217 }
218
219 __isl_give struct isl_upoly_cst *isl_upoly_cst_alloc(struct isl_ctx *ctx)
220 {
221         struct isl_upoly_cst *cst;
222
223         cst = isl_alloc_type(ctx, struct isl_upoly_cst);
224         if (!cst)
225                 return NULL;
226
227         cst->up.ref = 1;
228         cst->up.ctx = ctx;
229         isl_ctx_ref(ctx);
230         cst->up.var = -1;
231
232         isl_int_init(cst->n);
233         isl_int_init(cst->d);
234
235         return cst;
236 }
237
238 __isl_give struct isl_upoly *isl_upoly_zero(struct isl_ctx *ctx)
239 {
240         struct isl_upoly_cst *cst;
241
242         cst = isl_upoly_cst_alloc(ctx);
243         if (!cst)
244                 return NULL;
245
246         isl_int_set_si(cst->n, 0);
247         isl_int_set_si(cst->d, 1);
248
249         return &cst->up;
250 }
251
252 __isl_give struct isl_upoly *isl_upoly_one(struct isl_ctx *ctx)
253 {
254         struct isl_upoly_cst *cst;
255
256         cst = isl_upoly_cst_alloc(ctx);
257         if (!cst)
258                 return NULL;
259
260         isl_int_set_si(cst->n, 1);
261         isl_int_set_si(cst->d, 1);
262
263         return &cst->up;
264 }
265
266 __isl_give struct isl_upoly *isl_upoly_infty(struct isl_ctx *ctx)
267 {
268         struct isl_upoly_cst *cst;
269
270         cst = isl_upoly_cst_alloc(ctx);
271         if (!cst)
272                 return NULL;
273
274         isl_int_set_si(cst->n, 1);
275         isl_int_set_si(cst->d, 0);
276
277         return &cst->up;
278 }
279
280 __isl_give struct isl_upoly *isl_upoly_neginfty(struct isl_ctx *ctx)
281 {
282         struct isl_upoly_cst *cst;
283
284         cst = isl_upoly_cst_alloc(ctx);
285         if (!cst)
286                 return NULL;
287
288         isl_int_set_si(cst->n, -1);
289         isl_int_set_si(cst->d, 0);
290
291         return &cst->up;
292 }
293
294 __isl_give struct isl_upoly *isl_upoly_nan(struct isl_ctx *ctx)
295 {
296         struct isl_upoly_cst *cst;
297
298         cst = isl_upoly_cst_alloc(ctx);
299         if (!cst)
300                 return NULL;
301
302         isl_int_set_si(cst->n, 0);
303         isl_int_set_si(cst->d, 0);
304
305         return &cst->up;
306 }
307
308 __isl_give struct isl_upoly *isl_upoly_rat_cst(struct isl_ctx *ctx,
309         isl_int n, isl_int d)
310 {
311         struct isl_upoly_cst *cst;
312
313         cst = isl_upoly_cst_alloc(ctx);
314         if (!cst)
315                 return NULL;
316
317         isl_int_set(cst->n, n);
318         isl_int_set(cst->d, d);
319
320         return &cst->up;
321 }
322
323 __isl_give struct isl_upoly_rec *isl_upoly_alloc_rec(struct isl_ctx *ctx,
324         int var, int size)
325 {
326         struct isl_upoly_rec *rec;
327
328         isl_assert(ctx, var >= 0, return NULL);
329         isl_assert(ctx, size >= 0, return NULL);
330         rec = isl_calloc(ctx, struct isl_upoly_rec,
331                         sizeof(struct isl_upoly_rec) +
332                         size * sizeof(struct isl_upoly *));
333         if (!rec)
334                 return NULL;
335
336         rec->up.ref = 1;
337         rec->up.ctx = ctx;
338         isl_ctx_ref(ctx);
339         rec->up.var = var;
340
341         rec->n = 0;
342         rec->size = size;
343
344         return rec;
345 }
346
347 __isl_give isl_qpolynomial *isl_qpolynomial_reset_domain_space(
348         __isl_take isl_qpolynomial *qp, __isl_take isl_space *dim)
349 {
350         qp = isl_qpolynomial_cow(qp);
351         if (!qp || !dim)
352                 goto error;
353
354         isl_space_free(qp->dim);
355         qp->dim = dim;
356
357         return qp;
358 error:
359         isl_qpolynomial_free(qp);
360         isl_space_free(dim);
361         return NULL;
362 }
363
364 /* Reset the space of "qp".  This function is called from isl_pw_templ.c
365  * and doesn't know if the space of an element object is represented
366  * directly or through its domain.  It therefore passes along both.
367  */
368 __isl_give isl_qpolynomial *isl_qpolynomial_reset_space_and_domain(
369         __isl_take isl_qpolynomial *qp, __isl_take isl_space *space,
370         __isl_take isl_space *domain)
371 {
372         isl_space_free(space);
373         return isl_qpolynomial_reset_domain_space(qp, domain);
374 }
375
376 isl_ctx *isl_qpolynomial_get_ctx(__isl_keep isl_qpolynomial *qp)
377 {
378         return qp ? qp->dim->ctx : NULL;
379 }
380
381 __isl_give isl_space *isl_qpolynomial_get_domain_space(
382         __isl_keep isl_qpolynomial *qp)
383 {
384         return qp ? isl_space_copy(qp->dim) : NULL;
385 }
386
387 __isl_give isl_space *isl_qpolynomial_get_space(__isl_keep isl_qpolynomial *qp)
388 {
389         isl_space *space;
390         if (!qp)
391                 return NULL;
392         space = isl_space_copy(qp->dim);
393         space = isl_space_from_domain(space);
394         space = isl_space_add_dims(space, isl_dim_out, 1);
395         return space;
396 }
397
398 /* Externally, an isl_qpolynomial has a map space, but internally, the
399  * ls field corresponds to the domain of that space.
400  */
401 unsigned isl_qpolynomial_dim(__isl_keep isl_qpolynomial *qp,
402         enum isl_dim_type type)
403 {
404         if (!qp)
405                 return 0;
406         if (type == isl_dim_out)
407                 return 1;
408         if (type == isl_dim_in)
409                 type = isl_dim_set;
410         return isl_space_dim(qp->dim, type);
411 }
412
413 int isl_qpolynomial_is_zero(__isl_keep isl_qpolynomial *qp)
414 {
415         return qp ? isl_upoly_is_zero(qp->upoly) : -1;
416 }
417
418 int isl_qpolynomial_is_one(__isl_keep isl_qpolynomial *qp)
419 {
420         return qp ? isl_upoly_is_one(qp->upoly) : -1;
421 }
422
423 int isl_qpolynomial_is_nan(__isl_keep isl_qpolynomial *qp)
424 {
425         return qp ? isl_upoly_is_nan(qp->upoly) : -1;
426 }
427
428 int isl_qpolynomial_is_infty(__isl_keep isl_qpolynomial *qp)
429 {
430         return qp ? isl_upoly_is_infty(qp->upoly) : -1;
431 }
432
433 int isl_qpolynomial_is_neginfty(__isl_keep isl_qpolynomial *qp)
434 {
435         return qp ? isl_upoly_is_neginfty(qp->upoly) : -1;
436 }
437
438 int isl_qpolynomial_sgn(__isl_keep isl_qpolynomial *qp)
439 {
440         return qp ? isl_upoly_sgn(qp->upoly) : 0;
441 }
442
443 static void upoly_free_cst(__isl_take struct isl_upoly_cst *cst)
444 {
445         isl_int_clear(cst->n);
446         isl_int_clear(cst->d);
447 }
448
449 static void upoly_free_rec(__isl_take struct isl_upoly_rec *rec)
450 {
451         int i;
452
453         for (i = 0; i < rec->n; ++i)
454                 isl_upoly_free(rec->p[i]);
455 }
456
457 __isl_give struct isl_upoly *isl_upoly_copy(__isl_keep struct isl_upoly *up)
458 {
459         if (!up)
460                 return NULL;
461
462         up->ref++;
463         return up;
464 }
465
466 __isl_give struct isl_upoly *isl_upoly_dup_cst(__isl_keep struct isl_upoly *up)
467 {
468         struct isl_upoly_cst *cst;
469         struct isl_upoly_cst *dup;
470
471         cst = isl_upoly_as_cst(up);
472         if (!cst)
473                 return NULL;
474
475         dup = isl_upoly_as_cst(isl_upoly_zero(up->ctx));
476         if (!dup)
477                 return NULL;
478         isl_int_set(dup->n, cst->n);
479         isl_int_set(dup->d, cst->d);
480
481         return &dup->up;
482 }
483
484 __isl_give struct isl_upoly *isl_upoly_dup_rec(__isl_keep struct isl_upoly *up)
485 {
486         int i;
487         struct isl_upoly_rec *rec;
488         struct isl_upoly_rec *dup;
489
490         rec = isl_upoly_as_rec(up);
491         if (!rec)
492                 return NULL;
493
494         dup = isl_upoly_alloc_rec(up->ctx, up->var, rec->n);
495         if (!dup)
496                 return NULL;
497
498         for (i = 0; i < rec->n; ++i) {
499                 dup->p[i] = isl_upoly_copy(rec->p[i]);
500                 if (!dup->p[i])
501                         goto error;
502                 dup->n++;
503         }
504
505         return &dup->up;
506 error:
507         isl_upoly_free(&dup->up);
508         return NULL;
509 }
510
511 __isl_give struct isl_upoly *isl_upoly_dup(__isl_keep struct isl_upoly *up)
512 {
513         if (!up)
514                 return NULL;
515
516         if (isl_upoly_is_cst(up))
517                 return isl_upoly_dup_cst(up);
518         else
519                 return isl_upoly_dup_rec(up);
520 }
521
522 __isl_give struct isl_upoly *isl_upoly_cow(__isl_take struct isl_upoly *up)
523 {
524         if (!up)
525                 return NULL;
526
527         if (up->ref == 1)
528                 return up;
529         up->ref--;
530         return isl_upoly_dup(up);
531 }
532
533 void isl_upoly_free(__isl_take struct isl_upoly *up)
534 {
535         if (!up)
536                 return;
537
538         if (--up->ref > 0)
539                 return;
540
541         if (up->var < 0)
542                 upoly_free_cst((struct isl_upoly_cst *)up);
543         else
544                 upoly_free_rec((struct isl_upoly_rec *)up);
545
546         isl_ctx_deref(up->ctx);
547         free(up);
548 }
549
550 static void isl_upoly_cst_reduce(__isl_keep struct isl_upoly_cst *cst)
551 {
552         isl_int gcd;
553
554         isl_int_init(gcd);
555         isl_int_gcd(gcd, cst->n, cst->d);
556         if (!isl_int_is_zero(gcd) && !isl_int_is_one(gcd)) {
557                 isl_int_divexact(cst->n, cst->n, gcd);
558                 isl_int_divexact(cst->d, cst->d, gcd);
559         }
560         isl_int_clear(gcd);
561 }
562
563 __isl_give struct isl_upoly *isl_upoly_sum_cst(__isl_take struct isl_upoly *up1,
564         __isl_take struct isl_upoly *up2)
565 {
566         struct isl_upoly_cst *cst1;
567         struct isl_upoly_cst *cst2;
568
569         up1 = isl_upoly_cow(up1);
570         if (!up1 || !up2)
571                 goto error;
572
573         cst1 = isl_upoly_as_cst(up1);
574         cst2 = isl_upoly_as_cst(up2);
575
576         if (isl_int_eq(cst1->d, cst2->d))
577                 isl_int_add(cst1->n, cst1->n, cst2->n);
578         else {
579                 isl_int_mul(cst1->n, cst1->n, cst2->d);
580                 isl_int_addmul(cst1->n, cst2->n, cst1->d);
581                 isl_int_mul(cst1->d, cst1->d, cst2->d);
582         }
583
584         isl_upoly_cst_reduce(cst1);
585
586         isl_upoly_free(up2);
587         return up1;
588 error:
589         isl_upoly_free(up1);
590         isl_upoly_free(up2);
591         return NULL;
592 }
593
594 static __isl_give struct isl_upoly *replace_by_zero(
595         __isl_take struct isl_upoly *up)
596 {
597         struct isl_ctx *ctx;
598
599         if (!up)
600                 return NULL;
601         ctx = up->ctx;
602         isl_upoly_free(up);
603         return isl_upoly_zero(ctx);
604 }
605
606 static __isl_give struct isl_upoly *replace_by_constant_term(
607         __isl_take struct isl_upoly *up)
608 {
609         struct isl_upoly_rec *rec;
610         struct isl_upoly *cst;
611
612         if (!up)
613                 return NULL;
614
615         rec = isl_upoly_as_rec(up);
616         if (!rec)
617                 goto error;
618         cst = isl_upoly_copy(rec->p[0]);
619         isl_upoly_free(up);
620         return cst;
621 error:
622         isl_upoly_free(up);
623         return NULL;
624 }
625
626 __isl_give struct isl_upoly *isl_upoly_sum(__isl_take struct isl_upoly *up1,
627         __isl_take struct isl_upoly *up2)
628 {
629         int i;
630         struct isl_upoly_rec *rec1, *rec2;
631
632         if (!up1 || !up2)
633                 goto error;
634
635         if (isl_upoly_is_nan(up1)) {
636                 isl_upoly_free(up2);
637                 return up1;
638         }
639
640         if (isl_upoly_is_nan(up2)) {
641                 isl_upoly_free(up1);
642                 return up2;
643         }
644
645         if (isl_upoly_is_zero(up1)) {
646                 isl_upoly_free(up1);
647                 return up2;
648         }
649
650         if (isl_upoly_is_zero(up2)) {
651                 isl_upoly_free(up2);
652                 return up1;
653         }
654
655         if (up1->var < up2->var)
656                 return isl_upoly_sum(up2, up1);
657
658         if (up2->var < up1->var) {
659                 struct isl_upoly_rec *rec;
660                 if (isl_upoly_is_infty(up2) || isl_upoly_is_neginfty(up2)) {
661                         isl_upoly_free(up1);
662                         return up2;
663                 }
664                 up1 = isl_upoly_cow(up1);
665                 rec = isl_upoly_as_rec(up1);
666                 if (!rec)
667                         goto error;
668                 rec->p[0] = isl_upoly_sum(rec->p[0], up2);
669                 if (rec->n == 1)
670                         up1 = replace_by_constant_term(up1);
671                 return up1;
672         }
673
674         if (isl_upoly_is_cst(up1))
675                 return isl_upoly_sum_cst(up1, up2);
676
677         rec1 = isl_upoly_as_rec(up1);
678         rec2 = isl_upoly_as_rec(up2);
679         if (!rec1 || !rec2)
680                 goto error;
681
682         if (rec1->n < rec2->n)
683                 return isl_upoly_sum(up2, up1);
684
685         up1 = isl_upoly_cow(up1);
686         rec1 = isl_upoly_as_rec(up1);
687         if (!rec1)
688                 goto error;
689
690         for (i = rec2->n - 1; i >= 0; --i) {
691                 rec1->p[i] = isl_upoly_sum(rec1->p[i],
692                                             isl_upoly_copy(rec2->p[i]));
693                 if (!rec1->p[i])
694                         goto error;
695                 if (i == rec1->n - 1 && isl_upoly_is_zero(rec1->p[i])) {
696                         isl_upoly_free(rec1->p[i]);
697                         rec1->n--;
698                 }
699         }
700
701         if (rec1->n == 0)
702                 up1 = replace_by_zero(up1);
703         else if (rec1->n == 1)
704                 up1 = replace_by_constant_term(up1);
705
706         isl_upoly_free(up2);
707
708         return up1;
709 error:
710         isl_upoly_free(up1);
711         isl_upoly_free(up2);
712         return NULL;
713 }
714
715 __isl_give struct isl_upoly *isl_upoly_cst_add_isl_int(
716         __isl_take struct isl_upoly *up, isl_int v)
717 {
718         struct isl_upoly_cst *cst;
719
720         up = isl_upoly_cow(up);
721         if (!up)
722                 return NULL;
723
724         cst = isl_upoly_as_cst(up);
725
726         isl_int_addmul(cst->n, cst->d, v);
727
728         return up;
729 }
730
731 __isl_give struct isl_upoly *isl_upoly_add_isl_int(
732         __isl_take struct isl_upoly *up, isl_int v)
733 {
734         struct isl_upoly_rec *rec;
735
736         if (!up)
737                 return NULL;
738
739         if (isl_upoly_is_cst(up))
740                 return isl_upoly_cst_add_isl_int(up, v);
741
742         up = isl_upoly_cow(up);
743         rec = isl_upoly_as_rec(up);
744         if (!rec)
745                 goto error;
746
747         rec->p[0] = isl_upoly_add_isl_int(rec->p[0], v);
748         if (!rec->p[0])
749                 goto error;
750
751         return up;
752 error:
753         isl_upoly_free(up);
754         return NULL;
755 }
756
757 __isl_give struct isl_upoly *isl_upoly_cst_mul_isl_int(
758         __isl_take struct isl_upoly *up, isl_int v)
759 {
760         struct isl_upoly_cst *cst;
761
762         if (isl_upoly_is_zero(up))
763                 return up;
764
765         up = isl_upoly_cow(up);
766         if (!up)
767                 return NULL;
768
769         cst = isl_upoly_as_cst(up);
770
771         isl_int_mul(cst->n, cst->n, v);
772
773         return up;
774 }
775
776 __isl_give struct isl_upoly *isl_upoly_mul_isl_int(
777         __isl_take struct isl_upoly *up, isl_int v)
778 {
779         int i;
780         struct isl_upoly_rec *rec;
781
782         if (!up)
783                 return NULL;
784
785         if (isl_upoly_is_cst(up))
786                 return isl_upoly_cst_mul_isl_int(up, v);
787
788         up = isl_upoly_cow(up);
789         rec = isl_upoly_as_rec(up);
790         if (!rec)
791                 goto error;
792
793         for (i = 0; i < rec->n; ++i) {
794                 rec->p[i] = isl_upoly_mul_isl_int(rec->p[i], v);
795                 if (!rec->p[i])
796                         goto error;
797         }
798
799         return up;
800 error:
801         isl_upoly_free(up);
802         return NULL;
803 }
804
805 __isl_give struct isl_upoly *isl_upoly_mul_cst(__isl_take struct isl_upoly *up1,
806         __isl_take struct isl_upoly *up2)
807 {
808         struct isl_upoly_cst *cst1;
809         struct isl_upoly_cst *cst2;
810
811         up1 = isl_upoly_cow(up1);
812         if (!up1 || !up2)
813                 goto error;
814
815         cst1 = isl_upoly_as_cst(up1);
816         cst2 = isl_upoly_as_cst(up2);
817
818         isl_int_mul(cst1->n, cst1->n, cst2->n);
819         isl_int_mul(cst1->d, cst1->d, cst2->d);
820
821         isl_upoly_cst_reduce(cst1);
822
823         isl_upoly_free(up2);
824         return up1;
825 error:
826         isl_upoly_free(up1);
827         isl_upoly_free(up2);
828         return NULL;
829 }
830
831 __isl_give struct isl_upoly *isl_upoly_mul_rec(__isl_take struct isl_upoly *up1,
832         __isl_take struct isl_upoly *up2)
833 {
834         struct isl_upoly_rec *rec1;
835         struct isl_upoly_rec *rec2;
836         struct isl_upoly_rec *res = NULL;
837         int i, j;
838         int size;
839
840         rec1 = isl_upoly_as_rec(up1);
841         rec2 = isl_upoly_as_rec(up2);
842         if (!rec1 || !rec2)
843                 goto error;
844         size = rec1->n + rec2->n - 1;
845         res = isl_upoly_alloc_rec(up1->ctx, up1->var, size);
846         if (!res)
847                 goto error;
848
849         for (i = 0; i < rec1->n; ++i) {
850                 res->p[i] = isl_upoly_mul(isl_upoly_copy(rec2->p[0]),
851                                             isl_upoly_copy(rec1->p[i]));
852                 if (!res->p[i])
853                         goto error;
854                 res->n++;
855         }
856         for (; i < size; ++i) {
857                 res->p[i] = isl_upoly_zero(up1->ctx);
858                 if (!res->p[i])
859                         goto error;
860                 res->n++;
861         }
862         for (i = 0; i < rec1->n; ++i) {
863                 for (j = 1; j < rec2->n; ++j) {
864                         struct isl_upoly *up;
865                         up = isl_upoly_mul(isl_upoly_copy(rec2->p[j]),
866                                             isl_upoly_copy(rec1->p[i]));
867                         res->p[i + j] = isl_upoly_sum(res->p[i + j], up);
868                         if (!res->p[i + j])
869                                 goto error;
870                 }
871         }
872
873         isl_upoly_free(up1);
874         isl_upoly_free(up2);
875
876         return &res->up;
877 error:
878         isl_upoly_free(up1);
879         isl_upoly_free(up2);
880         isl_upoly_free(&res->up);
881         return NULL;
882 }
883
884 __isl_give struct isl_upoly *isl_upoly_mul(__isl_take struct isl_upoly *up1,
885         __isl_take struct isl_upoly *up2)
886 {
887         if (!up1 || !up2)
888                 goto error;
889
890         if (isl_upoly_is_nan(up1)) {
891                 isl_upoly_free(up2);
892                 return up1;
893         }
894
895         if (isl_upoly_is_nan(up2)) {
896                 isl_upoly_free(up1);
897                 return up2;
898         }
899
900         if (isl_upoly_is_zero(up1)) {
901                 isl_upoly_free(up2);
902                 return up1;
903         }
904
905         if (isl_upoly_is_zero(up2)) {
906                 isl_upoly_free(up1);
907                 return up2;
908         }
909
910         if (isl_upoly_is_one(up1)) {
911                 isl_upoly_free(up1);
912                 return up2;
913         }
914
915         if (isl_upoly_is_one(up2)) {
916                 isl_upoly_free(up2);
917                 return up1;
918         }
919
920         if (up1->var < up2->var)
921                 return isl_upoly_mul(up2, up1);
922
923         if (up2->var < up1->var) {
924                 int i;
925                 struct isl_upoly_rec *rec;
926                 if (isl_upoly_is_infty(up2) || isl_upoly_is_neginfty(up2)) {
927                         isl_ctx *ctx = up1->ctx;
928                         isl_upoly_free(up1);
929                         isl_upoly_free(up2);
930                         return isl_upoly_nan(ctx);
931                 }
932                 up1 = isl_upoly_cow(up1);
933                 rec = isl_upoly_as_rec(up1);
934                 if (!rec)
935                         goto error;
936
937                 for (i = 0; i < rec->n; ++i) {
938                         rec->p[i] = isl_upoly_mul(rec->p[i],
939                                                     isl_upoly_copy(up2));
940                         if (!rec->p[i])
941                                 goto error;
942                 }
943                 isl_upoly_free(up2);
944                 return up1;
945         }
946
947         if (isl_upoly_is_cst(up1))
948                 return isl_upoly_mul_cst(up1, up2);
949
950         return isl_upoly_mul_rec(up1, up2);
951 error:
952         isl_upoly_free(up1);
953         isl_upoly_free(up2);
954         return NULL;
955 }
956
957 __isl_give struct isl_upoly *isl_upoly_pow(__isl_take struct isl_upoly *up,
958         unsigned power)
959 {
960         struct isl_upoly *res;
961
962         if (!up)
963                 return NULL;
964         if (power == 1)
965                 return up;
966
967         if (power % 2)
968                 res = isl_upoly_copy(up);
969         else
970                 res = isl_upoly_one(up->ctx);
971
972         while (power >>= 1) {
973                 up = isl_upoly_mul(up, isl_upoly_copy(up));
974                 if (power % 2)
975                         res = isl_upoly_mul(res, isl_upoly_copy(up));
976         }
977
978         isl_upoly_free(up);
979         return res;
980 }
981
982 __isl_give isl_qpolynomial *isl_qpolynomial_alloc(__isl_take isl_space *dim,
983         unsigned n_div, __isl_take struct isl_upoly *up)
984 {
985         struct isl_qpolynomial *qp = NULL;
986         unsigned total;
987
988         if (!dim || !up)
989                 goto error;
990
991         if (!isl_space_is_set(dim))
992                 isl_die(isl_space_get_ctx(dim), isl_error_invalid,
993                         "domain of polynomial should be a set", goto error);
994
995         total = isl_space_dim(dim, isl_dim_all);
996
997         qp = isl_calloc_type(dim->ctx, struct isl_qpolynomial);
998         if (!qp)
999                 goto error;
1000
1001         qp->ref = 1;
1002         qp->div = isl_mat_alloc(dim->ctx, n_div, 1 + 1 + total + n_div);
1003         if (!qp->div)
1004                 goto error;
1005
1006         qp->dim = dim;
1007         qp->upoly = up;
1008
1009         return qp;
1010 error:
1011         isl_space_free(dim);
1012         isl_upoly_free(up);
1013         isl_qpolynomial_free(qp);
1014         return NULL;
1015 }
1016
1017 __isl_give isl_qpolynomial *isl_qpolynomial_copy(__isl_keep isl_qpolynomial *qp)
1018 {
1019         if (!qp)
1020                 return NULL;
1021
1022         qp->ref++;
1023         return qp;
1024 }
1025
1026 __isl_give isl_qpolynomial *isl_qpolynomial_dup(__isl_keep isl_qpolynomial *qp)
1027 {
1028         struct isl_qpolynomial *dup;
1029
1030         if (!qp)
1031                 return NULL;
1032
1033         dup = isl_qpolynomial_alloc(isl_space_copy(qp->dim), qp->div->n_row,
1034                                     isl_upoly_copy(qp->upoly));
1035         if (!dup)
1036                 return NULL;
1037         isl_mat_free(dup->div);
1038         dup->div = isl_mat_copy(qp->div);
1039         if (!dup->div)
1040                 goto error;
1041
1042         return dup;
1043 error:
1044         isl_qpolynomial_free(dup);
1045         return NULL;
1046 }
1047
1048 __isl_give isl_qpolynomial *isl_qpolynomial_cow(__isl_take isl_qpolynomial *qp)
1049 {
1050         if (!qp)
1051                 return NULL;
1052
1053         if (qp->ref == 1)
1054                 return qp;
1055         qp->ref--;
1056         return isl_qpolynomial_dup(qp);
1057 }
1058
1059 void *isl_qpolynomial_free(__isl_take isl_qpolynomial *qp)
1060 {
1061         if (!qp)
1062                 return NULL;
1063
1064         if (--qp->ref > 0)
1065                 return NULL;
1066
1067         isl_space_free(qp->dim);
1068         isl_mat_free(qp->div);
1069         isl_upoly_free(qp->upoly);
1070
1071         free(qp);
1072         return NULL;
1073 }
1074
1075 __isl_give struct isl_upoly *isl_upoly_var_pow(isl_ctx *ctx, int pos, int power)
1076 {
1077         int i;
1078         struct isl_upoly_rec *rec;
1079         struct isl_upoly_cst *cst;
1080
1081         rec = isl_upoly_alloc_rec(ctx, pos, 1 + power);
1082         if (!rec)
1083                 return NULL;
1084         for (i = 0; i < 1 + power; ++i) {
1085                 rec->p[i] = isl_upoly_zero(ctx);
1086                 if (!rec->p[i])
1087                         goto error;
1088                 rec->n++;
1089         }
1090         cst = isl_upoly_as_cst(rec->p[power]);
1091         isl_int_set_si(cst->n, 1);
1092
1093         return &rec->up;
1094 error:
1095         isl_upoly_free(&rec->up);
1096         return NULL;
1097 }
1098
1099 /* r array maps original positions to new positions.
1100  */
1101 static __isl_give struct isl_upoly *reorder(__isl_take struct isl_upoly *up,
1102         int *r)
1103 {
1104         int i;
1105         struct isl_upoly_rec *rec;
1106         struct isl_upoly *base;
1107         struct isl_upoly *res;
1108
1109         if (isl_upoly_is_cst(up))
1110                 return up;
1111
1112         rec = isl_upoly_as_rec(up);
1113         if (!rec)
1114                 goto error;
1115
1116         isl_assert(up->ctx, rec->n >= 1, goto error);
1117
1118         base = isl_upoly_var_pow(up->ctx, r[up->var], 1);
1119         res = reorder(isl_upoly_copy(rec->p[rec->n - 1]), r);
1120
1121         for (i = rec->n - 2; i >= 0; --i) {
1122                 res = isl_upoly_mul(res, isl_upoly_copy(base));
1123                 res = isl_upoly_sum(res, reorder(isl_upoly_copy(rec->p[i]), r));
1124         }
1125
1126         isl_upoly_free(base);
1127         isl_upoly_free(up);
1128
1129         return res;
1130 error:
1131         isl_upoly_free(up);
1132         return NULL;
1133 }
1134
1135 static int compatible_divs(__isl_keep isl_mat *div1, __isl_keep isl_mat *div2)
1136 {
1137         int n_row, n_col;
1138         int equal;
1139
1140         isl_assert(div1->ctx, div1->n_row >= div2->n_row &&
1141                                 div1->n_col >= div2->n_col, return -1);
1142
1143         if (div1->n_row == div2->n_row)
1144                 return isl_mat_is_equal(div1, div2);
1145
1146         n_row = div1->n_row;
1147         n_col = div1->n_col;
1148         div1->n_row = div2->n_row;
1149         div1->n_col = div2->n_col;
1150
1151         equal = isl_mat_is_equal(div1, div2);
1152
1153         div1->n_row = n_row;
1154         div1->n_col = n_col;
1155
1156         return equal;
1157 }
1158
1159 static int cmp_row(__isl_keep isl_mat *div, int i, int j)
1160 {
1161         int li, lj;
1162
1163         li = isl_seq_last_non_zero(div->row[i], div->n_col);
1164         lj = isl_seq_last_non_zero(div->row[j], div->n_col);
1165
1166         if (li != lj)
1167                 return li - lj;
1168
1169         return isl_seq_cmp(div->row[i], div->row[j], div->n_col);
1170 }
1171
1172 struct isl_div_sort_info {
1173         isl_mat *div;
1174         int      row;
1175 };
1176
1177 static int div_sort_cmp(const void *p1, const void *p2)
1178 {
1179         const struct isl_div_sort_info *i1, *i2;
1180         i1 = (const struct isl_div_sort_info *) p1;
1181         i2 = (const struct isl_div_sort_info *) p2;
1182
1183         return cmp_row(i1->div, i1->row, i2->row);
1184 }
1185
1186 /* Sort divs and remove duplicates.
1187  */
1188 static __isl_give isl_qpolynomial *sort_divs(__isl_take isl_qpolynomial *qp)
1189 {
1190         int i;
1191         int skip;
1192         int len;
1193         struct isl_div_sort_info *array = NULL;
1194         int *pos = NULL, *at = NULL;
1195         int *reordering = NULL;
1196         unsigned div_pos;
1197
1198         if (!qp)
1199                 return NULL;
1200         if (qp->div->n_row <= 1)
1201                 return qp;
1202
1203         div_pos = isl_space_dim(qp->dim, isl_dim_all);
1204
1205         array = isl_alloc_array(qp->div->ctx, struct isl_div_sort_info,
1206                                 qp->div->n_row);
1207         pos = isl_alloc_array(qp->div->ctx, int, qp->div->n_row);
1208         at = isl_alloc_array(qp->div->ctx, int, qp->div->n_row);
1209         len = qp->div->n_col - 2;
1210         reordering = isl_alloc_array(qp->div->ctx, int, len);
1211         if (!array || !pos || !at || !reordering)
1212                 goto error;
1213
1214         for (i = 0; i < qp->div->n_row; ++i) {
1215                 array[i].div = qp->div;
1216                 array[i].row = i;
1217                 pos[i] = i;
1218                 at[i] = i;
1219         }
1220
1221         qsort(array, qp->div->n_row, sizeof(struct isl_div_sort_info),
1222                 div_sort_cmp);
1223
1224         for (i = 0; i < div_pos; ++i)
1225                 reordering[i] = i;
1226
1227         for (i = 0; i < qp->div->n_row; ++i) {
1228                 if (pos[array[i].row] == i)
1229                         continue;
1230                 qp->div = isl_mat_swap_rows(qp->div, i, pos[array[i].row]);
1231                 pos[at[i]] = pos[array[i].row];
1232                 at[pos[array[i].row]] = at[i];
1233                 at[i] = array[i].row;
1234                 pos[array[i].row] = i;
1235         }
1236
1237         skip = 0;
1238         for (i = 0; i < len - div_pos; ++i) {
1239                 if (i > 0 &&
1240                     isl_seq_eq(qp->div->row[i - skip - 1],
1241                                qp->div->row[i - skip], qp->div->n_col)) {
1242                         qp->div = isl_mat_drop_rows(qp->div, i - skip, 1);
1243                         isl_mat_col_add(qp->div, 2 + div_pos + i - skip - 1,
1244                                                  2 + div_pos + i - skip);
1245                         qp->div = isl_mat_drop_cols(qp->div,
1246                                                     2 + div_pos + i - skip, 1);
1247                         skip++;
1248                 }
1249                 reordering[div_pos + array[i].row] = div_pos + i - skip;
1250         }
1251
1252         qp->upoly = reorder(qp->upoly, reordering);
1253
1254         if (!qp->upoly || !qp->div)
1255                 goto error;
1256
1257         free(at);
1258         free(pos);
1259         free(array);
1260         free(reordering);
1261
1262         return qp;
1263 error:
1264         free(at);
1265         free(pos);
1266         free(array);
1267         free(reordering);
1268         isl_qpolynomial_free(qp);
1269         return NULL;
1270 }
1271
1272 static __isl_give struct isl_upoly *expand(__isl_take struct isl_upoly *up,
1273         int *exp, int first)
1274 {
1275         int i;
1276         struct isl_upoly_rec *rec;
1277
1278         if (isl_upoly_is_cst(up))
1279                 return up;
1280
1281         if (up->var < first)
1282                 return up;
1283
1284         if (exp[up->var - first] == up->var - first)
1285                 return up;
1286
1287         up = isl_upoly_cow(up);
1288         if (!up)
1289                 goto error;
1290
1291         up->var = exp[up->var - first] + first;
1292
1293         rec = isl_upoly_as_rec(up);
1294         if (!rec)
1295                 goto error;
1296
1297         for (i = 0; i < rec->n; ++i) {
1298                 rec->p[i] = expand(rec->p[i], exp, first);
1299                 if (!rec->p[i])
1300                         goto error;
1301         }
1302
1303         return up;
1304 error:
1305         isl_upoly_free(up);
1306         return NULL;
1307 }
1308
1309 static __isl_give isl_qpolynomial *with_merged_divs(
1310         __isl_give isl_qpolynomial *(*fn)(__isl_take isl_qpolynomial *qp1,
1311                                           __isl_take isl_qpolynomial *qp2),
1312         __isl_take isl_qpolynomial *qp1, __isl_take isl_qpolynomial *qp2)
1313 {
1314         int *exp1 = NULL;
1315         int *exp2 = NULL;
1316         isl_mat *div = NULL;
1317
1318         qp1 = isl_qpolynomial_cow(qp1);
1319         qp2 = isl_qpolynomial_cow(qp2);
1320
1321         if (!qp1 || !qp2)
1322                 goto error;
1323
1324         isl_assert(qp1->div->ctx, qp1->div->n_row >= qp2->div->n_row &&
1325                                 qp1->div->n_col >= qp2->div->n_col, goto error);
1326
1327         exp1 = isl_alloc_array(qp1->div->ctx, int, qp1->div->n_row);
1328         exp2 = isl_alloc_array(qp2->div->ctx, int, qp2->div->n_row);
1329         if (!exp1 || !exp2)
1330                 goto error;
1331
1332         div = isl_merge_divs(qp1->div, qp2->div, exp1, exp2);
1333         if (!div)
1334                 goto error;
1335
1336         isl_mat_free(qp1->div);
1337         qp1->div = isl_mat_copy(div);
1338         isl_mat_free(qp2->div);
1339         qp2->div = isl_mat_copy(div);
1340
1341         qp1->upoly = expand(qp1->upoly, exp1, div->n_col - div->n_row - 2);
1342         qp2->upoly = expand(qp2->upoly, exp2, div->n_col - div->n_row - 2);
1343
1344         if (!qp1->upoly || !qp2->upoly)
1345                 goto error;
1346
1347         isl_mat_free(div);
1348         free(exp1);
1349         free(exp2);
1350
1351         return fn(qp1, qp2);
1352 error:
1353         isl_mat_free(div);
1354         free(exp1);
1355         free(exp2);
1356         isl_qpolynomial_free(qp1);
1357         isl_qpolynomial_free(qp2);
1358         return NULL;
1359 }
1360
1361 __isl_give isl_qpolynomial *isl_qpolynomial_add(__isl_take isl_qpolynomial *qp1,
1362         __isl_take isl_qpolynomial *qp2)
1363 {
1364         qp1 = isl_qpolynomial_cow(qp1);
1365
1366         if (!qp1 || !qp2)
1367                 goto error;
1368
1369         if (qp1->div->n_row < qp2->div->n_row)
1370                 return isl_qpolynomial_add(qp2, qp1);
1371
1372         isl_assert(qp1->dim->ctx, isl_space_is_equal(qp1->dim, qp2->dim), goto error);
1373         if (!compatible_divs(qp1->div, qp2->div))
1374                 return with_merged_divs(isl_qpolynomial_add, qp1, qp2);
1375
1376         qp1->upoly = isl_upoly_sum(qp1->upoly, isl_upoly_copy(qp2->upoly));
1377         if (!qp1->upoly)
1378                 goto error;
1379
1380         isl_qpolynomial_free(qp2);
1381
1382         return qp1;
1383 error:
1384         isl_qpolynomial_free(qp1);
1385         isl_qpolynomial_free(qp2);
1386         return NULL;
1387 }
1388
1389 __isl_give isl_qpolynomial *isl_qpolynomial_add_on_domain(
1390         __isl_keep isl_set *dom,
1391         __isl_take isl_qpolynomial *qp1,
1392         __isl_take isl_qpolynomial *qp2)
1393 {
1394         qp1 = isl_qpolynomial_add(qp1, qp2);
1395         qp1 = isl_qpolynomial_gist(qp1, isl_set_copy(dom));
1396         return qp1;
1397 }
1398
1399 __isl_give isl_qpolynomial *isl_qpolynomial_sub(__isl_take isl_qpolynomial *qp1,
1400         __isl_take isl_qpolynomial *qp2)
1401 {
1402         return isl_qpolynomial_add(qp1, isl_qpolynomial_neg(qp2));
1403 }
1404
1405 __isl_give isl_qpolynomial *isl_qpolynomial_add_isl_int(
1406         __isl_take isl_qpolynomial *qp, isl_int v)
1407 {
1408         if (isl_int_is_zero(v))
1409                 return qp;
1410
1411         qp = isl_qpolynomial_cow(qp);
1412         if (!qp)
1413                 return NULL;
1414
1415         qp->upoly = isl_upoly_add_isl_int(qp->upoly, v);
1416         if (!qp->upoly)
1417                 goto error;
1418
1419         return qp;
1420 error:
1421         isl_qpolynomial_free(qp);
1422         return NULL;
1423
1424 }
1425
1426 __isl_give isl_qpolynomial *isl_qpolynomial_neg(__isl_take isl_qpolynomial *qp)
1427 {
1428         if (!qp)
1429                 return NULL;
1430
1431         return isl_qpolynomial_mul_isl_int(qp, qp->dim->ctx->negone);
1432 }
1433
1434 __isl_give isl_qpolynomial *isl_qpolynomial_mul_isl_int(
1435         __isl_take isl_qpolynomial *qp, isl_int v)
1436 {
1437         if (isl_int_is_one(v))
1438                 return qp;
1439
1440         if (qp && isl_int_is_zero(v)) {
1441                 isl_qpolynomial *zero;
1442                 zero = isl_qpolynomial_zero_on_domain(isl_space_copy(qp->dim));
1443                 isl_qpolynomial_free(qp);
1444                 return zero;
1445         }
1446         
1447         qp = isl_qpolynomial_cow(qp);
1448         if (!qp)
1449                 return NULL;
1450
1451         qp->upoly = isl_upoly_mul_isl_int(qp->upoly, v);
1452         if (!qp->upoly)
1453                 goto error;
1454
1455         return qp;
1456 error:
1457         isl_qpolynomial_free(qp);
1458         return NULL;
1459 }
1460
1461 __isl_give isl_qpolynomial *isl_qpolynomial_scale(
1462         __isl_take isl_qpolynomial *qp, isl_int v)
1463 {
1464         return isl_qpolynomial_mul_isl_int(qp, v);
1465 }
1466
1467 __isl_give isl_qpolynomial *isl_qpolynomial_mul(__isl_take isl_qpolynomial *qp1,
1468         __isl_take isl_qpolynomial *qp2)
1469 {
1470         qp1 = isl_qpolynomial_cow(qp1);
1471
1472         if (!qp1 || !qp2)
1473                 goto error;
1474
1475         if (qp1->div->n_row < qp2->div->n_row)
1476                 return isl_qpolynomial_mul(qp2, qp1);
1477
1478         isl_assert(qp1->dim->ctx, isl_space_is_equal(qp1->dim, qp2->dim), goto error);
1479         if (!compatible_divs(qp1->div, qp2->div))
1480                 return with_merged_divs(isl_qpolynomial_mul, qp1, qp2);
1481
1482         qp1->upoly = isl_upoly_mul(qp1->upoly, isl_upoly_copy(qp2->upoly));
1483         if (!qp1->upoly)
1484                 goto error;
1485
1486         isl_qpolynomial_free(qp2);
1487
1488         return qp1;
1489 error:
1490         isl_qpolynomial_free(qp1);
1491         isl_qpolynomial_free(qp2);
1492         return NULL;
1493 }
1494
1495 __isl_give isl_qpolynomial *isl_qpolynomial_pow(__isl_take isl_qpolynomial *qp,
1496         unsigned power)
1497 {
1498         qp = isl_qpolynomial_cow(qp);
1499
1500         if (!qp)
1501                 return NULL;
1502
1503         qp->upoly = isl_upoly_pow(qp->upoly, power);
1504         if (!qp->upoly)
1505                 goto error;
1506
1507         return qp;
1508 error:
1509         isl_qpolynomial_free(qp);
1510         return NULL;
1511 }
1512
1513 __isl_give isl_pw_qpolynomial *isl_pw_qpolynomial_pow(
1514         __isl_take isl_pw_qpolynomial *pwqp, unsigned power)
1515 {
1516         int i;
1517
1518         if (power == 1)
1519                 return pwqp;
1520
1521         pwqp = isl_pw_qpolynomial_cow(pwqp);
1522         if (!pwqp)
1523                 return NULL;
1524
1525         for (i = 0; i < pwqp->n; ++i) {
1526                 pwqp->p[i].qp = isl_qpolynomial_pow(pwqp->p[i].qp, power);
1527                 if (!pwqp->p[i].qp)
1528                         return isl_pw_qpolynomial_free(pwqp);
1529         }
1530
1531         return pwqp;
1532 }
1533
1534 __isl_give isl_qpolynomial *isl_qpolynomial_zero_on_domain(
1535         __isl_take isl_space *dim)
1536 {
1537         if (!dim)
1538                 return NULL;
1539         return isl_qpolynomial_alloc(dim, 0, isl_upoly_zero(dim->ctx));
1540 }
1541
1542 __isl_give isl_qpolynomial *isl_qpolynomial_one_on_domain(
1543         __isl_take isl_space *dim)
1544 {
1545         if (!dim)
1546                 return NULL;
1547         return isl_qpolynomial_alloc(dim, 0, isl_upoly_one(dim->ctx));
1548 }
1549
1550 __isl_give isl_qpolynomial *isl_qpolynomial_infty_on_domain(
1551         __isl_take isl_space *dim)
1552 {
1553         if (!dim)
1554                 return NULL;
1555         return isl_qpolynomial_alloc(dim, 0, isl_upoly_infty(dim->ctx));
1556 }
1557
1558 __isl_give isl_qpolynomial *isl_qpolynomial_neginfty_on_domain(
1559         __isl_take isl_space *dim)
1560 {
1561         if (!dim)
1562                 return NULL;
1563         return isl_qpolynomial_alloc(dim, 0, isl_upoly_neginfty(dim->ctx));
1564 }
1565
1566 __isl_give isl_qpolynomial *isl_qpolynomial_nan_on_domain(
1567         __isl_take isl_space *dim)
1568 {
1569         if (!dim)
1570                 return NULL;
1571         return isl_qpolynomial_alloc(dim, 0, isl_upoly_nan(dim->ctx));
1572 }
1573
1574 __isl_give isl_qpolynomial *isl_qpolynomial_cst_on_domain(
1575         __isl_take isl_space *dim,
1576         isl_int v)
1577 {
1578         struct isl_qpolynomial *qp;
1579         struct isl_upoly_cst *cst;
1580
1581         if (!dim)
1582                 return NULL;
1583
1584         qp = isl_qpolynomial_alloc(dim, 0, isl_upoly_zero(dim->ctx));
1585         if (!qp)
1586                 return NULL;
1587
1588         cst = isl_upoly_as_cst(qp->upoly);
1589         isl_int_set(cst->n, v);
1590
1591         return qp;
1592 }
1593
1594 int isl_qpolynomial_is_cst(__isl_keep isl_qpolynomial *qp,
1595         isl_int *n, isl_int *d)
1596 {
1597         struct isl_upoly_cst *cst;
1598
1599         if (!qp)
1600                 return -1;
1601
1602         if (!isl_upoly_is_cst(qp->upoly))
1603                 return 0;
1604
1605         cst = isl_upoly_as_cst(qp->upoly);
1606         if (!cst)
1607                 return -1;
1608
1609         if (n)
1610                 isl_int_set(*n, cst->n);
1611         if (d)
1612                 isl_int_set(*d, cst->d);
1613
1614         return 1;
1615 }
1616
1617 int isl_upoly_is_affine(__isl_keep struct isl_upoly *up)
1618 {
1619         int is_cst;
1620         struct isl_upoly_rec *rec;
1621
1622         if (!up)
1623                 return -1;
1624
1625         if (up->var < 0)
1626                 return 1;
1627
1628         rec = isl_upoly_as_rec(up);
1629         if (!rec)
1630                 return -1;
1631
1632         if (rec->n > 2)
1633                 return 0;
1634
1635         isl_assert(up->ctx, rec->n > 1, return -1);
1636
1637         is_cst = isl_upoly_is_cst(rec->p[1]);
1638         if (is_cst < 0)
1639                 return -1;
1640         if (!is_cst)
1641                 return 0;
1642
1643         return isl_upoly_is_affine(rec->p[0]);
1644 }
1645
1646 int isl_qpolynomial_is_affine(__isl_keep isl_qpolynomial *qp)
1647 {
1648         if (!qp)
1649                 return -1;
1650
1651         if (qp->div->n_row > 0)
1652                 return 0;
1653
1654         return isl_upoly_is_affine(qp->upoly);
1655 }
1656
1657 static void update_coeff(__isl_keep isl_vec *aff,
1658         __isl_keep struct isl_upoly_cst *cst, int pos)
1659 {
1660         isl_int gcd;
1661         isl_int f;
1662
1663         if (isl_int_is_zero(cst->n))
1664                 return;
1665
1666         isl_int_init(gcd);
1667         isl_int_init(f);
1668         isl_int_gcd(gcd, cst->d, aff->el[0]);
1669         isl_int_divexact(f, cst->d, gcd);
1670         isl_int_divexact(gcd, aff->el[0], gcd);
1671         isl_seq_scale(aff->el, aff->el, f, aff->size);
1672         isl_int_mul(aff->el[1 + pos], gcd, cst->n);
1673         isl_int_clear(gcd);
1674         isl_int_clear(f);
1675 }
1676
1677 int isl_upoly_update_affine(__isl_keep struct isl_upoly *up,
1678         __isl_keep isl_vec *aff)
1679 {
1680         struct isl_upoly_cst *cst;
1681         struct isl_upoly_rec *rec;
1682
1683         if (!up || !aff)
1684                 return -1;
1685
1686         if (up->var < 0) {
1687                 struct isl_upoly_cst *cst;
1688
1689                 cst = isl_upoly_as_cst(up);
1690                 if (!cst)
1691                         return -1;
1692                 update_coeff(aff, cst, 0);
1693                 return 0;
1694         }
1695
1696         rec = isl_upoly_as_rec(up);
1697         if (!rec)
1698                 return -1;
1699         isl_assert(up->ctx, rec->n == 2, return -1);
1700
1701         cst = isl_upoly_as_cst(rec->p[1]);
1702         if (!cst)
1703                 return -1;
1704         update_coeff(aff, cst, 1 + up->var);
1705
1706         return isl_upoly_update_affine(rec->p[0], aff);
1707 }
1708
1709 __isl_give isl_vec *isl_qpolynomial_extract_affine(
1710         __isl_keep isl_qpolynomial *qp)
1711 {
1712         isl_vec *aff;
1713         unsigned d;
1714
1715         if (!qp)
1716                 return NULL;
1717
1718         d = isl_space_dim(qp->dim, isl_dim_all);
1719         aff = isl_vec_alloc(qp->div->ctx, 2 + d + qp->div->n_row);
1720         if (!aff)
1721                 return NULL;
1722
1723         isl_seq_clr(aff->el + 1, 1 + d + qp->div->n_row);
1724         isl_int_set_si(aff->el[0], 1);
1725
1726         if (isl_upoly_update_affine(qp->upoly, aff) < 0)
1727                 goto error;
1728
1729         return aff;
1730 error:
1731         isl_vec_free(aff);
1732         return NULL;
1733 }
1734
1735 int isl_qpolynomial_plain_is_equal(__isl_keep isl_qpolynomial *qp1,
1736         __isl_keep isl_qpolynomial *qp2)
1737 {
1738         int equal;
1739
1740         if (!qp1 || !qp2)
1741                 return -1;
1742
1743         equal = isl_space_is_equal(qp1->dim, qp2->dim);
1744         if (equal < 0 || !equal)
1745                 return equal;
1746
1747         equal = isl_mat_is_equal(qp1->div, qp2->div);
1748         if (equal < 0 || !equal)
1749                 return equal;
1750
1751         return isl_upoly_is_equal(qp1->upoly, qp2->upoly);
1752 }
1753
1754 static void upoly_update_den(__isl_keep struct isl_upoly *up, isl_int *d)
1755 {
1756         int i;
1757         struct isl_upoly_rec *rec;
1758
1759         if (isl_upoly_is_cst(up)) {
1760                 struct isl_upoly_cst *cst;
1761                 cst = isl_upoly_as_cst(up);
1762                 if (!cst)
1763                         return;
1764                 isl_int_lcm(*d, *d, cst->d);
1765                 return;
1766         }
1767
1768         rec = isl_upoly_as_rec(up);
1769         if (!rec)
1770                 return;
1771
1772         for (i = 0; i < rec->n; ++i)
1773                 upoly_update_den(rec->p[i], d);
1774 }
1775
1776 void isl_qpolynomial_get_den(__isl_keep isl_qpolynomial *qp, isl_int *d)
1777 {
1778         isl_int_set_si(*d, 1);
1779         if (!qp)
1780                 return;
1781         upoly_update_den(qp->upoly, d);
1782 }
1783
1784 __isl_give isl_qpolynomial *isl_qpolynomial_var_pow_on_domain(
1785         __isl_take isl_space *dim, int pos, int power)
1786 {
1787         struct isl_ctx *ctx;
1788
1789         if (!dim)
1790                 return NULL;
1791
1792         ctx = dim->ctx;
1793
1794         return isl_qpolynomial_alloc(dim, 0, isl_upoly_var_pow(ctx, pos, power));
1795 }
1796
1797 __isl_give isl_qpolynomial *isl_qpolynomial_var_on_domain(__isl_take isl_space *dim,
1798         enum isl_dim_type type, unsigned pos)
1799 {
1800         if (!dim)
1801                 return NULL;
1802
1803         isl_assert(dim->ctx, isl_space_dim(dim, isl_dim_in) == 0, goto error);
1804         isl_assert(dim->ctx, pos < isl_space_dim(dim, type), goto error);
1805
1806         if (type == isl_dim_set)
1807                 pos += isl_space_dim(dim, isl_dim_param);
1808
1809         return isl_qpolynomial_var_pow_on_domain(dim, pos, 1);
1810 error:
1811         isl_space_free(dim);
1812         return NULL;
1813 }
1814
1815 __isl_give struct isl_upoly *isl_upoly_subs(__isl_take struct isl_upoly *up,
1816         unsigned first, unsigned n, __isl_keep struct isl_upoly **subs)
1817 {
1818         int i;
1819         struct isl_upoly_rec *rec;
1820         struct isl_upoly *base, *res;
1821
1822         if (!up)
1823                 return NULL;
1824
1825         if (isl_upoly_is_cst(up))
1826                 return up;
1827
1828         if (up->var < first)
1829                 return up;
1830
1831         rec = isl_upoly_as_rec(up);
1832         if (!rec)
1833                 goto error;
1834
1835         isl_assert(up->ctx, rec->n >= 1, goto error);
1836
1837         if (up->var >= first + n)
1838                 base = isl_upoly_var_pow(up->ctx, up->var, 1);
1839         else
1840                 base = isl_upoly_copy(subs[up->var - first]);
1841
1842         res = isl_upoly_subs(isl_upoly_copy(rec->p[rec->n - 1]), first, n, subs);
1843         for (i = rec->n - 2; i >= 0; --i) {
1844                 struct isl_upoly *t;
1845                 t = isl_upoly_subs(isl_upoly_copy(rec->p[i]), first, n, subs);
1846                 res = isl_upoly_mul(res, isl_upoly_copy(base));
1847                 res = isl_upoly_sum(res, t);
1848         }
1849
1850         isl_upoly_free(base);
1851         isl_upoly_free(up);
1852                                 
1853         return res;
1854 error:
1855         isl_upoly_free(up);
1856         return NULL;
1857 }       
1858
1859 __isl_give struct isl_upoly *isl_upoly_from_affine(isl_ctx *ctx, isl_int *f,
1860         isl_int denom, unsigned len)
1861 {
1862         int i;
1863         struct isl_upoly *up;
1864
1865         isl_assert(ctx, len >= 1, return NULL);
1866
1867         up = isl_upoly_rat_cst(ctx, f[0], denom);
1868         for (i = 0; i < len - 1; ++i) {
1869                 struct isl_upoly *t;
1870                 struct isl_upoly *c;
1871
1872                 if (isl_int_is_zero(f[1 + i]))
1873                         continue;
1874
1875                 c = isl_upoly_rat_cst(ctx, f[1 + i], denom);
1876                 t = isl_upoly_var_pow(ctx, i, 1);
1877                 t = isl_upoly_mul(c, t);
1878                 up = isl_upoly_sum(up, t);
1879         }
1880
1881         return up;
1882 }
1883
1884 /* Remove common factor of non-constant terms and denominator.
1885  */
1886 static void normalize_div(__isl_keep isl_qpolynomial *qp, int div)
1887 {
1888         isl_ctx *ctx = qp->div->ctx;
1889         unsigned total = qp->div->n_col - 2;
1890
1891         isl_seq_gcd(qp->div->row[div] + 2, total, &ctx->normalize_gcd);
1892         isl_int_gcd(ctx->normalize_gcd,
1893                     ctx->normalize_gcd, qp->div->row[div][0]);
1894         if (isl_int_is_one(ctx->normalize_gcd))
1895                 return;
1896
1897         isl_seq_scale_down(qp->div->row[div] + 2, qp->div->row[div] + 2,
1898                             ctx->normalize_gcd, total);
1899         isl_int_divexact(qp->div->row[div][0], qp->div->row[div][0],
1900                             ctx->normalize_gcd);
1901         isl_int_fdiv_q(qp->div->row[div][1], qp->div->row[div][1],
1902                             ctx->normalize_gcd);
1903 }
1904
1905 /* Replace the integer division identified by "div" by the polynomial "s".
1906  * The integer division is assumed not to appear in the definition
1907  * of any other integer divisions.
1908  */
1909 static __isl_give isl_qpolynomial *substitute_div(
1910         __isl_take isl_qpolynomial *qp,
1911         int div, __isl_take struct isl_upoly *s)
1912 {
1913         int i;
1914         int total;
1915         int *reordering;
1916
1917         if (!qp || !s)
1918                 goto error;
1919
1920         qp = isl_qpolynomial_cow(qp);
1921         if (!qp)
1922                 goto error;
1923
1924         total = isl_space_dim(qp->dim, isl_dim_all);
1925         qp->upoly = isl_upoly_subs(qp->upoly, total + div, 1, &s);
1926         if (!qp->upoly)
1927                 goto error;
1928
1929         reordering = isl_alloc_array(qp->dim->ctx, int, total + qp->div->n_row);
1930         if (!reordering)
1931                 goto error;
1932         for (i = 0; i < total + div; ++i)
1933                 reordering[i] = i;
1934         for (i = total + div + 1; i < total + qp->div->n_row; ++i)
1935                 reordering[i] = i - 1;
1936         qp->div = isl_mat_drop_rows(qp->div, div, 1);
1937         qp->div = isl_mat_drop_cols(qp->div, 2 + total + div, 1);
1938         qp->upoly = reorder(qp->upoly, reordering);
1939         free(reordering);
1940
1941         if (!qp->upoly || !qp->div)
1942                 goto error;
1943
1944         isl_upoly_free(s);
1945         return qp;
1946 error:
1947         isl_qpolynomial_free(qp);
1948         isl_upoly_free(s);
1949         return NULL;
1950 }
1951
1952 /* Replace all integer divisions [e/d] that turn out to not actually be integer
1953  * divisions because d is equal to 1 by their definition, i.e., e.
1954  */
1955 static __isl_give isl_qpolynomial *substitute_non_divs(
1956         __isl_take isl_qpolynomial *qp)
1957 {
1958         int i, j;
1959         int total;
1960         struct isl_upoly *s;
1961
1962         if (!qp)
1963                 return NULL;
1964
1965         total = isl_space_dim(qp->dim, isl_dim_all);
1966         for (i = 0; qp && i < qp->div->n_row; ++i) {
1967                 if (!isl_int_is_one(qp->div->row[i][0]))
1968                         continue;
1969                 for (j = i + 1; j < qp->div->n_row; ++j) {
1970                         if (isl_int_is_zero(qp->div->row[j][2 + total + i]))
1971                                 continue;
1972                         isl_seq_combine(qp->div->row[j] + 1,
1973                                 qp->div->ctx->one, qp->div->row[j] + 1,
1974                                 qp->div->row[j][2 + total + i],
1975                                 qp->div->row[i] + 1, 1 + total + i);
1976                         isl_int_set_si(qp->div->row[j][2 + total + i], 0);
1977                         normalize_div(qp, j);
1978                 }
1979                 s = isl_upoly_from_affine(qp->dim->ctx, qp->div->row[i] + 1,
1980                                         qp->div->row[i][0], qp->div->n_col - 1);
1981                 qp = substitute_div(qp, i, s);
1982                 --i;
1983         }
1984
1985         return qp;
1986 }
1987
1988 /* Reduce the coefficients of div "div" to lie in the interval [0, d-1],
1989  * with d the denominator.  When replacing the coefficient e of x by
1990  * d * frac(e/d) = e - d * floor(e/d), we are subtracting d * floor(e/d) * x
1991  * inside the division, so we need to add floor(e/d) * x outside.
1992  * That is, we replace q by q' + floor(e/d) * x and we therefore need
1993  * to adjust the coefficient of x in each later div that depends on the
1994  * current div "div" and also in the affine expression "aff"
1995  * (if it too depends on "div").
1996  */
1997 static void reduce_div(__isl_keep isl_qpolynomial *qp, int div,
1998         __isl_keep isl_vec *aff)
1999 {
2000         int i, j;
2001         isl_int v;
2002         unsigned total = qp->div->n_col - qp->div->n_row - 2;
2003
2004         isl_int_init(v);
2005         for (i = 0; i < 1 + total + div; ++i) {
2006                 if (isl_int_is_nonneg(qp->div->row[div][1 + i]) &&
2007                     isl_int_lt(qp->div->row[div][1 + i], qp->div->row[div][0]))
2008                         continue;
2009                 isl_int_fdiv_q(v, qp->div->row[div][1 + i], qp->div->row[div][0]);
2010                 isl_int_fdiv_r(qp->div->row[div][1 + i],
2011                                 qp->div->row[div][1 + i], qp->div->row[div][0]);
2012                 if (!isl_int_is_zero(aff->el[1 + total + div]))
2013                         isl_int_addmul(aff->el[i], v, aff->el[1 + total + div]);
2014                 for (j = div + 1; j < qp->div->n_row; ++j) {
2015                         if (isl_int_is_zero(qp->div->row[j][2 + total + div]))
2016                                 continue;
2017                         isl_int_addmul(qp->div->row[j][1 + i],
2018                                         v, qp->div->row[j][2 + total + div]);
2019                 }
2020         }
2021         isl_int_clear(v);
2022 }
2023
2024 /* Check if the last non-zero coefficient is bigger that half of the
2025  * denominator.  If so, we will invert the div to further reduce the number
2026  * of distinct divs that may appear.
2027  * If the last non-zero coefficient is exactly half the denominator,
2028  * then we continue looking for earlier coefficients that are bigger
2029  * than half the denominator.
2030  */
2031 static int needs_invert(__isl_keep isl_mat *div, int row)
2032 {
2033         int i;
2034         int cmp;
2035
2036         for (i = div->n_col - 1; i >= 1; --i) {
2037                 if (isl_int_is_zero(div->row[row][i]))
2038                         continue;
2039                 isl_int_mul_ui(div->row[row][i], div->row[row][i], 2);
2040                 cmp = isl_int_cmp(div->row[row][i], div->row[row][0]);
2041                 isl_int_divexact_ui(div->row[row][i], div->row[row][i], 2);
2042                 if (cmp)
2043                         return cmp > 0;
2044                 if (i == 1)
2045                         return 1;
2046         }
2047
2048         return 0;
2049 }
2050
2051 /* Replace div "div" q = [e/d] by -[(-e+(d-1))/d].
2052  * We only invert the coefficients of e (and the coefficient of q in
2053  * later divs and in "aff").  After calling this function, the
2054  * coefficients of e should be reduced again.
2055  */
2056 static void invert_div(__isl_keep isl_qpolynomial *qp, int div,
2057         __isl_keep isl_vec *aff)
2058 {
2059         unsigned total = qp->div->n_col - qp->div->n_row - 2;
2060
2061         isl_seq_neg(qp->div->row[div] + 1,
2062                     qp->div->row[div] + 1, qp->div->n_col - 1);
2063         isl_int_sub_ui(qp->div->row[div][1], qp->div->row[div][1], 1);
2064         isl_int_add(qp->div->row[div][1],
2065                     qp->div->row[div][1], qp->div->row[div][0]);
2066         if (!isl_int_is_zero(aff->el[1 + total + div]))
2067                 isl_int_neg(aff->el[1 + total + div], aff->el[1 + total + div]);
2068         isl_mat_col_mul(qp->div, 2 + total + div,
2069                         qp->div->ctx->negone, 2 + total + div);
2070 }
2071
2072 /* Assuming "qp" is a monomial, reduce all its divs to have coefficients
2073  * in the interval [0, d-1], with d the denominator and such that the
2074  * last non-zero coefficient that is not equal to d/2 is smaller than d/2.
2075  *
2076  * After the reduction, some divs may have become redundant or identical,
2077  * so we call substitute_non_divs and sort_divs.  If these functions
2078  * eliminate divs or merge two or more divs into one, the coefficients
2079  * of the enclosing divs may have to be reduced again, so we call
2080  * ourselves recursively if the number of divs decreases.
2081  */
2082 static __isl_give isl_qpolynomial *reduce_divs(__isl_take isl_qpolynomial *qp)
2083 {
2084         int i;
2085         isl_vec *aff = NULL;
2086         struct isl_upoly *s;
2087         unsigned n_div;
2088
2089         if (!qp)
2090                 return NULL;
2091
2092         aff = isl_vec_alloc(qp->div->ctx, qp->div->n_col - 1);
2093         aff = isl_vec_clr(aff);
2094         if (!aff)
2095                 goto error;
2096
2097         isl_int_set_si(aff->el[1 + qp->upoly->var], 1);
2098
2099         for (i = 0; i < qp->div->n_row; ++i) {
2100                 normalize_div(qp, i);
2101                 reduce_div(qp, i, aff);
2102                 if (needs_invert(qp->div, i)) {
2103                         invert_div(qp, i, aff);
2104                         reduce_div(qp, i, aff);
2105                 }
2106         }
2107
2108         s = isl_upoly_from_affine(qp->div->ctx, aff->el,
2109                                   qp->div->ctx->one, aff->size);
2110         qp->upoly = isl_upoly_subs(qp->upoly, qp->upoly->var, 1, &s);
2111         isl_upoly_free(s);
2112         if (!qp->upoly)
2113                 goto error;
2114
2115         isl_vec_free(aff);
2116
2117         n_div = qp->div->n_row;
2118         qp = substitute_non_divs(qp);
2119         qp = sort_divs(qp);
2120         if (qp && qp->div->n_row < n_div)
2121                 return reduce_divs(qp);
2122
2123         return qp;
2124 error:
2125         isl_qpolynomial_free(qp);
2126         isl_vec_free(aff);
2127         return NULL;
2128 }
2129
2130 __isl_give isl_qpolynomial *isl_qpolynomial_rat_cst_on_domain(
2131         __isl_take isl_space *dim, const isl_int n, const isl_int d)
2132 {
2133         struct isl_qpolynomial *qp;
2134         struct isl_upoly_cst *cst;
2135
2136         if (!dim)
2137                 return NULL;
2138
2139         qp = isl_qpolynomial_alloc(dim, 0, isl_upoly_zero(dim->ctx));
2140         if (!qp)
2141                 return NULL;
2142
2143         cst = isl_upoly_as_cst(qp->upoly);
2144         isl_int_set(cst->n, n);
2145         isl_int_set(cst->d, d);
2146
2147         return qp;
2148 }
2149
2150 static int up_set_active(__isl_keep struct isl_upoly *up, int *active, int d)
2151 {
2152         struct isl_upoly_rec *rec;
2153         int i;
2154
2155         if (!up)
2156                 return -1;
2157
2158         if (isl_upoly_is_cst(up))
2159                 return 0;
2160
2161         if (up->var < d)
2162                 active[up->var] = 1;
2163
2164         rec = isl_upoly_as_rec(up);
2165         for (i = 0; i < rec->n; ++i)
2166                 if (up_set_active(rec->p[i], active, d) < 0)
2167                         return -1;
2168
2169         return 0;
2170 }
2171
2172 static int set_active(__isl_keep isl_qpolynomial *qp, int *active)
2173 {
2174         int i, j;
2175         int d = isl_space_dim(qp->dim, isl_dim_all);
2176
2177         if (!qp || !active)
2178                 return -1;
2179
2180         for (i = 0; i < d; ++i)
2181                 for (j = 0; j < qp->div->n_row; ++j) {
2182                         if (isl_int_is_zero(qp->div->row[j][2 + i]))
2183                                 continue;
2184                         active[i] = 1;
2185                         break;
2186                 }
2187
2188         return up_set_active(qp->upoly, active, d);
2189 }
2190
2191 int isl_qpolynomial_involves_dims(__isl_keep isl_qpolynomial *qp,
2192         enum isl_dim_type type, unsigned first, unsigned n)
2193 {
2194         int i;
2195         int *active = NULL;
2196         int involves = 0;
2197
2198         if (!qp)
2199                 return -1;
2200         if (n == 0)
2201                 return 0;
2202
2203         isl_assert(qp->dim->ctx,
2204                     first + n <= isl_qpolynomial_dim(qp, type), return -1);
2205         isl_assert(qp->dim->ctx, type == isl_dim_param ||
2206                                  type == isl_dim_in, return -1);
2207
2208         active = isl_calloc_array(qp->dim->ctx, int,
2209                                         isl_space_dim(qp->dim, isl_dim_all));
2210         if (set_active(qp, active) < 0)
2211                 goto error;
2212
2213         if (type == isl_dim_in)
2214                 first += isl_space_dim(qp->dim, isl_dim_param);
2215         for (i = 0; i < n; ++i)
2216                 if (active[first + i]) {
2217                         involves = 1;
2218                         break;
2219                 }
2220
2221         free(active);
2222
2223         return involves;
2224 error:
2225         free(active);
2226         return -1;
2227 }
2228
2229 /* Remove divs that do not appear in the quasi-polynomial, nor in any
2230  * of the divs that do appear in the quasi-polynomial.
2231  */
2232 static __isl_give isl_qpolynomial *remove_redundant_divs(
2233         __isl_take isl_qpolynomial *qp)
2234 {
2235         int i, j;
2236         int d;
2237         int len;
2238         int skip;
2239         int *active = NULL;
2240         int *reordering = NULL;
2241         int redundant = 0;
2242         int n_div;
2243         isl_ctx *ctx;
2244
2245         if (!qp)
2246                 return NULL;
2247         if (qp->div->n_row == 0)
2248                 return qp;
2249
2250         d = isl_space_dim(qp->dim, isl_dim_all);
2251         len = qp->div->n_col - 2;
2252         ctx = isl_qpolynomial_get_ctx(qp);
2253         active = isl_calloc_array(ctx, int, len);
2254         if (!active)
2255                 goto error;
2256
2257         if (up_set_active(qp->upoly, active, len) < 0)
2258                 goto error;
2259
2260         for (i = qp->div->n_row - 1; i >= 0; --i) {
2261                 if (!active[d + i]) {
2262                         redundant = 1;
2263                         continue;
2264                 }
2265                 for (j = 0; j < i; ++j) {
2266                         if (isl_int_is_zero(qp->div->row[i][2 + d + j]))
2267                                 continue;
2268                         active[d + j] = 1;
2269                         break;
2270                 }
2271         }
2272
2273         if (!redundant) {
2274                 free(active);
2275                 return qp;
2276         }
2277
2278         reordering = isl_alloc_array(qp->div->ctx, int, len);
2279         if (!reordering)
2280                 goto error;
2281
2282         for (i = 0; i < d; ++i)
2283                 reordering[i] = i;
2284
2285         skip = 0;
2286         n_div = qp->div->n_row;
2287         for (i = 0; i < n_div; ++i) {
2288                 if (!active[d + i]) {
2289                         qp->div = isl_mat_drop_rows(qp->div, i - skip, 1);
2290                         qp->div = isl_mat_drop_cols(qp->div,
2291                                                     2 + d + i - skip, 1);
2292                         skip++;
2293                 }
2294                 reordering[d + i] = d + i - skip;
2295         }
2296
2297         qp->upoly = reorder(qp->upoly, reordering);
2298
2299         if (!qp->upoly || !qp->div)
2300                 goto error;
2301
2302         free(active);
2303         free(reordering);
2304
2305         return qp;
2306 error:
2307         free(active);
2308         free(reordering);
2309         isl_qpolynomial_free(qp);
2310         return NULL;
2311 }
2312
2313 __isl_give struct isl_upoly *isl_upoly_drop(__isl_take struct isl_upoly *up,
2314         unsigned first, unsigned n)
2315 {
2316         int i;
2317         struct isl_upoly_rec *rec;
2318
2319         if (!up)
2320                 return NULL;
2321         if (n == 0 || up->var < 0 || up->var < first)
2322                 return up;
2323         if (up->var < first + n) {
2324                 up = replace_by_constant_term(up);
2325                 return isl_upoly_drop(up, first, n);
2326         }
2327         up = isl_upoly_cow(up);
2328         if (!up)
2329                 return NULL;
2330         up->var -= n;
2331         rec = isl_upoly_as_rec(up);
2332         if (!rec)
2333                 goto error;
2334
2335         for (i = 0; i < rec->n; ++i) {
2336                 rec->p[i] = isl_upoly_drop(rec->p[i], first, n);
2337                 if (!rec->p[i])
2338                         goto error;
2339         }
2340
2341         return up;
2342 error:
2343         isl_upoly_free(up);
2344         return NULL;
2345 }
2346
2347 __isl_give isl_qpolynomial *isl_qpolynomial_set_dim_name(
2348         __isl_take isl_qpolynomial *qp,
2349         enum isl_dim_type type, unsigned pos, const char *s)
2350 {
2351         qp = isl_qpolynomial_cow(qp);
2352         if (!qp)
2353                 return NULL;
2354         qp->dim = isl_space_set_dim_name(qp->dim, type, pos, s);
2355         if (!qp->dim)
2356                 goto error;
2357         return qp;
2358 error:
2359         isl_qpolynomial_free(qp);
2360         return NULL;
2361 }
2362
2363 __isl_give isl_qpolynomial *isl_qpolynomial_drop_dims(
2364         __isl_take isl_qpolynomial *qp,
2365         enum isl_dim_type type, unsigned first, unsigned n)
2366 {
2367         if (!qp)
2368                 return NULL;
2369         if (type == isl_dim_out)
2370                 isl_die(qp->dim->ctx, isl_error_invalid,
2371                         "cannot drop output/set dimension",
2372                         goto error);
2373         if (type == isl_dim_in)
2374                 type = isl_dim_set;
2375         if (n == 0 && !isl_space_is_named_or_nested(qp->dim, type))
2376                 return qp;
2377
2378         qp = isl_qpolynomial_cow(qp);
2379         if (!qp)
2380                 return NULL;
2381
2382         isl_assert(qp->dim->ctx, first + n <= isl_space_dim(qp->dim, type),
2383                         goto error);
2384         isl_assert(qp->dim->ctx, type == isl_dim_param ||
2385                                  type == isl_dim_set, goto error);
2386
2387         qp->dim = isl_space_drop_dims(qp->dim, type, first, n);
2388         if (!qp->dim)
2389                 goto error;
2390
2391         if (type == isl_dim_set)
2392                 first += isl_space_dim(qp->dim, isl_dim_param);
2393
2394         qp->div = isl_mat_drop_cols(qp->div, 2 + first, n);
2395         if (!qp->div)
2396                 goto error;
2397
2398         qp->upoly = isl_upoly_drop(qp->upoly, first, n);
2399         if (!qp->upoly)
2400                 goto error;
2401
2402         return qp;
2403 error:
2404         isl_qpolynomial_free(qp);
2405         return NULL;
2406 }
2407
2408 /* Project the domain of the quasi-polynomial onto its parameter space.
2409  * The quasi-polynomial may not involve any of the domain dimensions.
2410  */
2411 __isl_give isl_qpolynomial *isl_qpolynomial_project_domain_on_params(
2412         __isl_take isl_qpolynomial *qp)
2413 {
2414         isl_space *space;
2415         unsigned n;
2416         int involves;
2417
2418         n = isl_qpolynomial_dim(qp, isl_dim_in);
2419         involves = isl_qpolynomial_involves_dims(qp, isl_dim_in, 0, n);
2420         if (involves < 0)
2421                 return isl_qpolynomial_free(qp);
2422         if (involves)
2423                 isl_die(isl_qpolynomial_get_ctx(qp), isl_error_invalid,
2424                         "polynomial involves some of the domain dimensions",
2425                         return isl_qpolynomial_free(qp));
2426         qp = isl_qpolynomial_drop_dims(qp, isl_dim_in, 0, n);
2427         space = isl_qpolynomial_get_domain_space(qp);
2428         space = isl_space_params(space);
2429         qp = isl_qpolynomial_reset_domain_space(qp, space);
2430         return qp;
2431 }
2432
2433 static __isl_give isl_qpolynomial *isl_qpolynomial_substitute_equalities_lifted(
2434         __isl_take isl_qpolynomial *qp, __isl_take isl_basic_set *eq)
2435 {
2436         int i, j, k;
2437         isl_int denom;
2438         unsigned total;
2439         unsigned n_div;
2440         struct isl_upoly *up;
2441
2442         if (!eq)
2443                 goto error;
2444         if (eq->n_eq == 0) {
2445                 isl_basic_set_free(eq);
2446                 return qp;
2447         }
2448
2449         qp = isl_qpolynomial_cow(qp);
2450         if (!qp)
2451                 goto error;
2452         qp->div = isl_mat_cow(qp->div);
2453         if (!qp->div)
2454                 goto error;
2455
2456         total = 1 + isl_space_dim(eq->dim, isl_dim_all);
2457         n_div = eq->n_div;
2458         isl_int_init(denom);
2459         for (i = 0; i < eq->n_eq; ++i) {
2460                 j = isl_seq_last_non_zero(eq->eq[i], total + n_div);
2461                 if (j < 0 || j == 0 || j >= total)
2462                         continue;
2463
2464                 for (k = 0; k < qp->div->n_row; ++k) {
2465                         if (isl_int_is_zero(qp->div->row[k][1 + j]))
2466                                 continue;
2467                         isl_seq_elim(qp->div->row[k] + 1, eq->eq[i], j, total,
2468                                         &qp->div->row[k][0]);
2469                         normalize_div(qp, k);
2470                 }
2471
2472                 if (isl_int_is_pos(eq->eq[i][j]))
2473                         isl_seq_neg(eq->eq[i], eq->eq[i], total);
2474                 isl_int_abs(denom, eq->eq[i][j]);
2475                 isl_int_set_si(eq->eq[i][j], 0);
2476
2477                 up = isl_upoly_from_affine(qp->dim->ctx,
2478                                                    eq->eq[i], denom, total);
2479                 qp->upoly = isl_upoly_subs(qp->upoly, j - 1, 1, &up);
2480                 isl_upoly_free(up);
2481         }
2482         isl_int_clear(denom);
2483
2484         if (!qp->upoly)
2485                 goto error;
2486
2487         isl_basic_set_free(eq);
2488
2489         qp = substitute_non_divs(qp);
2490         qp = sort_divs(qp);
2491
2492         return qp;
2493 error:
2494         isl_basic_set_free(eq);
2495         isl_qpolynomial_free(qp);
2496         return NULL;
2497 }
2498
2499 /* Exploit the equalities in "eq" to simplify the quasi-polynomial.
2500  */
2501 __isl_give isl_qpolynomial *isl_qpolynomial_substitute_equalities(
2502         __isl_take isl_qpolynomial *qp, __isl_take isl_basic_set *eq)
2503 {
2504         if (!qp || !eq)
2505                 goto error;
2506         if (qp->div->n_row > 0)
2507                 eq = isl_basic_set_add_dims(eq, isl_dim_set, qp->div->n_row);
2508         return isl_qpolynomial_substitute_equalities_lifted(qp, eq);
2509 error:
2510         isl_basic_set_free(eq);
2511         isl_qpolynomial_free(qp);
2512         return NULL;
2513 }
2514
2515 static __isl_give isl_basic_set *add_div_constraints(
2516         __isl_take isl_basic_set *bset, __isl_take isl_mat *div)
2517 {
2518         int i;
2519         unsigned total;
2520
2521         if (!bset || !div)
2522                 goto error;
2523
2524         bset = isl_basic_set_extend_constraints(bset, 0, 2 * div->n_row);
2525         if (!bset)
2526                 goto error;
2527         total = isl_basic_set_total_dim(bset);
2528         for (i = 0; i < div->n_row; ++i)
2529                 if (isl_basic_set_add_div_constraints_var(bset,
2530                                     total - div->n_row + i, div->row[i]) < 0)
2531                         goto error;
2532
2533         isl_mat_free(div);
2534         return bset;
2535 error:
2536         isl_mat_free(div);
2537         isl_basic_set_free(bset);
2538         return NULL;
2539 }
2540
2541 /* Look for equalities among the variables shared by context and qp
2542  * and the integer divisions of qp, if any.
2543  * The equalities are then used to eliminate variables and/or integer
2544  * divisions from qp.
2545  */
2546 __isl_give isl_qpolynomial *isl_qpolynomial_gist(
2547         __isl_take isl_qpolynomial *qp, __isl_take isl_set *context)
2548 {
2549         isl_basic_set *aff;
2550
2551         if (!qp)
2552                 goto error;
2553         if (qp->div->n_row > 0) {
2554                 isl_basic_set *bset;
2555                 context = isl_set_add_dims(context, isl_dim_set,
2556                                             qp->div->n_row);
2557                 bset = isl_basic_set_universe(isl_set_get_space(context));
2558                 bset = add_div_constraints(bset, isl_mat_copy(qp->div));
2559                 context = isl_set_intersect(context,
2560                                             isl_set_from_basic_set(bset));
2561         }
2562
2563         aff = isl_set_affine_hull(context);
2564         return isl_qpolynomial_substitute_equalities_lifted(qp, aff);
2565 error:
2566         isl_qpolynomial_free(qp);
2567         isl_set_free(context);
2568         return NULL;
2569 }
2570
2571 __isl_give isl_qpolynomial *isl_qpolynomial_gist_params(
2572         __isl_take isl_qpolynomial *qp, __isl_take isl_set *context)
2573 {
2574         isl_space *space = isl_qpolynomial_get_domain_space(qp);
2575         isl_set *dom_context = isl_set_universe(space);
2576         dom_context = isl_set_intersect_params(dom_context, context);
2577         return isl_qpolynomial_gist(qp, dom_context);
2578 }
2579
2580 __isl_give isl_pw_qpolynomial *isl_pw_qpolynomial_from_qpolynomial(
2581         __isl_take isl_qpolynomial *qp)
2582 {
2583         isl_set *dom;
2584
2585         if (!qp)
2586                 return NULL;
2587         if (isl_qpolynomial_is_zero(qp)) {
2588                 isl_space *dim = isl_qpolynomial_get_space(qp);
2589                 isl_qpolynomial_free(qp);
2590                 return isl_pw_qpolynomial_zero(dim);
2591         }
2592
2593         dom = isl_set_universe(isl_qpolynomial_get_domain_space(qp));
2594         return isl_pw_qpolynomial_alloc(dom, qp);
2595 }
2596
2597 #undef PW
2598 #define PW isl_pw_qpolynomial
2599 #undef EL
2600 #define EL isl_qpolynomial
2601 #undef EL_IS_ZERO
2602 #define EL_IS_ZERO is_zero
2603 #undef ZERO
2604 #define ZERO zero
2605 #undef IS_ZERO
2606 #define IS_ZERO is_zero
2607 #undef FIELD
2608 #define FIELD qp
2609 #undef DEFAULT_IS_ZERO
2610 #define DEFAULT_IS_ZERO 1
2611
2612 #define NO_PULLBACK
2613
2614 #include <isl_pw_templ.c>
2615
2616 #undef UNION
2617 #define UNION isl_union_pw_qpolynomial
2618 #undef PART
2619 #define PART isl_pw_qpolynomial
2620 #undef PARTS
2621 #define PARTS pw_qpolynomial
2622 #define ALIGN_DOMAIN
2623
2624 #include <isl_union_templ.c>
2625
2626 int isl_pw_qpolynomial_is_one(__isl_keep isl_pw_qpolynomial *pwqp)
2627 {
2628         if (!pwqp)
2629                 return -1;
2630
2631         if (pwqp->n != -1)
2632                 return 0;
2633
2634         if (!isl_set_plain_is_universe(pwqp->p[0].set))
2635                 return 0;
2636
2637         return isl_qpolynomial_is_one(pwqp->p[0].qp);
2638 }
2639
2640 __isl_give isl_pw_qpolynomial *isl_pw_qpolynomial_add(
2641         __isl_take isl_pw_qpolynomial *pwqp1,
2642         __isl_take isl_pw_qpolynomial *pwqp2)
2643 {
2644         return isl_pw_qpolynomial_union_add_(pwqp1, pwqp2);
2645 }
2646
2647 __isl_give isl_pw_qpolynomial *isl_pw_qpolynomial_mul(
2648         __isl_take isl_pw_qpolynomial *pwqp1,
2649         __isl_take isl_pw_qpolynomial *pwqp2)
2650 {
2651         int i, j, n;
2652         struct isl_pw_qpolynomial *res;
2653
2654         if (!pwqp1 || !pwqp2)
2655                 goto error;
2656
2657         isl_assert(pwqp1->dim->ctx, isl_space_is_equal(pwqp1->dim, pwqp2->dim),
2658                         goto error);
2659
2660         if (isl_pw_qpolynomial_is_zero(pwqp1)) {
2661                 isl_pw_qpolynomial_free(pwqp2);
2662                 return pwqp1;
2663         }
2664
2665         if (isl_pw_qpolynomial_is_zero(pwqp2)) {
2666                 isl_pw_qpolynomial_free(pwqp1);
2667                 return pwqp2;
2668         }
2669
2670         if (isl_pw_qpolynomial_is_one(pwqp1)) {
2671                 isl_pw_qpolynomial_free(pwqp1);
2672                 return pwqp2;
2673         }
2674
2675         if (isl_pw_qpolynomial_is_one(pwqp2)) {
2676                 isl_pw_qpolynomial_free(pwqp2);
2677                 return pwqp1;
2678         }
2679
2680         n = pwqp1->n * pwqp2->n;
2681         res = isl_pw_qpolynomial_alloc_size(isl_space_copy(pwqp1->dim), n);
2682
2683         for (i = 0; i < pwqp1->n; ++i) {
2684                 for (j = 0; j < pwqp2->n; ++j) {
2685                         struct isl_set *common;
2686                         struct isl_qpolynomial *prod;
2687                         common = isl_set_intersect(isl_set_copy(pwqp1->p[i].set),
2688                                                 isl_set_copy(pwqp2->p[j].set));
2689                         if (isl_set_plain_is_empty(common)) {
2690                                 isl_set_free(common);
2691                                 continue;
2692                         }
2693
2694                         prod = isl_qpolynomial_mul(
2695                                 isl_qpolynomial_copy(pwqp1->p[i].qp),
2696                                 isl_qpolynomial_copy(pwqp2->p[j].qp));
2697
2698                         res = isl_pw_qpolynomial_add_piece(res, common, prod);
2699                 }
2700         }
2701
2702         isl_pw_qpolynomial_free(pwqp1);
2703         isl_pw_qpolynomial_free(pwqp2);
2704
2705         return res;
2706 error:
2707         isl_pw_qpolynomial_free(pwqp1);
2708         isl_pw_qpolynomial_free(pwqp2);
2709         return NULL;
2710 }
2711
2712 __isl_give struct isl_upoly *isl_upoly_eval(
2713         __isl_take struct isl_upoly *up, __isl_take isl_vec *vec)
2714 {
2715         int i;
2716         struct isl_upoly_rec *rec;
2717         struct isl_upoly *res;
2718         struct isl_upoly *base;
2719
2720         if (isl_upoly_is_cst(up)) {
2721                 isl_vec_free(vec);
2722                 return up;
2723         }
2724
2725         rec = isl_upoly_as_rec(up);
2726         if (!rec)
2727                 goto error;
2728
2729         isl_assert(up->ctx, rec->n >= 1, goto error);
2730
2731         base = isl_upoly_rat_cst(up->ctx, vec->el[1 + up->var], vec->el[0]);
2732
2733         res = isl_upoly_eval(isl_upoly_copy(rec->p[rec->n - 1]),
2734                                 isl_vec_copy(vec));
2735
2736         for (i = rec->n - 2; i >= 0; --i) {
2737                 res = isl_upoly_mul(res, isl_upoly_copy(base));
2738                 res = isl_upoly_sum(res, 
2739                             isl_upoly_eval(isl_upoly_copy(rec->p[i]),
2740                                                             isl_vec_copy(vec)));
2741         }
2742
2743         isl_upoly_free(base);
2744         isl_upoly_free(up);
2745         isl_vec_free(vec);
2746         return res;
2747 error:
2748         isl_upoly_free(up);
2749         isl_vec_free(vec);
2750         return NULL;
2751 }
2752
2753 __isl_give isl_qpolynomial *isl_qpolynomial_eval(
2754         __isl_take isl_qpolynomial *qp, __isl_take isl_point *pnt)
2755 {
2756         isl_vec *ext;
2757         struct isl_upoly *up;
2758         isl_space *dim;
2759
2760         if (!qp || !pnt)
2761                 goto error;
2762         isl_assert(pnt->dim->ctx, isl_space_is_equal(pnt->dim, qp->dim), goto error);
2763
2764         if (qp->div->n_row == 0)
2765                 ext = isl_vec_copy(pnt->vec);
2766         else {
2767                 int i;
2768                 unsigned dim = isl_space_dim(qp->dim, isl_dim_all);
2769                 ext = isl_vec_alloc(qp->dim->ctx, 1 + dim + qp->div->n_row);
2770                 if (!ext)
2771                         goto error;
2772
2773                 isl_seq_cpy(ext->el, pnt->vec->el, pnt->vec->size);
2774                 for (i = 0; i < qp->div->n_row; ++i) {
2775                         isl_seq_inner_product(qp->div->row[i] + 1, ext->el,
2776                                                 1 + dim + i, &ext->el[1+dim+i]);
2777                         isl_int_fdiv_q(ext->el[1+dim+i], ext->el[1+dim+i],
2778                                         qp->div->row[i][0]);
2779                 }
2780         }
2781
2782         up = isl_upoly_eval(isl_upoly_copy(qp->upoly), ext);
2783         if (!up)
2784                 goto error;
2785
2786         dim = isl_space_copy(qp->dim);
2787         isl_qpolynomial_free(qp);
2788         isl_point_free(pnt);
2789
2790         return isl_qpolynomial_alloc(dim, 0, up);
2791 error:
2792         isl_qpolynomial_free(qp);
2793         isl_point_free(pnt);
2794         return NULL;
2795 }
2796
2797 int isl_upoly_cmp(__isl_keep struct isl_upoly_cst *cst1,
2798         __isl_keep struct isl_upoly_cst *cst2)
2799 {
2800         int cmp;
2801         isl_int t;
2802         isl_int_init(t);
2803         isl_int_mul(t, cst1->n, cst2->d);
2804         isl_int_submul(t, cst2->n, cst1->d);
2805         cmp = isl_int_sgn(t);
2806         isl_int_clear(t);
2807         return cmp;
2808 }
2809
2810 int isl_qpolynomial_le_cst(__isl_keep isl_qpolynomial *qp1,
2811         __isl_keep isl_qpolynomial *qp2)
2812 {
2813         struct isl_upoly_cst *cst1, *cst2;
2814
2815         if (!qp1 || !qp2)
2816                 return -1;
2817         isl_assert(qp1->dim->ctx, isl_upoly_is_cst(qp1->upoly), return -1);
2818         isl_assert(qp2->dim->ctx, isl_upoly_is_cst(qp2->upoly), return -1);
2819         if (isl_qpolynomial_is_nan(qp1))
2820                 return -1;
2821         if (isl_qpolynomial_is_nan(qp2))
2822                 return -1;
2823         cst1 = isl_upoly_as_cst(qp1->upoly);
2824         cst2 = isl_upoly_as_cst(qp2->upoly);
2825
2826         return isl_upoly_cmp(cst1, cst2) <= 0;
2827 }
2828
2829 __isl_give isl_qpolynomial *isl_qpolynomial_min_cst(
2830         __isl_take isl_qpolynomial *qp1, __isl_take isl_qpolynomial *qp2)
2831 {
2832         struct isl_upoly_cst *cst1, *cst2;
2833         int cmp;
2834
2835         if (!qp1 || !qp2)
2836                 goto error;
2837         isl_assert(qp1->dim->ctx, isl_upoly_is_cst(qp1->upoly), goto error);
2838         isl_assert(qp2->dim->ctx, isl_upoly_is_cst(qp2->upoly), goto error);
2839         cst1 = isl_upoly_as_cst(qp1->upoly);
2840         cst2 = isl_upoly_as_cst(qp2->upoly);
2841         cmp = isl_upoly_cmp(cst1, cst2);
2842
2843         if (cmp <= 0) {
2844                 isl_qpolynomial_free(qp2);
2845         } else {
2846                 isl_qpolynomial_free(qp1);
2847                 qp1 = qp2;
2848         }
2849         return qp1;
2850 error:
2851         isl_qpolynomial_free(qp1);
2852         isl_qpolynomial_free(qp2);
2853         return NULL;
2854 }
2855
2856 __isl_give isl_qpolynomial *isl_qpolynomial_max_cst(
2857         __isl_take isl_qpolynomial *qp1, __isl_take isl_qpolynomial *qp2)
2858 {
2859         struct isl_upoly_cst *cst1, *cst2;
2860         int cmp;
2861
2862         if (!qp1 || !qp2)
2863                 goto error;
2864         isl_assert(qp1->dim->ctx, isl_upoly_is_cst(qp1->upoly), goto error);
2865         isl_assert(qp2->dim->ctx, isl_upoly_is_cst(qp2->upoly), goto error);
2866         cst1 = isl_upoly_as_cst(qp1->upoly);
2867         cst2 = isl_upoly_as_cst(qp2->upoly);
2868         cmp = isl_upoly_cmp(cst1, cst2);
2869
2870         if (cmp >= 0) {
2871                 isl_qpolynomial_free(qp2);
2872         } else {
2873                 isl_qpolynomial_free(qp1);
2874                 qp1 = qp2;
2875         }
2876         return qp1;
2877 error:
2878         isl_qpolynomial_free(qp1);
2879         isl_qpolynomial_free(qp2);
2880         return NULL;
2881 }
2882
2883 __isl_give isl_qpolynomial *isl_qpolynomial_insert_dims(
2884         __isl_take isl_qpolynomial *qp, enum isl_dim_type type,
2885         unsigned first, unsigned n)
2886 {
2887         unsigned total;
2888         unsigned g_pos;
2889         int *exp;
2890
2891         if (!qp)
2892                 return NULL;
2893         if (type == isl_dim_out)
2894                 isl_die(qp->div->ctx, isl_error_invalid,
2895                         "cannot insert output/set dimensions",
2896                         goto error);
2897         if (type == isl_dim_in)
2898                 type = isl_dim_set;
2899         if (n == 0 && !isl_space_is_named_or_nested(qp->dim, type))
2900                 return qp;
2901
2902         qp = isl_qpolynomial_cow(qp);
2903         if (!qp)
2904                 return NULL;
2905
2906         isl_assert(qp->div->ctx, first <= isl_space_dim(qp->dim, type),
2907                     goto error);
2908
2909         g_pos = pos(qp->dim, type) + first;
2910
2911         qp->div = isl_mat_insert_zero_cols(qp->div, 2 + g_pos, n);
2912         if (!qp->div)
2913                 goto error;
2914
2915         total = qp->div->n_col - 2;
2916         if (total > g_pos) {
2917                 int i;
2918                 exp = isl_alloc_array(qp->div->ctx, int, total - g_pos);
2919                 if (!exp)
2920                         goto error;
2921                 for (i = 0; i < total - g_pos; ++i)
2922                         exp[i] = i + n;
2923                 qp->upoly = expand(qp->upoly, exp, g_pos);
2924                 free(exp);
2925                 if (!qp->upoly)
2926                         goto error;
2927         }
2928
2929         qp->dim = isl_space_insert_dims(qp->dim, type, first, n);
2930         if (!qp->dim)
2931                 goto error;
2932
2933         return qp;
2934 error:
2935         isl_qpolynomial_free(qp);
2936         return NULL;
2937 }
2938
2939 __isl_give isl_qpolynomial *isl_qpolynomial_add_dims(
2940         __isl_take isl_qpolynomial *qp, enum isl_dim_type type, unsigned n)
2941 {
2942         unsigned pos;
2943
2944         pos = isl_qpolynomial_dim(qp, type);
2945
2946         return isl_qpolynomial_insert_dims(qp, type, pos, n);
2947 }
2948
2949 __isl_give isl_pw_qpolynomial *isl_pw_qpolynomial_add_dims(
2950         __isl_take isl_pw_qpolynomial *pwqp,
2951         enum isl_dim_type type, unsigned n)
2952 {
2953         unsigned pos;
2954
2955         pos = isl_pw_qpolynomial_dim(pwqp, type);
2956
2957         return isl_pw_qpolynomial_insert_dims(pwqp, type, pos, n);
2958 }
2959
2960 static int *reordering_move(isl_ctx *ctx,
2961         unsigned len, unsigned dst, unsigned src, unsigned n)
2962 {
2963         int i;
2964         int *reordering;
2965
2966         reordering = isl_alloc_array(ctx, int, len);
2967         if (!reordering)
2968                 return NULL;
2969
2970         if (dst <= src) {
2971                 for (i = 0; i < dst; ++i)
2972                         reordering[i] = i;
2973                 for (i = 0; i < n; ++i)
2974                         reordering[src + i] = dst + i;
2975                 for (i = 0; i < src - dst; ++i)
2976                         reordering[dst + i] = dst + n + i;
2977                 for (i = 0; i < len - src - n; ++i)
2978                         reordering[src + n + i] = src + n + i;
2979         } else {
2980                 for (i = 0; i < src; ++i)
2981                         reordering[i] = i;
2982                 for (i = 0; i < n; ++i)
2983                         reordering[src + i] = dst + i;
2984                 for (i = 0; i < dst - src; ++i)
2985                         reordering[src + n + i] = src + i;
2986                 for (i = 0; i < len - dst - n; ++i)
2987                         reordering[dst + n + i] = dst + n + i;
2988         }
2989
2990         return reordering;
2991 }
2992
2993 __isl_give isl_qpolynomial *isl_qpolynomial_move_dims(
2994         __isl_take isl_qpolynomial *qp,
2995         enum isl_dim_type dst_type, unsigned dst_pos,
2996         enum isl_dim_type src_type, unsigned src_pos, unsigned n)
2997 {
2998         unsigned g_dst_pos;
2999         unsigned g_src_pos;
3000         int *reordering;
3001
3002         qp = isl_qpolynomial_cow(qp);
3003         if (!qp)
3004                 return NULL;
3005
3006         if (dst_type == isl_dim_out || src_type == isl_dim_out)
3007                 isl_die(qp->dim->ctx, isl_error_invalid,
3008                         "cannot move output/set dimension",
3009                         goto error);
3010         if (dst_type == isl_dim_in)
3011                 dst_type = isl_dim_set;
3012         if (src_type == isl_dim_in)
3013                 src_type = isl_dim_set;
3014
3015         isl_assert(qp->dim->ctx, src_pos + n <= isl_space_dim(qp->dim, src_type),
3016                 goto error);
3017
3018         g_dst_pos = pos(qp->dim, dst_type) + dst_pos;
3019         g_src_pos = pos(qp->dim, src_type) + src_pos;
3020         if (dst_type > src_type)
3021                 g_dst_pos -= n;
3022
3023         qp->div = isl_mat_move_cols(qp->div, 2 + g_dst_pos, 2 + g_src_pos, n);
3024         if (!qp->div)
3025                 goto error;
3026         qp = sort_divs(qp);
3027         if (!qp)
3028                 goto error;
3029
3030         reordering = reordering_move(qp->dim->ctx,
3031                                 qp->div->n_col - 2, g_dst_pos, g_src_pos, n);
3032         if (!reordering)
3033                 goto error;
3034
3035         qp->upoly = reorder(qp->upoly, reordering);
3036         free(reordering);
3037         if (!qp->upoly)
3038                 goto error;
3039
3040         qp->dim = isl_space_move_dims(qp->dim, dst_type, dst_pos, src_type, src_pos, n);
3041         if (!qp->dim)
3042                 goto error;
3043
3044         return qp;
3045 error:
3046         isl_qpolynomial_free(qp);
3047         return NULL;
3048 }
3049
3050 __isl_give isl_qpolynomial *isl_qpolynomial_from_affine(__isl_take isl_space *dim,
3051         isl_int *f, isl_int denom)
3052 {
3053         struct isl_upoly *up;
3054
3055         dim = isl_space_domain(dim);
3056         if (!dim)
3057                 return NULL;
3058
3059         up = isl_upoly_from_affine(dim->ctx, f, denom,
3060                                         1 + isl_space_dim(dim, isl_dim_all));
3061
3062         return isl_qpolynomial_alloc(dim, 0, up);
3063 }
3064
3065 __isl_give isl_qpolynomial *isl_qpolynomial_from_aff(__isl_take isl_aff *aff)
3066 {
3067         isl_ctx *ctx;
3068         struct isl_upoly *up;
3069         isl_qpolynomial *qp;
3070
3071         if (!aff)
3072                 return NULL;
3073
3074         ctx = isl_aff_get_ctx(aff);
3075         up = isl_upoly_from_affine(ctx, aff->v->el + 1, aff->v->el[0],
3076                                     aff->v->size - 1);
3077
3078         qp = isl_qpolynomial_alloc(isl_aff_get_domain_space(aff),
3079                                     aff->ls->div->n_row, up);
3080         if (!qp)
3081                 goto error;
3082
3083         isl_mat_free(qp->div);
3084         qp->div = isl_mat_copy(aff->ls->div);
3085         qp->div = isl_mat_cow(qp->div);
3086         if (!qp->div)
3087                 goto error;
3088
3089         isl_aff_free(aff);
3090         qp = reduce_divs(qp);
3091         qp = remove_redundant_divs(qp);
3092         return qp;
3093 error:
3094         isl_aff_free(aff);
3095         return NULL;
3096 }
3097
3098 __isl_give isl_pw_qpolynomial *isl_pw_qpolynomial_from_pw_aff(
3099         __isl_take isl_pw_aff *pwaff)
3100 {
3101         int i;
3102         isl_pw_qpolynomial *pwqp;
3103
3104         if (!pwaff)
3105                 return NULL;
3106
3107         pwqp = isl_pw_qpolynomial_alloc_size(isl_pw_aff_get_space(pwaff),
3108                                                 pwaff->n);
3109
3110         for (i = 0; i < pwaff->n; ++i) {
3111                 isl_set *dom;
3112                 isl_qpolynomial *qp;
3113
3114                 dom = isl_set_copy(pwaff->p[i].set);
3115                 qp = isl_qpolynomial_from_aff(isl_aff_copy(pwaff->p[i].aff));
3116                 pwqp = isl_pw_qpolynomial_add_piece(pwqp,  dom, qp);
3117         }
3118
3119         isl_pw_aff_free(pwaff);
3120         return pwqp;
3121 }
3122
3123 __isl_give isl_qpolynomial *isl_qpolynomial_from_constraint(
3124         __isl_take isl_constraint *c, enum isl_dim_type type, unsigned pos)
3125 {
3126         isl_aff *aff;
3127
3128         aff = isl_constraint_get_bound(c, type, pos);
3129         isl_constraint_free(c);
3130         return isl_qpolynomial_from_aff(aff);
3131 }
3132
3133 /* For each 0 <= i < "n", replace variable "first" + i of type "type"
3134  * in "qp" by subs[i].
3135  */
3136 __isl_give isl_qpolynomial *isl_qpolynomial_substitute(
3137         __isl_take isl_qpolynomial *qp,
3138         enum isl_dim_type type, unsigned first, unsigned n,
3139         __isl_keep isl_qpolynomial **subs)
3140 {
3141         int i;
3142         struct isl_upoly **ups;
3143
3144         if (n == 0)
3145                 return qp;
3146
3147         qp = isl_qpolynomial_cow(qp);
3148         if (!qp)
3149                 return NULL;
3150
3151         if (type == isl_dim_out)
3152                 isl_die(qp->dim->ctx, isl_error_invalid,
3153                         "cannot substitute output/set dimension",
3154                         goto error);
3155         if (type == isl_dim_in)
3156                 type = isl_dim_set;
3157
3158         for (i = 0; i < n; ++i)
3159                 if (!subs[i])
3160                         goto error;
3161
3162         isl_assert(qp->dim->ctx, first + n <= isl_space_dim(qp->dim, type),
3163                         goto error);
3164
3165         for (i = 0; i < n; ++i)
3166                 isl_assert(qp->dim->ctx, isl_space_is_equal(qp->dim, subs[i]->dim),
3167                                 goto error);
3168
3169         isl_assert(qp->dim->ctx, qp->div->n_row == 0, goto error);
3170         for (i = 0; i < n; ++i)
3171                 isl_assert(qp->dim->ctx, subs[i]->div->n_row == 0, goto error);
3172
3173         first += pos(qp->dim, type);
3174
3175         ups = isl_alloc_array(qp->dim->ctx, struct isl_upoly *, n);
3176         if (!ups)
3177                 goto error;
3178         for (i = 0; i < n; ++i)
3179                 ups[i] = subs[i]->upoly;
3180
3181         qp->upoly = isl_upoly_subs(qp->upoly, first, n, ups);
3182
3183         free(ups);
3184
3185         if (!qp->upoly)
3186                 goto error;
3187
3188         return qp;
3189 error:
3190         isl_qpolynomial_free(qp);
3191         return NULL;
3192 }
3193
3194 /* Extend "bset" with extra set dimensions for each integer division
3195  * in "qp" and then call "fn" with the extended bset and the polynomial
3196  * that results from replacing each of the integer divisions by the
3197  * corresponding extra set dimension.
3198  */
3199 int isl_qpolynomial_as_polynomial_on_domain(__isl_keep isl_qpolynomial *qp,
3200         __isl_keep isl_basic_set *bset,
3201         int (*fn)(__isl_take isl_basic_set *bset,
3202                   __isl_take isl_qpolynomial *poly, void *user), void *user)
3203 {
3204         isl_space *dim;
3205         isl_mat *div;
3206         isl_qpolynomial *poly;
3207
3208         if (!qp || !bset)
3209                 goto error;
3210         if (qp->div->n_row == 0)
3211                 return fn(isl_basic_set_copy(bset), isl_qpolynomial_copy(qp),
3212                           user);
3213
3214         div = isl_mat_copy(qp->div);
3215         dim = isl_space_copy(qp->dim);
3216         dim = isl_space_add_dims(dim, isl_dim_set, qp->div->n_row);
3217         poly = isl_qpolynomial_alloc(dim, 0, isl_upoly_copy(qp->upoly));
3218         bset = isl_basic_set_copy(bset);
3219         bset = isl_basic_set_add_dims(bset, isl_dim_set, qp->div->n_row);
3220         bset = add_div_constraints(bset, div);
3221
3222         return fn(bset, poly, user);
3223 error:
3224         return -1;
3225 }
3226
3227 /* Return total degree in variables first (inclusive) up to last (exclusive).
3228  */
3229 int isl_upoly_degree(__isl_keep struct isl_upoly *up, int first, int last)
3230 {
3231         int deg = -1;
3232         int i;
3233         struct isl_upoly_rec *rec;
3234
3235         if (!up)
3236                 return -2;
3237         if (isl_upoly_is_zero(up))
3238                 return -1;
3239         if (isl_upoly_is_cst(up) || up->var < first)
3240                 return 0;
3241
3242         rec = isl_upoly_as_rec(up);
3243         if (!rec)
3244                 return -2;
3245
3246         for (i = 0; i < rec->n; ++i) {
3247                 int d;
3248
3249                 if (isl_upoly_is_zero(rec->p[i]))
3250                         continue;
3251                 d = isl_upoly_degree(rec->p[i], first, last);
3252                 if (up->var < last)
3253                         d += i;
3254                 if (d > deg)
3255                         deg = d;
3256         }
3257
3258         return deg;
3259 }
3260
3261 /* Return total degree in set variables.
3262  */
3263 int isl_qpolynomial_degree(__isl_keep isl_qpolynomial *poly)
3264 {
3265         unsigned ovar;
3266         unsigned nvar;
3267
3268         if (!poly)
3269                 return -2;
3270
3271         ovar = isl_space_offset(poly->dim, isl_dim_set);
3272         nvar = isl_space_dim(poly->dim, isl_dim_set);
3273         return isl_upoly_degree(poly->upoly, ovar, ovar + nvar);
3274 }
3275
3276 __isl_give struct isl_upoly *isl_upoly_coeff(__isl_keep struct isl_upoly *up,
3277         unsigned pos, int deg)
3278 {
3279         int i;
3280         struct isl_upoly_rec *rec;
3281
3282         if (!up)
3283                 return NULL;
3284
3285         if (isl_upoly_is_cst(up) || up->var < pos) {
3286                 if (deg == 0)
3287                         return isl_upoly_copy(up);
3288                 else
3289                         return isl_upoly_zero(up->ctx);
3290         }
3291
3292         rec = isl_upoly_as_rec(up);
3293         if (!rec)
3294                 return NULL;
3295
3296         if (up->var == pos) {
3297                 if (deg < rec->n)
3298                         return isl_upoly_copy(rec->p[deg]);
3299                 else
3300                         return isl_upoly_zero(up->ctx);
3301         }
3302
3303         up = isl_upoly_copy(up);
3304         up = isl_upoly_cow(up);
3305         rec = isl_upoly_as_rec(up);
3306         if (!rec)
3307                 goto error;
3308
3309         for (i = 0; i < rec->n; ++i) {
3310                 struct isl_upoly *t;
3311                 t = isl_upoly_coeff(rec->p[i], pos, deg);
3312                 if (!t)
3313                         goto error;
3314                 isl_upoly_free(rec->p[i]);
3315                 rec->p[i] = t;
3316         }
3317
3318         return up;
3319 error:
3320         isl_upoly_free(up);
3321         return NULL;
3322 }
3323
3324 /* Return coefficient of power "deg" of variable "t_pos" of type "type".
3325  */
3326 __isl_give isl_qpolynomial *isl_qpolynomial_coeff(
3327         __isl_keep isl_qpolynomial *qp,
3328         enum isl_dim_type type, unsigned t_pos, int deg)
3329 {
3330         unsigned g_pos;
3331         struct isl_upoly *up;
3332         isl_qpolynomial *c;
3333
3334         if (!qp)
3335                 return NULL;
3336
3337         if (type == isl_dim_out)
3338                 isl_die(qp->div->ctx, isl_error_invalid,
3339                         "output/set dimension does not have a coefficient",
3340                         return NULL);
3341         if (type == isl_dim_in)
3342                 type = isl_dim_set;
3343
3344         isl_assert(qp->div->ctx, t_pos < isl_space_dim(qp->dim, type),
3345                         return NULL);
3346
3347         g_pos = pos(qp->dim, type) + t_pos;
3348         up = isl_upoly_coeff(qp->upoly, g_pos, deg);
3349
3350         c = isl_qpolynomial_alloc(isl_space_copy(qp->dim), qp->div->n_row, up);
3351         if (!c)
3352                 return NULL;
3353         isl_mat_free(c->div);
3354         c->div = isl_mat_copy(qp->div);
3355         if (!c->div)
3356                 goto error;
3357         return c;
3358 error:
3359         isl_qpolynomial_free(c);
3360         return NULL;
3361 }
3362
3363 /* Homogenize the polynomial in the variables first (inclusive) up to
3364  * last (exclusive) by inserting powers of variable first.
3365  * Variable first is assumed not to appear in the input.
3366  */
3367 __isl_give struct isl_upoly *isl_upoly_homogenize(
3368         __isl_take struct isl_upoly *up, int deg, int target,
3369         int first, int last)
3370 {
3371         int i;
3372         struct isl_upoly_rec *rec;
3373
3374         if (!up)
3375                 return NULL;
3376         if (isl_upoly_is_zero(up))
3377                 return up;
3378         if (deg == target)
3379                 return up;
3380         if (isl_upoly_is_cst(up) || up->var < first) {
3381                 struct isl_upoly *hom;
3382
3383                 hom = isl_upoly_var_pow(up->ctx, first, target - deg);
3384                 if (!hom)
3385                         goto error;
3386                 rec = isl_upoly_as_rec(hom);
3387                 rec->p[target - deg] = isl_upoly_mul(rec->p[target - deg], up);
3388
3389                 return hom;
3390         }
3391
3392         up = isl_upoly_cow(up);
3393         rec = isl_upoly_as_rec(up);
3394         if (!rec)
3395                 goto error;
3396
3397         for (i = 0; i < rec->n; ++i) {
3398                 if (isl_upoly_is_zero(rec->p[i]))
3399                         continue;
3400                 rec->p[i] = isl_upoly_homogenize(rec->p[i],
3401                                 up->var < last ? deg + i : i, target,
3402                                 first, last);
3403                 if (!rec->p[i])
3404                         goto error;
3405         }
3406
3407         return up;
3408 error:
3409         isl_upoly_free(up);
3410         return NULL;
3411 }
3412
3413 /* Homogenize the polynomial in the set variables by introducing
3414  * powers of an extra set variable at position 0.
3415  */
3416 __isl_give isl_qpolynomial *isl_qpolynomial_homogenize(
3417         __isl_take isl_qpolynomial *poly)
3418 {
3419         unsigned ovar;
3420         unsigned nvar;
3421         int deg = isl_qpolynomial_degree(poly);
3422
3423         if (deg < -1)
3424                 goto error;
3425
3426         poly = isl_qpolynomial_insert_dims(poly, isl_dim_in, 0, 1);
3427         poly = isl_qpolynomial_cow(poly);
3428         if (!poly)
3429                 goto error;
3430
3431         ovar = isl_space_offset(poly->dim, isl_dim_set);
3432         nvar = isl_space_dim(poly->dim, isl_dim_set);
3433         poly->upoly = isl_upoly_homogenize(poly->upoly, 0, deg,
3434                                                 ovar, ovar + nvar);
3435         if (!poly->upoly)
3436                 goto error;
3437
3438         return poly;
3439 error:
3440         isl_qpolynomial_free(poly);
3441         return NULL;
3442 }
3443
3444 __isl_give isl_term *isl_term_alloc(__isl_take isl_space *dim,
3445         __isl_take isl_mat *div)
3446 {
3447         isl_term *term;
3448         int n;
3449
3450         if (!dim || !div)
3451                 goto error;
3452
3453         n = isl_space_dim(dim, isl_dim_all) + div->n_row;
3454
3455         term = isl_calloc(dim->ctx, struct isl_term,
3456                         sizeof(struct isl_term) + (n - 1) * sizeof(int));
3457         if (!term)
3458                 goto error;
3459
3460         term->ref = 1;
3461         term->dim = dim;
3462         term->div = div;
3463         isl_int_init(term->n);
3464         isl_int_init(term->d);
3465         
3466         return term;
3467 error:
3468         isl_space_free(dim);
3469         isl_mat_free(div);
3470         return NULL;
3471 }
3472
3473 __isl_give isl_term *isl_term_copy(__isl_keep isl_term *term)
3474 {
3475         if (!term)
3476                 return NULL;
3477
3478         term->ref++;
3479         return term;
3480 }
3481
3482 __isl_give isl_term *isl_term_dup(__isl_keep isl_term *term)
3483 {
3484         int i;
3485         isl_term *dup;
3486         unsigned total;
3487
3488         if (!term)
3489                 return NULL;
3490
3491         total = isl_space_dim(term->dim, isl_dim_all) + term->div->n_row;
3492
3493         dup = isl_term_alloc(isl_space_copy(term->dim), isl_mat_copy(term->div));
3494         if (!dup)
3495                 return NULL;
3496
3497         isl_int_set(dup->n, term->n);
3498         isl_int_set(dup->d, term->d);
3499
3500         for (i = 0; i < total; ++i)
3501                 dup->pow[i] = term->pow[i];
3502
3503         return dup;
3504 }
3505
3506 __isl_give isl_term *isl_term_cow(__isl_take isl_term *term)
3507 {
3508         if (!term)
3509                 return NULL;
3510
3511         if (term->ref == 1)
3512                 return term;
3513         term->ref--;
3514         return isl_term_dup(term);
3515 }
3516
3517 void isl_term_free(__isl_take isl_term *term)
3518 {
3519         if (!term)
3520                 return;
3521
3522         if (--term->ref > 0)
3523                 return;
3524
3525         isl_space_free(term->dim);
3526         isl_mat_free(term->div);
3527         isl_int_clear(term->n);
3528         isl_int_clear(term->d);
3529         free(term);
3530 }
3531
3532 unsigned isl_term_dim(__isl_keep isl_term *term, enum isl_dim_type type)
3533 {
3534         if (!term)
3535                 return 0;
3536
3537         switch (type) {
3538         case isl_dim_param:
3539         case isl_dim_in:
3540         case isl_dim_out:       return isl_space_dim(term->dim, type);
3541         case isl_dim_div:       return term->div->n_row;
3542         case isl_dim_all:       return isl_space_dim(term->dim, isl_dim_all) +
3543                                                                 term->div->n_row;
3544         default:                return 0;
3545         }
3546 }
3547
3548 isl_ctx *isl_term_get_ctx(__isl_keep isl_term *term)
3549 {
3550         return term ? term->dim->ctx : NULL;
3551 }
3552
3553 void isl_term_get_num(__isl_keep isl_term *term, isl_int *n)
3554 {
3555         if (!term)
3556                 return;
3557         isl_int_set(*n, term->n);
3558 }
3559
3560 void isl_term_get_den(__isl_keep isl_term *term, isl_int *d)
3561 {
3562         if (!term)
3563                 return;
3564         isl_int_set(*d, term->d);
3565 }
3566
3567 /* Return the coefficient of the term "term".
3568  */
3569 __isl_give isl_val *isl_term_get_coefficient_val(__isl_keep isl_term *term)
3570 {
3571         if (!term)
3572                 return NULL;
3573
3574         return isl_val_rat_from_isl_int(isl_term_get_ctx(term),
3575                                         term->n, term->d);
3576 }
3577
3578 int isl_term_get_exp(__isl_keep isl_term *term,
3579         enum isl_dim_type type, unsigned pos)
3580 {
3581         if (!term)
3582                 return -1;
3583
3584         isl_assert(term->dim->ctx, pos < isl_term_dim(term, type), return -1);
3585
3586         if (type >= isl_dim_set)
3587                 pos += isl_space_dim(term->dim, isl_dim_param);
3588         if (type >= isl_dim_div)
3589                 pos += isl_space_dim(term->dim, isl_dim_set);
3590
3591         return term->pow[pos];
3592 }
3593
3594 __isl_give isl_aff *isl_term_get_div(__isl_keep isl_term *term, unsigned pos)
3595 {
3596         isl_local_space *ls;
3597         isl_aff *aff;
3598
3599         if (!term)
3600                 return NULL;
3601
3602         isl_assert(term->dim->ctx, pos < isl_term_dim(term, isl_dim_div),
3603                         return NULL);
3604
3605         ls = isl_local_space_alloc_div(isl_space_copy(term->dim),
3606                                         isl_mat_copy(term->div));
3607         aff = isl_aff_alloc(ls);
3608         if (!aff)
3609                 return NULL;
3610
3611         isl_seq_cpy(aff->v->el, term->div->row[pos], aff->v->size);
3612
3613         aff = isl_aff_normalize(aff);
3614
3615         return aff;
3616 }
3617
3618 __isl_give isl_term *isl_upoly_foreach_term(__isl_keep struct isl_upoly *up,
3619         int (*fn)(__isl_take isl_term *term, void *user),
3620         __isl_take isl_term *term, void *user)
3621 {
3622         int i;
3623         struct isl_upoly_rec *rec;
3624
3625         if (!up || !term)
3626                 goto error;
3627
3628         if (isl_upoly_is_zero(up))
3629                 return term;
3630
3631         isl_assert(up->ctx, !isl_upoly_is_nan(up), goto error);
3632         isl_assert(up->ctx, !isl_upoly_is_infty(up), goto error);
3633         isl_assert(up->ctx, !isl_upoly_is_neginfty(up), goto error);
3634
3635         if (isl_upoly_is_cst(up)) {
3636                 struct isl_upoly_cst *cst;
3637                 cst = isl_upoly_as_cst(up);
3638                 if (!cst)
3639                         goto error;
3640                 term = isl_term_cow(term);
3641                 if (!term)
3642                         goto error;
3643                 isl_int_set(term->n, cst->n);
3644                 isl_int_set(term->d, cst->d);
3645                 if (fn(isl_term_copy(term), user) < 0)
3646                         goto error;
3647                 return term;
3648         }
3649
3650         rec = isl_upoly_as_rec(up);
3651         if (!rec)
3652                 goto error;
3653
3654         for (i = 0; i < rec->n; ++i) {
3655                 term = isl_term_cow(term);
3656                 if (!term)
3657                         goto error;
3658                 term->pow[up->var] = i;
3659                 term = isl_upoly_foreach_term(rec->p[i], fn, term, user);
3660                 if (!term)
3661                         goto error;
3662         }
3663         term->pow[up->var] = 0;
3664
3665         return term;
3666 error:
3667         isl_term_free(term);
3668         return NULL;
3669 }
3670
3671 int isl_qpolynomial_foreach_term(__isl_keep isl_qpolynomial *qp,
3672         int (*fn)(__isl_take isl_term *term, void *user), void *user)
3673 {
3674         isl_term *term;
3675
3676         if (!qp)
3677                 return -1;
3678
3679         term = isl_term_alloc(isl_space_copy(qp->dim), isl_mat_copy(qp->div));
3680         if (!term)
3681                 return -1;
3682
3683         term = isl_upoly_foreach_term(qp->upoly, fn, term, user);
3684
3685         isl_term_free(term);
3686
3687         return term ? 0 : -1;
3688 }
3689
3690 __isl_give isl_qpolynomial *isl_qpolynomial_from_term(__isl_take isl_term *term)
3691 {
3692         struct isl_upoly *up;
3693         isl_qpolynomial *qp;
3694         int i, n;
3695
3696         if (!term)
3697                 return NULL;
3698
3699         n = isl_space_dim(term->dim, isl_dim_all) + term->div->n_row;
3700
3701         up = isl_upoly_rat_cst(term->dim->ctx, term->n, term->d);
3702         for (i = 0; i < n; ++i) {
3703                 if (!term->pow[i])
3704                         continue;
3705                 up = isl_upoly_mul(up,
3706                         isl_upoly_var_pow(term->dim->ctx, i, term->pow[i]));
3707         }
3708
3709         qp = isl_qpolynomial_alloc(isl_space_copy(term->dim), term->div->n_row, up);
3710         if (!qp)
3711                 goto error;
3712         isl_mat_free(qp->div);
3713         qp->div = isl_mat_copy(term->div);
3714         if (!qp->div)
3715                 goto error;
3716
3717         isl_term_free(term);
3718         return qp;
3719 error:
3720         isl_qpolynomial_free(qp);
3721         isl_term_free(term);
3722         return NULL;
3723 }
3724
3725 __isl_give isl_qpolynomial *isl_qpolynomial_lift(__isl_take isl_qpolynomial *qp,
3726         __isl_take isl_space *dim)
3727 {
3728         int i;
3729         int extra;
3730         unsigned total;
3731
3732         if (!qp || !dim)
3733                 goto error;
3734
3735         if (isl_space_is_equal(qp->dim, dim)) {
3736                 isl_space_free(dim);
3737                 return qp;
3738         }
3739
3740         qp = isl_qpolynomial_cow(qp);
3741         if (!qp)
3742                 goto error;
3743
3744         extra = isl_space_dim(dim, isl_dim_set) -
3745                         isl_space_dim(qp->dim, isl_dim_set);
3746         total = isl_space_dim(qp->dim, isl_dim_all);
3747         if (qp->div->n_row) {
3748                 int *exp;
3749
3750                 exp = isl_alloc_array(qp->div->ctx, int, qp->div->n_row);
3751                 if (!exp)
3752                         goto error;
3753                 for (i = 0; i < qp->div->n_row; ++i)
3754                         exp[i] = extra + i;
3755                 qp->upoly = expand(qp->upoly, exp, total);
3756                 free(exp);
3757                 if (!qp->upoly)
3758                         goto error;
3759         }
3760         qp->div = isl_mat_insert_cols(qp->div, 2 + total, extra);
3761         if (!qp->div)
3762                 goto error;
3763         for (i = 0; i < qp->div->n_row; ++i)
3764                 isl_seq_clr(qp->div->row[i] + 2 + total, extra);
3765
3766         isl_space_free(qp->dim);
3767         qp->dim = dim;
3768
3769         return qp;
3770 error:
3771         isl_space_free(dim);
3772         isl_qpolynomial_free(qp);
3773         return NULL;
3774 }
3775
3776 /* For each parameter or variable that does not appear in qp,
3777  * first eliminate the variable from all constraints and then set it to zero.
3778  */
3779 static __isl_give isl_set *fix_inactive(__isl_take isl_set *set,
3780         __isl_keep isl_qpolynomial *qp)
3781 {
3782         int *active = NULL;
3783         int i;
3784         int d;
3785         unsigned nparam;
3786         unsigned nvar;
3787
3788         if (!set || !qp)
3789                 goto error;
3790
3791         d = isl_space_dim(set->dim, isl_dim_all);
3792         active = isl_calloc_array(set->ctx, int, d);
3793         if (set_active(qp, active) < 0)
3794                 goto error;
3795
3796         for (i = 0; i < d; ++i)
3797                 if (!active[i])
3798                         break;
3799
3800         if (i == d) {
3801                 free(active);
3802                 return set;
3803         }
3804
3805         nparam = isl_space_dim(set->dim, isl_dim_param);
3806         nvar = isl_space_dim(set->dim, isl_dim_set);
3807         for (i = 0; i < nparam; ++i) {
3808                 if (active[i])
3809                         continue;
3810                 set = isl_set_eliminate(set, isl_dim_param, i, 1);
3811                 set = isl_set_fix_si(set, isl_dim_param, i, 0);
3812         }
3813         for (i = 0; i < nvar; ++i) {
3814                 if (active[nparam + i])
3815                         continue;
3816                 set = isl_set_eliminate(set, isl_dim_set, i, 1);
3817                 set = isl_set_fix_si(set, isl_dim_set, i, 0);
3818         }
3819
3820         free(active);
3821
3822         return set;
3823 error:
3824         free(active);
3825         isl_set_free(set);
3826         return NULL;
3827 }
3828
3829 struct isl_opt_data {
3830         isl_qpolynomial *qp;
3831         int first;
3832         isl_qpolynomial *opt;
3833         int max;
3834 };
3835
3836 static int opt_fn(__isl_take isl_point *pnt, void *user)
3837 {
3838         struct isl_opt_data *data = (struct isl_opt_data *)user;
3839         isl_qpolynomial *val;
3840
3841         val = isl_qpolynomial_eval(isl_qpolynomial_copy(data->qp), pnt);
3842         if (data->first) {
3843                 data->first = 0;
3844                 data->opt = val;
3845         } else if (data->max) {
3846                 data->opt = isl_qpolynomial_max_cst(data->opt, val);
3847         } else {
3848                 data->opt = isl_qpolynomial_min_cst(data->opt, val);
3849         }
3850
3851         return 0;
3852 }
3853
3854 __isl_give isl_qpolynomial *isl_qpolynomial_opt_on_domain(
3855         __isl_take isl_qpolynomial *qp, __isl_take isl_set *set, int max)
3856 {
3857         struct isl_opt_data data = { NULL, 1, NULL, max };
3858
3859         if (!set || !qp)
3860                 goto error;
3861
3862         if (isl_upoly_is_cst(qp->upoly)) {
3863                 isl_set_free(set);
3864                 return qp;
3865         }
3866
3867         set = fix_inactive(set, qp);
3868
3869         data.qp = qp;
3870         if (isl_set_foreach_point(set, opt_fn, &data) < 0)
3871                 goto error;
3872
3873         if (data.first) {
3874                 isl_space *space = isl_qpolynomial_get_domain_space(qp);
3875                 data.opt = isl_qpolynomial_zero_on_domain(space);
3876         }
3877
3878         isl_set_free(set);
3879         isl_qpolynomial_free(qp);
3880         return data.opt;
3881 error:
3882         isl_set_free(set);
3883         isl_qpolynomial_free(qp);
3884         isl_qpolynomial_free(data.opt);
3885         return NULL;
3886 }
3887
3888 __isl_give isl_qpolynomial *isl_qpolynomial_morph_domain(
3889         __isl_take isl_qpolynomial *qp, __isl_take isl_morph *morph)
3890 {
3891         int i;
3892         int n_sub;
3893         isl_ctx *ctx;
3894         struct isl_upoly **subs;
3895         isl_mat *mat, *diag;
3896
3897         qp = isl_qpolynomial_cow(qp);
3898         if (!qp || !morph)
3899                 goto error;
3900
3901         ctx = qp->dim->ctx;
3902         isl_assert(ctx, isl_space_is_equal(qp->dim, morph->dom->dim), goto error);
3903
3904         n_sub = morph->inv->n_row - 1;
3905         if (morph->inv->n_row != morph->inv->n_col)
3906                 n_sub += qp->div->n_row;
3907         subs = isl_calloc_array(ctx, struct isl_upoly *, n_sub);
3908         if (!subs)
3909                 goto error;
3910
3911         for (i = 0; 1 + i < morph->inv->n_row; ++i)
3912                 subs[i] = isl_upoly_from_affine(ctx, morph->inv->row[1 + i],
3913                                         morph->inv->row[0][0], morph->inv->n_col);
3914         if (morph->inv->n_row != morph->inv->n_col)
3915                 for (i = 0; i < qp->div->n_row; ++i)
3916                         subs[morph->inv->n_row - 1 + i] =
3917                             isl_upoly_var_pow(ctx, morph->inv->n_col - 1 + i, 1);
3918
3919         qp->upoly = isl_upoly_subs(qp->upoly, 0, n_sub, subs);
3920
3921         for (i = 0; i < n_sub; ++i)
3922                 isl_upoly_free(subs[i]);
3923         free(subs);
3924
3925         diag = isl_mat_diag(ctx, 1, morph->inv->row[0][0]);
3926         mat = isl_mat_diagonal(diag, isl_mat_copy(morph->inv));
3927         diag = isl_mat_diag(ctx, qp->div->n_row, morph->inv->row[0][0]);
3928         mat = isl_mat_diagonal(mat, diag);
3929         qp->div = isl_mat_product(qp->div, mat);
3930         isl_space_free(qp->dim);
3931         qp->dim = isl_space_copy(morph->ran->dim);
3932
3933         if (!qp->upoly || !qp->div || !qp->dim)
3934                 goto error;
3935
3936         isl_morph_free(morph);
3937
3938         return qp;
3939 error:
3940         isl_qpolynomial_free(qp);
3941         isl_morph_free(morph);
3942         return NULL;
3943 }
3944
3945 static int neg_entry(void **entry, void *user)
3946 {
3947         isl_pw_qpolynomial **pwqp = (isl_pw_qpolynomial **)entry;
3948
3949         *pwqp = isl_pw_qpolynomial_neg(*pwqp);
3950
3951         return *pwqp ? 0 : -1;
3952 }
3953
3954 __isl_give isl_union_pw_qpolynomial *isl_union_pw_qpolynomial_neg(
3955         __isl_take isl_union_pw_qpolynomial *upwqp)
3956 {
3957         upwqp = isl_union_pw_qpolynomial_cow(upwqp);
3958         if (!upwqp)
3959                 return NULL;
3960
3961         if (isl_hash_table_foreach(upwqp->dim->ctx, &upwqp->table,
3962                                    &neg_entry, NULL) < 0)
3963                 goto error;
3964
3965         return upwqp;
3966 error:
3967         isl_union_pw_qpolynomial_free(upwqp);
3968         return NULL;
3969 }
3970
3971 __isl_give isl_union_pw_qpolynomial *isl_union_pw_qpolynomial_mul(
3972         __isl_take isl_union_pw_qpolynomial *upwqp1,
3973         __isl_take isl_union_pw_qpolynomial *upwqp2)
3974 {
3975         return match_bin_op(upwqp1, upwqp2, &isl_pw_qpolynomial_mul);
3976 }
3977
3978 /* Reorder the columns of the given div definitions according to the
3979  * given reordering.
3980  */
3981 static __isl_give isl_mat *reorder_divs(__isl_take isl_mat *div,
3982         __isl_take isl_reordering *r)
3983 {
3984         int i, j;
3985         isl_mat *mat;
3986         int extra;
3987
3988         if (!div || !r)
3989                 goto error;
3990
3991         extra = isl_space_dim(r->dim, isl_dim_all) + div->n_row - r->len;
3992         mat = isl_mat_alloc(div->ctx, div->n_row, div->n_col + extra);
3993         if (!mat)
3994                 goto error;
3995
3996         for (i = 0; i < div->n_row; ++i) {
3997                 isl_seq_cpy(mat->row[i], div->row[i], 2);
3998                 isl_seq_clr(mat->row[i] + 2, mat->n_col - 2);
3999                 for (j = 0; j < r->len; ++j)
4000                         isl_int_set(mat->row[i][2 + r->pos[j]],
4001                                     div->row[i][2 + j]);
4002         }
4003
4004         isl_reordering_free(r);
4005         isl_mat_free(div);
4006         return mat;
4007 error:
4008         isl_reordering_free(r);
4009         isl_mat_free(div);
4010         return NULL;
4011 }
4012
4013 /* Reorder the dimension of "qp" according to the given reordering.
4014  */
4015 __isl_give isl_qpolynomial *isl_qpolynomial_realign_domain(
4016         __isl_take isl_qpolynomial *qp, __isl_take isl_reordering *r)
4017 {
4018         qp = isl_qpolynomial_cow(qp);
4019         if (!qp)
4020                 goto error;
4021
4022         r = isl_reordering_extend(r, qp->div->n_row);
4023         if (!r)
4024                 goto error;
4025
4026         qp->div = reorder_divs(qp->div, isl_reordering_copy(r));
4027         if (!qp->div)
4028                 goto error;
4029
4030         qp->upoly = reorder(qp->upoly, r->pos);
4031         if (!qp->upoly)
4032                 goto error;
4033
4034         qp = isl_qpolynomial_reset_domain_space(qp, isl_space_copy(r->dim));
4035
4036         isl_reordering_free(r);
4037         return qp;
4038 error:
4039         isl_qpolynomial_free(qp);
4040         isl_reordering_free(r);
4041         return NULL;
4042 }
4043
4044 __isl_give isl_qpolynomial *isl_qpolynomial_align_params(
4045         __isl_take isl_qpolynomial *qp, __isl_take isl_space *model)
4046 {
4047         if (!qp || !model)
4048                 goto error;
4049
4050         if (!isl_space_match(qp->dim, isl_dim_param, model, isl_dim_param)) {
4051                 isl_reordering *exp;
4052
4053                 model = isl_space_drop_dims(model, isl_dim_in,
4054                                         0, isl_space_dim(model, isl_dim_in));
4055                 model = isl_space_drop_dims(model, isl_dim_out,
4056                                         0, isl_space_dim(model, isl_dim_out));
4057                 exp = isl_parameter_alignment_reordering(qp->dim, model);
4058                 exp = isl_reordering_extend_space(exp,
4059                                         isl_qpolynomial_get_domain_space(qp));
4060                 qp = isl_qpolynomial_realign_domain(qp, exp);
4061         }
4062
4063         isl_space_free(model);
4064         return qp;
4065 error:
4066         isl_space_free(model);
4067         isl_qpolynomial_free(qp);
4068         return NULL;
4069 }
4070
4071 struct isl_split_periods_data {
4072         int max_periods;
4073         isl_pw_qpolynomial *res;
4074 };
4075
4076 /* Create a slice where the integer division "div" has the fixed value "v".
4077  * In particular, if "div" refers to floor(f/m), then create a slice
4078  *
4079  *      m v <= f <= m v + (m - 1)
4080  *
4081  * or
4082  *
4083  *      f - m v >= 0
4084  *      -f + m v + (m - 1) >= 0
4085  */
4086 static __isl_give isl_set *set_div_slice(__isl_take isl_space *dim,
4087         __isl_keep isl_qpolynomial *qp, int div, isl_int v)
4088 {
4089         int total;
4090         isl_basic_set *bset = NULL;
4091         int k;
4092
4093         if (!dim || !qp)
4094                 goto error;
4095
4096         total = isl_space_dim(dim, isl_dim_all);
4097         bset = isl_basic_set_alloc_space(isl_space_copy(dim), 0, 0, 2);
4098
4099         k = isl_basic_set_alloc_inequality(bset);
4100         if (k < 0)
4101                 goto error;
4102         isl_seq_cpy(bset->ineq[k], qp->div->row[div] + 1, 1 + total);
4103         isl_int_submul(bset->ineq[k][0], v, qp->div->row[div][0]);
4104
4105         k = isl_basic_set_alloc_inequality(bset);
4106         if (k < 0)
4107                 goto error;
4108         isl_seq_neg(bset->ineq[k], qp->div->row[div] + 1, 1 + total);
4109         isl_int_addmul(bset->ineq[k][0], v, qp->div->row[div][0]);
4110         isl_int_add(bset->ineq[k][0], bset->ineq[k][0], qp->div->row[div][0]);
4111         isl_int_sub_ui(bset->ineq[k][0], bset->ineq[k][0], 1);
4112
4113         isl_space_free(dim);
4114         return isl_set_from_basic_set(bset);
4115 error:
4116         isl_basic_set_free(bset);
4117         isl_space_free(dim);
4118         return NULL;
4119 }
4120
4121 static int split_periods(__isl_take isl_set *set,
4122         __isl_take isl_qpolynomial *qp, void *user);
4123
4124 /* Create a slice of the domain "set" such that integer division "div"
4125  * has the fixed value "v" and add the results to data->res,
4126  * replacing the integer division by "v" in "qp".
4127  */
4128 static int set_div(__isl_take isl_set *set,
4129         __isl_take isl_qpolynomial *qp, int div, isl_int v,
4130         struct isl_split_periods_data *data)
4131 {
4132         int i;
4133         int total;
4134         isl_set *slice;
4135         struct isl_upoly *cst;
4136
4137         slice = set_div_slice(isl_set_get_space(set), qp, div, v);
4138         set = isl_set_intersect(set, slice);
4139
4140         if (!qp)
4141                 goto error;
4142
4143         total = isl_space_dim(qp->dim, isl_dim_all);
4144
4145         for (i = div + 1; i < qp->div->n_row; ++i) {
4146                 if (isl_int_is_zero(qp->div->row[i][2 + total + div]))
4147                         continue;
4148                 isl_int_addmul(qp->div->row[i][1],
4149                                 qp->div->row[i][2 + total + div], v);
4150                 isl_int_set_si(qp->div->row[i][2 + total + div], 0);
4151         }
4152
4153         cst = isl_upoly_rat_cst(qp->dim->ctx, v, qp->dim->ctx->one);
4154         qp = substitute_div(qp, div, cst);
4155
4156         return split_periods(set, qp, data);
4157 error:
4158         isl_set_free(set);
4159         isl_qpolynomial_free(qp);
4160         return -1;
4161 }
4162
4163 /* Split the domain "set" such that integer division "div"
4164  * has a fixed value (ranging from "min" to "max") on each slice
4165  * and add the results to data->res.
4166  */
4167 static int split_div(__isl_take isl_set *set,
4168         __isl_take isl_qpolynomial *qp, int div, isl_int min, isl_int max,
4169         struct isl_split_periods_data *data)
4170 {
4171         for (; isl_int_le(min, max); isl_int_add_ui(min, min, 1)) {
4172                 isl_set *set_i = isl_set_copy(set);
4173                 isl_qpolynomial *qp_i = isl_qpolynomial_copy(qp);
4174
4175                 if (set_div(set_i, qp_i, div, min, data) < 0)
4176                         goto error;
4177         }
4178         isl_set_free(set);
4179         isl_qpolynomial_free(qp);
4180         return 0;
4181 error:
4182         isl_set_free(set);
4183         isl_qpolynomial_free(qp);
4184         return -1;
4185 }
4186
4187 /* If "qp" refers to any integer division
4188  * that can only attain "max_periods" distinct values on "set"
4189  * then split the domain along those distinct values.
4190  * Add the results (or the original if no splitting occurs)
4191  * to data->res.
4192  */
4193 static int split_periods(__isl_take isl_set *set,
4194         __isl_take isl_qpolynomial *qp, void *user)
4195 {
4196         int i;
4197         isl_pw_qpolynomial *pwqp;
4198         struct isl_split_periods_data *data;
4199         isl_int min, max;
4200         int total;
4201         int r = 0;
4202
4203         data = (struct isl_split_periods_data *)user;
4204
4205         if (!set || !qp)
4206                 goto error;
4207
4208         if (qp->div->n_row == 0) {
4209                 pwqp = isl_pw_qpolynomial_alloc(set, qp);
4210                 data->res = isl_pw_qpolynomial_add_disjoint(data->res, pwqp);
4211                 return 0;
4212         }
4213
4214         isl_int_init(min);
4215         isl_int_init(max);
4216         total = isl_space_dim(qp->dim, isl_dim_all);
4217         for (i = 0; i < qp->div->n_row; ++i) {
4218                 enum isl_lp_result lp_res;
4219
4220                 if (isl_seq_first_non_zero(qp->div->row[i] + 2 + total,
4221                                                 qp->div->n_row) != -1)
4222                         continue;
4223
4224                 lp_res = isl_set_solve_lp(set, 0, qp->div->row[i] + 1,
4225                                           set->ctx->one, &min, NULL, NULL);
4226                 if (lp_res == isl_lp_error)
4227                         goto error2;
4228                 if (lp_res == isl_lp_unbounded || lp_res == isl_lp_empty)
4229                         continue;
4230                 isl_int_fdiv_q(min, min, qp->div->row[i][0]);
4231
4232                 lp_res = isl_set_solve_lp(set, 1, qp->div->row[i] + 1,
4233                                           set->ctx->one, &max, NULL, NULL);
4234                 if (lp_res == isl_lp_error)
4235                         goto error2;
4236                 if (lp_res == isl_lp_unbounded || lp_res == isl_lp_empty)
4237                         continue;
4238                 isl_int_fdiv_q(max, max, qp->div->row[i][0]);
4239
4240                 isl_int_sub(max, max, min);
4241                 if (isl_int_cmp_si(max, data->max_periods) < 0) {
4242                         isl_int_add(max, max, min);
4243                         break;
4244                 }
4245         }
4246
4247         if (i < qp->div->n_row) {
4248                 r = split_div(set, qp, i, min, max, data);
4249         } else {
4250                 pwqp = isl_pw_qpolynomial_alloc(set, qp);
4251                 data->res = isl_pw_qpolynomial_add_disjoint(data->res, pwqp);
4252         }
4253
4254         isl_int_clear(max);
4255         isl_int_clear(min);
4256
4257         return r;
4258 error2:
4259         isl_int_clear(max);
4260         isl_int_clear(min);
4261 error:
4262         isl_set_free(set);
4263         isl_qpolynomial_free(qp);
4264         return -1;
4265 }
4266
4267 /* If any quasi-polynomial in pwqp refers to any integer division
4268  * that can only attain "max_periods" distinct values on its domain
4269  * then split the domain along those distinct values.
4270  */
4271 __isl_give isl_pw_qpolynomial *isl_pw_qpolynomial_split_periods(
4272         __isl_take isl_pw_qpolynomial *pwqp, int max_periods)
4273 {
4274         struct isl_split_periods_data data;
4275
4276         data.max_periods = max_periods;
4277         data.res = isl_pw_qpolynomial_zero(isl_pw_qpolynomial_get_space(pwqp));
4278
4279         if (isl_pw_qpolynomial_foreach_piece(pwqp, &split_periods, &data) < 0)
4280                 goto error;
4281
4282         isl_pw_qpolynomial_free(pwqp);
4283
4284         return data.res;
4285 error:
4286         isl_pw_qpolynomial_free(data.res);
4287         isl_pw_qpolynomial_free(pwqp);
4288         return NULL;
4289 }
4290
4291 /* Construct a piecewise quasipolynomial that is constant on the given
4292  * domain.  In particular, it is
4293  *      0       if cst == 0
4294  *      1       if cst == 1
4295  *  infinity    if cst == -1
4296  */
4297 static __isl_give isl_pw_qpolynomial *constant_on_domain(
4298         __isl_take isl_basic_set *bset, int cst)
4299 {
4300         isl_space *dim;
4301         isl_qpolynomial *qp;
4302
4303         if (!bset)
4304                 return NULL;
4305
4306         bset = isl_basic_set_params(bset);
4307         dim = isl_basic_set_get_space(bset);
4308         if (cst < 0)
4309                 qp = isl_qpolynomial_infty_on_domain(dim);
4310         else if (cst == 0)
4311                 qp = isl_qpolynomial_zero_on_domain(dim);
4312         else
4313                 qp = isl_qpolynomial_one_on_domain(dim);
4314         return isl_pw_qpolynomial_alloc(isl_set_from_basic_set(bset), qp);
4315 }
4316
4317 /* Factor bset, call fn on each of the factors and return the product.
4318  *
4319  * If no factors can be found, simply call fn on the input.
4320  * Otherwise, construct the factors based on the factorizer,
4321  * call fn on each factor and compute the product.
4322  */
4323 static __isl_give isl_pw_qpolynomial *compressed_multiplicative_call(
4324         __isl_take isl_basic_set *bset,
4325         __isl_give isl_pw_qpolynomial *(*fn)(__isl_take isl_basic_set *bset))
4326 {
4327         int i, n;
4328         isl_space *dim;
4329         isl_set *set;
4330         isl_factorizer *f;
4331         isl_qpolynomial *qp;
4332         isl_pw_qpolynomial *pwqp;
4333         unsigned nparam;
4334         unsigned nvar;
4335
4336         f = isl_basic_set_factorizer(bset);
4337         if (!f)
4338                 goto error;
4339         if (f->n_group == 0) {
4340                 isl_factorizer_free(f);
4341                 return fn(bset);
4342         }
4343
4344         nparam = isl_basic_set_dim(bset, isl_dim_param);
4345         nvar = isl_basic_set_dim(bset, isl_dim_set);
4346
4347         dim = isl_basic_set_get_space(bset);
4348         dim = isl_space_domain(dim);
4349         set = isl_set_universe(isl_space_copy(dim));
4350         qp = isl_qpolynomial_one_on_domain(dim);
4351         pwqp = isl_pw_qpolynomial_alloc(set, qp);
4352
4353         bset = isl_morph_basic_set(isl_morph_copy(f->morph), bset);
4354
4355         for (i = 0, n = 0; i < f->n_group; ++i) {
4356                 isl_basic_set *bset_i;
4357                 isl_pw_qpolynomial *pwqp_i;
4358
4359                 bset_i = isl_basic_set_copy(bset);
4360                 bset_i = isl_basic_set_drop_constraints_involving(bset_i,
4361                             nparam + n + f->len[i], nvar - n - f->len[i]);
4362                 bset_i = isl_basic_set_drop_constraints_involving(bset_i,
4363                             nparam, n);
4364                 bset_i = isl_basic_set_drop(bset_i, isl_dim_set,
4365                             n + f->len[i], nvar - n - f->len[i]);
4366                 bset_i = isl_basic_set_drop(bset_i, isl_dim_set, 0, n);
4367
4368                 pwqp_i = fn(bset_i);
4369                 pwqp = isl_pw_qpolynomial_mul(pwqp, pwqp_i);
4370
4371                 n += f->len[i];
4372         }
4373
4374         isl_basic_set_free(bset);
4375         isl_factorizer_free(f);
4376
4377         return pwqp;
4378 error:
4379         isl_basic_set_free(bset);
4380         return NULL;
4381 }
4382
4383 /* Factor bset, call fn on each of the factors and return the product.
4384  * The function is assumed to evaluate to zero on empty domains,
4385  * to one on zero-dimensional domains and to infinity on unbounded domains
4386  * and will not be called explicitly on zero-dimensional or unbounded domains.
4387  *
4388  * We first check for some special cases and remove all equalities.
4389  * Then we hand over control to compressed_multiplicative_call.
4390  */
4391 __isl_give isl_pw_qpolynomial *isl_basic_set_multiplicative_call(
4392         __isl_take isl_basic_set *bset,
4393         __isl_give isl_pw_qpolynomial *(*fn)(__isl_take isl_basic_set *bset))
4394 {
4395         int bounded;
4396         isl_morph *morph;
4397         isl_pw_qpolynomial *pwqp;
4398
4399         if (!bset)
4400                 return NULL;
4401
4402         if (isl_basic_set_plain_is_empty(bset))
4403                 return constant_on_domain(bset, 0);
4404
4405         if (isl_basic_set_dim(bset, isl_dim_set) == 0)
4406                 return constant_on_domain(bset, 1);
4407
4408         bounded = isl_basic_set_is_bounded(bset);
4409         if (bounded < 0)
4410                 goto error;
4411         if (!bounded)
4412                 return constant_on_domain(bset, -1);
4413
4414         if (bset->n_eq == 0)
4415                 return compressed_multiplicative_call(bset, fn);
4416
4417         morph = isl_basic_set_full_compression(bset);
4418         bset = isl_morph_basic_set(isl_morph_copy(morph), bset);
4419
4420         pwqp = compressed_multiplicative_call(bset, fn);
4421
4422         morph = isl_morph_dom_params(morph);
4423         morph = isl_morph_ran_params(morph);
4424         morph = isl_morph_inverse(morph);
4425
4426         pwqp = isl_pw_qpolynomial_morph_domain(pwqp, morph);
4427
4428         return pwqp;
4429 error:
4430         isl_basic_set_free(bset);
4431         return NULL;
4432 }
4433
4434 /* Drop all floors in "qp", turning each integer division [a/m] into
4435  * a rational division a/m.  If "down" is set, then the integer division
4436  * is replaces by (a-(m-1))/m instead.
4437  */
4438 static __isl_give isl_qpolynomial *qp_drop_floors(
4439         __isl_take isl_qpolynomial *qp, int down)
4440 {
4441         int i;
4442         struct isl_upoly *s;
4443
4444         if (!qp)
4445                 return NULL;
4446         if (qp->div->n_row == 0)
4447                 return qp;
4448
4449         qp = isl_qpolynomial_cow(qp);
4450         if (!qp)
4451                 return NULL;
4452
4453         for (i = qp->div->n_row - 1; i >= 0; --i) {
4454                 if (down) {
4455                         isl_int_sub(qp->div->row[i][1],
4456                                     qp->div->row[i][1], qp->div->row[i][0]);
4457                         isl_int_add_ui(qp->div->row[i][1],
4458                                        qp->div->row[i][1], 1);
4459                 }
4460                 s = isl_upoly_from_affine(qp->dim->ctx, qp->div->row[i] + 1,
4461                                         qp->div->row[i][0], qp->div->n_col - 1);
4462                 qp = substitute_div(qp, i, s);
4463                 if (!qp)
4464                         return NULL;
4465         }
4466
4467         return qp;
4468 }
4469
4470 /* Drop all floors in "pwqp", turning each integer division [a/m] into
4471  * a rational division a/m.
4472  */
4473 static __isl_give isl_pw_qpolynomial *pwqp_drop_floors(
4474         __isl_take isl_pw_qpolynomial *pwqp)
4475 {
4476         int i;
4477
4478         if (!pwqp)
4479                 return NULL;
4480
4481         if (isl_pw_qpolynomial_is_zero(pwqp))
4482                 return pwqp;
4483
4484         pwqp = isl_pw_qpolynomial_cow(pwqp);
4485         if (!pwqp)
4486                 return NULL;
4487
4488         for (i = 0; i < pwqp->n; ++i) {
4489                 pwqp->p[i].qp = qp_drop_floors(pwqp->p[i].qp, 0);
4490                 if (!pwqp->p[i].qp)
4491                         goto error;
4492         }
4493
4494         return pwqp;
4495 error:
4496         isl_pw_qpolynomial_free(pwqp);
4497         return NULL;
4498 }
4499
4500 /* Adjust all the integer divisions in "qp" such that they are at least
4501  * one over the given orthant (identified by "signs").  This ensures
4502  * that they will still be non-negative even after subtracting (m-1)/m.
4503  *
4504  * In particular, f is replaced by f' + v, changing f = [a/m]
4505  * to f' = [(a - m v)/m].
4506  * If the constant term k in a is smaller than m,
4507  * the constant term of v is set to floor(k/m) - 1.
4508  * For any other term, if the coefficient c and the variable x have
4509  * the same sign, then no changes are needed.
4510  * Otherwise, if the variable is positive (and c is negative),
4511  * then the coefficient of x in v is set to floor(c/m).
4512  * If the variable is negative (and c is positive),
4513  * then the coefficient of x in v is set to ceil(c/m).
4514  */
4515 static __isl_give isl_qpolynomial *make_divs_pos(__isl_take isl_qpolynomial *qp,
4516         int *signs)
4517 {
4518         int i, j;
4519         int total;
4520         isl_vec *v = NULL;
4521         struct isl_upoly *s;
4522
4523         qp = isl_qpolynomial_cow(qp);
4524         if (!qp)
4525                 return NULL;
4526         qp->div = isl_mat_cow(qp->div);
4527         if (!qp->div)
4528                 goto error;
4529
4530         total = isl_space_dim(qp->dim, isl_dim_all);
4531         v = isl_vec_alloc(qp->div->ctx, qp->div->n_col - 1);
4532
4533         for (i = 0; i < qp->div->n_row; ++i) {
4534                 isl_int *row = qp->div->row[i];
4535                 v = isl_vec_clr(v);
4536                 if (!v)
4537                         goto error;
4538                 if (isl_int_lt(row[1], row[0])) {
4539                         isl_int_fdiv_q(v->el[0], row[1], row[0]);
4540                         isl_int_sub_ui(v->el[0], v->el[0], 1);
4541                         isl_int_submul(row[1], row[0], v->el[0]);
4542                 }
4543                 for (j = 0; j < total; ++j) {
4544                         if (isl_int_sgn(row[2 + j]) * signs[j] >= 0)
4545                                 continue;
4546                         if (signs[j] < 0)
4547                                 isl_int_cdiv_q(v->el[1 + j], row[2 + j], row[0]);
4548                         else
4549                                 isl_int_fdiv_q(v->el[1 + j], row[2 + j], row[0]);
4550                         isl_int_submul(row[2 + j], row[0], v->el[1 + j]);
4551                 }
4552                 for (j = 0; j < i; ++j) {
4553                         if (isl_int_sgn(row[2 + total + j]) >= 0)
4554                                 continue;
4555                         isl_int_fdiv_q(v->el[1 + total + j],
4556                                         row[2 + total + j], row[0]);
4557                         isl_int_submul(row[2 + total + j],
4558                                         row[0], v->el[1 + total + j]);
4559                 }
4560                 for (j = i + 1; j < qp->div->n_row; ++j) {
4561                         if (isl_int_is_zero(qp->div->row[j][2 + total + i]))
4562                                 continue;
4563                         isl_seq_combine(qp->div->row[j] + 1,
4564                                 qp->div->ctx->one, qp->div->row[j] + 1,
4565                                 qp->div->row[j][2 + total + i], v->el, v->size);
4566                 }
4567                 isl_int_set_si(v->el[1 + total + i], 1);
4568                 s = isl_upoly_from_affine(qp->dim->ctx, v->el,
4569                                         qp->div->ctx->one, v->size);
4570                 qp->upoly = isl_upoly_subs(qp->upoly, total + i, 1, &s);
4571                 isl_upoly_free(s);
4572                 if (!qp->upoly)
4573                         goto error;
4574         }
4575
4576         isl_vec_free(v);
4577         return qp;
4578 error:
4579         isl_vec_free(v);
4580         isl_qpolynomial_free(qp);
4581         return NULL;
4582 }
4583
4584 struct isl_to_poly_data {
4585         int sign;
4586         isl_pw_qpolynomial *res;
4587         isl_qpolynomial *qp;
4588 };
4589
4590 /* Appoximate data->qp by a polynomial on the orthant identified by "signs".
4591  * We first make all integer divisions positive and then split the
4592  * quasipolynomials into terms with sign data->sign (the direction
4593  * of the requested approximation) and terms with the opposite sign.
4594  * In the first set of terms, each integer division [a/m] is
4595  * overapproximated by a/m, while in the second it is underapproximated
4596  * by (a-(m-1))/m.
4597  */
4598 static int to_polynomial_on_orthant(__isl_take isl_set *orthant, int *signs,
4599         void *user)
4600 {
4601         struct isl_to_poly_data *data = user;
4602         isl_pw_qpolynomial *t;
4603         isl_qpolynomial *qp, *up, *down;
4604
4605         qp = isl_qpolynomial_copy(data->qp);
4606         qp = make_divs_pos(qp, signs);
4607
4608         up = isl_qpolynomial_terms_of_sign(qp, signs, data->sign);
4609         up = qp_drop_floors(up, 0);
4610         down = isl_qpolynomial_terms_of_sign(qp, signs, -data->sign);
4611         down = qp_drop_floors(down, 1);
4612
4613         isl_qpolynomial_free(qp);
4614         qp = isl_qpolynomial_add(up, down);
4615
4616         t = isl_pw_qpolynomial_alloc(orthant, qp);
4617         data->res = isl_pw_qpolynomial_add_disjoint(data->res, t);
4618
4619         return 0;
4620 }
4621
4622 /* Approximate each quasipolynomial by a polynomial.  If "sign" is positive,
4623  * the polynomial will be an overapproximation.  If "sign" is negative,
4624  * it will be an underapproximation.  If "sign" is zero, the approximation
4625  * will lie somewhere in between.
4626  *
4627  * In particular, is sign == 0, we simply drop the floors, turning
4628  * the integer divisions into rational divisions.
4629  * Otherwise, we split the domains into orthants, make all integer divisions
4630  * positive and then approximate each [a/m] by either a/m or (a-(m-1))/m,
4631  * depending on the requested sign and the sign of the term in which
4632  * the integer division appears.
4633  */
4634 __isl_give isl_pw_qpolynomial *isl_pw_qpolynomial_to_polynomial(
4635         __isl_take isl_pw_qpolynomial *pwqp, int sign)
4636 {
4637         int i;
4638         struct isl_to_poly_data data;
4639
4640         if (sign == 0)
4641                 return pwqp_drop_floors(pwqp);
4642
4643         if (!pwqp)
4644                 return NULL;
4645
4646         data.sign = sign;
4647         data.res = isl_pw_qpolynomial_zero(isl_pw_qpolynomial_get_space(pwqp));
4648
4649         for (i = 0; i < pwqp->n; ++i) {
4650                 if (pwqp->p[i].qp->div->n_row == 0) {
4651                         isl_pw_qpolynomial *t;
4652                         t = isl_pw_qpolynomial_alloc(
4653                                         isl_set_copy(pwqp->p[i].set),
4654                                         isl_qpolynomial_copy(pwqp->p[i].qp));
4655                         data.res = isl_pw_qpolynomial_add_disjoint(data.res, t);
4656                         continue;
4657                 }
4658                 data.qp = pwqp->p[i].qp;
4659                 if (isl_set_foreach_orthant(pwqp->p[i].set,
4660                                         &to_polynomial_on_orthant, &data) < 0)
4661                         goto error;
4662         }
4663
4664         isl_pw_qpolynomial_free(pwqp);
4665
4666         return data.res;
4667 error:
4668         isl_pw_qpolynomial_free(pwqp);
4669         isl_pw_qpolynomial_free(data.res);
4670         return NULL;
4671 }
4672
4673 static int poly_entry(void **entry, void *user)
4674 {
4675         int *sign = user;
4676         isl_pw_qpolynomial **pwqp = (isl_pw_qpolynomial **)entry;
4677
4678         *pwqp = isl_pw_qpolynomial_to_polynomial(*pwqp, *sign);
4679
4680         return *pwqp ? 0 : -1;
4681 }
4682
4683 __isl_give isl_union_pw_qpolynomial *isl_union_pw_qpolynomial_to_polynomial(
4684         __isl_take isl_union_pw_qpolynomial *upwqp, int sign)
4685 {
4686         upwqp = isl_union_pw_qpolynomial_cow(upwqp);
4687         if (!upwqp)
4688                 return NULL;
4689
4690         if (isl_hash_table_foreach(upwqp->dim->ctx, &upwqp->table,
4691                                    &poly_entry, &sign) < 0)
4692                 goto error;
4693
4694         return upwqp;
4695 error:
4696         isl_union_pw_qpolynomial_free(upwqp);
4697         return NULL;
4698 }
4699
4700 __isl_give isl_basic_map *isl_basic_map_from_qpolynomial(
4701         __isl_take isl_qpolynomial *qp)
4702 {
4703         int i, k;
4704         isl_space *dim;
4705         isl_vec *aff = NULL;
4706         isl_basic_map *bmap = NULL;
4707         unsigned pos;
4708         unsigned n_div;
4709
4710         if (!qp)
4711                 return NULL;
4712         if (!isl_upoly_is_affine(qp->upoly))
4713                 isl_die(qp->dim->ctx, isl_error_invalid,
4714                         "input quasi-polynomial not affine", goto error);
4715         aff = isl_qpolynomial_extract_affine(qp);
4716         if (!aff)
4717                 goto error;
4718         dim = isl_qpolynomial_get_space(qp);
4719         pos = 1 + isl_space_offset(dim, isl_dim_out);
4720         n_div = qp->div->n_row;
4721         bmap = isl_basic_map_alloc_space(dim, n_div, 1, 2 * n_div);
4722
4723         for (i = 0; i < n_div; ++i) {
4724                 k = isl_basic_map_alloc_div(bmap);
4725                 if (k < 0)
4726                         goto error;
4727                 isl_seq_cpy(bmap->div[k], qp->div->row[i], qp->div->n_col);
4728                 isl_int_set_si(bmap->div[k][qp->div->n_col], 0);
4729                 if (isl_basic_map_add_div_constraints(bmap, k) < 0)
4730                         goto error;
4731         }
4732         k = isl_basic_map_alloc_equality(bmap);
4733         if (k < 0)
4734                 goto error;
4735         isl_int_neg(bmap->eq[k][pos], aff->el[0]);
4736         isl_seq_cpy(bmap->eq[k], aff->el + 1, pos);
4737         isl_seq_cpy(bmap->eq[k] + pos + 1, aff->el + 1 + pos, n_div);
4738
4739         isl_vec_free(aff);
4740         isl_qpolynomial_free(qp);
4741         bmap = isl_basic_map_finalize(bmap);
4742         return bmap;
4743 error:
4744         isl_vec_free(aff);
4745         isl_qpolynomial_free(qp);
4746         isl_basic_map_free(bmap);
4747         return NULL;
4748 }