1 /*
2  * Copyright 2008-2009 Katholieke Universiteit Leuven
3  * Copyright 2010      INRIA Saclay
4  * Copyright 2012-2013 Ecole Normale Superieure
5  * Copyright 2014      INRIA Rocquencourt
6  * Copyright 2016      INRIA Paris
7  * Copyright 2020      Cerebras Systems
8  *
9  * Use of this software is governed by the MIT license
10  *
11  * Written by Sven Verdoolaege, K.U.Leuven, Departement
12  * Computerwetenschappen, Celestijnenlaan 200A, B-3001 Leuven, Belgium
13  * and INRIA Saclay - Ile-de-France, Parc Club Orsay Universite,
14  * ZAC des vignes, 4 rue Jacques Monod, 91893 Orsay, France
15  * and Ecole Normale Superieure, 45 rue d’Ulm, 75230 Paris, France
16  * and Inria Paris - Rocquencourt, Domaine de Voluceau - Rocquencourt,
17  * B.P. 105 - 78153 Le Chesnay, France
18  * and Centre de Recherche Inria de Paris, 2 rue Simone Iff - Voie DQ12,
19  * CS 42112, 75589 Paris Cedex 12, France
20  * and Cerebras Systems, 175 S San Antonio Rd, Los Altos, CA, USA
21  */
22 
23 #include <isl_ctx_private.h>
24 #include "isl_map_private.h"
25 #include <isl_seq.h>
26 #include <isl/options.h>
27 #include "isl_tab.h"
28 #include <isl_mat_private.h>
29 #include <isl_local_space_private.h>
30 #include <isl_val_private.h>
31 #include <isl_vec_private.h>
32 #include <isl_aff_private.h>
33 #include <isl_equalities.h>
34 #include <isl_constraint_private.h>
35 
36 #include <set_to_map.c>
37 #include <set_from_map.c>
38 
39 #define STATUS_ERROR		-1
40 #define STATUS_REDUNDANT	 1
41 #define STATUS_VALID	 	 2
42 #define STATUS_SEPARATE	 	 3
43 #define STATUS_CUT	 	 4
44 #define STATUS_ADJ_EQ	 	 5
45 #define STATUS_ADJ_INEQ	 	 6
46 
status_in(isl_int * ineq,struct isl_tab * tab)47 static int status_in(isl_int *ineq, struct isl_tab *tab)
48 {
49 	enum isl_ineq_type type = isl_tab_ineq_type(tab, ineq);
50 	switch (type) {
51 	default:
52 	case isl_ineq_error:		return STATUS_ERROR;
53 	case isl_ineq_redundant:	return STATUS_VALID;
54 	case isl_ineq_separate:		return STATUS_SEPARATE;
55 	case isl_ineq_cut:		return STATUS_CUT;
56 	case isl_ineq_adj_eq:		return STATUS_ADJ_EQ;
57 	case isl_ineq_adj_ineq:		return STATUS_ADJ_INEQ;
58 	}
59 }
60 
61 /* Compute the position of the equalities of basic map "bmap_i"
62  * with respect to the basic map represented by "tab_j".
63  * The resulting array has twice as many entries as the number
64  * of equalities corresponding to the two inequalities to which
65  * each equality corresponds.
66  */
eq_status_in(__isl_keep isl_basic_map * bmap_i,struct isl_tab * tab_j)67 static int *eq_status_in(__isl_keep isl_basic_map *bmap_i,
68 	struct isl_tab *tab_j)
69 {
70 	int k, l;
71 	int *eq;
72 	isl_size dim;
73 
74 	dim = isl_basic_map_dim(bmap_i, isl_dim_all);
75 	if (dim < 0)
76 		return NULL;
77 
78 	eq = isl_calloc_array(bmap_i->ctx, int, 2 * bmap_i->n_eq);
79 	if (!eq)
80 		return NULL;
81 
82 	for (k = 0; k < bmap_i->n_eq; ++k) {
83 		for (l = 0; l < 2; ++l) {
84 			isl_seq_neg(bmap_i->eq[k], bmap_i->eq[k], 1+dim);
85 			eq[2 * k + l] = status_in(bmap_i->eq[k], tab_j);
86 			if (eq[2 * k + l] == STATUS_ERROR)
87 				goto error;
88 		}
89 	}
90 
91 	return eq;
92 error:
93 	free(eq);
94 	return NULL;
95 }
96 
97 /* Compute the position of the inequalities of basic map "bmap_i"
98  * (also represented by "tab_i", if not NULL) with respect to the basic map
99  * represented by "tab_j".
100  */
ineq_status_in(__isl_keep isl_basic_map * bmap_i,struct isl_tab * tab_i,struct isl_tab * tab_j)101 static int *ineq_status_in(__isl_keep isl_basic_map *bmap_i,
102 	struct isl_tab *tab_i, struct isl_tab *tab_j)
103 {
104 	int k;
105 	unsigned n_eq = bmap_i->n_eq;
106 	int *ineq = isl_calloc_array(bmap_i->ctx, int, bmap_i->n_ineq);
107 
108 	if (!ineq)
109 		return NULL;
110 
111 	for (k = 0; k < bmap_i->n_ineq; ++k) {
112 		if (tab_i && isl_tab_is_redundant(tab_i, n_eq + k)) {
113 			ineq[k] = STATUS_REDUNDANT;
114 			continue;
115 		}
116 		ineq[k] = status_in(bmap_i->ineq[k], tab_j);
117 		if (ineq[k] == STATUS_ERROR)
118 			goto error;
119 		if (ineq[k] == STATUS_SEPARATE)
120 			break;
121 	}
122 
123 	return ineq;
124 error:
125 	free(ineq);
126 	return NULL;
127 }
128 
any(int * con,unsigned len,int status)129 static int any(int *con, unsigned len, int status)
130 {
131 	int i;
132 
133 	for (i = 0; i < len ; ++i)
134 		if (con[i] == status)
135 			return 1;
136 	return 0;
137 }
138 
139 /* Return the first position of "status" in the list "con" of length "len".
140  * Return -1 if there is no such entry.
141  */
find(int * con,unsigned len,int status)142 static int find(int *con, unsigned len, int status)
143 {
144 	int i;
145 
146 	for (i = 0; i < len ; ++i)
147 		if (con[i] == status)
148 			return i;
149 	return -1;
150 }
151 
count(int * con,unsigned len,int status)152 static int count(int *con, unsigned len, int status)
153 {
154 	int i;
155 	int c = 0;
156 
157 	for (i = 0; i < len ; ++i)
158 		if (con[i] == status)
159 			c++;
160 	return c;
161 }
162 
all(int * con,unsigned len,int status)163 static int all(int *con, unsigned len, int status)
164 {
165 	int i;
166 
167 	for (i = 0; i < len ; ++i) {
168 		if (con[i] == STATUS_REDUNDANT)
169 			continue;
170 		if (con[i] != status)
171 			return 0;
172 	}
173 	return 1;
174 }
175 
176 /* Internal information associated to a basic map in a map
177  * that is to be coalesced by isl_map_coalesce.
178  *
179  * "bmap" is the basic map itself (or NULL if "removed" is set)
180  * "tab" is the corresponding tableau (or NULL if "removed" is set)
181  * "hull_hash" identifies the affine space in which "bmap" lives.
182  * "modified" is set if this basic map may not be identical
183  * to any of the basic maps in the input.
184  * "removed" is set if this basic map has been removed from the map
185  * "simplify" is set if this basic map may have some unknown integer
186  * divisions that were not present in the input basic maps.  The basic
187  * map should then be simplified such that we may be able to find
188  * a definition among the constraints.
189  *
190  * "eq" and "ineq" are only set if we are currently trying to coalesce
191  * this basic map with another basic map, in which case they represent
192  * the position of the inequalities of this basic map with respect to
193  * the other basic map.  The number of elements in the "eq" array
194  * is twice the number of equalities in the "bmap", corresponding
195  * to the two inequalities that make up each equality.
196  */
197 struct isl_coalesce_info {
198 	isl_basic_map *bmap;
199 	struct isl_tab *tab;
200 	uint32_t hull_hash;
201 	int modified;
202 	int removed;
203 	int simplify;
204 	int *eq;
205 	int *ineq;
206 };
207 
208 /* Is there any (half of an) equality constraint in the description
209  * of the basic map represented by "info" that
210  * has position "status" with respect to the other basic map?
211  */
any_eq(struct isl_coalesce_info * info,int status)212 static int any_eq(struct isl_coalesce_info *info, int status)
213 {
214 	isl_size n_eq;
215 
216 	n_eq = isl_basic_map_n_equality(info->bmap);
217 	return any(info->eq, 2 * n_eq, status);
218 }
219 
220 /* Is there any inequality constraint in the description
221  * of the basic map represented by "info" that
222  * has position "status" with respect to the other basic map?
223  */
any_ineq(struct isl_coalesce_info * info,int status)224 static int any_ineq(struct isl_coalesce_info *info, int status)
225 {
226 	isl_size n_ineq;
227 
228 	n_ineq = isl_basic_map_n_inequality(info->bmap);
229 	return any(info->ineq, n_ineq, status);
230 }
231 
232 /* Return the position of the first half on an equality constraint
233  * in the description of the basic map represented by "info" that
234  * has position "status" with respect to the other basic map.
235  * The returned value is twice the position of the equality constraint
236  * plus zero for the negative half and plus one for the positive half.
237  * Return -1 if there is no such entry.
238  */
find_eq(struct isl_coalesce_info * info,int status)239 static int find_eq(struct isl_coalesce_info *info, int status)
240 {
241 	isl_size n_eq;
242 
243 	n_eq = isl_basic_map_n_equality(info->bmap);
244 	return find(info->eq, 2 * n_eq, status);
245 }
246 
247 /* Return the position of the first inequality constraint in the description
248  * of the basic map represented by "info" that
249  * has position "status" with respect to the other basic map.
250  * Return -1 if there is no such entry.
251  */
find_ineq(struct isl_coalesce_info * info,int status)252 static int find_ineq(struct isl_coalesce_info *info, int status)
253 {
254 	isl_size n_ineq;
255 
256 	n_ineq = isl_basic_map_n_inequality(info->bmap);
257 	return find(info->ineq, n_ineq, status);
258 }
259 
260 /* Return the number of (halves of) equality constraints in the description
261  * of the basic map represented by "info" that
262  * have position "status" with respect to the other basic map.
263  */
count_eq(struct isl_coalesce_info * info,int status)264 static int count_eq(struct isl_coalesce_info *info, int status)
265 {
266 	isl_size n_eq;
267 
268 	n_eq = isl_basic_map_n_equality(info->bmap);
269 	return count(info->eq, 2 * n_eq, status);
270 }
271 
272 /* Return the number of inequality constraints in the description
273  * of the basic map represented by "info" that
274  * have position "status" with respect to the other basic map.
275  */
count_ineq(struct isl_coalesce_info * info,int status)276 static int count_ineq(struct isl_coalesce_info *info, int status)
277 {
278 	isl_size n_ineq;
279 
280 	n_ineq = isl_basic_map_n_inequality(info->bmap);
281 	return count(info->ineq, n_ineq, status);
282 }
283 
284 /* Are all non-redundant constraints of the basic map represented by "info"
285  * either valid or cut constraints with respect to the other basic map?
286  */
all_valid_or_cut(struct isl_coalesce_info * info)287 static int all_valid_or_cut(struct isl_coalesce_info *info)
288 {
289 	int i;
290 
291 	for (i = 0; i < 2 * info->bmap->n_eq; ++i) {
292 		if (info->eq[i] == STATUS_REDUNDANT)
293 			continue;
294 		if (info->eq[i] == STATUS_VALID)
295 			continue;
296 		if (info->eq[i] == STATUS_CUT)
297 			continue;
298 		return 0;
299 	}
300 
301 	for (i = 0; i < info->bmap->n_ineq; ++i) {
302 		if (info->ineq[i] == STATUS_REDUNDANT)
303 			continue;
304 		if (info->ineq[i] == STATUS_VALID)
305 			continue;
306 		if (info->ineq[i] == STATUS_CUT)
307 			continue;
308 		return 0;
309 	}
310 
311 	return 1;
312 }
313 
314 /* Compute the hash of the (apparent) affine hull of info->bmap (with
315  * the existentially quantified variables removed) and store it
316  * in info->hash.
317  */
coalesce_info_set_hull_hash(struct isl_coalesce_info * info)318 static int coalesce_info_set_hull_hash(struct isl_coalesce_info *info)
319 {
320 	isl_basic_map *hull;
321 	isl_size n_div;
322 
323 	hull = isl_basic_map_copy(info->bmap);
324 	hull = isl_basic_map_plain_affine_hull(hull);
325 	n_div = isl_basic_map_dim(hull, isl_dim_div);
326 	if (n_div < 0)
327 		hull = isl_basic_map_free(hull);
328 	hull = isl_basic_map_drop_constraints_involving_dims(hull,
329 							isl_dim_div, 0, n_div);
330 	info->hull_hash = isl_basic_map_get_hash(hull);
331 	isl_basic_map_free(hull);
332 
333 	return hull ? 0 : -1;
334 }
335 
336 /* Free all the allocated memory in an array
337  * of "n" isl_coalesce_info elements.
338  */
clear_coalesce_info(int n,struct isl_coalesce_info * info)339 static void clear_coalesce_info(int n, struct isl_coalesce_info *info)
340 {
341 	int i;
342 
343 	if (!info)
344 		return;
345 
346 	for (i = 0; i < n; ++i) {
347 		isl_basic_map_free(info[i].bmap);
348 		isl_tab_free(info[i].tab);
349 	}
350 
351 	free(info);
352 }
353 
354 /* Clear the memory associated to "info".
355  */
clear(struct isl_coalesce_info * info)356 static void clear(struct isl_coalesce_info *info)
357 {
358 	info->bmap = isl_basic_map_free(info->bmap);
359 	isl_tab_free(info->tab);
360 	info->tab = NULL;
361 }
362 
363 /* Drop the basic map represented by "info".
364  * That is, clear the memory associated to the entry and
365  * mark it as having been removed.
366  */
drop(struct isl_coalesce_info * info)367 static void drop(struct isl_coalesce_info *info)
368 {
369 	clear(info);
370 	info->removed = 1;
371 }
372 
373 /* Exchange the information in "info1" with that in "info2".
374  */
exchange(struct isl_coalesce_info * info1,struct isl_coalesce_info * info2)375 static void exchange(struct isl_coalesce_info *info1,
376 	struct isl_coalesce_info *info2)
377 {
378 	struct isl_coalesce_info info;
379 
380 	info = *info1;
381 	*info1 = *info2;
382 	*info2 = info;
383 }
384 
385 /* This type represents the kind of change that has been performed
386  * while trying to coalesce two basic maps.
387  *
388  * isl_change_none: nothing was changed
389  * isl_change_drop_first: the first basic map was removed
390  * isl_change_drop_second: the second basic map was removed
391  * isl_change_fuse: the two basic maps were replaced by a new basic map.
392  */
393 enum isl_change {
394 	isl_change_error = -1,
395 	isl_change_none = 0,
396 	isl_change_drop_first,
397 	isl_change_drop_second,
398 	isl_change_fuse,
399 };
400 
401 /* Update "change" based on an interchange of the first and the second
402  * basic map.  That is, interchange isl_change_drop_first and
403  * isl_change_drop_second.
404  */
invert_change(enum isl_change change)405 static enum isl_change invert_change(enum isl_change change)
406 {
407 	switch (change) {
408 	case isl_change_error:
409 		return isl_change_error;
410 	case isl_change_none:
411 		return isl_change_none;
412 	case isl_change_drop_first:
413 		return isl_change_drop_second;
414 	case isl_change_drop_second:
415 		return isl_change_drop_first;
416 	case isl_change_fuse:
417 		return isl_change_fuse;
418 	}
419 
420 	return isl_change_error;
421 }
422 
423 /* Add the valid constraints of the basic map represented by "info"
424  * to "bmap".  "len" is the size of the constraints.
425  * If only one of the pair of inequalities that make up an equality
426  * is valid, then add that inequality.
427  */
add_valid_constraints(__isl_take isl_basic_map * bmap,struct isl_coalesce_info * info,unsigned len)428 static __isl_give isl_basic_map *add_valid_constraints(
429 	__isl_take isl_basic_map *bmap, struct isl_coalesce_info *info,
430 	unsigned len)
431 {
432 	int k, l;
433 
434 	if (!bmap)
435 		return NULL;
436 
437 	for (k = 0; k < info->bmap->n_eq; ++k) {
438 		if (info->eq[2 * k] == STATUS_VALID &&
439 		    info->eq[2 * k + 1] == STATUS_VALID) {
440 			l = isl_basic_map_alloc_equality(bmap);
441 			if (l < 0)
442 				return isl_basic_map_free(bmap);
443 			isl_seq_cpy(bmap->eq[l], info->bmap->eq[k], len);
444 		} else if (info->eq[2 * k] == STATUS_VALID) {
445 			l = isl_basic_map_alloc_inequality(bmap);
446 			if (l < 0)
447 				return isl_basic_map_free(bmap);
448 			isl_seq_neg(bmap->ineq[l], info->bmap->eq[k], len);
449 		} else if (info->eq[2 * k + 1] == STATUS_VALID) {
450 			l = isl_basic_map_alloc_inequality(bmap);
451 			if (l < 0)
452 				return isl_basic_map_free(bmap);
453 			isl_seq_cpy(bmap->ineq[l], info->bmap->eq[k], len);
454 		}
455 	}
456 
457 	for (k = 0; k < info->bmap->n_ineq; ++k) {
458 		if (info->ineq[k] != STATUS_VALID)
459 			continue;
460 		l = isl_basic_map_alloc_inequality(bmap);
461 		if (l < 0)
462 			return isl_basic_map_free(bmap);
463 		isl_seq_cpy(bmap->ineq[l], info->bmap->ineq[k], len);
464 	}
465 
466 	return bmap;
467 }
468 
469 /* Is "bmap" defined by a number of (non-redundant) constraints that
470  * is greater than the number of constraints of basic maps i and j combined?
471  * Equalities are counted as two inequalities.
472  */
number_of_constraints_increases(int i,int j,struct isl_coalesce_info * info,__isl_keep isl_basic_map * bmap,struct isl_tab * tab)473 static int number_of_constraints_increases(int i, int j,
474 	struct isl_coalesce_info *info,
475 	__isl_keep isl_basic_map *bmap, struct isl_tab *tab)
476 {
477 	int k, n_old, n_new;
478 
479 	n_old = 2 * info[i].bmap->n_eq + info[i].bmap->n_ineq;
480 	n_old += 2 * info[j].bmap->n_eq + info[j].bmap->n_ineq;
481 
482 	n_new = 2 * bmap->n_eq;
483 	for (k = 0; k < bmap->n_ineq; ++k)
484 		if (!isl_tab_is_redundant(tab, bmap->n_eq + k))
485 			++n_new;
486 
487 	return n_new > n_old;
488 }
489 
490 /* Replace the pair of basic maps i and j by the basic map bounded
491  * by the valid constraints in both basic maps and the constraints
492  * in extra (if not NULL).
493  * Place the fused basic map in the position that is the smallest of i and j.
494  *
495  * If "detect_equalities" is set, then look for equalities encoded
496  * as pairs of inequalities.
497  * If "check_number" is set, then the original basic maps are only
498  * replaced if the total number of constraints does not increase.
499  * While the number of integer divisions in the two basic maps
500  * is assumed to be the same, the actual definitions may be different.
501  * We only copy the definition from one of the basic map if it is
502  * the same as that of the other basic map.  Otherwise, we mark
503  * the integer division as unknown and simplify the basic map
504  * in an attempt to recover the integer division definition.
505  * If any extra constraints get introduced, then these may
506  * involve integer divisions with a unit coefficient.
507  * Eliminate those that do not appear with any other coefficient
508  * in other constraints, to ensure they get eliminated completely,
509  * improving the chances of further coalescing.
510  */
fuse(int i,int j,struct isl_coalesce_info * info,__isl_keep isl_mat * extra,int detect_equalities,int check_number)511 static enum isl_change fuse(int i, int j, struct isl_coalesce_info *info,
512 	__isl_keep isl_mat *extra, int detect_equalities, int check_number)
513 {
514 	int k, l;
515 	struct isl_basic_map *fused = NULL;
516 	struct isl_tab *fused_tab = NULL;
517 	isl_size total = isl_basic_map_dim(info[i].bmap, isl_dim_all);
518 	unsigned extra_rows = extra ? extra->n_row : 0;
519 	unsigned n_eq, n_ineq;
520 	int simplify = 0;
521 
522 	if (total < 0)
523 		return isl_change_error;
524 	if (j < i)
525 		return fuse(j, i, info, extra, detect_equalities, check_number);
526 
527 	n_eq = info[i].bmap->n_eq + info[j].bmap->n_eq;
528 	n_ineq = info[i].bmap->n_ineq + info[j].bmap->n_ineq;
529 	fused = isl_basic_map_alloc_space(isl_space_copy(info[i].bmap->dim),
530 		    info[i].bmap->n_div, n_eq, n_eq + n_ineq + extra_rows);
531 	fused = add_valid_constraints(fused, &info[i], 1 + total);
532 	fused = add_valid_constraints(fused, &info[j], 1 + total);
533 	if (!fused)
534 		goto error;
535 	if (ISL_F_ISSET(info[i].bmap, ISL_BASIC_MAP_RATIONAL) &&
536 	    ISL_F_ISSET(info[j].bmap, ISL_BASIC_MAP_RATIONAL))
537 		ISL_F_SET(fused, ISL_BASIC_MAP_RATIONAL);
538 
539 	for (k = 0; k < info[i].bmap->n_div; ++k) {
540 		int l = isl_basic_map_alloc_div(fused);
541 		if (l < 0)
542 			goto error;
543 		if (isl_seq_eq(info[i].bmap->div[k], info[j].bmap->div[k],
544 				1 + 1 + total)) {
545 			isl_seq_cpy(fused->div[l], info[i].bmap->div[k],
546 				1 + 1 + total);
547 		} else {
548 			isl_int_set_si(fused->div[l][0], 0);
549 			simplify = 1;
550 		}
551 	}
552 
553 	for (k = 0; k < extra_rows; ++k) {
554 		l = isl_basic_map_alloc_inequality(fused);
555 		if (l < 0)
556 			goto error;
557 		isl_seq_cpy(fused->ineq[l], extra->row[k], 1 + total);
558 	}
559 
560 	if (detect_equalities)
561 		fused = isl_basic_map_detect_inequality_pairs(fused, NULL);
562 	fused = isl_basic_map_gauss(fused, NULL);
563 	if (simplify || info[j].simplify) {
564 		fused = isl_basic_map_simplify(fused);
565 		info[i].simplify = 0;
566 	} else if (extra_rows > 0) {
567 		fused = isl_basic_map_eliminate_pure_unit_divs(fused);
568 	}
569 	fused = isl_basic_map_finalize(fused);
570 
571 	fused_tab = isl_tab_from_basic_map(fused, 0);
572 	if (isl_tab_detect_redundant(fused_tab) < 0)
573 		goto error;
574 
575 	if (check_number &&
576 	    number_of_constraints_increases(i, j, info, fused, fused_tab)) {
577 		isl_tab_free(fused_tab);
578 		isl_basic_map_free(fused);
579 		return isl_change_none;
580 	}
581 
582 	clear(&info[i]);
583 	info[i].bmap = fused;
584 	info[i].tab = fused_tab;
585 	info[i].modified = 1;
586 	drop(&info[j]);
587 
588 	return isl_change_fuse;
589 error:
590 	isl_tab_free(fused_tab);
591 	isl_basic_map_free(fused);
592 	return isl_change_error;
593 }
594 
595 /* Given a pair of basic maps i and j such that all constraints are either
596  * "valid" or "cut", check if the facets corresponding to the "cut"
597  * constraints of i lie entirely within basic map j.
598  * If so, replace the pair by the basic map consisting of the valid
599  * constraints in both basic maps.
600  * Checking whether the facet lies entirely within basic map j
601  * is performed by checking whether the constraints of basic map j
602  * are valid for the facet.  These tests are performed on a rational
603  * tableau to avoid the theoretical possibility that a constraint
604  * that was considered to be a cut constraint for the entire basic map i
605  * happens to be considered to be a valid constraint for the facet,
606  * even though it cuts off the same rational points.
607  *
608  * To see that we are not introducing any extra points, call the
609  * two basic maps A and B and the resulting map U and let x
610  * be an element of U \setminus ( A \cup B ).
611  * A line connecting x with an element of A \cup B meets a facet F
612  * of either A or B.  Assume it is a facet of B and let c_1 be
613  * the corresponding facet constraint.  We have c_1(x) < 0 and
614  * so c_1 is a cut constraint.  This implies that there is some
615  * (possibly rational) point x' satisfying the constraints of A
616  * and the opposite of c_1 as otherwise c_1 would have been marked
617  * valid for A.  The line connecting x and x' meets a facet of A
618  * in a (possibly rational) point that also violates c_1, but this
619  * is impossible since all cut constraints of B are valid for all
620  * cut facets of A.
621  * In case F is a facet of A rather than B, then we can apply the
622  * above reasoning to find a facet of B separating x from A \cup B first.
623  */
check_facets(int i,int j,struct isl_coalesce_info * info)624 static enum isl_change check_facets(int i, int j,
625 	struct isl_coalesce_info *info)
626 {
627 	int k, l;
628 	struct isl_tab_undo *snap, *snap2;
629 	unsigned n_eq = info[i].bmap->n_eq;
630 
631 	snap = isl_tab_snap(info[i].tab);
632 	if (isl_tab_mark_rational(info[i].tab) < 0)
633 		return isl_change_error;
634 	snap2 = isl_tab_snap(info[i].tab);
635 
636 	for (k = 0; k < info[i].bmap->n_ineq; ++k) {
637 		if (info[i].ineq[k] != STATUS_CUT)
638 			continue;
639 		if (isl_tab_select_facet(info[i].tab, n_eq + k) < 0)
640 			return isl_change_error;
641 		for (l = 0; l < info[j].bmap->n_ineq; ++l) {
642 			int stat;
643 			if (info[j].ineq[l] != STATUS_CUT)
644 				continue;
645 			stat = status_in(info[j].bmap->ineq[l], info[i].tab);
646 			if (stat < 0)
647 				return isl_change_error;
648 			if (stat != STATUS_VALID)
649 				break;
650 		}
651 		if (isl_tab_rollback(info[i].tab, snap2) < 0)
652 			return isl_change_error;
653 		if (l < info[j].bmap->n_ineq)
654 			break;
655 	}
656 
657 	if (k < info[i].bmap->n_ineq) {
658 		if (isl_tab_rollback(info[i].tab, snap) < 0)
659 			return isl_change_error;
660 		return isl_change_none;
661 	}
662 	return fuse(i, j, info, NULL, 0, 0);
663 }
664 
665 /* Check if info->bmap contains the basic map represented
666  * by the tableau "tab".
667  * For each equality, we check both the constraint itself
668  * (as an inequality) and its negation.  Make sure the
669  * equality is returned to its original state before returning.
670  */
contains(struct isl_coalesce_info * info,struct isl_tab * tab)671 static isl_bool contains(struct isl_coalesce_info *info, struct isl_tab *tab)
672 {
673 	int k;
674 	isl_size dim;
675 	isl_basic_map *bmap = info->bmap;
676 
677 	dim = isl_basic_map_dim(bmap, isl_dim_all);
678 	if (dim < 0)
679 		return isl_bool_error;
680 	for (k = 0; k < bmap->n_eq; ++k) {
681 		int stat;
682 		isl_seq_neg(bmap->eq[k], bmap->eq[k], 1 + dim);
683 		stat = status_in(bmap->eq[k], tab);
684 		isl_seq_neg(bmap->eq[k], bmap->eq[k], 1 + dim);
685 		if (stat < 0)
686 			return isl_bool_error;
687 		if (stat != STATUS_VALID)
688 			return isl_bool_false;
689 		stat = status_in(bmap->eq[k], tab);
690 		if (stat < 0)
691 			return isl_bool_error;
692 		if (stat != STATUS_VALID)
693 			return isl_bool_false;
694 	}
695 
696 	for (k = 0; k < bmap->n_ineq; ++k) {
697 		int stat;
698 		if (info->ineq[k] == STATUS_REDUNDANT)
699 			continue;
700 		stat = status_in(bmap->ineq[k], tab);
701 		if (stat < 0)
702 			return isl_bool_error;
703 		if (stat != STATUS_VALID)
704 			return isl_bool_false;
705 	}
706 	return isl_bool_true;
707 }
708 
709 /* Basic map "i" has an inequality "k" that is adjacent
710  * to some inequality of basic map "j".  All the other inequalities
711  * are valid for "j".
712  * If not NULL, then "extra" contains extra wrapping constraints that are valid
713  * for both "i" and "j".
714  * Check if basic map "j" forms an extension of basic map "i",
715  * taking into account the extra constraints, if any.
716  *
717  * Note that this function is only called if some of the equalities or
718  * inequalities of basic map "j" do cut basic map "i".  The function is
719  * correct even if there are no such cut constraints, but in that case
720  * the additional checks performed by this function are overkill.
721  *
722  * In particular, we replace constraint k, say f >= 0, by constraint
723  * f <= -1, add the inequalities of "j" that are valid for "i",
724  * as well as the "extra" constraints, if any,
725  * and check if the result is a subset of basic map "j".
726  * To improve the chances of the subset relation being detected,
727  * any variable that only attains a single integer value
728  * in the tableau of "i" is first fixed to that value.
729  * If the result is a subset, then we know that this result is exactly equal
730  * to basic map "j" since all its constraints are valid for basic map "j".
731  * By combining the valid constraints of "i" (all equalities and all
732  * inequalities except "k"), the valid constraints of "j" and
733  * the "extra" constraints, if any, we therefore
734  * obtain a basic map that is equal to their union.
735  * In this case, there is no need to perform a rollback of the tableau
736  * since it is going to be destroyed in fuse().
737  *
738  *
739  *	|\__			|\__
740  *	|   \__			|   \__
741  *	|      \_	=>	|      \__
742  *	|_______| _		|_________\
743  *
744  *
745  *	|\			|\
746  *	| \			| \
747  *	|  \			|  \
748  *	|  |			|   \
749  *	|  ||\		=>      |    \
750  *	|  || \			|     \
751  *	|  ||  |		|      |
752  *	|__||_/			|_____/
753  *
754  *
755  *	_______			 _______
756  *     |       | __		|       \__
757  *     |       ||__|	=>	|        __|
758  *     |_______|		|_______/
759  */
is_adj_ineq_extension_with_wraps(int i,int j,int k,struct isl_coalesce_info * info,__isl_keep isl_mat * extra)760 static enum isl_change is_adj_ineq_extension_with_wraps(int i, int j, int k,
761 	struct isl_coalesce_info *info, __isl_keep isl_mat *extra)
762 {
763 	struct isl_tab_undo *snap;
764 	isl_size n_eq_i, n_ineq_j, n_extra;
765 	isl_size total = isl_basic_map_dim(info[i].bmap, isl_dim_all);
766 	isl_stat r;
767 	isl_bool super;
768 
769 	if (total < 0)
770 		return isl_change_error;
771 
772 	n_eq_i = isl_basic_map_n_equality(info[i].bmap);
773 	n_ineq_j = isl_basic_map_n_inequality(info[j].bmap);
774 	n_extra = isl_mat_rows(extra);
775 	if (n_eq_i < 0 || n_ineq_j < 0 || n_extra < 0)
776 		return isl_change_error;
777 
778 	if (isl_tab_extend_cons(info[i].tab, 1 + n_ineq_j + n_extra) < 0)
779 		return isl_change_error;
780 
781 	snap = isl_tab_snap(info[i].tab);
782 
783 	if (isl_tab_unrestrict(info[i].tab, n_eq_i + k) < 0)
784 		return isl_change_error;
785 
786 	isl_seq_neg(info[i].bmap->ineq[k], info[i].bmap->ineq[k], 1 + total);
787 	isl_int_sub_ui(info[i].bmap->ineq[k][0], info[i].bmap->ineq[k][0], 1);
788 	r = isl_tab_add_ineq(info[i].tab, info[i].bmap->ineq[k]);
789 	isl_seq_neg(info[i].bmap->ineq[k], info[i].bmap->ineq[k], 1 + total);
790 	isl_int_sub_ui(info[i].bmap->ineq[k][0], info[i].bmap->ineq[k][0], 1);
791 	if (r < 0)
792 		return isl_change_error;
793 
794 	for (k = 0; k < n_ineq_j; ++k) {
795 		if (info[j].ineq[k] != STATUS_VALID)
796 			continue;
797 		if (isl_tab_add_ineq(info[i].tab, info[j].bmap->ineq[k]) < 0)
798 			return isl_change_error;
799 	}
800 	for (k = 0; k < n_extra; ++k) {
801 		if (isl_tab_add_ineq(info[i].tab, extra->row[k]) < 0)
802 			return isl_change_error;
803 	}
804 	if (isl_tab_detect_constants(info[i].tab) < 0)
805 		return isl_change_error;
806 
807 	super = contains(&info[j], info[i].tab);
808 	if (super < 0)
809 		return isl_change_error;
810 	if (super)
811 		return fuse(i, j, info, extra, 0, 0);
812 
813 	if (isl_tab_rollback(info[i].tab, snap) < 0)
814 		return isl_change_error;
815 
816 	return isl_change_none;
817 }
818 
819 /* Given an affine transformation matrix "T", does row "row" represent
820  * anything other than a unit vector (possibly shifted by a constant)
821  * that is not involved in any of the other rows?
822  *
823  * That is, if a constraint involves the variable corresponding to
824  * the row, then could its preimage by "T" have any coefficients
825  * that are different from those in the original constraint?
826  */
not_unique_unit_row(__isl_keep isl_mat * T,int row)827 static int not_unique_unit_row(__isl_keep isl_mat *T, int row)
828 {
829 	int i, j;
830 	int len = T->n_col - 1;
831 
832 	i = isl_seq_first_non_zero(T->row[row] + 1, len);
833 	if (i < 0)
834 		return 1;
835 	if (!isl_int_is_one(T->row[row][1 + i]) &&
836 	    !isl_int_is_negone(T->row[row][1 + i]))
837 		return 1;
838 
839 	j = isl_seq_first_non_zero(T->row[row] + 1 + i + 1, len - (i + 1));
840 	if (j >= 0)
841 		return 1;
842 
843 	for (j = 1; j < T->n_row; ++j) {
844 		if (j == row)
845 			continue;
846 		if (!isl_int_is_zero(T->row[j][1 + i]))
847 			return 1;
848 	}
849 
850 	return 0;
851 }
852 
853 /* Does inequality constraint "ineq" of "bmap" involve any of
854  * the variables marked in "affected"?
855  * "total" is the total number of variables, i.e., the number
856  * of entries in "affected".
857  */
is_affected(__isl_keep isl_basic_map * bmap,int ineq,int * affected,int total)858 static isl_bool is_affected(__isl_keep isl_basic_map *bmap, int ineq,
859 	int *affected, int total)
860 {
861 	int i;
862 
863 	for (i = 0; i < total; ++i) {
864 		if (!affected[i])
865 			continue;
866 		if (!isl_int_is_zero(bmap->ineq[ineq][1 + i]))
867 			return isl_bool_true;
868 	}
869 
870 	return isl_bool_false;
871 }
872 
873 /* Given the compressed version of inequality constraint "ineq"
874  * of info->bmap in "v", check if the constraint can be tightened,
875  * where the compression is based on an equality constraint valid
876  * for info->tab.
877  * If so, add the tightened version of the inequality constraint
878  * to info->tab.  "v" may be modified by this function.
879  *
880  * That is, if the compressed constraint is of the form
881  *
882  *	m f() + c >= 0
883  *
884  * with 0 < c < m, then it is equivalent to
885  *
886  *	f() >= 0
887  *
888  * This means that c can also be subtracted from the original,
889  * uncompressed constraint without affecting the integer points
890  * in info->tab.  Add this tightened constraint as an extra row
891  * to info->tab to make this information explicitly available.
892  */
try_tightening(struct isl_coalesce_info * info,int ineq,__isl_take isl_vec * v)893 static __isl_give isl_vec *try_tightening(struct isl_coalesce_info *info,
894 	int ineq, __isl_take isl_vec *v)
895 {
896 	isl_ctx *ctx;
897 	isl_stat r;
898 
899 	if (!v)
900 		return NULL;
901 
902 	ctx = isl_vec_get_ctx(v);
903 	isl_seq_gcd(v->el + 1, v->size - 1, &ctx->normalize_gcd);
904 	if (isl_int_is_zero(ctx->normalize_gcd) ||
905 	    isl_int_is_one(ctx->normalize_gcd)) {
906 		return v;
907 	}
908 
909 	v = isl_vec_cow(v);
910 	if (!v)
911 		return NULL;
912 
913 	isl_int_fdiv_r(v->el[0], v->el[0], ctx->normalize_gcd);
914 	if (isl_int_is_zero(v->el[0]))
915 		return v;
916 
917 	if (isl_tab_extend_cons(info->tab, 1) < 0)
918 		return isl_vec_free(v);
919 
920 	isl_int_sub(info->bmap->ineq[ineq][0],
921 		    info->bmap->ineq[ineq][0], v->el[0]);
922 	r = isl_tab_add_ineq(info->tab, info->bmap->ineq[ineq]);
923 	isl_int_add(info->bmap->ineq[ineq][0],
924 		    info->bmap->ineq[ineq][0], v->el[0]);
925 
926 	if (r < 0)
927 		return isl_vec_free(v);
928 
929 	return v;
930 }
931 
932 /* Tighten the (non-redundant) constraints on the facet represented
933  * by info->tab.
934  * In particular, on input, info->tab represents the result
935  * of relaxing the "n" inequality constraints of info->bmap in "relaxed"
936  * by one, i.e., replacing f_i >= 0 by f_i + 1 >= 0, and then
937  * replacing the one at index "l" by the corresponding equality,
938  * i.e., f_k + 1 = 0, with k = relaxed[l].
939  *
940  * Compute a variable compression from the equality constraint f_k + 1 = 0
941  * and use it to tighten the other constraints of info->bmap
942  * (that is, all constraints that have not been relaxed),
943  * updating info->tab (and leaving info->bmap untouched).
944  * The compression handles essentially two cases, one where a variable
945  * is assigned a fixed value and can therefore be eliminated, and one
946  * where one variable is a shifted multiple of some other variable and
947  * can therefore be replaced by that multiple.
948  * Gaussian elimination would also work for the first case, but for
949  * the second case, the effectiveness would depend on the order
950  * of the variables.
951  * After compression, some of the constraints may have coefficients
952  * with a common divisor.  If this divisor does not divide the constant
953  * term, then the constraint can be tightened.
954  * The tightening is performed on the tableau info->tab by introducing
955  * extra (temporary) constraints.
956  *
957  * Only constraints that are possibly affected by the compression are
958  * considered.  In particular, if the constraint only involves variables
959  * that are directly mapped to a distinct set of other variables, then
960  * no common divisor can be introduced and no tightening can occur.
961  *
962  * It is important to only consider the non-redundant constraints
963  * since the facet constraint has been relaxed prior to the call
964  * to this function, meaning that the constraints that were redundant
965  * prior to the relaxation may no longer be redundant.
966  * These constraints will be ignored in the fused result, so
967  * the fusion detection should not exploit them.
968  */
tighten_on_relaxed_facet(struct isl_coalesce_info * info,int n,int * relaxed,int l)969 static isl_stat tighten_on_relaxed_facet(struct isl_coalesce_info *info,
970 	int n, int *relaxed, int l)
971 {
972 	isl_size total;
973 	isl_ctx *ctx;
974 	isl_vec *v = NULL;
975 	isl_mat *T;
976 	int i;
977 	int k;
978 	int *affected;
979 
980 	k = relaxed[l];
981 	ctx = isl_basic_map_get_ctx(info->bmap);
982 	total = isl_basic_map_dim(info->bmap, isl_dim_all);
983 	if (total < 0)
984 		return isl_stat_error;
985 	isl_int_add_ui(info->bmap->ineq[k][0], info->bmap->ineq[k][0], 1);
986 	T = isl_mat_sub_alloc6(ctx, info->bmap->ineq, k, 1, 0, 1 + total);
987 	T = isl_mat_variable_compression(T, NULL);
988 	isl_int_sub_ui(info->bmap->ineq[k][0], info->bmap->ineq[k][0], 1);
989 	if (!T)
990 		return isl_stat_error;
991 	if (T->n_col == 0) {
992 		isl_mat_free(T);
993 		return isl_stat_ok;
994 	}
995 
996 	affected = isl_alloc_array(ctx, int, total);
997 	if (!affected)
998 		goto error;
999 
1000 	for (i = 0; i < total; ++i)
1001 		affected[i] = not_unique_unit_row(T, 1 + i);
1002 
1003 	for (i = 0; i < info->bmap->n_ineq; ++i) {
1004 		isl_bool handle;
1005 		if (any(relaxed, n, i))
1006 			continue;
1007 		if (info->ineq[i] == STATUS_REDUNDANT)
1008 			continue;
1009 		handle = is_affected(info->bmap, i, affected, total);
1010 		if (handle < 0)
1011 			goto error;
1012 		if (!handle)
1013 			continue;
1014 		v = isl_vec_alloc(ctx, 1 + total);
1015 		if (!v)
1016 			goto error;
1017 		isl_seq_cpy(v->el, info->bmap->ineq[i], 1 + total);
1018 		v = isl_vec_mat_product(v, isl_mat_copy(T));
1019 		v = try_tightening(info, i, v);
1020 		isl_vec_free(v);
1021 		if (!v)
1022 			goto error;
1023 	}
1024 
1025 	isl_mat_free(T);
1026 	free(affected);
1027 	return isl_stat_ok;
1028 error:
1029 	isl_mat_free(T);
1030 	free(affected);
1031 	return isl_stat_error;
1032 }
1033 
1034 /* Replace the basic maps "i" and "j" by an extension of "i"
1035  * along the "n" inequality constraints in "relax" by one.
1036  * The tableau info[i].tab has already been extended.
1037  * Extend info[i].bmap accordingly by relaxing all constraints in "relax"
1038  * by one.
1039  * Each integer division that does not have exactly the same
1040  * definition in "i" and "j" is marked unknown and the basic map
1041  * is scheduled to be simplified in an attempt to recover
1042  * the integer division definition.
1043  * Place the extension in the position that is the smallest of i and j.
1044  */
extend(int i,int j,int n,int * relax,struct isl_coalesce_info * info)1045 static enum isl_change extend(int i, int j, int n, int *relax,
1046 	struct isl_coalesce_info *info)
1047 {
1048 	int l;
1049 	isl_size total;
1050 
1051 	info[i].bmap = isl_basic_map_cow(info[i].bmap);
1052 	total = isl_basic_map_dim(info[i].bmap, isl_dim_all);
1053 	if (total < 0)
1054 		return isl_change_error;
1055 	for (l = 0; l < info[i].bmap->n_div; ++l)
1056 		if (!isl_seq_eq(info[i].bmap->div[l],
1057 				info[j].bmap->div[l], 1 + 1 + total)) {
1058 			isl_int_set_si(info[i].bmap->div[l][0], 0);
1059 			info[i].simplify = 1;
1060 		}
1061 	for (l = 0; l < n; ++l)
1062 		isl_int_add_ui(info[i].bmap->ineq[relax[l]][0],
1063 				info[i].bmap->ineq[relax[l]][0], 1);
1064 	ISL_F_CLR(info[i].bmap, ISL_BASIC_MAP_NO_REDUNDANT);
1065 	ISL_F_SET(info[i].bmap, ISL_BASIC_MAP_FINAL);
1066 	drop(&info[j]);
1067 	info[i].modified = 1;
1068 	if (j < i)
1069 		exchange(&info[i], &info[j]);
1070 	return isl_change_fuse;
1071 }
1072 
1073 /* Basic map "i" has "n" inequality constraints (collected in "relax")
1074  * that are such that they include basic map "j" if they are relaxed
1075  * by one.  All the other inequalities are valid for "j".
1076  * Check if basic map "j" forms an extension of basic map "i".
1077  *
1078  * In particular, relax the constraints in "relax", compute the corresponding
1079  * facets one by one and check whether each of these is included
1080  * in the other basic map.
1081  * Before testing for inclusion, the constraints on each facet
1082  * are tightened to increase the chance of an inclusion being detected.
1083  * (Adding the valid constraints of "j" to the tableau of "i", as is done
1084  * in is_adj_ineq_extension, may further increase those chances, but this
1085  * is not currently done.)
1086  * If each facet is included, we know that relaxing the constraints extends
1087  * the basic map with exactly the other basic map (we already know that this
1088  * other basic map is included in the extension, because all other
1089  * inequality constraints are valid of "j") and we can replace the
1090  * two basic maps by this extension.
1091  *
1092  * If any of the relaxed constraints turn out to be redundant, then bail out.
1093  * isl_tab_select_facet refuses to handle such constraints.  It may be
1094  * possible to handle them anyway by making a distinction between
1095  * redundant constraints with a corresponding facet that still intersects
1096  * the set (allowing isl_tab_select_facet to handle them) and
1097  * those where the facet does not intersect the set (which can be ignored
1098  * because the empty facet is trivially included in the other disjunct).
1099  * However, relaxed constraints that turn out to be redundant should
1100  * be fairly rare and no such instance has been reported where
1101  * coalescing would be successful.
1102  *        ____			  _____
1103  *       /    || 		 /     |
1104  *      /     ||  		/      |
1105  *      \     ||   	=>	\      |
1106  *       \    ||		 \     |
1107  *        \___||		  \____|
1108  *
1109  *
1110  *	 \			|\
1111  *	|\\			| \
1112  *	| \\			|  \
1113  *	|  |		=>	|  /
1114  *	| /			| /
1115  *	|/			|/
1116  */
is_relaxed_extension(int i,int j,int n,int * relax,struct isl_coalesce_info * info)1117 static enum isl_change is_relaxed_extension(int i, int j, int n, int *relax,
1118 	struct isl_coalesce_info *info)
1119 {
1120 	int l;
1121 	isl_bool super;
1122 	struct isl_tab_undo *snap, *snap2;
1123 	unsigned n_eq = info[i].bmap->n_eq;
1124 
1125 	for (l = 0; l < n; ++l)
1126 		if (isl_tab_is_equality(info[i].tab, n_eq + relax[l]))
1127 			return isl_change_none;
1128 
1129 	snap = isl_tab_snap(info[i].tab);
1130 	for (l = 0; l < n; ++l)
1131 		if (isl_tab_relax(info[i].tab, n_eq + relax[l]) < 0)
1132 			return isl_change_error;
1133 	for (l = 0; l < n; ++l) {
1134 		if (!isl_tab_is_redundant(info[i].tab, n_eq + relax[l]))
1135 			continue;
1136 		if (isl_tab_rollback(info[i].tab, snap) < 0)
1137 			return isl_change_error;
1138 		return isl_change_none;
1139 	}
1140 	snap2 = isl_tab_snap(info[i].tab);
1141 	for (l = 0; l < n; ++l) {
1142 		if (isl_tab_rollback(info[i].tab, snap2) < 0)
1143 			return isl_change_error;
1144 		if (isl_tab_select_facet(info[i].tab, n_eq + relax[l]) < 0)
1145 			return isl_change_error;
1146 		if (tighten_on_relaxed_facet(&info[i], n, relax, l) < 0)
1147 			return isl_change_error;
1148 		super = contains(&info[j], info[i].tab);
1149 		if (super < 0)
1150 			return isl_change_error;
1151 		if (super)
1152 			continue;
1153 		if (isl_tab_rollback(info[i].tab, snap) < 0)
1154 			return isl_change_error;
1155 		return isl_change_none;
1156 	}
1157 
1158 	if (isl_tab_rollback(info[i].tab, snap2) < 0)
1159 		return isl_change_error;
1160 	return extend(i, j, n, relax, info);
1161 }
1162 
1163 /* Data structure that keeps track of the wrapping constraints
1164  * and of information to bound the coefficients of those constraints.
1165  *
1166  * "failed" is set if wrapping has failed.
1167  * bound is set if we want to apply a bound on the coefficients
1168  * mat contains the wrapping constraints
1169  * max is the bound on the coefficients (if bound is set)
1170  */
1171 struct isl_wraps {
1172 	int failed;
1173 	int bound;
1174 	isl_mat *mat;
1175 	isl_int max;
1176 };
1177 
1178 /* Update wraps->max to be greater than or equal to the coefficients
1179  * in the equalities and inequalities of info->bmap that can be removed
1180  * if we end up applying wrapping.
1181  */
wraps_update_max(struct isl_wraps * wraps,struct isl_coalesce_info * info)1182 static isl_stat wraps_update_max(struct isl_wraps *wraps,
1183 	struct isl_coalesce_info *info)
1184 {
1185 	int k;
1186 	isl_int max_k;
1187 	isl_size total = isl_basic_map_dim(info->bmap, isl_dim_all);
1188 
1189 	if (total < 0)
1190 		return isl_stat_error;
1191 	isl_int_init(max_k);
1192 
1193 	for (k = 0; k < info->bmap->n_eq; ++k) {
1194 		if (info->eq[2 * k] == STATUS_VALID &&
1195 		    info->eq[2 * k + 1] == STATUS_VALID)
1196 			continue;
1197 		isl_seq_abs_max(info->bmap->eq[k] + 1, total, &max_k);
1198 		if (isl_int_abs_gt(max_k, wraps->max))
1199 			isl_int_set(wraps->max, max_k);
1200 	}
1201 
1202 	for (k = 0; k < info->bmap->n_ineq; ++k) {
1203 		if (info->ineq[k] == STATUS_VALID ||
1204 		    info->ineq[k] == STATUS_REDUNDANT)
1205 			continue;
1206 		isl_seq_abs_max(info->bmap->ineq[k] + 1, total, &max_k);
1207 		if (isl_int_abs_gt(max_k, wraps->max))
1208 			isl_int_set(wraps->max, max_k);
1209 	}
1210 
1211 	isl_int_clear(max_k);
1212 
1213 	return isl_stat_ok;
1214 }
1215 
1216 /* Initialize the isl_wraps data structure.
1217  * If we want to bound the coefficients of the wrapping constraints,
1218  * we set wraps->max to the largest coefficient
1219  * in the equalities and inequalities that can be removed if we end up
1220  * applying wrapping.
1221  */
wraps_init(struct isl_wraps * wraps,__isl_take isl_mat * mat,struct isl_coalesce_info * info,int i,int j)1222 static isl_stat wraps_init(struct isl_wraps *wraps, __isl_take isl_mat *mat,
1223 	struct isl_coalesce_info *info, int i, int j)
1224 {
1225 	isl_ctx *ctx;
1226 
1227 	wraps->failed = 0;
1228 	wraps->bound = 0;
1229 	wraps->mat = mat;
1230 	if (!mat)
1231 		return isl_stat_error;
1232 	wraps->mat->n_row = 0;
1233 	ctx = isl_mat_get_ctx(mat);
1234 	wraps->bound = isl_options_get_coalesce_bounded_wrapping(ctx);
1235 	if (!wraps->bound)
1236 		return isl_stat_ok;
1237 	isl_int_init(wraps->max);
1238 	isl_int_set_si(wraps->max, 0);
1239 	if (wraps_update_max(wraps, &info[i]) < 0)
1240 		return isl_stat_error;
1241 	if (wraps_update_max(wraps, &info[j]) < 0)
1242 		return isl_stat_error;
1243 
1244 	return isl_stat_ok;
1245 }
1246 
1247 /* Free the contents of the isl_wraps data structure.
1248  */
wraps_free(struct isl_wraps * wraps)1249 static void wraps_free(struct isl_wraps *wraps)
1250 {
1251 	isl_mat_free(wraps->mat);
1252 	if (wraps->bound)
1253 		isl_int_clear(wraps->max);
1254 }
1255 
1256 /* Mark the wrapping as failed.
1257  */
wraps_mark_failed(struct isl_wraps * wraps)1258 static isl_stat wraps_mark_failed(struct isl_wraps *wraps)
1259 {
1260 	wraps->failed = 1;
1261 	return isl_stat_ok;
1262 }
1263 
1264 /* Is the wrapping constraint in row "row" allowed?
1265  *
1266  * If wraps->bound is set, we check that none of the coefficients
1267  * is greater than wraps->max.
1268  */
allow_wrap(struct isl_wraps * wraps,int row)1269 static int allow_wrap(struct isl_wraps *wraps, int row)
1270 {
1271 	int i;
1272 
1273 	if (!wraps->bound)
1274 		return 1;
1275 
1276 	for (i = 1; i < wraps->mat->n_col; ++i)
1277 		if (isl_int_abs_gt(wraps->mat->row[row][i], wraps->max))
1278 			return 0;
1279 
1280 	return 1;
1281 }
1282 
1283 /* Wrap "ineq" (or its opposite if "negate" is set) around "bound"
1284  * to include "set" and add the result in position "w" of "wraps".
1285  * "len" is the total number of coefficients in "bound" and "ineq".
1286  * Return 1 on success, 0 on failure and -1 on error.
1287  * Wrapping can fail if the result of wrapping is equal to "bound"
1288  * or if we want to bound the sizes of the coefficients and
1289  * the wrapped constraint does not satisfy this bound.
1290  */
add_wrap(struct isl_wraps * wraps,int w,isl_int * bound,isl_int * ineq,unsigned len,__isl_keep isl_set * set,int negate)1291 static int add_wrap(struct isl_wraps *wraps, int w, isl_int *bound,
1292 	isl_int *ineq, unsigned len, __isl_keep isl_set *set, int negate)
1293 {
1294 	isl_seq_cpy(wraps->mat->row[w], bound, len);
1295 	if (negate) {
1296 		isl_seq_neg(wraps->mat->row[w + 1], ineq, len);
1297 		ineq = wraps->mat->row[w + 1];
1298 	}
1299 	if (!isl_set_wrap_facet(set, wraps->mat->row[w], ineq))
1300 		return -1;
1301 	if (isl_seq_eq(wraps->mat->row[w], bound, len))
1302 		return 0;
1303 	if (!allow_wrap(wraps, w))
1304 		return 0;
1305 	return 1;
1306 }
1307 
1308 /* This function has two modes of operations.
1309  *
1310  * If "add_valid" is set, then all the constraints of info->bmap
1311  * (except the opposite of "bound") are valid for the other basic map.
1312  * In this case, attempts are made to wrap some of these valid constraints
1313  * to more tightly fit around "set".  Only successful wrappings are recorded
1314  * and failed wrappings are ignored.
1315  *
1316  * If "add_valid" is not set, then some of the constraints of info->bmap
1317  * are not valid for the other basic map, and only those are considered
1318  * for wrapping.  In this case all attempted wrappings need to succeed.
1319  * Otherwise "wraps" is marked as failed.
1320  * Note that the constraints that are valid for the other basic map
1321  * will be added to the combined basic map by default, so there is
1322  * no need to wrap them.
1323  * The caller wrap_in_facets even relies on this function not wrapping
1324  * any constraints that are already valid.
1325  *
1326  * Only consider constraints that are not redundant (as determined
1327  * by info->tab) and that are valid or invalid depending on "add_valid".
1328  * Wrap each constraint around "bound" such that it includes the whole
1329  * set "set" and append the resulting constraint to "wraps".
1330  * "wraps" is assumed to have been pre-allocated to the appropriate size.
1331  * wraps->n_row is the number of actual wrapped constraints that have
1332  * been added.
1333  * If any of the wrapping problems results in a constraint that is
1334  * identical to "bound", then this means that "set" is unbounded in such
1335  * a way that no wrapping is possible.
1336  * Similarly, if we want to bound the coefficients of the wrapping
1337  * constraints and a newly added wrapping constraint does not
1338  * satisfy the bound, then the wrapping is considered to have failed.
1339  * Note though that "wraps" is only marked failed if "add_valid" is not set.
1340  */
add_selected_wraps(struct isl_wraps * wraps,struct isl_coalesce_info * info,isl_int * bound,__isl_keep isl_set * set,int add_valid)1341 static isl_stat add_selected_wraps(struct isl_wraps *wraps,
1342 	struct isl_coalesce_info *info, isl_int *bound, __isl_keep isl_set *set,
1343 	int add_valid)
1344 {
1345 	int l, m;
1346 	int w;
1347 	int added;
1348 	isl_basic_map *bmap = info->bmap;
1349 	isl_size total = isl_basic_map_dim(bmap, isl_dim_all);
1350 	unsigned len = 1 + total;
1351 
1352 	if (total < 0)
1353 		return isl_stat_error;
1354 
1355 	w = wraps->mat->n_row;
1356 
1357 	for (l = 0; l < bmap->n_ineq; ++l) {
1358 		int is_valid = info->ineq[l] == STATUS_VALID;
1359 		if ((!add_valid && is_valid) ||
1360 		    info->ineq[l] == STATUS_REDUNDANT)
1361 			continue;
1362 		if (isl_seq_is_neg(bound, bmap->ineq[l], len))
1363 			continue;
1364 		if (isl_seq_eq(bound, bmap->ineq[l], len))
1365 			continue;
1366 		if (isl_tab_is_redundant(info->tab, bmap->n_eq + l))
1367 			continue;
1368 
1369 		added = add_wrap(wraps, w, bound, bmap->ineq[l], len, set, 0);
1370 		if (added < 0)
1371 			return isl_stat_error;
1372 		if (!added && !is_valid)
1373 			goto unbounded;
1374 		if (added)
1375 			++w;
1376 	}
1377 	for (l = 0; l < bmap->n_eq; ++l) {
1378 		if (isl_seq_is_neg(bound, bmap->eq[l], len))
1379 			continue;
1380 		if (isl_seq_eq(bound, bmap->eq[l], len))
1381 			continue;
1382 
1383 		for (m = 0; m < 2; ++m) {
1384 			if (info->eq[2 * l + m] == STATUS_VALID)
1385 				continue;
1386 			added = add_wrap(wraps, w, bound, bmap->eq[l], len,
1387 					set, !m);
1388 			if (added < 0)
1389 				return isl_stat_error;
1390 			if (!added)
1391 				goto unbounded;
1392 			++w;
1393 		}
1394 	}
1395 
1396 	wraps->mat->n_row = w;
1397 	return isl_stat_ok;
1398 unbounded:
1399 	return wraps_mark_failed(wraps);
1400 }
1401 
1402 /* For each constraint in info->bmap that is not redundant (as determined
1403  * by info->tab) and that is not a valid constraint for the other basic map,
1404  * wrap the constraint around "bound" such that it includes the whole
1405  * set "set" and append the resulting constraint to "wraps".
1406  * Note that the constraints that are valid for the other basic map
1407  * will be added to the combined basic map by default, so there is
1408  * no need to wrap them.
1409  * The caller wrap_in_facets even relies on this function not wrapping
1410  * any constraints that are already valid.
1411  * "wraps" is assumed to have been pre-allocated to the appropriate size.
1412  * wraps->n_row is the number of actual wrapped constraints that have
1413  * been added.
1414  * If any of the wrapping problems results in a constraint that is
1415  * identical to "bound", then this means that "set" is unbounded in such
1416  * a way that no wrapping is possible.  If this happens then "wraps"
1417  * is marked as failed.
1418  * Similarly, if we want to bound the coefficients of the wrapping
1419  * constraints and a newly added wrapping constraint does not
1420  * satisfy the bound, then "wraps" is also marked as failed.
1421  */
add_wraps(struct isl_wraps * wraps,struct isl_coalesce_info * info,isl_int * bound,__isl_keep isl_set * set)1422 static isl_stat add_wraps(struct isl_wraps *wraps,
1423 	struct isl_coalesce_info *info, isl_int *bound, __isl_keep isl_set *set)
1424 {
1425 	return add_selected_wraps(wraps, info, bound, set, 0);
1426 }
1427 
1428 /* Check if the constraints in "wraps" from "first" until the last
1429  * are all valid for the basic set represented by "tab",
1430  * dropping the invalid constraints if "keep" is set and
1431  * marking the wrapping as failed if "keep" is not set and
1432  * any constraint turns out to be invalid.
1433  */
check_wraps(struct isl_wraps * wraps,int first,struct isl_tab * tab,int keep)1434 static isl_stat check_wraps(struct isl_wraps *wraps, int first,
1435 	struct isl_tab *tab, int keep)
1436 {
1437 	int i;
1438 
1439 	for (i = wraps->mat->n_row - 1; i >= first; --i) {
1440 		enum isl_ineq_type type;
1441 		type = isl_tab_ineq_type(tab, wraps->mat->row[i]);
1442 		if (type == isl_ineq_error)
1443 			return isl_stat_error;
1444 		if (type == isl_ineq_redundant)
1445 			continue;
1446 		if (!keep)
1447 			return wraps_mark_failed(wraps);
1448 		wraps->mat = isl_mat_drop_rows(wraps->mat, i, 1);
1449 		if (!wraps->mat)
1450 			return isl_stat_error;
1451 	}
1452 
1453 	return isl_stat_ok;
1454 }
1455 
1456 /* Return a set that corresponds to the non-redundant constraints
1457  * (as recorded in tab) of bmap.
1458  *
1459  * It's important to remove the redundant constraints as some
1460  * of the other constraints may have been modified after the
1461  * constraints were marked redundant.
1462  * In particular, a constraint may have been relaxed.
1463  * Redundant constraints are ignored when a constraint is relaxed
1464  * and should therefore continue to be ignored ever after.
1465  * Otherwise, the relaxation might be thwarted by some of
1466  * these constraints.
1467  *
1468  * Update the underlying set to ensure that the dimension doesn't change.
1469  * Otherwise the integer divisions could get dropped if the tab
1470  * turns out to be empty.
1471  */
set_from_updated_bmap(__isl_keep isl_basic_map * bmap,struct isl_tab * tab)1472 static __isl_give isl_set *set_from_updated_bmap(__isl_keep isl_basic_map *bmap,
1473 	struct isl_tab *tab)
1474 {
1475 	isl_basic_set *bset;
1476 
1477 	bmap = isl_basic_map_copy(bmap);
1478 	bset = isl_basic_map_underlying_set(bmap);
1479 	bset = isl_basic_set_cow(bset);
1480 	bset = isl_basic_set_update_from_tab(bset, tab);
1481 	return isl_set_from_basic_set(bset);
1482 }
1483 
1484 /* Does "info" have any cut constraints that are redundant?
1485  */
has_redundant_cuts(struct isl_coalesce_info * info)1486 static isl_bool has_redundant_cuts(struct isl_coalesce_info *info)
1487 {
1488 	int l;
1489 	isl_size n_eq, n_ineq;
1490 
1491 	n_eq = isl_basic_map_n_equality(info->bmap);
1492 	n_ineq = isl_basic_map_n_inequality(info->bmap);
1493 	if (n_eq < 0 || n_ineq < 0)
1494 		return isl_bool_error;
1495 	for (l = 0; l < n_ineq; ++l) {
1496 		int red;
1497 
1498 		if (info->ineq[l] != STATUS_CUT)
1499 			continue;
1500 		red = isl_tab_is_redundant(info->tab, n_eq + l);
1501 		if (red < 0)
1502 			return isl_bool_error;
1503 		if (red)
1504 			return isl_bool_true;
1505 	}
1506 
1507 	return isl_bool_false;
1508 }
1509 
1510 /* Wrap some constraints of info->bmap that bound the facet defined
1511  * by inequality "k" around (the opposite of) this inequality to
1512  * include "set".  "bound" may be used to store the negated inequality.
1513  *
1514  * If "add_valid" is set, then all ridges are already valid and
1515  * the purpose is to wrap "set" more tightly.  In this case,
1516  * wrapping doesn't fail, although it is possible that no constraint
1517  * gets wrapped.
1518  *
1519  * If "add_valid" is not set, then some of the ridges are cut constraints
1520  * and only those are wrapped around "set".
1521  *
1522  * Since the wrapped constraints are not guaranteed to contain the whole
1523  * of info->bmap, we check them in check_wraps.
1524  * If any of the wrapped constraints turn out to be invalid, then
1525  * check_wraps will mark "wraps" as failed if "add_valid" is not set.
1526  * If "add_valid" is set, then the offending constraints are
1527  * simply removed.
1528  *
1529  * If any of the cut constraints of info->bmap turn out
1530  * to be redundant with respect to other constraints
1531  * then these will neither be wrapped nor added directly to the result.
1532  * The result may therefore not be correct.
1533  * Skip wrapping and mark "wraps" as failed in this case.
1534  */
add_selected_wraps_around_facet(struct isl_wraps * wraps,struct isl_coalesce_info * info,int k,isl_int * bound,__isl_keep isl_set * set,int add_valid)1535 static isl_stat add_selected_wraps_around_facet(struct isl_wraps *wraps,
1536 	struct isl_coalesce_info *info, int k, isl_int *bound,
1537 	__isl_keep isl_set *set, int add_valid)
1538 {
1539 	isl_bool nowrap;
1540 	struct isl_tab_undo *snap;
1541 	int n;
1542 	isl_size total = isl_basic_map_dim(info->bmap, isl_dim_all);
1543 
1544 	if (total < 0)
1545 		return isl_stat_error;
1546 
1547 	snap = isl_tab_snap(info->tab);
1548 
1549 	if (isl_tab_select_facet(info->tab, info->bmap->n_eq + k) < 0)
1550 		return isl_stat_error;
1551 	if (isl_tab_detect_redundant(info->tab) < 0)
1552 		return isl_stat_error;
1553 	nowrap = has_redundant_cuts(info);
1554 	if (nowrap < 0)
1555 		return isl_stat_error;
1556 
1557 	n = wraps->mat->n_row;
1558 	if (!nowrap) {
1559 		isl_seq_neg(bound, info->bmap->ineq[k], 1 + total);
1560 
1561 		if (add_selected_wraps(wraps, info, bound, set, add_valid) < 0)
1562 			return isl_stat_error;
1563 	}
1564 
1565 	if (isl_tab_rollback(info->tab, snap) < 0)
1566 		return isl_stat_error;
1567 	if (nowrap)
1568 		return wraps_mark_failed(wraps);
1569 	if (check_wraps(wraps, n, info->tab, add_valid) < 0)
1570 		return isl_stat_error;
1571 
1572 	return isl_stat_ok;
1573 }
1574 
1575 /* Wrap the constraints of info->bmap that bound the facet defined
1576  * by inequality "k" around (the opposite of) this inequality to
1577  * include "set".  "bound" may be used to store the negated inequality.
1578  * If any of the wrapped constraints turn out to be invalid for info->bmap
1579  * itself, then mark "wraps" as failed.
1580  */
add_wraps_around_facet(struct isl_wraps * wraps,struct isl_coalesce_info * info,int k,isl_int * bound,__isl_keep isl_set * set)1581 static isl_stat add_wraps_around_facet(struct isl_wraps *wraps,
1582 	struct isl_coalesce_info *info, int k, isl_int *bound,
1583 	__isl_keep isl_set *set)
1584 {
1585 	return add_selected_wraps_around_facet(wraps, info, k, bound, set, 0);
1586 }
1587 
1588 /* Wrap the (valid) constraints of info->bmap that bound the facet defined
1589  * by inequality "k" around (the opposite of) this inequality to
1590  * include "set" more tightly.
1591  * "bound" may be used to store the negated inequality.
1592  * Remove any wrapping constraints that turn out to be invalid
1593  * for info->bmap itself.
1594  */
add_valid_wraps_around_facet(struct isl_wraps * wraps,struct isl_coalesce_info * info,int k,isl_int * bound,__isl_keep isl_set * set)1595 static isl_stat add_valid_wraps_around_facet(struct isl_wraps *wraps,
1596 	struct isl_coalesce_info *info, int k, isl_int *bound,
1597 	__isl_keep isl_set *set)
1598 {
1599 	return add_selected_wraps_around_facet(wraps, info, k, bound, set, 1);
1600 }
1601 
1602 /* Basic map "i" has an inequality (say "k") that is adjacent
1603  * to some inequality of basic map "j".  All the other inequalities
1604  * are valid for "j".
1605  * Check if basic map "j" forms an extension of basic map "i".
1606  *
1607  * Note that this function is only called if some of the equalities or
1608  * inequalities of basic map "j" do cut basic map "i".  The function is
1609  * correct even if there are no such cut constraints, but in that case
1610  * the additional checks performed by this function are overkill.
1611  *
1612  * First try and wrap the ridges of "k" around "j".
1613  * Note that those ridges are already valid for "j",
1614  * but the wrapped versions may wrap "j" more tightly,
1615  * increasing the chances of "j" being detected as an extension of "i"
1616  */
is_adj_ineq_extension(int i,int j,struct isl_coalesce_info * info)1617 static enum isl_change is_adj_ineq_extension(int i, int j,
1618 	struct isl_coalesce_info *info)
1619 {
1620 	int k;
1621 	enum isl_change change;
1622 	isl_size total;
1623 	isl_size n_eq_i, n_ineq_i;
1624 	struct isl_wraps wraps;
1625 	isl_ctx *ctx;
1626 	isl_mat *mat;
1627 	isl_vec *bound;
1628 	isl_set *set_j;
1629 	isl_stat r;
1630 
1631 	k = find_ineq(&info[i], STATUS_ADJ_INEQ);
1632 	if (k < 0)
1633 		isl_die(isl_basic_map_get_ctx(info[i].bmap), isl_error_internal,
1634 			"info[i].ineq should have exactly one STATUS_ADJ_INEQ",
1635 			return isl_change_error);
1636 
1637 	total = isl_basic_map_dim(info[i].bmap, isl_dim_all);
1638 	n_eq_i = isl_basic_map_n_equality(info[i].bmap);
1639 	n_ineq_i = isl_basic_map_n_inequality(info[i].bmap);
1640 	if (total < 0 || n_eq_i < 0 || n_ineq_i < 0)
1641 		return isl_change_error;
1642 
1643 	set_j = set_from_updated_bmap(info[j].bmap, info[j].tab);
1644 	ctx = isl_basic_map_get_ctx(info[i].bmap);
1645 	bound = isl_vec_alloc(ctx, 1 + total);
1646 	mat = isl_mat_alloc(ctx, 2 * n_eq_i + n_ineq_i, 1 + total);
1647 	if (wraps_init(&wraps, mat, info, i, j) < 0)
1648 		goto error;
1649 	if (!bound || !set_j)
1650 		goto error;
1651 	r = add_valid_wraps_around_facet(&wraps, &info[i], k, bound->el, set_j);
1652 	if (r < 0)
1653 		goto error;
1654 
1655 	change = is_adj_ineq_extension_with_wraps(i, j, k, info, wraps.mat);
1656 
1657 	wraps_free(&wraps);
1658 	isl_vec_free(bound);
1659 	isl_set_free(set_j);
1660 
1661 	return change;
1662 error:
1663 	wraps_free(&wraps);
1664 	isl_vec_free(bound);
1665 	isl_set_free(set_j);
1666 	return isl_change_error;
1667 }
1668 
1669 /* Both basic maps have at least one inequality with and adjacent
1670  * (but opposite) inequality in the other basic map.
1671  * Check that there are no cut constraints and that there is only
1672  * a single pair of adjacent inequalities.
1673  * If so, we can replace the pair by a single basic map described
1674  * by all but the pair of adjacent inequalities.
1675  * Any additional points introduced lie strictly between the two
1676  * adjacent hyperplanes and can therefore be integral.
1677  *
1678  *        ____			  _____
1679  *       /    ||\		 /     \
1680  *      /     || \		/       \
1681  *      \     ||  \	=>	\        \
1682  *       \    ||  /		 \       /
1683  *        \___||_/		  \_____/
1684  *
1685  * The test for a single pair of adjacent inequalities is important
1686  * for avoiding the combination of two basic maps like the following
1687  *
1688  *       /|
1689  *      / |
1690  *     /__|
1691  *         _____
1692  *         |   |
1693  *         |   |
1694  *         |___|
1695  *
1696  * If there are some cut constraints on one side, then we may
1697  * still be able to fuse the two basic maps, but we need to perform
1698  * some additional checks in is_adj_ineq_extension.
1699  */
check_adj_ineq(int i,int j,struct isl_coalesce_info * info)1700 static enum isl_change check_adj_ineq(int i, int j,
1701 	struct isl_coalesce_info *info)
1702 {
1703 	int count_i, count_j;
1704 	int cut_i, cut_j;
1705 
1706 	count_i = count_ineq(&info[i], STATUS_ADJ_INEQ);
1707 	count_j = count_ineq(&info[j], STATUS_ADJ_INEQ);
1708 
1709 	if (count_i != 1 && count_j != 1)
1710 		return isl_change_none;
1711 
1712 	cut_i = any_eq(&info[i], STATUS_CUT) || any_ineq(&info[i], STATUS_CUT);
1713 	cut_j = any_eq(&info[j], STATUS_CUT) || any_ineq(&info[j], STATUS_CUT);
1714 
1715 	if (!cut_i && !cut_j && count_i == 1 && count_j == 1)
1716 		return fuse(i, j, info, NULL, 0, 0);
1717 
1718 	if (count_i == 1 && !cut_i)
1719 		return is_adj_ineq_extension(i, j, info);
1720 
1721 	if (count_j == 1 && !cut_j)
1722 		return is_adj_ineq_extension(j, i, info);
1723 
1724 	return isl_change_none;
1725 }
1726 
1727 /* Given a basic set i with a constraint k that is adjacent to
1728  * basic set j, check if we can wrap
1729  * both the facet corresponding to k (if "wrap_facet" is set) and basic map j
1730  * (always) around their ridges to include the other set.
1731  * If so, replace the pair of basic sets by their union.
1732  *
1733  * All constraints of i (except k) are assumed to be valid or
1734  * cut constraints for j.
1735  * Wrapping the cut constraints to include basic map j may result
1736  * in constraints that are no longer valid of basic map i
1737  * we have to check that the resulting wrapping constraints are valid for i.
1738  * If "wrap_facet" is not set, then all constraints of i (except k)
1739  * are assumed to be valid for j.
1740  *        ____			  _____
1741  *       /    | 		 /     \
1742  *      /     ||  		/      |
1743  *      \     ||   	=>	\      |
1744  *       \    ||		 \     |
1745  *        \___||		  \____|
1746  *
1747  */
can_wrap_in_facet(int i,int j,int k,struct isl_coalesce_info * info,int wrap_facet)1748 static enum isl_change can_wrap_in_facet(int i, int j, int k,
1749 	struct isl_coalesce_info *info, int wrap_facet)
1750 {
1751 	enum isl_change change = isl_change_none;
1752 	struct isl_wraps wraps;
1753 	isl_ctx *ctx;
1754 	isl_mat *mat;
1755 	struct isl_set *set_i = NULL;
1756 	struct isl_set *set_j = NULL;
1757 	struct isl_vec *bound = NULL;
1758 	isl_size total = isl_basic_map_dim(info[i].bmap, isl_dim_all);
1759 
1760 	if (total < 0)
1761 		return isl_change_error;
1762 	set_i = set_from_updated_bmap(info[i].bmap, info[i].tab);
1763 	set_j = set_from_updated_bmap(info[j].bmap, info[j].tab);
1764 	ctx = isl_basic_map_get_ctx(info[i].bmap);
1765 	mat = isl_mat_alloc(ctx, 2 * (info[i].bmap->n_eq + info[j].bmap->n_eq) +
1766 				    info[i].bmap->n_ineq + info[j].bmap->n_ineq,
1767 				    1 + total);
1768 	if (wraps_init(&wraps, mat, info, i, j) < 0)
1769 		goto error;
1770 	bound = isl_vec_alloc(ctx, 1 + total);
1771 	if (!set_i || !set_j || !bound)
1772 		goto error;
1773 
1774 	isl_seq_cpy(bound->el, info[i].bmap->ineq[k], 1 + total);
1775 	isl_int_add_ui(bound->el[0], bound->el[0], 1);
1776 	isl_seq_normalize(ctx, bound->el, 1 + total);
1777 
1778 	isl_seq_cpy(wraps.mat->row[0], bound->el, 1 + total);
1779 	wraps.mat->n_row = 1;
1780 
1781 	if (add_wraps(&wraps, &info[j], bound->el, set_i) < 0)
1782 		goto error;
1783 	if (wraps.failed)
1784 		goto unbounded;
1785 
1786 	if (wrap_facet) {
1787 		if (add_wraps_around_facet(&wraps, &info[i], k,
1788 					    bound->el, set_j) < 0)
1789 			goto error;
1790 		if (wraps.failed)
1791 			goto unbounded;
1792 	}
1793 
1794 	change = fuse(i, j, info, wraps.mat, 0, 0);
1795 
1796 unbounded:
1797 	wraps_free(&wraps);
1798 
1799 	isl_set_free(set_i);
1800 	isl_set_free(set_j);
1801 
1802 	isl_vec_free(bound);
1803 
1804 	return change;
1805 error:
1806 	wraps_free(&wraps);
1807 	isl_vec_free(bound);
1808 	isl_set_free(set_i);
1809 	isl_set_free(set_j);
1810 	return isl_change_error;
1811 }
1812 
1813 /* Given a cut constraint t(x) >= 0 of basic map i, stored in row "w"
1814  * of wrap.mat, replace it by its relaxed version t(x) + 1 >= 0, and
1815  * add wrapping constraints to wrap.mat for all constraints
1816  * of basic map j that bound the part of basic map j that sticks out
1817  * of the cut constraint.
1818  * "set_i" is the underlying set of basic map i.
1819  * If any wrapping fails, then wraps->mat.n_row is reset to zero.
1820  *
1821  * In particular, we first intersect basic map j with t(x) + 1 = 0.
1822  * If the result is empty, then t(x) >= 0 was actually a valid constraint
1823  * (with respect to the integer points), so we add t(x) >= 0 instead.
1824  * Otherwise, we wrap the constraints of basic map j that are not
1825  * redundant in this intersection and that are not already valid
1826  * for basic map i over basic map i.
1827  * Note that it is sufficient to wrap the constraints to include
1828  * basic map i, because we will only wrap the constraints that do
1829  * not include basic map i already.  The wrapped constraint will
1830  * therefore be more relaxed compared to the original constraint.
1831  * Since the original constraint is valid for basic map j, so is
1832  * the wrapped constraint.
1833  */
wrap_in_facet(struct isl_wraps * wraps,int w,struct isl_coalesce_info * info_j,__isl_keep isl_set * set_i,struct isl_tab_undo * snap)1834 static isl_stat wrap_in_facet(struct isl_wraps *wraps, int w,
1835 	struct isl_coalesce_info *info_j, __isl_keep isl_set *set_i,
1836 	struct isl_tab_undo *snap)
1837 {
1838 	isl_int_add_ui(wraps->mat->row[w][0], wraps->mat->row[w][0], 1);
1839 	if (isl_tab_add_eq(info_j->tab, wraps->mat->row[w]) < 0)
1840 		return isl_stat_error;
1841 	if (isl_tab_detect_redundant(info_j->tab) < 0)
1842 		return isl_stat_error;
1843 
1844 	if (info_j->tab->empty)
1845 		isl_int_sub_ui(wraps->mat->row[w][0], wraps->mat->row[w][0], 1);
1846 	else if (add_wraps(wraps, info_j, wraps->mat->row[w], set_i) < 0)
1847 		return isl_stat_error;
1848 
1849 	if (isl_tab_rollback(info_j->tab, snap) < 0)
1850 		return isl_stat_error;
1851 
1852 	return isl_stat_ok;
1853 }
1854 
1855 /* Given a pair of basic maps i and j such that j sticks out
1856  * of i at n cut constraints, each time by at most one,
1857  * try to compute wrapping constraints and replace the two
1858  * basic maps by a single basic map.
1859  * The other constraints of i are assumed to be valid for j.
1860  * "set_i" is the underlying set of basic map i.
1861  * "wraps" has been initialized to be of the right size.
1862  *
1863  * For each cut constraint t(x) >= 0 of i, we add the relaxed version
1864  * t(x) + 1 >= 0, along with wrapping constraints for all constraints
1865  * of basic map j that bound the part of basic map j that sticks out
1866  * of the cut constraint.
1867  *
1868  * If any wrapping fails, i.e., if we cannot wrap to touch
1869  * the union, then we give up.
1870  * Otherwise, the pair of basic maps is replaced by their union.
1871  */
try_wrap_in_facets(int i,int j,struct isl_coalesce_info * info,struct isl_wraps * wraps,__isl_keep isl_set * set_i)1872 static enum isl_change try_wrap_in_facets(int i, int j,
1873 	struct isl_coalesce_info *info, struct isl_wraps *wraps,
1874 	__isl_keep isl_set *set_i)
1875 {
1876 	int k, l, w;
1877 	isl_size total;
1878 	struct isl_tab_undo *snap;
1879 
1880 	total = isl_basic_map_dim(info[i].bmap, isl_dim_all);
1881 	if (total < 0)
1882 		return isl_change_error;
1883 
1884 	snap = isl_tab_snap(info[j].tab);
1885 
1886 	for (k = 0; k < info[i].bmap->n_eq; ++k) {
1887 		for (l = 0; l < 2; ++l) {
1888 			if (info[i].eq[2 * k + l] != STATUS_CUT)
1889 				continue;
1890 			w = wraps->mat->n_row++;
1891 			if (l == 0)
1892 				isl_seq_neg(wraps->mat->row[w],
1893 					    info[i].bmap->eq[k], 1 + total);
1894 			else
1895 				isl_seq_cpy(wraps->mat->row[w],
1896 					    info[i].bmap->eq[k], 1 + total);
1897 			if (wrap_in_facet(wraps, w, &info[j], set_i, snap) < 0)
1898 				return isl_change_error;
1899 
1900 			if (wraps->failed)
1901 				return isl_change_none;
1902 		}
1903 	}
1904 
1905 	for (k = 0; k < info[i].bmap->n_ineq; ++k) {
1906 		if (info[i].ineq[k] != STATUS_CUT)
1907 			continue;
1908 		w = wraps->mat->n_row++;
1909 		isl_seq_cpy(wraps->mat->row[w],
1910 			    info[i].bmap->ineq[k], 1 + total);
1911 		if (wrap_in_facet(wraps, w, &info[j], set_i, snap) < 0)
1912 			return isl_change_error;
1913 
1914 		if (wraps->failed)
1915 			return isl_change_none;
1916 	}
1917 
1918 	return fuse(i, j, info, wraps->mat, 0, 1);
1919 }
1920 
1921 /* Given a pair of basic maps i and j such that j sticks out
1922  * of i at n cut constraints, each time by at most one,
1923  * try to compute wrapping constraints and replace the two
1924  * basic maps by a single basic map.
1925  * The other constraints of i are assumed to be valid for j.
1926  *
1927  * The core computation is performed by try_wrap_in_facets.
1928  * This function simply extracts an underlying set representation
1929  * of basic map i and initializes the data structure for keeping
1930  * track of wrapping constraints.
1931  */
wrap_in_facets(int i,int j,int n,struct isl_coalesce_info * info)1932 static enum isl_change wrap_in_facets(int i, int j, int n,
1933 	struct isl_coalesce_info *info)
1934 {
1935 	enum isl_change change = isl_change_none;
1936 	struct isl_wraps wraps;
1937 	isl_ctx *ctx;
1938 	isl_mat *mat;
1939 	isl_set *set_i = NULL;
1940 	isl_size total = isl_basic_map_dim(info[i].bmap, isl_dim_all);
1941 	int max_wrap;
1942 
1943 	if (total < 0)
1944 		return isl_change_error;
1945 	if (isl_tab_extend_cons(info[j].tab, 1) < 0)
1946 		return isl_change_error;
1947 
1948 	max_wrap = 1 + 2 * info[j].bmap->n_eq + info[j].bmap->n_ineq;
1949 	max_wrap *= n;
1950 
1951 	set_i = set_from_updated_bmap(info[i].bmap, info[i].tab);
1952 	ctx = isl_basic_map_get_ctx(info[i].bmap);
1953 	mat = isl_mat_alloc(ctx, max_wrap, 1 + total);
1954 	if (wraps_init(&wraps, mat, info, i, j) < 0)
1955 		goto error;
1956 	if (!set_i)
1957 		goto error;
1958 
1959 	change = try_wrap_in_facets(i, j, info, &wraps, set_i);
1960 
1961 	wraps_free(&wraps);
1962 	isl_set_free(set_i);
1963 
1964 	return change;
1965 error:
1966 	wraps_free(&wraps);
1967 	isl_set_free(set_i);
1968 	return isl_change_error;
1969 }
1970 
1971 /* Return the effect of inequality "ineq" on the tableau "tab",
1972  * after relaxing the constant term of "ineq" by one.
1973  */
type_of_relaxed(struct isl_tab * tab,isl_int * ineq)1974 static enum isl_ineq_type type_of_relaxed(struct isl_tab *tab, isl_int *ineq)
1975 {
1976 	enum isl_ineq_type type;
1977 
1978 	isl_int_add_ui(ineq[0], ineq[0], 1);
1979 	type = isl_tab_ineq_type(tab, ineq);
1980 	isl_int_sub_ui(ineq[0], ineq[0], 1);
1981 
1982 	return type;
1983 }
1984 
1985 /* Given two basic sets i and j,
1986  * check if relaxing all the cut constraints of i by one turns
1987  * them into valid constraint for j and check if we can wrap in
1988  * the bits that are sticking out.
1989  * If so, replace the pair by their union.
1990  *
1991  * We first check if all relaxed cut inequalities of i are valid for j
1992  * and then try to wrap in the intersections of the relaxed cut inequalities
1993  * with j.
1994  *
1995  * During this wrapping, we consider the points of j that lie at a distance
1996  * of exactly 1 from i.  In particular, we ignore the points that lie in
1997  * between this lower-dimensional space and the basic map i.
1998  * We can therefore only apply this to integer maps.
1999  *        ____			  _____
2000  *       / ___|_		 /     \
2001  *      / |    |  		/      |
2002  *      \ |    |   	=>	\      |
2003  *       \|____|		 \     |
2004  *        \___| 		  \____/
2005  *
2006  *	 _____			 ______
2007  *	| ____|_		|      \
2008  *	| |     |		|       |
2009  *	| |	|	=>	|       |
2010  *	|_|     |		|       |
2011  *	  |_____|		 \______|
2012  *
2013  *	 _______
2014  *	|       |
2015  *	|  |\   |
2016  *	|  | \  |
2017  *	|  |  \ |
2018  *	|  |   \|
2019  *	|  |    \
2020  *	|  |_____\
2021  *	|       |
2022  *	|_______|
2023  *
2024  * Wrapping can fail if the result of wrapping one of the facets
2025  * around its edges does not produce any new facet constraint.
2026  * In particular, this happens when we try to wrap in unbounded sets.
2027  *
2028  *	 _______________________________________________________________________
2029  *	|
2030  *	|  ___
2031  *	| |   |
2032  *	|_|   |_________________________________________________________________
2033  *	  |___|
2034  *
2035  * The following is not an acceptable result of coalescing the above two
2036  * sets as it includes extra integer points.
2037  *	 _______________________________________________________________________
2038  *	|
2039  *	|
2040  *	|
2041  *	|
2042  *	 \______________________________________________________________________
2043  */
can_wrap_in_set(int i,int j,struct isl_coalesce_info * info)2044 static enum isl_change can_wrap_in_set(int i, int j,
2045 	struct isl_coalesce_info *info)
2046 {
2047 	int k, l;
2048 	int n;
2049 	isl_size total;
2050 
2051 	if (ISL_F_ISSET(info[i].bmap, ISL_BASIC_MAP_RATIONAL) ||
2052 	    ISL_F_ISSET(info[j].bmap, ISL_BASIC_MAP_RATIONAL))
2053 		return isl_change_none;
2054 
2055 	n = count_eq(&info[i], STATUS_CUT) + count_ineq(&info[i], STATUS_CUT);
2056 	if (n == 0)
2057 		return isl_change_none;
2058 
2059 	total = isl_basic_map_dim(info[i].bmap, isl_dim_all);
2060 	if (total < 0)
2061 		return isl_change_error;
2062 	for (k = 0; k < info[i].bmap->n_eq; ++k) {
2063 		for (l = 0; l < 2; ++l) {
2064 			enum isl_ineq_type type;
2065 
2066 			if (info[i].eq[2 * k + l] != STATUS_CUT)
2067 				continue;
2068 
2069 			if (l == 0)
2070 				isl_seq_neg(info[i].bmap->eq[k],
2071 					    info[i].bmap->eq[k], 1 + total);
2072 			type = type_of_relaxed(info[j].tab,
2073 					    info[i].bmap->eq[k]);
2074 			if (l == 0)
2075 				isl_seq_neg(info[i].bmap->eq[k],
2076 					    info[i].bmap->eq[k], 1 + total);
2077 			if (type == isl_ineq_error)
2078 				return isl_change_error;
2079 			if (type != isl_ineq_redundant)
2080 				return isl_change_none;
2081 		}
2082 	}
2083 
2084 	for (k = 0; k < info[i].bmap->n_ineq; ++k) {
2085 		enum isl_ineq_type type;
2086 
2087 		if (info[i].ineq[k] != STATUS_CUT)
2088 			continue;
2089 
2090 		type = type_of_relaxed(info[j].tab, info[i].bmap->ineq[k]);
2091 		if (type == isl_ineq_error)
2092 			return isl_change_error;
2093 		if (type != isl_ineq_redundant)
2094 			return isl_change_none;
2095 	}
2096 
2097 	return wrap_in_facets(i, j, n, info);
2098 }
2099 
2100 /* Check if either i or j has only cut constraints that can
2101  * be used to wrap in (a facet of) the other basic set.
2102  * if so, replace the pair by their union.
2103  */
check_wrap(int i,int j,struct isl_coalesce_info * info)2104 static enum isl_change check_wrap(int i, int j, struct isl_coalesce_info *info)
2105 {
2106 	enum isl_change change = isl_change_none;
2107 
2108 	change = can_wrap_in_set(i, j, info);
2109 	if (change != isl_change_none)
2110 		return change;
2111 
2112 	change = can_wrap_in_set(j, i, info);
2113 	return change;
2114 }
2115 
2116 /* Check if all inequality constraints of "i" that cut "j" cease
2117  * to be cut constraints if they are relaxed by one.
2118  * If so, collect the cut constraints in "list".
2119  * The caller is responsible for allocating "list".
2120  */
all_cut_by_one(int i,int j,struct isl_coalesce_info * info,int * list)2121 static isl_bool all_cut_by_one(int i, int j, struct isl_coalesce_info *info,
2122 	int *list)
2123 {
2124 	int l, n;
2125 
2126 	n = 0;
2127 	for (l = 0; l < info[i].bmap->n_ineq; ++l) {
2128 		enum isl_ineq_type type;
2129 
2130 		if (info[i].ineq[l] != STATUS_CUT)
2131 			continue;
2132 		type = type_of_relaxed(info[j].tab, info[i].bmap->ineq[l]);
2133 		if (type == isl_ineq_error)
2134 			return isl_bool_error;
2135 		if (type != isl_ineq_redundant)
2136 			return isl_bool_false;
2137 		list[n++] = l;
2138 	}
2139 
2140 	return isl_bool_true;
2141 }
2142 
2143 /* Given two basic maps such that "j" has at least one equality constraint
2144  * that is adjacent to an inequality constraint of "i" and such that "i" has
2145  * exactly one inequality constraint that is adjacent to an equality
2146  * constraint of "j", check whether "i" can be extended to include "j" or
2147  * whether "j" can be wrapped into "i".
2148  * All remaining constraints of "i" and "j" are assumed to be valid
2149  * or cut constraints of the other basic map.
2150  * However, none of the equality constraints of "i" are cut constraints.
2151  *
2152  * If "i" has any "cut" inequality constraints, then check if relaxing
2153  * each of them by one is sufficient for them to become valid.
2154  * If so, check if the inequality constraint adjacent to an equality
2155  * constraint of "j" along with all these cut constraints
2156  * can be relaxed by one to contain exactly "j".
2157  * Otherwise, or if this fails, check if "j" can be wrapped into "i".
2158  */
check_single_adj_eq(int i,int j,struct isl_coalesce_info * info)2159 static enum isl_change check_single_adj_eq(int i, int j,
2160 	struct isl_coalesce_info *info)
2161 {
2162 	enum isl_change change = isl_change_none;
2163 	int k;
2164 	int n_cut;
2165 	int *relax;
2166 	isl_ctx *ctx;
2167 	isl_bool try_relax;
2168 
2169 	n_cut = count_ineq(&info[i], STATUS_CUT);
2170 
2171 	k = find_ineq(&info[i], STATUS_ADJ_EQ);
2172 
2173 	if (n_cut > 0) {
2174 		ctx = isl_basic_map_get_ctx(info[i].bmap);
2175 		relax = isl_calloc_array(ctx, int, 1 + n_cut);
2176 		if (!relax)
2177 			return isl_change_error;
2178 		relax[0] = k;
2179 		try_relax = all_cut_by_one(i, j, info, relax + 1);
2180 		if (try_relax < 0)
2181 			change = isl_change_error;
2182 	} else {
2183 		try_relax = isl_bool_true;
2184 		relax = &k;
2185 	}
2186 	if (try_relax && change == isl_change_none)
2187 		change = is_relaxed_extension(i, j, 1 + n_cut, relax, info);
2188 	if (n_cut > 0)
2189 		free(relax);
2190 	if (change != isl_change_none)
2191 		return change;
2192 
2193 	change = can_wrap_in_facet(i, j, k, info, n_cut > 0);
2194 
2195 	return change;
2196 }
2197 
2198 /* At least one of the basic maps has an equality that is adjacent
2199  * to an inequality.  Make sure that only one of the basic maps has
2200  * such an equality and that the other basic map has exactly one
2201  * inequality adjacent to an equality.
2202  * If the other basic map does not have such an inequality, then
2203  * check if all its constraints are either valid or cut constraints
2204  * and, if so, try wrapping in the first map into the second.
2205  * Otherwise, try to extend one basic map with the other or
2206  * wrap one basic map in the other.
2207  */
check_adj_eq(int i,int j,struct isl_coalesce_info * info)2208 static enum isl_change check_adj_eq(int i, int j,
2209 	struct isl_coalesce_info *info)
2210 {
2211 	if (any_eq(&info[i], STATUS_ADJ_INEQ) &&
2212 	    any_eq(&info[j], STATUS_ADJ_INEQ))
2213 		/* ADJ EQ TOO MANY */
2214 		return isl_change_none;
2215 
2216 	if (any_eq(&info[i], STATUS_ADJ_INEQ))
2217 		return check_adj_eq(j, i, info);
2218 
2219 	/* j has an equality adjacent to an inequality in i */
2220 
2221 	if (count_ineq(&info[i], STATUS_ADJ_EQ) != 1) {
2222 		if (all_valid_or_cut(&info[i]))
2223 			return can_wrap_in_set(i, j, info);
2224 		return isl_change_none;
2225 	}
2226 	if (any_eq(&info[i], STATUS_CUT))
2227 		return isl_change_none;
2228 	if (any_ineq(&info[j], STATUS_ADJ_EQ) ||
2229 	    any_ineq(&info[i], STATUS_ADJ_INEQ) ||
2230 	    any_ineq(&info[j], STATUS_ADJ_INEQ))
2231 		/* ADJ EQ TOO MANY */
2232 		return isl_change_none;
2233 
2234 	return check_single_adj_eq(i, j, info);
2235 }
2236 
2237 /* Disjunct "j" lies on a hyperplane that is adjacent to disjunct "i".
2238  * In particular, disjunct "i" has an inequality constraint that is adjacent
2239  * to a (combination of) equality constraint(s) of disjunct "j",
2240  * but disjunct "j" has no explicit equality constraint adjacent
2241  * to an inequality constraint of disjunct "i".
2242  *
2243  * Disjunct "i" is already known not to have any equality constraints
2244  * that are adjacent to an equality or inequality constraint.
2245  * Check that, other than the inequality constraint mentioned above,
2246  * all other constraints of disjunct "i" are valid for disjunct "j".
2247  * If so, try and wrap in disjunct "j".
2248  */
check_ineq_adj_eq(int i,int j,struct isl_coalesce_info * info)2249 static enum isl_change check_ineq_adj_eq(int i, int j,
2250 	struct isl_coalesce_info *info)
2251 {
2252 	int k;
2253 
2254 	if (any_eq(&info[i], STATUS_CUT))
2255 		return isl_change_none;
2256 	if (any_ineq(&info[i], STATUS_CUT))
2257 		return isl_change_none;
2258 	if (any_ineq(&info[i], STATUS_ADJ_INEQ))
2259 		return isl_change_none;
2260 	if (count_ineq(&info[i], STATUS_ADJ_EQ) != 1)
2261 		return isl_change_none;
2262 
2263 	k = find_ineq(&info[i], STATUS_ADJ_EQ);
2264 
2265 	return can_wrap_in_facet(i, j, k, info, 0);
2266 }
2267 
2268 /* The two basic maps lie on adjacent hyperplanes.  In particular,
2269  * basic map "i" has an equality that lies parallel to basic map "j".
2270  * Check if we can wrap the facets around the parallel hyperplanes
2271  * to include the other set.
2272  *
2273  * We perform basically the same operations as can_wrap_in_facet,
2274  * except that we don't need to select a facet of one of the sets.
2275  *				_
2276  *	\\			\\
2277  *	 \\		=>	 \\
2278  *	  \			  \|
2279  *
2280  * If there is more than one equality of "i" adjacent to an equality of "j",
2281  * then the result will satisfy one or more equalities that are a linear
2282  * combination of these equalities.  These will be encoded as pairs
2283  * of inequalities in the wrapping constraints and need to be made
2284  * explicit.
2285  */
check_eq_adj_eq(int i,int j,struct isl_coalesce_info * info)2286 static enum isl_change check_eq_adj_eq(int i, int j,
2287 	struct isl_coalesce_info *info)
2288 {
2289 	int k;
2290 	enum isl_change change = isl_change_none;
2291 	int detect_equalities = 0;
2292 	struct isl_wraps wraps;
2293 	isl_ctx *ctx;
2294 	isl_mat *mat;
2295 	struct isl_set *set_i = NULL;
2296 	struct isl_set *set_j = NULL;
2297 	struct isl_vec *bound = NULL;
2298 	isl_size total = isl_basic_map_dim(info[i].bmap, isl_dim_all);
2299 
2300 	if (total < 0)
2301 		return isl_change_error;
2302 	if (count_eq(&info[i], STATUS_ADJ_EQ) != 1)
2303 		detect_equalities = 1;
2304 
2305 	k = find_eq(&info[i], STATUS_ADJ_EQ);
2306 
2307 	set_i = set_from_updated_bmap(info[i].bmap, info[i].tab);
2308 	set_j = set_from_updated_bmap(info[j].bmap, info[j].tab);
2309 	ctx = isl_basic_map_get_ctx(info[i].bmap);
2310 	mat = isl_mat_alloc(ctx, 2 * (info[i].bmap->n_eq + info[j].bmap->n_eq) +
2311 				    info[i].bmap->n_ineq + info[j].bmap->n_ineq,
2312 				    1 + total);
2313 	if (wraps_init(&wraps, mat, info, i, j) < 0)
2314 		goto error;
2315 	bound = isl_vec_alloc(ctx, 1 + total);
2316 	if (!set_i || !set_j || !bound)
2317 		goto error;
2318 
2319 	if (k % 2 == 0)
2320 		isl_seq_neg(bound->el, info[i].bmap->eq[k / 2], 1 + total);
2321 	else
2322 		isl_seq_cpy(bound->el, info[i].bmap->eq[k / 2], 1 + total);
2323 	isl_int_add_ui(bound->el[0], bound->el[0], 1);
2324 
2325 	isl_seq_cpy(wraps.mat->row[0], bound->el, 1 + total);
2326 	wraps.mat->n_row = 1;
2327 
2328 	if (add_wraps(&wraps, &info[j], bound->el, set_i) < 0)
2329 		goto error;
2330 	if (wraps.failed)
2331 		goto unbounded;
2332 
2333 	isl_int_sub_ui(bound->el[0], bound->el[0], 1);
2334 	isl_seq_neg(bound->el, bound->el, 1 + total);
2335 
2336 	isl_seq_cpy(wraps.mat->row[wraps.mat->n_row], bound->el, 1 + total);
2337 	wraps.mat->n_row++;
2338 
2339 	if (add_wraps(&wraps, &info[i], bound->el, set_j) < 0)
2340 		goto error;
2341 	if (wraps.failed)
2342 		goto unbounded;
2343 
2344 	change = fuse(i, j, info, wraps.mat, detect_equalities, 0);
2345 
2346 	if (0) {
2347 error:		change = isl_change_error;
2348 	}
2349 unbounded:
2350 
2351 	wraps_free(&wraps);
2352 	isl_set_free(set_i);
2353 	isl_set_free(set_j);
2354 	isl_vec_free(bound);
2355 
2356 	return change;
2357 }
2358 
2359 /* Initialize the "eq" and "ineq" fields of "info".
2360  */
init_status(struct isl_coalesce_info * info)2361 static void init_status(struct isl_coalesce_info *info)
2362 {
2363 	info->eq = info->ineq = NULL;
2364 }
2365 
2366 /* Set info->eq to the positions of the equalities of info->bmap
2367  * with respect to the basic map represented by "tab".
2368  * If info->eq has already been computed, then do not compute it again.
2369  */
set_eq_status_in(struct isl_coalesce_info * info,struct isl_tab * tab)2370 static void set_eq_status_in(struct isl_coalesce_info *info,
2371 	struct isl_tab *tab)
2372 {
2373 	if (info->eq)
2374 		return;
2375 	info->eq = eq_status_in(info->bmap, tab);
2376 }
2377 
2378 /* Set info->ineq to the positions of the inequalities of info->bmap
2379  * with respect to the basic map represented by "tab".
2380  * If info->ineq has already been computed, then do not compute it again.
2381  */
set_ineq_status_in(struct isl_coalesce_info * info,struct isl_tab * tab)2382 static void set_ineq_status_in(struct isl_coalesce_info *info,
2383 	struct isl_tab *tab)
2384 {
2385 	if (info->ineq)
2386 		return;
2387 	info->ineq = ineq_status_in(info->bmap, info->tab, tab);
2388 }
2389 
2390 /* Free the memory allocated by the "eq" and "ineq" fields of "info".
2391  * This function assumes that init_status has been called on "info" first,
2392  * after which the "eq" and "ineq" fields may or may not have been
2393  * assigned a newly allocated array.
2394  */
clear_status(struct isl_coalesce_info * info)2395 static void clear_status(struct isl_coalesce_info *info)
2396 {
2397 	free(info->eq);
2398 	free(info->ineq);
2399 }
2400 
2401 /* Are all inequality constraints of the basic map represented by "info"
2402  * valid for the other basic map, except for a single constraint
2403  * that is adjacent to an inequality constraint of the other basic map?
2404  */
all_ineq_valid_or_single_adj_ineq(struct isl_coalesce_info * info)2405 static int all_ineq_valid_or_single_adj_ineq(struct isl_coalesce_info *info)
2406 {
2407 	int i;
2408 	int k = -1;
2409 
2410 	for (i = 0; i < info->bmap->n_ineq; ++i) {
2411 		if (info->ineq[i] == STATUS_REDUNDANT)
2412 			continue;
2413 		if (info->ineq[i] == STATUS_VALID)
2414 			continue;
2415 		if (info->ineq[i] != STATUS_ADJ_INEQ)
2416 			return 0;
2417 		if (k != -1)
2418 			return 0;
2419 		k = i;
2420 	}
2421 
2422 	return k != -1;
2423 }
2424 
2425 /* Basic map "i" has one or more equality constraints that separate it
2426  * from basic map "j".  Check if it happens to be an extension
2427  * of basic map "j".
2428  * In particular, check that all constraints of "j" are valid for "i",
2429  * except for one inequality constraint that is adjacent
2430  * to an inequality constraints of "i".
2431  * If so, check for "i" being an extension of "j" by calling
2432  * is_adj_ineq_extension.
2433  *
2434  * Clean up the memory allocated for keeping track of the status
2435  * of the constraints before returning.
2436  */
separating_equality(int i,int j,struct isl_coalesce_info * info)2437 static enum isl_change separating_equality(int i, int j,
2438 	struct isl_coalesce_info *info)
2439 {
2440 	enum isl_change change = isl_change_none;
2441 
2442 	if (all(info[j].eq, 2 * info[j].bmap->n_eq, STATUS_VALID) &&
2443 	    all_ineq_valid_or_single_adj_ineq(&info[j]))
2444 		change = is_adj_ineq_extension(j, i, info);
2445 
2446 	clear_status(&info[i]);
2447 	clear_status(&info[j]);
2448 	return change;
2449 }
2450 
2451 /* Check if the union of the given pair of basic maps
2452  * can be represented by a single basic map.
2453  * If so, replace the pair by the single basic map and return
2454  * isl_change_drop_first, isl_change_drop_second or isl_change_fuse.
2455  * Otherwise, return isl_change_none.
2456  * The two basic maps are assumed to live in the same local space.
2457  * The "eq" and "ineq" fields of info[i] and info[j] are assumed
2458  * to have been initialized by the caller, either to NULL or
2459  * to valid information.
2460  *
2461  * We first check the effect of each constraint of one basic map
2462  * on the other basic map.
2463  * The constraint may be
2464  *	redundant	the constraint is redundant in its own
2465  *			basic map and should be ignore and removed
2466  *			in the end
2467  *	valid		all (integer) points of the other basic map
2468  *			satisfy the constraint
2469  *	separate	no (integer) point of the other basic map
2470  *			satisfies the constraint
2471  *	cut		some but not all points of the other basic map
2472  *			satisfy the constraint
2473  *	adj_eq		the given constraint is adjacent (on the outside)
2474  *			to an equality of the other basic map
2475  *	adj_ineq	the given constraint is adjacent (on the outside)
2476  *			to an inequality of the other basic map
2477  *
2478  * We consider seven cases in which we can replace the pair by a single
2479  * basic map.  We ignore all "redundant" constraints.
2480  *
2481  *	1. all constraints of one basic map are valid
2482  *		=> the other basic map is a subset and can be removed
2483  *
2484  *	2. all constraints of both basic maps are either "valid" or "cut"
2485  *	   and the facets corresponding to the "cut" constraints
2486  *	   of one of the basic maps lies entirely inside the other basic map
2487  *		=> the pair can be replaced by a basic map consisting
2488  *		   of the valid constraints in both basic maps
2489  *
2490  *	3. there is a single pair of adjacent inequalities
2491  *	   (all other constraints are "valid")
2492  *		=> the pair can be replaced by a basic map consisting
2493  *		   of the valid constraints in both basic maps
2494  *
2495  *	4. one basic map has a single adjacent inequality, while the other
2496  *	   constraints are "valid".  The other basic map has some
2497  *	   "cut" constraints, but replacing the adjacent inequality by
2498  *	   its opposite and adding the valid constraints of the other
2499  *	   basic map results in a subset of the other basic map
2500  *		=> the pair can be replaced by a basic map consisting
2501  *		   of the valid constraints in both basic maps
2502  *
2503  *	5. there is a single adjacent pair of an inequality and an equality,
2504  *	   the other constraints of the basic map containing the inequality are
2505  *	   "valid".  Moreover, if the inequality the basic map is relaxed
2506  *	   and then turned into an equality, then resulting facet lies
2507  *	   entirely inside the other basic map
2508  *		=> the pair can be replaced by the basic map containing
2509  *		   the inequality, with the inequality relaxed.
2510  *
2511  *	6. there is a single inequality adjacent to an equality,
2512  *	   the other constraints of the basic map containing the inequality are
2513  *	   "valid".  Moreover, the facets corresponding to both
2514  *	   the inequality and the equality can be wrapped around their
2515  *	   ridges to include the other basic map
2516  *		=> the pair can be replaced by a basic map consisting
2517  *		   of the valid constraints in both basic maps together
2518  *		   with all wrapping constraints
2519  *
2520  *	7. one of the basic maps extends beyond the other by at most one.
2521  *	   Moreover, the facets corresponding to the cut constraints and
2522  *	   the pieces of the other basic map at offset one from these cut
2523  *	   constraints can be wrapped around their ridges to include
2524  *	   the union of the two basic maps
2525  *		=> the pair can be replaced by a basic map consisting
2526  *		   of the valid constraints in both basic maps together
2527  *		   with all wrapping constraints
2528  *
2529  *	8. the two basic maps live in adjacent hyperplanes.  In principle
2530  *	   such sets can always be combined through wrapping, but we impose
2531  *	   that there is only one such pair, to avoid overeager coalescing.
2532  *
2533  * Throughout the computation, we maintain a collection of tableaus
2534  * corresponding to the basic maps.  When the basic maps are dropped
2535  * or combined, the tableaus are modified accordingly.
2536  */
coalesce_local_pair_reuse(int i,int j,struct isl_coalesce_info * info)2537 static enum isl_change coalesce_local_pair_reuse(int i, int j,
2538 	struct isl_coalesce_info *info)
2539 {
2540 	enum isl_change change = isl_change_none;
2541 
2542 	set_ineq_status_in(&info[i], info[j].tab);
2543 	if (info[i].bmap->n_ineq && !info[i].ineq)
2544 		goto error;
2545 	if (any_ineq(&info[i], STATUS_ERROR))
2546 		goto error;
2547 	if (any_ineq(&info[i], STATUS_SEPARATE))
2548 		goto done;
2549 
2550 	set_ineq_status_in(&info[j], info[i].tab);
2551 	if (info[j].bmap->n_ineq && !info[j].ineq)
2552 		goto error;
2553 	if (any_ineq(&info[j], STATUS_ERROR))
2554 		goto error;
2555 	if (any_ineq(&info[j], STATUS_SEPARATE))
2556 		goto done;
2557 
2558 	set_eq_status_in(&info[i], info[j].tab);
2559 	if (info[i].bmap->n_eq && !info[i].eq)
2560 		goto error;
2561 	if (any_eq(&info[i], STATUS_ERROR))
2562 		goto error;
2563 
2564 	set_eq_status_in(&info[j], info[i].tab);
2565 	if (info[j].bmap->n_eq && !info[j].eq)
2566 		goto error;
2567 	if (any_eq(&info[j], STATUS_ERROR))
2568 		goto error;
2569 
2570 	if (any_eq(&info[i], STATUS_SEPARATE))
2571 		return separating_equality(i, j, info);
2572 	if (any_eq(&info[j], STATUS_SEPARATE))
2573 		return separating_equality(j, i, info);
2574 
2575 	if (all(info[i].eq, 2 * info[i].bmap->n_eq, STATUS_VALID) &&
2576 	    all(info[i].ineq, info[i].bmap->n_ineq, STATUS_VALID)) {
2577 		drop(&info[j]);
2578 		change = isl_change_drop_second;
2579 	} else if (all(info[j].eq, 2 * info[j].bmap->n_eq, STATUS_VALID) &&
2580 		   all(info[j].ineq, info[j].bmap->n_ineq, STATUS_VALID)) {
2581 		drop(&info[i]);
2582 		change = isl_change_drop_first;
2583 	} else if (any_eq(&info[i], STATUS_ADJ_EQ)) {
2584 		change = check_eq_adj_eq(i, j, info);
2585 	} else if (any_eq(&info[j], STATUS_ADJ_EQ)) {
2586 		change = check_eq_adj_eq(j, i, info);
2587 	} else if (any_eq(&info[i], STATUS_ADJ_INEQ) ||
2588 		   any_eq(&info[j], STATUS_ADJ_INEQ)) {
2589 		change = check_adj_eq(i, j, info);
2590 	} else if (any_ineq(&info[i], STATUS_ADJ_EQ)) {
2591 		change = check_ineq_adj_eq(i, j, info);
2592 	} else if (any_ineq(&info[j], STATUS_ADJ_EQ)) {
2593 		change = check_ineq_adj_eq(j, i, info);
2594 	} else if (any_ineq(&info[i], STATUS_ADJ_INEQ) ||
2595 		   any_ineq(&info[j], STATUS_ADJ_INEQ)) {
2596 		change = check_adj_ineq(i, j, info);
2597 	} else {
2598 		if (!any_eq(&info[i], STATUS_CUT) &&
2599 		    !any_eq(&info[j], STATUS_CUT))
2600 			change = check_facets(i, j, info);
2601 		if (change == isl_change_none)
2602 			change = check_wrap(i, j, info);
2603 	}
2604 
2605 done:
2606 	clear_status(&info[i]);
2607 	clear_status(&info[j]);
2608 	return change;
2609 error:
2610 	clear_status(&info[i]);
2611 	clear_status(&info[j]);
2612 	return isl_change_error;
2613 }
2614 
2615 /* Check if the union of the given pair of basic maps
2616  * can be represented by a single basic map.
2617  * If so, replace the pair by the single basic map and return
2618  * isl_change_drop_first, isl_change_drop_second or isl_change_fuse.
2619  * Otherwise, return isl_change_none.
2620  * The two basic maps are assumed to live in the same local space.
2621  */
coalesce_local_pair(int i,int j,struct isl_coalesce_info * info)2622 static enum isl_change coalesce_local_pair(int i, int j,
2623 	struct isl_coalesce_info *info)
2624 {
2625 	init_status(&info[i]);
2626 	init_status(&info[j]);
2627 	return coalesce_local_pair_reuse(i, j, info);
2628 }
2629 
2630 /* Shift the integer division at position "div" of the basic map
2631  * represented by "info" by "shift".
2632  *
2633  * That is, if the integer division has the form
2634  *
2635  *	floor(f(x)/d)
2636  *
2637  * then replace it by
2638  *
2639  *	floor((f(x) + shift * d)/d) - shift
2640  */
shift_div(struct isl_coalesce_info * info,int div,isl_int shift)2641 static isl_stat shift_div(struct isl_coalesce_info *info, int div,
2642 	isl_int shift)
2643 {
2644 	isl_size total, n_div;
2645 
2646 	info->bmap = isl_basic_map_shift_div(info->bmap, div, 0, shift);
2647 	if (!info->bmap)
2648 		return isl_stat_error;
2649 
2650 	total = isl_basic_map_dim(info->bmap, isl_dim_all);
2651 	n_div = isl_basic_map_dim(info->bmap, isl_dim_div);
2652 	if (total < 0 || n_div < 0)
2653 		return isl_stat_error;
2654 	total -= n_div;
2655 	if (isl_tab_shift_var(info->tab, total + div, shift) < 0)
2656 		return isl_stat_error;
2657 
2658 	return isl_stat_ok;
2659 }
2660 
2661 /* If the integer division at position "div" is defined by an equality,
2662  * i.e., a stride constraint, then change the integer division expression
2663  * to have a constant term equal to zero.
2664  *
2665  * Let the equality constraint be
2666  *
2667  *	c + f + m a = 0
2668  *
2669  * The integer division expression is then typically of the form
2670  *
2671  *	a = floor((-f - c')/m)
2672  *
2673  * The integer division is first shifted by t = floor(c/m),
2674  * turning the equality constraint into
2675  *
2676  *	c - m floor(c/m) + f + m a' = 0
2677  *
2678  * i.e.,
2679  *
2680  *	(c mod m) + f + m a' = 0
2681  *
2682  * That is,
2683  *
2684  *	a' = (-f - (c mod m))/m = floor((-f)/m)
2685  *
2686  * because a' is an integer and 0 <= (c mod m) < m.
2687  * The constant term of a' can therefore be zeroed out,
2688  * but only if the integer division expression is of the expected form.
2689  */
normalize_stride_div(struct isl_coalesce_info * info,int div)2690 static isl_stat normalize_stride_div(struct isl_coalesce_info *info, int div)
2691 {
2692 	isl_bool defined, valid;
2693 	isl_stat r;
2694 	isl_constraint *c;
2695 	isl_int shift, stride;
2696 
2697 	defined = isl_basic_map_has_defining_equality(info->bmap, isl_dim_div,
2698 							div, &c);
2699 	if (defined < 0)
2700 		return isl_stat_error;
2701 	if (!defined)
2702 		return isl_stat_ok;
2703 	if (!c)
2704 		return isl_stat_error;
2705 	valid = isl_constraint_is_div_equality(c, div);
2706 	isl_int_init(shift);
2707 	isl_int_init(stride);
2708 	isl_constraint_get_constant(c, &shift);
2709 	isl_constraint_get_coefficient(c, isl_dim_div, div, &stride);
2710 	isl_int_fdiv_q(shift, shift, stride);
2711 	r = shift_div(info, div, shift);
2712 	isl_int_clear(stride);
2713 	isl_int_clear(shift);
2714 	isl_constraint_free(c);
2715 	if (r < 0 || valid < 0)
2716 		return isl_stat_error;
2717 	if (!valid)
2718 		return isl_stat_ok;
2719 	info->bmap = isl_basic_map_set_div_expr_constant_num_si_inplace(
2720 							    info->bmap, div, 0);
2721 	if (!info->bmap)
2722 		return isl_stat_error;
2723 	return isl_stat_ok;
2724 }
2725 
2726 /* The basic maps represented by "info1" and "info2" are known
2727  * to have the same number of integer divisions.
2728  * Check if pairs of integer divisions are equal to each other
2729  * despite the fact that they differ by a rational constant.
2730  *
2731  * In particular, look for any pair of integer divisions that
2732  * only differ in their constant terms.
2733  * If either of these integer divisions is defined
2734  * by stride constraints, then modify it to have a zero constant term.
2735  * If both are defined by stride constraints then in the end they will have
2736  * the same (zero) constant term.
2737  */
harmonize_stride_divs(struct isl_coalesce_info * info1,struct isl_coalesce_info * info2)2738 static isl_stat harmonize_stride_divs(struct isl_coalesce_info *info1,
2739 	struct isl_coalesce_info *info2)
2740 {
2741 	int i;
2742 	isl_size n;
2743 
2744 	n = isl_basic_map_dim(info1->bmap, isl_dim_div);
2745 	if (n < 0)
2746 		return isl_stat_error;
2747 	for (i = 0; i < n; ++i) {
2748 		isl_bool known, harmonize;
2749 
2750 		known = isl_basic_map_div_is_known(info1->bmap, i);
2751 		if (known >= 0 && known)
2752 			known = isl_basic_map_div_is_known(info2->bmap, i);
2753 		if (known < 0)
2754 			return isl_stat_error;
2755 		if (!known)
2756 			continue;
2757 		harmonize = isl_basic_map_equal_div_expr_except_constant(
2758 					    info1->bmap, i, info2->bmap, i);
2759 		if (harmonize < 0)
2760 			return isl_stat_error;
2761 		if (!harmonize)
2762 			continue;
2763 		if (normalize_stride_div(info1, i) < 0)
2764 			return isl_stat_error;
2765 		if (normalize_stride_div(info2, i) < 0)
2766 			return isl_stat_error;
2767 	}
2768 
2769 	return isl_stat_ok;
2770 }
2771 
2772 /* If "shift" is an integer constant, then shift the integer division
2773  * at position "div" of the basic map represented by "info" by "shift".
2774  * If "shift" is not an integer constant, then do nothing.
2775  * If "shift" is equal to zero, then no shift needs to be performed either.
2776  *
2777  * That is, if the integer division has the form
2778  *
2779  *	floor(f(x)/d)
2780  *
2781  * then replace it by
2782  *
2783  *	floor((f(x) + shift * d)/d) - shift
2784  */
shift_if_cst_int(struct isl_coalesce_info * info,int div,__isl_keep isl_aff * shift)2785 static isl_stat shift_if_cst_int(struct isl_coalesce_info *info, int div,
2786 	__isl_keep isl_aff *shift)
2787 {
2788 	isl_bool cst;
2789 	isl_stat r;
2790 	isl_int d;
2791 	isl_val *c;
2792 
2793 	cst = isl_aff_is_cst(shift);
2794 	if (cst < 0 || !cst)
2795 		return cst < 0 ? isl_stat_error : isl_stat_ok;
2796 
2797 	c = isl_aff_get_constant_val(shift);
2798 	cst = isl_val_is_int(c);
2799 	if (cst >= 0 && cst)
2800 		cst = isl_bool_not(isl_val_is_zero(c));
2801 	if (cst < 0 || !cst) {
2802 		isl_val_free(c);
2803 		return cst < 0 ? isl_stat_error : isl_stat_ok;
2804 	}
2805 
2806 	isl_int_init(d);
2807 	r = isl_val_get_num_isl_int(c, &d);
2808 	if (r >= 0)
2809 		r = shift_div(info, div, d);
2810 	isl_int_clear(d);
2811 
2812 	isl_val_free(c);
2813 
2814 	return r;
2815 }
2816 
2817 /* Check if some of the divs in the basic map represented by "info1"
2818  * are shifts of the corresponding divs in the basic map represented
2819  * by "info2", taking into account the equality constraints "eq1" of "info1"
2820  * and "eq2" of "info2".  If so, align them with those of "info2".
2821  * "info1" and "info2" are assumed to have the same number
2822  * of integer divisions.
2823  *
2824  * An integer division is considered to be a shift of another integer
2825  * division if, after simplification with respect to the equality
2826  * constraints of the other basic map, one is equal to the other
2827  * plus a constant.
2828  *
2829  * In particular, for each pair of integer divisions, if both are known,
2830  * have the same denominator and are not already equal to each other,
2831  * simplify each with respect to the equality constraints
2832  * of the other basic map.  If the difference is an integer constant,
2833  * then move this difference outside.
2834  * That is, if, after simplification, one integer division is of the form
2835  *
2836  *	floor((f(x) + c_1)/d)
2837  *
2838  * while the other is of the form
2839  *
2840  *	floor((f(x) + c_2)/d)
2841  *
2842  * and n = (c_2 - c_1)/d is an integer, then replace the first
2843  * integer division by
2844  *
2845  *	floor((f_1(x) + c_1 + n * d)/d) - n,
2846  *
2847  * where floor((f_1(x) + c_1 + n * d)/d) = floor((f2(x) + c_2)/d)
2848  * after simplification with respect to the equality constraints.
2849  */
harmonize_divs_with_hulls(struct isl_coalesce_info * info1,struct isl_coalesce_info * info2,__isl_keep isl_basic_set * eq1,__isl_keep isl_basic_set * eq2)2850 static isl_stat harmonize_divs_with_hulls(struct isl_coalesce_info *info1,
2851 	struct isl_coalesce_info *info2, __isl_keep isl_basic_set *eq1,
2852 	__isl_keep isl_basic_set *eq2)
2853 {
2854 	int i;
2855 	isl_size total;
2856 	isl_local_space *ls1, *ls2;
2857 
2858 	total = isl_basic_map_dim(info1->bmap, isl_dim_all);
2859 	if (total < 0)
2860 		return isl_stat_error;
2861 	ls1 = isl_local_space_wrap(isl_basic_map_get_local_space(info1->bmap));
2862 	ls2 = isl_local_space_wrap(isl_basic_map_get_local_space(info2->bmap));
2863 	for (i = 0; i < info1->bmap->n_div; ++i) {
2864 		isl_stat r;
2865 		isl_aff *div1, *div2;
2866 
2867 		if (!isl_local_space_div_is_known(ls1, i) ||
2868 		    !isl_local_space_div_is_known(ls2, i))
2869 			continue;
2870 		if (isl_int_ne(info1->bmap->div[i][0], info2->bmap->div[i][0]))
2871 			continue;
2872 		if (isl_seq_eq(info1->bmap->div[i] + 1,
2873 				info2->bmap->div[i] + 1, 1 + total))
2874 			continue;
2875 		div1 = isl_local_space_get_div(ls1, i);
2876 		div2 = isl_local_space_get_div(ls2, i);
2877 		div1 = isl_aff_substitute_equalities(div1,
2878 						    isl_basic_set_copy(eq2));
2879 		div2 = isl_aff_substitute_equalities(div2,
2880 						    isl_basic_set_copy(eq1));
2881 		div2 = isl_aff_sub(div2, div1);
2882 		r = shift_if_cst_int(info1, i, div2);
2883 		isl_aff_free(div2);
2884 		if (r < 0)
2885 			break;
2886 	}
2887 	isl_local_space_free(ls1);
2888 	isl_local_space_free(ls2);
2889 
2890 	if (i < info1->bmap->n_div)
2891 		return isl_stat_error;
2892 	return isl_stat_ok;
2893 }
2894 
2895 /* Check if some of the divs in the basic map represented by "info1"
2896  * are shifts of the corresponding divs in the basic map represented
2897  * by "info2".  If so, align them with those of "info2".
2898  * Only do this if "info1" and "info2" have the same number
2899  * of integer divisions.
2900  *
2901  * An integer division is considered to be a shift of another integer
2902  * division if, after simplification with respect to the equality
2903  * constraints of the other basic map, one is equal to the other
2904  * plus a constant.
2905  *
2906  * First check if pairs of integer divisions are equal to each other
2907  * despite the fact that they differ by a rational constant.
2908  * If so, try and arrange for them to have the same constant term.
2909  *
2910  * Then, extract the equality constraints and continue with
2911  * harmonize_divs_with_hulls.
2912  *
2913  * If the equality constraints of both basic maps are the same,
2914  * then there is no need to perform any shifting since
2915  * the coefficients of the integer divisions should have been
2916  * reduced in the same way.
2917  */
harmonize_divs(struct isl_coalesce_info * info1,struct isl_coalesce_info * info2)2918 static isl_stat harmonize_divs(struct isl_coalesce_info *info1,
2919 	struct isl_coalesce_info *info2)
2920 {
2921 	isl_bool equal;
2922 	isl_basic_map *bmap1, *bmap2;
2923 	isl_basic_set *eq1, *eq2;
2924 	isl_stat r;
2925 
2926 	if (!info1->bmap || !info2->bmap)
2927 		return isl_stat_error;
2928 
2929 	if (info1->bmap->n_div != info2->bmap->n_div)
2930 		return isl_stat_ok;
2931 	if (info1->bmap->n_div == 0)
2932 		return isl_stat_ok;
2933 
2934 	if (harmonize_stride_divs(info1, info2) < 0)
2935 		return isl_stat_error;
2936 
2937 	bmap1 = isl_basic_map_copy(info1->bmap);
2938 	bmap2 = isl_basic_map_copy(info2->bmap);
2939 	eq1 = isl_basic_map_wrap(isl_basic_map_plain_affine_hull(bmap1));
2940 	eq2 = isl_basic_map_wrap(isl_basic_map_plain_affine_hull(bmap2));
2941 	equal = isl_basic_set_plain_is_equal(eq1, eq2);
2942 	if (equal < 0)
2943 		r = isl_stat_error;
2944 	else if (equal)
2945 		r = isl_stat_ok;
2946 	else
2947 		r = harmonize_divs_with_hulls(info1, info2, eq1, eq2);
2948 	isl_basic_set_free(eq1);
2949 	isl_basic_set_free(eq2);
2950 
2951 	return r;
2952 }
2953 
2954 /* Do the two basic maps live in the same local space, i.e.,
2955  * do they have the same (known) divs?
2956  * If either basic map has any unknown divs, then we can only assume
2957  * that they do not live in the same local space.
2958  */
same_divs(__isl_keep isl_basic_map * bmap1,__isl_keep isl_basic_map * bmap2)2959 static isl_bool same_divs(__isl_keep isl_basic_map *bmap1,
2960 	__isl_keep isl_basic_map *bmap2)
2961 {
2962 	int i;
2963 	isl_bool known;
2964 	isl_size total;
2965 
2966 	if (!bmap1 || !bmap2)
2967 		return isl_bool_error;
2968 	if (bmap1->n_div != bmap2->n_div)
2969 		return isl_bool_false;
2970 
2971 	if (bmap1->n_div == 0)
2972 		return isl_bool_true;
2973 
2974 	known = isl_basic_map_divs_known(bmap1);
2975 	if (known < 0 || !known)
2976 		return known;
2977 	known = isl_basic_map_divs_known(bmap2);
2978 	if (known < 0 || !known)
2979 		return known;
2980 
2981 	total = isl_basic_map_dim(bmap1, isl_dim_all);
2982 	if (total < 0)
2983 		return isl_bool_error;
2984 	for (i = 0; i < bmap1->n_div; ++i)
2985 		if (!isl_seq_eq(bmap1->div[i], bmap2->div[i], 2 + total))
2986 			return isl_bool_false;
2987 
2988 	return isl_bool_true;
2989 }
2990 
2991 /* Assuming that "tab" contains the equality constraints and
2992  * the initial inequality constraints of "bmap", copy the remaining
2993  * inequality constraints of "bmap" to "Tab".
2994  */
copy_ineq(struct isl_tab * tab,__isl_keep isl_basic_map * bmap)2995 static isl_stat copy_ineq(struct isl_tab *tab, __isl_keep isl_basic_map *bmap)
2996 {
2997 	int i, n_ineq;
2998 
2999 	if (!bmap)
3000 		return isl_stat_error;
3001 
3002 	n_ineq = tab->n_con - tab->n_eq;
3003 	for (i = n_ineq; i < bmap->n_ineq; ++i)
3004 		if (isl_tab_add_ineq(tab, bmap->ineq[i]) < 0)
3005 			return isl_stat_error;
3006 
3007 	return isl_stat_ok;
3008 }
3009 
3010 /* Description of an integer division that is added
3011  * during an expansion.
3012  * "pos" is the position of the corresponding variable.
3013  * "cst" indicates whether this integer division has a fixed value.
3014  * "val" contains the fixed value, if the value is fixed.
3015  */
3016 struct isl_expanded {
3017 	int pos;
3018 	isl_bool cst;
3019 	isl_int val;
3020 };
3021 
3022 /* For each of the "n" integer division variables "expanded",
3023  * if the variable has a fixed value, then add two inequality
3024  * constraints expressing the fixed value.
3025  * Otherwise, add the corresponding div constraints.
3026  * The caller is responsible for removing the div constraints
3027  * that it added for all these "n" integer divisions.
3028  *
3029  * The div constraints and the pair of inequality constraints
3030  * forcing the fixed value cannot both be added for a given variable
3031  * as the combination may render some of the original constraints redundant.
3032  * These would then be ignored during the coalescing detection,
3033  * while they could remain in the fused result.
3034  *
3035  * The two added inequality constraints are
3036  *
3037  *	-a + v >= 0
3038  *	a - v >= 0
3039  *
3040  * with "a" the variable and "v" its fixed value.
3041  * The facet corresponding to one of these two constraints is selected
3042  * in the tableau to ensure that the pair of inequality constraints
3043  * is treated as an equality constraint.
3044  *
3045  * The information in info->ineq is thrown away because it was
3046  * computed in terms of div constraints, while some of those
3047  * have now been replaced by these pairs of inequality constraints.
3048  */
fix_constant_divs(struct isl_coalesce_info * info,int n,struct isl_expanded * expanded)3049 static isl_stat fix_constant_divs(struct isl_coalesce_info *info,
3050 	int n, struct isl_expanded *expanded)
3051 {
3052 	unsigned o_div;
3053 	int i;
3054 	isl_vec *ineq;
3055 
3056 	o_div = isl_basic_map_offset(info->bmap, isl_dim_div) - 1;
3057 	ineq = isl_vec_alloc(isl_tab_get_ctx(info->tab), 1 + info->tab->n_var);
3058 	if (!ineq)
3059 		return isl_stat_error;
3060 	isl_seq_clr(ineq->el + 1, info->tab->n_var);
3061 
3062 	for (i = 0; i < n; ++i) {
3063 		if (!expanded[i].cst) {
3064 			info->bmap = isl_basic_map_extend_constraints(
3065 						info->bmap, 0, 2);
3066 			info->bmap = isl_basic_map_add_div_constraints(
3067 					info->bmap, expanded[i].pos - o_div);
3068 		} else {
3069 			isl_int_set_si(ineq->el[1 + expanded[i].pos], -1);
3070 			isl_int_set(ineq->el[0], expanded[i].val);
3071 			info->bmap = isl_basic_map_add_ineq(info->bmap,
3072 								ineq->el);
3073 			isl_int_set_si(ineq->el[1 + expanded[i].pos], 1);
3074 			isl_int_neg(ineq->el[0], expanded[i].val);
3075 			info->bmap = isl_basic_map_add_ineq(info->bmap,
3076 								ineq->el);
3077 			isl_int_set_si(ineq->el[1 + expanded[i].pos], 0);
3078 		}
3079 		if (copy_ineq(info->tab, info->bmap) < 0)
3080 			break;
3081 		if (expanded[i].cst &&
3082 		    isl_tab_select_facet(info->tab, info->tab->n_con - 1) < 0)
3083 			break;
3084 	}
3085 
3086 	isl_vec_free(ineq);
3087 
3088 	clear_status(info);
3089 	init_status(info);
3090 
3091 	return i < n ? isl_stat_error : isl_stat_ok;
3092 }
3093 
3094 /* Insert the "n" integer division variables "expanded"
3095  * into info->tab and info->bmap and
3096  * update info->ineq with respect to the redundant constraints
3097  * in the resulting tableau.
3098  * "bmap" contains the result of this insertion in info->bmap,
3099  * while info->bmap is the original version
3100  * of "bmap", i.e., the one that corresponds to the current
3101  * state of info->tab.  The number of constraints in info->bmap
3102  * is assumed to be the same as the number of constraints
3103  * in info->tab.  This is required to be able to detect
3104  * the extra constraints in "bmap".
3105  *
3106  * In particular, introduce extra variables corresponding
3107  * to the extra integer divisions and add the div constraints
3108  * that were added to "bmap" after info->tab was created
3109  * from info->bmap.
3110  * Furthermore, check if these extra integer divisions happen
3111  * to attain a fixed integer value in info->tab.
3112  * If so, replace the corresponding div constraints by pairs
3113  * of inequality constraints that fix these
3114  * integer divisions to their single integer values.
3115  * Replace info->bmap by "bmap" to match the changes to info->tab.
3116  * info->ineq was computed without a tableau and therefore
3117  * does not take into account the redundant constraints
3118  * in the tableau.  Mark them here.
3119  * There is no need to check the newly added div constraints
3120  * since they cannot be redundant.
3121  * The redundancy check is not performed when constants have been discovered
3122  * since info->ineq is completely thrown away in this case.
3123  */
tab_insert_divs(struct isl_coalesce_info * info,int n,struct isl_expanded * expanded,__isl_take isl_basic_map * bmap)3124 static isl_stat tab_insert_divs(struct isl_coalesce_info *info,
3125 	int n, struct isl_expanded *expanded, __isl_take isl_basic_map *bmap)
3126 {
3127 	int i, n_ineq;
3128 	unsigned n_eq;
3129 	struct isl_tab_undo *snap;
3130 	int any;
3131 
3132 	if (!bmap)
3133 		return isl_stat_error;
3134 	if (info->bmap->n_eq + info->bmap->n_ineq != info->tab->n_con)
3135 		isl_die(isl_basic_map_get_ctx(bmap), isl_error_internal,
3136 			"original tableau does not correspond "
3137 			"to original basic map", goto error);
3138 
3139 	if (isl_tab_extend_vars(info->tab, n) < 0)
3140 		goto error;
3141 	if (isl_tab_extend_cons(info->tab, 2 * n) < 0)
3142 		goto error;
3143 
3144 	for (i = 0; i < n; ++i) {
3145 		if (isl_tab_insert_var(info->tab, expanded[i].pos) < 0)
3146 			goto error;
3147 	}
3148 
3149 	snap = isl_tab_snap(info->tab);
3150 
3151 	n_ineq = info->tab->n_con - info->tab->n_eq;
3152 	if (copy_ineq(info->tab, bmap) < 0)
3153 		goto error;
3154 
3155 	isl_basic_map_free(info->bmap);
3156 	info->bmap = bmap;
3157 
3158 	any = 0;
3159 	for (i = 0; i < n; ++i) {
3160 		expanded[i].cst = isl_tab_is_constant(info->tab,
3161 					    expanded[i].pos, &expanded[i].val);
3162 		if (expanded[i].cst < 0)
3163 			return isl_stat_error;
3164 		if (expanded[i].cst)
3165 			any = 1;
3166 	}
3167 
3168 	if (any) {
3169 		if (isl_tab_rollback(info->tab, snap) < 0)
3170 			return isl_stat_error;
3171 		info->bmap = isl_basic_map_cow(info->bmap);
3172 		info->bmap = isl_basic_map_free_inequality(info->bmap, 2 * n);
3173 		if (info->bmap < 0)
3174 			return isl_stat_error;
3175 
3176 		return fix_constant_divs(info, n, expanded);
3177 	}
3178 
3179 	n_eq = info->bmap->n_eq;
3180 	for (i = 0; i < n_ineq; ++i) {
3181 		if (isl_tab_is_redundant(info->tab, n_eq + i))
3182 			info->ineq[i] = STATUS_REDUNDANT;
3183 	}
3184 
3185 	return isl_stat_ok;
3186 error:
3187 	isl_basic_map_free(bmap);
3188 	return isl_stat_error;
3189 }
3190 
3191 /* Expand info->tab and info->bmap in the same way "bmap" was expanded
3192  * in isl_basic_map_expand_divs using the expansion "exp" and
3193  * update info->ineq with respect to the redundant constraints
3194  * in the resulting tableau. info->bmap is the original version
3195  * of "bmap", i.e., the one that corresponds to the current
3196  * state of info->tab.  The number of constraints in info->bmap
3197  * is assumed to be the same as the number of constraints
3198  * in info->tab.  This is required to be able to detect
3199  * the extra constraints in "bmap".
3200  *
3201  * Extract the positions where extra local variables are introduced
3202  * from "exp" and call tab_insert_divs.
3203  */
expand_tab(struct isl_coalesce_info * info,int * exp,__isl_take isl_basic_map * bmap)3204 static isl_stat expand_tab(struct isl_coalesce_info *info, int *exp,
3205 	__isl_take isl_basic_map *bmap)
3206 {
3207 	isl_ctx *ctx;
3208 	struct isl_expanded *expanded;
3209 	int i, j, k, n;
3210 	int extra_var;
3211 	isl_size total, n_div;
3212 	unsigned pos;
3213 	isl_stat r;
3214 
3215 	total = isl_basic_map_dim(bmap, isl_dim_all);
3216 	n_div = isl_basic_map_dim(bmap, isl_dim_div);
3217 	if (total < 0 || n_div < 0)
3218 		return isl_stat_error;
3219 	pos = total - n_div;
3220 	extra_var = total - info->tab->n_var;
3221 	n = n_div - extra_var;
3222 
3223 	ctx = isl_basic_map_get_ctx(bmap);
3224 	expanded = isl_calloc_array(ctx, struct isl_expanded, extra_var);
3225 	if (extra_var && !expanded)
3226 		goto error;
3227 
3228 	i = 0;
3229 	k = 0;
3230 	for (j = 0; j < n_div; ++j) {
3231 		if (i < n && exp[i] == j) {
3232 			++i;
3233 			continue;
3234 		}
3235 		expanded[k++].pos = pos + j;
3236 	}
3237 
3238 	for (k = 0; k < extra_var; ++k)
3239 		isl_int_init(expanded[k].val);
3240 
3241 	r = tab_insert_divs(info, extra_var, expanded, bmap);
3242 
3243 	for (k = 0; k < extra_var; ++k)
3244 		isl_int_clear(expanded[k].val);
3245 	free(expanded);
3246 
3247 	return r;
3248 error:
3249 	isl_basic_map_free(bmap);
3250 	return isl_stat_error;
3251 }
3252 
3253 /* Check if the union of the basic maps represented by info[i] and info[j]
3254  * can be represented by a single basic map,
3255  * after expanding the divs of info[i] to match those of info[j].
3256  * If so, replace the pair by the single basic map and return
3257  * isl_change_drop_first, isl_change_drop_second or isl_change_fuse.
3258  * Otherwise, return isl_change_none.
3259  *
3260  * The caller has already checked for info[j] being a subset of info[i].
3261  * If some of the divs of info[j] are unknown, then the expanded info[i]
3262  * will not have the corresponding div constraints.  The other patterns
3263  * therefore cannot apply.  Skip the computation in this case.
3264  *
3265  * The expansion is performed using the divs "div" and expansion "exp"
3266  * computed by the caller.
3267  * info[i].bmap has already been expanded and the result is passed in
3268  * as "bmap".
3269  * The "eq" and "ineq" fields of info[i] reflect the status of
3270  * the constraints of the expanded "bmap" with respect to info[j].tab.
3271  * However, inequality constraints that are redundant in info[i].tab
3272  * have not yet been marked as such because no tableau was available.
3273  *
3274  * Replace info[i].bmap by "bmap" and expand info[i].tab as well,
3275  * updating info[i].ineq with respect to the redundant constraints.
3276  * Then try and coalesce the expanded info[i] with info[j],
3277  * reusing the information in info[i].eq and info[i].ineq.
3278  * If this does not result in any coalescing or if it results in info[j]
3279  * getting dropped (which should not happen in practice, since the case
3280  * of info[j] being a subset of info[i] has already been checked by
3281  * the caller), then revert info[i] to its original state.
3282  */
coalesce_expand_tab_divs(__isl_take isl_basic_map * bmap,int i,int j,struct isl_coalesce_info * info,__isl_keep isl_mat * div,int * exp)3283 static enum isl_change coalesce_expand_tab_divs(__isl_take isl_basic_map *bmap,
3284 	int i, int j, struct isl_coalesce_info *info, __isl_keep isl_mat *div,
3285 	int *exp)
3286 {
3287 	isl_bool known;
3288 	isl_basic_map *bmap_i;
3289 	struct isl_tab_undo *snap;
3290 	enum isl_change change = isl_change_none;
3291 
3292 	known = isl_basic_map_divs_known(info[j].bmap);
3293 	if (known < 0 || !known) {
3294 		clear_status(&info[i]);
3295 		isl_basic_map_free(bmap);
3296 		return known < 0 ? isl_change_error : isl_change_none;
3297 	}
3298 
3299 	bmap_i = isl_basic_map_copy(info[i].bmap);
3300 	snap = isl_tab_snap(info[i].tab);
3301 	if (expand_tab(&info[i], exp, bmap) < 0)
3302 		change = isl_change_error;
3303 
3304 	init_status(&info[j]);
3305 	if (change == isl_change_none)
3306 		change = coalesce_local_pair_reuse(i, j, info);
3307 	else
3308 		clear_status(&info[i]);
3309 	if (change != isl_change_none && change != isl_change_drop_second) {
3310 		isl_basic_map_free(bmap_i);
3311 	} else {
3312 		isl_basic_map_free(info[i].bmap);
3313 		info[i].bmap = bmap_i;
3314 
3315 		if (isl_tab_rollback(info[i].tab, snap) < 0)
3316 			change = isl_change_error;
3317 	}
3318 
3319 	return change;
3320 }
3321 
3322 /* Check if the union of "bmap" and the basic map represented by info[j]
3323  * can be represented by a single basic map,
3324  * after expanding the divs of "bmap" to match those of info[j].
3325  * If so, replace the pair by the single basic map and return
3326  * isl_change_drop_first, isl_change_drop_second or isl_change_fuse.
3327  * Otherwise, return isl_change_none.
3328  *
3329  * In particular, check if the expanded "bmap" contains the basic map
3330  * represented by the tableau info[j].tab.
3331  * The expansion is performed using the divs "div" and expansion "exp"
3332  * computed by the caller.
3333  * Then we check if all constraints of the expanded "bmap" are valid for
3334  * info[j].tab.
3335  *
3336  * If "i" is not equal to -1, then "bmap" is equal to info[i].bmap.
3337  * In this case, the positions of the constraints of info[i].bmap
3338  * with respect to the basic map represented by info[j] are stored
3339  * in info[i].
3340  *
3341  * If the expanded "bmap" does not contain the basic map
3342  * represented by the tableau info[j].tab and if "i" is not -1,
3343  * i.e., if the original "bmap" is info[i].bmap, then expand info[i].tab
3344  * as well and check if that results in coalescing.
3345  */
coalesce_with_expanded_divs(__isl_keep isl_basic_map * bmap,int i,int j,struct isl_coalesce_info * info,__isl_keep isl_mat * div,int * exp)3346 static enum isl_change coalesce_with_expanded_divs(
3347 	__isl_keep isl_basic_map *bmap, int i, int j,
3348 	struct isl_coalesce_info *info, __isl_keep isl_mat *div, int *exp)
3349 {
3350 	enum isl_change change = isl_change_none;
3351 	struct isl_coalesce_info info_local, *info_i;
3352 
3353 	info_i = i >= 0 ? &info[i] : &info_local;
3354 	init_status(info_i);
3355 	bmap = isl_basic_map_copy(bmap);
3356 	bmap = isl_basic_map_expand_divs(bmap, isl_mat_copy(div), exp);
3357 	bmap = isl_basic_map_mark_final(bmap);
3358 
3359 	if (!bmap)
3360 		goto error;
3361 
3362 	info_local.bmap = bmap;
3363 	info_i->eq = eq_status_in(bmap, info[j].tab);
3364 	if (bmap->n_eq && !info_i->eq)
3365 		goto error;
3366 	if (any_eq(info_i, STATUS_ERROR))
3367 		goto error;
3368 	if (any_eq(info_i, STATUS_SEPARATE))
3369 		goto done;
3370 
3371 	info_i->ineq = ineq_status_in(bmap, NULL, info[j].tab);
3372 	if (bmap->n_ineq && !info_i->ineq)
3373 		goto error;
3374 	if (any_ineq(info_i, STATUS_ERROR))
3375 		goto error;
3376 	if (any_ineq(info_i, STATUS_SEPARATE))
3377 		goto done;
3378 
3379 	if (all(info_i->eq, 2 * bmap->n_eq, STATUS_VALID) &&
3380 	    all(info_i->ineq, bmap->n_ineq, STATUS_VALID)) {
3381 		drop(&info[j]);
3382 		change = isl_change_drop_second;
3383 	}
3384 
3385 	if (change == isl_change_none && i != -1)
3386 		return coalesce_expand_tab_divs(bmap, i, j, info, div, exp);
3387 
3388 done:
3389 	isl_basic_map_free(bmap);
3390 	clear_status(info_i);
3391 	return change;
3392 error:
3393 	isl_basic_map_free(bmap);
3394 	clear_status(info_i);
3395 	return isl_change_error;
3396 }
3397 
3398 /* Check if the union of "bmap_i" and the basic map represented by info[j]
3399  * can be represented by a single basic map,
3400  * after aligning the divs of "bmap_i" to match those of info[j].
3401  * If so, replace the pair by the single basic map and return
3402  * isl_change_drop_first, isl_change_drop_second or isl_change_fuse.
3403  * Otherwise, return isl_change_none.
3404  *
3405  * In particular, check if "bmap_i" contains the basic map represented by
3406  * info[j] after aligning the divs of "bmap_i" to those of info[j].
3407  * Note that this can only succeed if the number of divs of "bmap_i"
3408  * is smaller than (or equal to) the number of divs of info[j].
3409  *
3410  * We first check if the divs of "bmap_i" are all known and form a subset
3411  * of those of info[j].bmap.  If so, we pass control over to
3412  * coalesce_with_expanded_divs.
3413  *
3414  * If "i" is not equal to -1, then "bmap" is equal to info[i].bmap.
3415  */
coalesce_after_aligning_divs(__isl_keep isl_basic_map * bmap_i,int i,int j,struct isl_coalesce_info * info)3416 static enum isl_change coalesce_after_aligning_divs(
3417 	__isl_keep isl_basic_map *bmap_i, int i, int j,
3418 	struct isl_coalesce_info *info)
3419 {
3420 	isl_bool known;
3421 	isl_mat *div_i, *div_j, *div;
3422 	int *exp1 = NULL;
3423 	int *exp2 = NULL;
3424 	isl_ctx *ctx;
3425 	enum isl_change change;
3426 
3427 	known = isl_basic_map_divs_known(bmap_i);
3428 	if (known < 0)
3429 		return isl_change_error;
3430 	if (!known)
3431 		return isl_change_none;
3432 
3433 	ctx = isl_basic_map_get_ctx(bmap_i);
3434 
3435 	div_i = isl_basic_map_get_divs(bmap_i);
3436 	div_j = isl_basic_map_get_divs(info[j].bmap);
3437 
3438 	if (!div_i || !div_j)
3439 		goto error;
3440 
3441 	exp1 = isl_alloc_array(ctx, int, div_i->n_row);
3442 	exp2 = isl_alloc_array(ctx, int, div_j->n_row);
3443 	if ((div_i->n_row && !exp1) || (div_j->n_row && !exp2))
3444 		goto error;
3445 
3446 	div = isl_merge_divs(div_i, div_j, exp1, exp2);
3447 	if (!div)
3448 		goto error;
3449 
3450 	if (div->n_row == div_j->n_row)
3451 		change = coalesce_with_expanded_divs(bmap_i,
3452 							i, j, info, div, exp1);
3453 	else
3454 		change = isl_change_none;
3455 
3456 	isl_mat_free(div);
3457 
3458 	isl_mat_free(div_i);
3459 	isl_mat_free(div_j);
3460 
3461 	free(exp2);
3462 	free(exp1);
3463 
3464 	return change;
3465 error:
3466 	isl_mat_free(div_i);
3467 	isl_mat_free(div_j);
3468 	free(exp1);
3469 	free(exp2);
3470 	return isl_change_error;
3471 }
3472 
3473 /* Check if basic map "j" is a subset of basic map "i" after
3474  * exploiting the extra equalities of "j" to simplify the divs of "i".
3475  * If so, remove basic map "j" and return isl_change_drop_second.
3476  *
3477  * If "j" does not have any equalities or if they are the same
3478  * as those of "i", then we cannot exploit them to simplify the divs.
3479  * Similarly, if there are no divs in "i", then they cannot be simplified.
3480  * If, on the other hand, the affine hulls of "i" and "j" do not intersect,
3481  * then "j" cannot be a subset of "i".
3482  *
3483  * Otherwise, we intersect "i" with the affine hull of "j" and then
3484  * check if "j" is a subset of the result after aligning the divs.
3485  * If so, then "j" is definitely a subset of "i" and can be removed.
3486  * Note that if after intersection with the affine hull of "j".
3487  * "i" still has more divs than "j", then there is no way we can
3488  * align the divs of "i" to those of "j".
3489  */
coalesce_subset_with_equalities(int i,int j,struct isl_coalesce_info * info)3490 static enum isl_change coalesce_subset_with_equalities(int i, int j,
3491 	struct isl_coalesce_info *info)
3492 {
3493 	isl_basic_map *hull_i, *hull_j, *bmap_i;
3494 	int equal, empty;
3495 	enum isl_change change;
3496 
3497 	if (info[j].bmap->n_eq == 0)
3498 		return isl_change_none;
3499 	if (info[i].bmap->n_div == 0)
3500 		return isl_change_none;
3501 
3502 	hull_i = isl_basic_map_copy(info[i].bmap);
3503 	hull_i = isl_basic_map_plain_affine_hull(hull_i);
3504 	hull_j = isl_basic_map_copy(info[j].bmap);
3505 	hull_j = isl_basic_map_plain_affine_hull(hull_j);
3506 
3507 	hull_j = isl_basic_map_intersect(hull_j, isl_basic_map_copy(hull_i));
3508 	equal = isl_basic_map_plain_is_equal(hull_i, hull_j);
3509 	empty = isl_basic_map_plain_is_empty(hull_j);
3510 	isl_basic_map_free(hull_i);
3511 
3512 	if (equal < 0 || equal || empty < 0 || empty) {
3513 		isl_basic_map_free(hull_j);
3514 		if (equal < 0 || empty < 0)
3515 			return isl_change_error;
3516 		return isl_change_none;
3517 	}
3518 
3519 	bmap_i = isl_basic_map_copy(info[i].bmap);
3520 	bmap_i = isl_basic_map_intersect(bmap_i, hull_j);
3521 	if (!bmap_i)
3522 		return isl_change_error;
3523 
3524 	if (bmap_i->n_div > info[j].bmap->n_div) {
3525 		isl_basic_map_free(bmap_i);
3526 		return isl_change_none;
3527 	}
3528 
3529 	change = coalesce_after_aligning_divs(bmap_i, -1, j, info);
3530 
3531 	isl_basic_map_free(bmap_i);
3532 
3533 	return change;
3534 }
3535 
3536 /* Check if the union of and the basic maps represented by info[i] and info[j]
3537  * can be represented by a single basic map, by aligning or equating
3538  * their integer divisions.
3539  * If so, replace the pair by the single basic map and return
3540  * isl_change_drop_first, isl_change_drop_second or isl_change_fuse.
3541  * Otherwise, return isl_change_none.
3542  *
3543  * Note that we only perform any test if the number of divs is different
3544  * in the two basic maps.  In case the number of divs is the same,
3545  * we have already established that the divs are different
3546  * in the two basic maps.
3547  * In particular, if the number of divs of basic map i is smaller than
3548  * the number of divs of basic map j, then we check if j is a subset of i
3549  * and vice versa.
3550  */
coalesce_divs(int i,int j,struct isl_coalesce_info * info)3551 static enum isl_change coalesce_divs(int i, int j,
3552 	struct isl_coalesce_info *info)
3553 {
3554 	enum isl_change change = isl_change_none;
3555 
3556 	if (info[i].bmap->n_div < info[j].bmap->n_div)
3557 		change = coalesce_after_aligning_divs(info[i].bmap, i, j, info);
3558 	if (change != isl_change_none)
3559 		return change;
3560 
3561 	if (info[j].bmap->n_div < info[i].bmap->n_div)
3562 		change = coalesce_after_aligning_divs(info[j].bmap, j, i, info);
3563 	if (change != isl_change_none)
3564 		return invert_change(change);
3565 
3566 	change = coalesce_subset_with_equalities(i, j, info);
3567 	if (change != isl_change_none)
3568 		return change;
3569 
3570 	change = coalesce_subset_with_equalities(j, i, info);
3571 	if (change != isl_change_none)
3572 		return invert_change(change);
3573 
3574 	return isl_change_none;
3575 }
3576 
3577 /* Does "bmap" involve any divs that themselves refer to divs?
3578  */
has_nested_div(__isl_keep isl_basic_map * bmap)3579 static isl_bool has_nested_div(__isl_keep isl_basic_map *bmap)
3580 {
3581 	int i;
3582 	isl_size total;
3583 	isl_size n_div;
3584 
3585 	total = isl_basic_map_dim(bmap, isl_dim_all);
3586 	n_div = isl_basic_map_dim(bmap, isl_dim_div);
3587 	if (total < 0 || n_div < 0)
3588 		return isl_bool_error;
3589 	total -= n_div;
3590 
3591 	for (i = 0; i < n_div; ++i)
3592 		if (isl_seq_first_non_zero(bmap->div[i] + 2 + total,
3593 					    n_div) != -1)
3594 			return isl_bool_true;
3595 
3596 	return isl_bool_false;
3597 }
3598 
3599 /* Return a list of affine expressions, one for each integer division
3600  * in "bmap_i".  For each integer division that also appears in "bmap_j",
3601  * the affine expression is set to NaN.  The number of NaNs in the list
3602  * is equal to the number of integer divisions in "bmap_j".
3603  * For the other integer divisions of "bmap_i", the corresponding
3604  * element in the list is a purely affine expression equal to the integer
3605  * division in "hull".
3606  * If no such list can be constructed, then the number of elements
3607  * in the returned list is smaller than the number of integer divisions
3608  * in "bmap_i".
3609  */
set_up_substitutions(__isl_keep isl_basic_map * bmap_i,__isl_keep isl_basic_map * bmap_j,__isl_take isl_basic_map * hull)3610 static __isl_give isl_aff_list *set_up_substitutions(
3611 	__isl_keep isl_basic_map *bmap_i, __isl_keep isl_basic_map *bmap_j,
3612 	__isl_take isl_basic_map *hull)
3613 {
3614 	isl_size n_div_i, n_div_j, total;
3615 	isl_ctx *ctx;
3616 	isl_local_space *ls;
3617 	isl_basic_set *wrap_hull;
3618 	isl_aff *aff_nan;
3619 	isl_aff_list *list;
3620 	int i, j;
3621 
3622 	n_div_i = isl_basic_map_dim(bmap_i, isl_dim_div);
3623 	n_div_j = isl_basic_map_dim(bmap_j, isl_dim_div);
3624 	total = isl_basic_map_dim(bmap_i, isl_dim_all);
3625 	if (!hull || n_div_i < 0 || n_div_j < 0 || total < 0)
3626 		return NULL;
3627 
3628 	ctx = isl_basic_map_get_ctx(hull);
3629 	total -= n_div_i;
3630 
3631 	ls = isl_basic_map_get_local_space(bmap_i);
3632 	ls = isl_local_space_wrap(ls);
3633 	wrap_hull = isl_basic_map_wrap(hull);
3634 
3635 	aff_nan = isl_aff_nan_on_domain(isl_local_space_copy(ls));
3636 	list = isl_aff_list_alloc(ctx, n_div_i);
3637 
3638 	j = 0;
3639 	for (i = 0; i < n_div_i; ++i) {
3640 		isl_aff *aff;
3641 		isl_size n_div;
3642 
3643 		if (j < n_div_j &&
3644 		    isl_basic_map_equal_div_expr_part(bmap_i, i, bmap_j, j,
3645 						    0, 2 + total)) {
3646 			++j;
3647 			list = isl_aff_list_add(list, isl_aff_copy(aff_nan));
3648 			continue;
3649 		}
3650 		if (n_div_i - i <= n_div_j - j)
3651 			break;
3652 
3653 		aff = isl_local_space_get_div(ls, i);
3654 		aff = isl_aff_substitute_equalities(aff,
3655 						isl_basic_set_copy(wrap_hull));
3656 		aff = isl_aff_floor(aff);
3657 		n_div = isl_aff_dim(aff, isl_dim_div);
3658 		if (n_div < 0)
3659 			goto error;
3660 		if (n_div != 0) {
3661 			isl_aff_free(aff);
3662 			break;
3663 		}
3664 
3665 		list = isl_aff_list_add(list, aff);
3666 	}
3667 
3668 	isl_aff_free(aff_nan);
3669 	isl_local_space_free(ls);
3670 	isl_basic_set_free(wrap_hull);
3671 
3672 	return list;
3673 error:
3674 	isl_aff_free(aff_nan);
3675 	isl_local_space_free(ls);
3676 	isl_basic_set_free(wrap_hull);
3677 	isl_aff_list_free(list);
3678 	return NULL;
3679 }
3680 
3681 /* Add variables to info->bmap and info->tab corresponding to the elements
3682  * in "list" that are not set to NaN.
3683  * "extra_var" is the number of these elements.
3684  * "dim" is the offset in the variables of "tab" where we should
3685  * start considering the elements in "list".
3686  * When this function returns, the total number of variables in "tab"
3687  * is equal to "dim" plus the number of elements in "list".
3688  *
3689  * The newly added existentially quantified variables are not given
3690  * an explicit representation because the corresponding div constraints
3691  * do not appear in info->bmap.  These constraints are not added
3692  * to info->bmap because for internal consistency, they would need to
3693  * be added to info->tab as well, where they could combine with the equality
3694  * that is added later to result in constraints that do not hold
3695  * in the original input.
3696  */
add_sub_vars(struct isl_coalesce_info * info,__isl_keep isl_aff_list * list,int dim,int extra_var)3697 static isl_stat add_sub_vars(struct isl_coalesce_info *info,
3698 	__isl_keep isl_aff_list *list, int dim, int extra_var)
3699 {
3700 	int i, j, d;
3701 	isl_size n;
3702 
3703 	info->bmap = isl_basic_map_cow(info->bmap);
3704 	info->bmap = isl_basic_map_extend(info->bmap, extra_var, 0, 0);
3705 	n = isl_aff_list_n_aff(list);
3706 	if (!info->bmap || n < 0)
3707 		return isl_stat_error;
3708 	for (i = 0; i < n; ++i) {
3709 		int is_nan;
3710 		isl_aff *aff;
3711 
3712 		aff = isl_aff_list_get_aff(list, i);
3713 		is_nan = isl_aff_is_nan(aff);
3714 		isl_aff_free(aff);
3715 		if (is_nan < 0)
3716 			return isl_stat_error;
3717 		if (is_nan)
3718 			continue;
3719 
3720 		if (isl_tab_insert_var(info->tab, dim + i) < 0)
3721 			return isl_stat_error;
3722 		d = isl_basic_map_alloc_div(info->bmap);
3723 		if (d < 0)
3724 			return isl_stat_error;
3725 		info->bmap = isl_basic_map_mark_div_unknown(info->bmap, d);
3726 		for (j = d; j > i; --j)
3727 			info->bmap = isl_basic_map_swap_div(info->bmap,
3728 							    j - 1, j);
3729 		if (!info->bmap)
3730 			return isl_stat_error;
3731 	}
3732 
3733 	return isl_stat_ok;
3734 }
3735 
3736 /* For each element in "list" that is not set to NaN, fix the corresponding
3737  * variable in "tab" to the purely affine expression defined by the element.
3738  * "dim" is the offset in the variables of "tab" where we should
3739  * start considering the elements in "list".
3740  *
3741  * This function assumes that a sufficient number of rows and
3742  * elements in the constraint array are available in the tableau.
3743  */
add_sub_equalities(struct isl_tab * tab,__isl_keep isl_aff_list * list,int dim)3744 static isl_stat add_sub_equalities(struct isl_tab *tab,
3745 	__isl_keep isl_aff_list *list, int dim)
3746 {
3747 	int i;
3748 	isl_size n;
3749 	isl_ctx *ctx;
3750 	isl_vec *sub;
3751 	isl_aff *aff;
3752 
3753 	n = isl_aff_list_n_aff(list);
3754 	if (n < 0)
3755 		return isl_stat_error;
3756 
3757 	ctx = isl_tab_get_ctx(tab);
3758 	sub = isl_vec_alloc(ctx, 1 + dim + n);
3759 	if (!sub)
3760 		return isl_stat_error;
3761 	isl_seq_clr(sub->el + 1 + dim, n);
3762 
3763 	for (i = 0; i < n; ++i) {
3764 		aff = isl_aff_list_get_aff(list, i);
3765 		if (!aff)
3766 			goto error;
3767 		if (isl_aff_is_nan(aff)) {
3768 			isl_aff_free(aff);
3769 			continue;
3770 		}
3771 		isl_seq_cpy(sub->el, aff->v->el + 1, 1 + dim);
3772 		isl_int_neg(sub->el[1 + dim + i], aff->v->el[0]);
3773 		if (isl_tab_add_eq(tab, sub->el) < 0)
3774 			goto error;
3775 		isl_int_set_si(sub->el[1 + dim + i], 0);
3776 		isl_aff_free(aff);
3777 	}
3778 
3779 	isl_vec_free(sub);
3780 	return isl_stat_ok;
3781 error:
3782 	isl_aff_free(aff);
3783 	isl_vec_free(sub);
3784 	return isl_stat_error;
3785 }
3786 
3787 /* Add variables to info->tab and info->bmap corresponding to the elements
3788  * in "list" that are not set to NaN.  The value of the added variable
3789  * in info->tab is fixed to the purely affine expression defined by the element.
3790  * "dim" is the offset in the variables of info->tab where we should
3791  * start considering the elements in "list".
3792  * When this function returns, the total number of variables in info->tab
3793  * is equal to "dim" plus the number of elements in "list".
3794  */
add_subs(struct isl_coalesce_info * info,__isl_keep isl_aff_list * list,int dim)3795 static isl_stat add_subs(struct isl_coalesce_info *info,
3796 	__isl_keep isl_aff_list *list, int dim)
3797 {
3798 	int extra_var;
3799 	isl_size n;
3800 
3801 	n = isl_aff_list_n_aff(list);
3802 	if (n < 0)
3803 		return isl_stat_error;
3804 
3805 	extra_var = n - (info->tab->n_var - dim);
3806 
3807 	if (isl_tab_extend_vars(info->tab, extra_var) < 0)
3808 		return isl_stat_error;
3809 	if (isl_tab_extend_cons(info->tab, 2 * extra_var) < 0)
3810 		return isl_stat_error;
3811 	if (add_sub_vars(info, list, dim, extra_var) < 0)
3812 		return isl_stat_error;
3813 
3814 	return add_sub_equalities(info->tab, list, dim);
3815 }
3816 
3817 /* Coalesce basic map "j" into basic map "i" after adding the extra integer
3818  * divisions in "i" but not in "j" to basic map "j", with values
3819  * specified by "list".  The total number of elements in "list"
3820  * is equal to the number of integer divisions in "i", while the number
3821  * of NaN elements in the list is equal to the number of integer divisions
3822  * in "j".
3823  *
3824  * If no coalescing can be performed, then we need to revert basic map "j"
3825  * to its original state.  We do the same if basic map "i" gets dropped
3826  * during the coalescing, even though this should not happen in practice
3827  * since we have already checked for "j" being a subset of "i"
3828  * before we reach this stage.
3829  */
coalesce_with_subs(int i,int j,struct isl_coalesce_info * info,__isl_keep isl_aff_list * list)3830 static enum isl_change coalesce_with_subs(int i, int j,
3831 	struct isl_coalesce_info *info, __isl_keep isl_aff_list *list)
3832 {
3833 	isl_basic_map *bmap_j;
3834 	struct isl_tab_undo *snap;
3835 	isl_size dim, n_div;
3836 	enum isl_change change;
3837 
3838 	bmap_j = isl_basic_map_copy(info[j].bmap);
3839 	snap = isl_tab_snap(info[j].tab);
3840 
3841 	dim = isl_basic_map_dim(bmap_j, isl_dim_all);
3842 	n_div = isl_basic_map_dim(bmap_j, isl_dim_div);
3843 	if (dim < 0 || n_div < 0)
3844 		goto error;
3845 	dim -= n_div;
3846 	if (add_subs(&info[j], list, dim) < 0)
3847 		goto error;
3848 
3849 	change = coalesce_local_pair(i, j, info);
3850 	if (change != isl_change_none && change != isl_change_drop_first) {
3851 		isl_basic_map_free(bmap_j);
3852 	} else {
3853 		isl_basic_map_free(info[j].bmap);
3854 		info[j].bmap = bmap_j;
3855 
3856 		if (isl_tab_rollback(info[j].tab, snap) < 0)
3857 			return isl_change_error;
3858 	}
3859 
3860 	return change;
3861 error:
3862 	isl_basic_map_free(bmap_j);
3863 	return isl_change_error;
3864 }
3865 
3866 /* Check if we can coalesce basic map "j" into basic map "i" after copying
3867  * those extra integer divisions in "i" that can be simplified away
3868  * using the extra equalities in "j".
3869  * All divs are assumed to be known and not contain any nested divs.
3870  *
3871  * We first check if there are any extra equalities in "j" that we
3872  * can exploit.  Then we check if every integer division in "i"
3873  * either already appears in "j" or can be simplified using the
3874  * extra equalities to a purely affine expression.
3875  * If these tests succeed, then we try to coalesce the two basic maps
3876  * by introducing extra dimensions in "j" corresponding to
3877  * the extra integer divisions "i" fixed to the corresponding
3878  * purely affine expression.
3879  */
check_coalesce_into_eq(int i,int j,struct isl_coalesce_info * info)3880 static enum isl_change check_coalesce_into_eq(int i, int j,
3881 	struct isl_coalesce_info *info)
3882 {
3883 	isl_size n_div_i, n_div_j, n;
3884 	isl_basic_map *hull_i, *hull_j;
3885 	isl_bool equal, empty;
3886 	isl_aff_list *list;
3887 	enum isl_change change;
3888 
3889 	n_div_i = isl_basic_map_dim(info[i].bmap, isl_dim_div);
3890 	n_div_j = isl_basic_map_dim(info[j].bmap, isl_dim_div);
3891 	if (n_div_i < 0 || n_div_j < 0)
3892 		return isl_change_error;
3893 	if (n_div_i <= n_div_j)
3894 		return isl_change_none;
3895 	if (info[j].bmap->n_eq == 0)
3896 		return isl_change_none;
3897 
3898 	hull_i = isl_basic_map_copy(info[i].bmap);
3899 	hull_i = isl_basic_map_plain_affine_hull(hull_i);
3900 	hull_j = isl_basic_map_copy(info[j].bmap);
3901 	hull_j = isl_basic_map_plain_affine_hull(hull_j);
3902 
3903 	hull_j = isl_basic_map_intersect(hull_j, isl_basic_map_copy(hull_i));
3904 	equal = isl_basic_map_plain_is_equal(hull_i, hull_j);
3905 	empty = isl_basic_map_plain_is_empty(hull_j);
3906 	isl_basic_map_free(hull_i);
3907 
3908 	if (equal < 0 || empty < 0)
3909 		goto error;
3910 	if (equal || empty) {
3911 		isl_basic_map_free(hull_j);
3912 		return isl_change_none;
3913 	}
3914 
3915 	list = set_up_substitutions(info[i].bmap, info[j].bmap, hull_j);
3916 	if (!list)
3917 		return isl_change_error;
3918 	n = isl_aff_list_n_aff(list);
3919 	if (n < 0)
3920 		change = isl_change_error;
3921 	else if (n < n_div_i)
3922 		change = isl_change_none;
3923 	else
3924 		change = coalesce_with_subs(i, j, info, list);
3925 
3926 	isl_aff_list_free(list);
3927 
3928 	return change;
3929 error:
3930 	isl_basic_map_free(hull_j);
3931 	return isl_change_error;
3932 }
3933 
3934 /* Check if we can coalesce basic maps "i" and "j" after copying
3935  * those extra integer divisions in one of the basic maps that can
3936  * be simplified away using the extra equalities in the other basic map.
3937  * We require all divs to be known in both basic maps.
3938  * Furthermore, to simplify the comparison of div expressions,
3939  * we do not allow any nested integer divisions.
3940  */
check_coalesce_eq(int i,int j,struct isl_coalesce_info * info)3941 static enum isl_change check_coalesce_eq(int i, int j,
3942 	struct isl_coalesce_info *info)
3943 {
3944 	isl_bool known, nested;
3945 	enum isl_change change;
3946 
3947 	known = isl_basic_map_divs_known(info[i].bmap);
3948 	if (known < 0 || !known)
3949 		return known < 0 ? isl_change_error : isl_change_none;
3950 	known = isl_basic_map_divs_known(info[j].bmap);
3951 	if (known < 0 || !known)
3952 		return known < 0 ? isl_change_error : isl_change_none;
3953 	nested = has_nested_div(info[i].bmap);
3954 	if (nested < 0 || nested)
3955 		return nested < 0 ? isl_change_error : isl_change_none;
3956 	nested = has_nested_div(info[j].bmap);
3957 	if (nested < 0 || nested)
3958 		return nested < 0 ? isl_change_error : isl_change_none;
3959 
3960 	change = check_coalesce_into_eq(i, j, info);
3961 	if (change != isl_change_none)
3962 		return change;
3963 	change = check_coalesce_into_eq(j, i, info);
3964 	if (change != isl_change_none)
3965 		return invert_change(change);
3966 
3967 	return isl_change_none;
3968 }
3969 
3970 /* Check if the union of the given pair of basic maps
3971  * can be represented by a single basic map.
3972  * If so, replace the pair by the single basic map and return
3973  * isl_change_drop_first, isl_change_drop_second or isl_change_fuse.
3974  * Otherwise, return isl_change_none.
3975  *
3976  * We first check if the two basic maps live in the same local space,
3977  * after aligning the divs that differ by only an integer constant.
3978  * If so, we do the complete check.  Otherwise, we check if they have
3979  * the same number of integer divisions and can be coalesced, if one is
3980  * an obvious subset of the other or if the extra integer divisions
3981  * of one basic map can be simplified away using the extra equalities
3982  * of the other basic map.
3983  *
3984  * Note that trying to coalesce pairs of disjuncts with the same
3985  * number, but different local variables may drop the explicit
3986  * representation of some of these local variables.
3987  * This operation is therefore not performed when
3988  * the "coalesce_preserve_locals" option is set.
3989  */
coalesce_pair(int i,int j,struct isl_coalesce_info * info)3990 static enum isl_change coalesce_pair(int i, int j,
3991 	struct isl_coalesce_info *info)
3992 {
3993 	int preserve;
3994 	isl_bool same;
3995 	enum isl_change change;
3996 	isl_ctx *ctx;
3997 
3998 	if (harmonize_divs(&info[i], &info[j]) < 0)
3999 		return isl_change_error;
4000 	same = same_divs(info[i].bmap, info[j].bmap);
4001 	if (same < 0)
4002 		return isl_change_error;
4003 	if (same)
4004 		return coalesce_local_pair(i, j, info);
4005 
4006 	ctx = isl_basic_map_get_ctx(info[i].bmap);
4007 	preserve = isl_options_get_coalesce_preserve_locals(ctx);
4008 	if (!preserve && info[i].bmap->n_div == info[j].bmap->n_div) {
4009 		change = coalesce_local_pair(i, j, info);
4010 		if (change != isl_change_none)
4011 			return change;
4012 	}
4013 
4014 	change = coalesce_divs(i, j, info);
4015 	if (change != isl_change_none)
4016 		return change;
4017 
4018 	return check_coalesce_eq(i, j, info);
4019 }
4020 
4021 /* Return the maximum of "a" and "b".
4022  */
isl_max(int a,int b)4023 static int isl_max(int a, int b)
4024 {
4025 	return a > b ? a : b;
4026 }
4027 
4028 /* Pairwise coalesce the basic maps in the range [start1, end1[ of "info"
4029  * with those in the range [start2, end2[, skipping basic maps
4030  * that have been removed (either before or within this function).
4031  *
4032  * For each basic map i in the first range, we check if it can be coalesced
4033  * with respect to any previously considered basic map j in the second range.
4034  * If i gets dropped (because it was a subset of some j), then
4035  * we can move on to the next basic map.
4036  * If j gets dropped, we need to continue checking against the other
4037  * previously considered basic maps.
4038  * If the two basic maps got fused, then we recheck the fused basic map
4039  * against the previously considered basic maps, starting at i + 1
4040  * (even if start2 is greater than i + 1).
4041  */
coalesce_range(isl_ctx * ctx,struct isl_coalesce_info * info,int start1,int end1,int start2,int end2)4042 static int coalesce_range(isl_ctx *ctx, struct isl_coalesce_info *info,
4043 	int start1, int end1, int start2, int end2)
4044 {
4045 	int i, j;
4046 
4047 	for (i = end1 - 1; i >= start1; --i) {
4048 		if (info[i].removed)
4049 			continue;
4050 		for (j = isl_max(i + 1, start2); j < end2; ++j) {
4051 			enum isl_change changed;
4052 
4053 			if (info[j].removed)
4054 				continue;
4055 			if (info[i].removed)
4056 				isl_die(ctx, isl_error_internal,
4057 					"basic map unexpectedly removed",
4058 					return -1);
4059 			changed = coalesce_pair(i, j, info);
4060 			switch (changed) {
4061 			case isl_change_error:
4062 				return -1;
4063 			case isl_change_none:
4064 			case isl_change_drop_second:
4065 				continue;
4066 			case isl_change_drop_first:
4067 				j = end2;
4068 				break;
4069 			case isl_change_fuse:
4070 				j = i;
4071 				break;
4072 			}
4073 		}
4074 	}
4075 
4076 	return 0;
4077 }
4078 
4079 /* Pairwise coalesce the basic maps described by the "n" elements of "info".
4080  *
4081  * We consider groups of basic maps that live in the same apparent
4082  * affine hull and we first coalesce within such a group before we
4083  * coalesce the elements in the group with elements of previously
4084  * considered groups.  If a fuse happens during the second phase,
4085  * then we also reconsider the elements within the group.
4086  */
coalesce(isl_ctx * ctx,int n,struct isl_coalesce_info * info)4087 static int coalesce(isl_ctx *ctx, int n, struct isl_coalesce_info *info)
4088 {
4089 	int start, end;
4090 
4091 	for (end = n; end > 0; end = start) {
4092 		start = end - 1;
4093 		while (start >= 1 &&
4094 		    info[start - 1].hull_hash == info[start].hull_hash)
4095 			start--;
4096 		if (coalesce_range(ctx, info, start, end, start, end) < 0)
4097 			return -1;
4098 		if (coalesce_range(ctx, info, start, end, end, n) < 0)
4099 			return -1;
4100 	}
4101 
4102 	return 0;
4103 }
4104 
4105 /* Update the basic maps in "map" based on the information in "info".
4106  * In particular, remove the basic maps that have been marked removed and
4107  * update the others based on the information in the corresponding tableau.
4108  * Since we detected implicit equalities without calling
4109  * isl_basic_map_gauss, we need to do it now.
4110  * Also call isl_basic_map_simplify if we may have lost the definition
4111  * of one or more integer divisions.
4112  * If a basic map is still equal to the one from which the corresponding "info"
4113  * entry was created, then redundant constraint and
4114  * implicit equality constraint detection have been performed
4115  * on the corresponding tableau and the basic map can be marked as such.
4116  */
update_basic_maps(__isl_take isl_map * map,int n,struct isl_coalesce_info * info)4117 static __isl_give isl_map *update_basic_maps(__isl_take isl_map *map,
4118 	int n, struct isl_coalesce_info *info)
4119 {
4120 	int i;
4121 
4122 	if (!map)
4123 		return NULL;
4124 
4125 	for (i = n - 1; i >= 0; --i) {
4126 		if (info[i].removed) {
4127 			isl_basic_map_free(map->p[i]);
4128 			if (i != map->n - 1)
4129 				map->p[i] = map->p[map->n - 1];
4130 			map->n--;
4131 			continue;
4132 		}
4133 
4134 		info[i].bmap = isl_basic_map_update_from_tab(info[i].bmap,
4135 							info[i].tab);
4136 		info[i].bmap = isl_basic_map_gauss(info[i].bmap, NULL);
4137 		if (info[i].simplify)
4138 			info[i].bmap = isl_basic_map_simplify(info[i].bmap);
4139 		info[i].bmap = isl_basic_map_finalize(info[i].bmap);
4140 		if (!info[i].bmap)
4141 			return isl_map_free(map);
4142 		if (!info[i].modified) {
4143 			ISL_F_SET(info[i].bmap, ISL_BASIC_MAP_NO_IMPLICIT);
4144 			ISL_F_SET(info[i].bmap, ISL_BASIC_MAP_NO_REDUNDANT);
4145 		}
4146 		isl_basic_map_free(map->p[i]);
4147 		map->p[i] = info[i].bmap;
4148 		info[i].bmap = NULL;
4149 	}
4150 
4151 	return map;
4152 }
4153 
4154 /* For each pair of basic maps in the map, check if the union of the two
4155  * can be represented by a single basic map.
4156  * If so, replace the pair by the single basic map and start over.
4157  *
4158  * We factor out any (hidden) common factor from the constraint
4159  * coefficients to improve the detection of adjacent constraints.
4160  * Note that this function does not call isl_basic_map_gauss,
4161  * but it does make sure that only a single copy of the basic map
4162  * is affected.  This means that isl_basic_map_gauss may have
4163  * to be called at the end of the computation (in update_basic_maps)
4164  * on this single copy to ensure that
4165  * the basic maps are not left in an unexpected state.
4166  *
4167  * Since we are constructing the tableaus of the basic maps anyway,
4168  * we exploit them to detect implicit equalities and redundant constraints.
4169  * This also helps the coalescing as it can ignore the redundant constraints.
4170  * In order to avoid confusion, we make all implicit equalities explicit
4171  * in the basic maps.  If the basic map only has a single reference
4172  * (this happens in particular if it was modified by
4173  * isl_basic_map_reduce_coefficients), then isl_basic_map_gauss
4174  * does not get called on the result.  The call to
4175  * isl_basic_map_gauss in update_basic_maps resolves this as well.
4176  * For each basic map, we also compute the hash of the apparent affine hull
4177  * for use in coalesce.
4178  */
isl_map_coalesce(__isl_take isl_map * map)4179 __isl_give isl_map *isl_map_coalesce(__isl_take isl_map *map)
4180 {
4181 	int i;
4182 	unsigned n;
4183 	isl_ctx *ctx;
4184 	struct isl_coalesce_info *info = NULL;
4185 
4186 	map = isl_map_remove_empty_parts(map);
4187 	if (!map)
4188 		return NULL;
4189 
4190 	if (map->n <= 1)
4191 		return map;
4192 
4193 	ctx = isl_map_get_ctx(map);
4194 	map = isl_map_sort_divs(map);
4195 	map = isl_map_cow(map);
4196 
4197 	if (!map)
4198 		return NULL;
4199 
4200 	n = map->n;
4201 
4202 	info = isl_calloc_array(map->ctx, struct isl_coalesce_info, n);
4203 	if (!info)
4204 		goto error;
4205 
4206 	for (i = 0; i < map->n; ++i) {
4207 		map->p[i] = isl_basic_map_reduce_coefficients(map->p[i]);
4208 		if (!map->p[i])
4209 			goto error;
4210 		info[i].bmap = isl_basic_map_copy(map->p[i]);
4211 		info[i].tab = isl_tab_from_basic_map(info[i].bmap, 0);
4212 		if (!info[i].tab)
4213 			goto error;
4214 		if (!ISL_F_ISSET(info[i].bmap, ISL_BASIC_MAP_NO_IMPLICIT))
4215 			if (isl_tab_detect_implicit_equalities(info[i].tab) < 0)
4216 				goto error;
4217 		info[i].bmap = isl_tab_make_equalities_explicit(info[i].tab,
4218 								info[i].bmap);
4219 		if (!info[i].bmap)
4220 			goto error;
4221 		if (!ISL_F_ISSET(info[i].bmap, ISL_BASIC_MAP_NO_REDUNDANT))
4222 			if (isl_tab_detect_redundant(info[i].tab) < 0)
4223 				goto error;
4224 		if (coalesce_info_set_hull_hash(&info[i]) < 0)
4225 			goto error;
4226 	}
4227 	for (i = map->n - 1; i >= 0; --i)
4228 		if (info[i].tab->empty)
4229 			drop(&info[i]);
4230 
4231 	if (coalesce(ctx, n, info) < 0)
4232 		goto error;
4233 
4234 	map = update_basic_maps(map, n, info);
4235 
4236 	clear_coalesce_info(n, info);
4237 
4238 	return map;
4239 error:
4240 	clear_coalesce_info(n, info);
4241 	isl_map_free(map);
4242 	return NULL;
4243 }
4244 
4245 /* For each pair of basic sets in the set, check if the union of the two
4246  * can be represented by a single basic set.
4247  * If so, replace the pair by the single basic set and start over.
4248  */
isl_set_coalesce(__isl_take isl_set * set)4249 __isl_give isl_set *isl_set_coalesce(__isl_take isl_set *set)
4250 {
4251 	return set_from_map(isl_map_coalesce(set_to_map(set)));
4252 }
4253