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