isl_ast_codegen.c: remove dependence on internals of isl_constraint_list
[platform/upstream/isl.git] / isl_ast_codegen.c
1 /*
2  * Copyright 2012      Ecole Normale Superieure
3  *
4  * Use of this software is governed by the MIT license
5  *
6  * Written by Sven Verdoolaege,
7  * Ecole Normale Superieure, 45 rue d’Ulm, 75230 Paris, France
8  */
9
10 #include <limits.h>
11 #include <isl/aff.h>
12 #include <isl/set.h>
13 #include <isl/ilp.h>
14 #include <isl/union_map.h>
15 #include <isl_sort.h>
16 #include <isl_tarjan.h>
17 #include <isl_ast_private.h>
18 #include <isl_ast_build_expr.h>
19 #include <isl_ast_build_private.h>
20 #include <isl_ast_graft_private.h>
21
22 /* Add the constraint to the list that "user" points to, if it is not
23  * a div constraint.
24  */
25 static int collect_constraint(__isl_take isl_constraint *constraint,
26         void *user)
27 {
28         isl_constraint_list **list = user;
29
30         if (isl_constraint_is_div_constraint(constraint))
31                 isl_constraint_free(constraint);
32         else
33                 *list = isl_constraint_list_add(*list, constraint);
34
35         return 0;
36 }
37
38 /* Extract the constraints of "bset" (except the div constraints)
39  * and collect them in an isl_constraint_list.
40  */
41 static __isl_give isl_constraint_list *isl_constraint_list_from_basic_set(
42         __isl_take isl_basic_set *bset)
43 {
44         int n;
45         isl_ctx *ctx;
46         isl_constraint_list *list;
47
48         if (!bset)
49                 return NULL;
50
51         ctx = isl_basic_set_get_ctx(bset);
52
53         n = isl_basic_set_n_constraint(bset);
54         list = isl_constraint_list_alloc(ctx, n);
55         if (isl_basic_set_foreach_constraint(bset,
56                                             &collect_constraint, &list) < 0)
57                 list = isl_constraint_list_free(list);
58
59         isl_basic_set_free(bset);
60         return list;
61 }
62
63 /* Data used in generate_domain.
64  *
65  * "build" is the input build.
66  * "list" collects the results.
67  */
68 struct isl_generate_domain_data {
69         isl_ast_build *build;
70
71         isl_ast_graft_list *list;
72 };
73
74 static __isl_give isl_ast_graft_list *generate_next_level(
75         __isl_take isl_union_map *executed,
76         __isl_take isl_ast_build *build);
77 static __isl_give isl_ast_graft_list *generate_code(
78         __isl_take isl_union_map *executed, __isl_take isl_ast_build *build,
79         int internal);
80
81 /* Generate an AST for a single domain based on
82  * the (non single valued) inverse schedule "executed".
83  *
84  * We extend the schedule with the iteration domain
85  * and continue generating through a call to generate_code.
86  *
87  * In particular, if executed has the form
88  *
89  *      S -> D
90  *
91  * then we continue generating code on
92  *
93  *      [S -> D] -> D
94  *
95  * The extended inverse schedule is clearly single valued
96  * ensuring that the nested generate_code will not reach this function,
97  * but will instead create calls to all elements of D that need
98  * to be executed from the current schedule domain.
99  */
100 static int generate_non_single_valued(__isl_take isl_map *executed,
101         struct isl_generate_domain_data *data)
102 {
103         isl_map *identity;
104         isl_ast_build *build;
105         isl_ast_graft_list *list;
106
107         build = isl_ast_build_copy(data->build);
108
109         identity = isl_set_identity(isl_map_range(isl_map_copy(executed)));
110         executed = isl_map_domain_product(executed, identity);
111         build = isl_ast_build_set_single_valued(build, 1);
112
113         list = generate_code(isl_union_map_from_map(executed), build, 1);
114
115         data->list = isl_ast_graft_list_concat(data->list, list);
116
117         return 0;
118 }
119
120 /* Call the at_each_domain callback, if requested by the user,
121  * after recording the current inverse schedule in the build.
122  */
123 static __isl_give isl_ast_graft *at_each_domain(__isl_take isl_ast_graft *graft,
124         __isl_keep isl_map *executed, __isl_keep isl_ast_build *build)
125 {
126         if (!graft || !build)
127                 return isl_ast_graft_free(graft);
128         if (!build->at_each_domain)
129                 return graft;
130
131         build = isl_ast_build_copy(build);
132         build = isl_ast_build_set_executed(build,
133                         isl_union_map_from_map(isl_map_copy(executed)));
134         if (!build)
135                 return isl_ast_graft_free(graft);
136
137         graft->node = build->at_each_domain(graft->node,
138                                         build, build->at_each_domain_user);
139         isl_ast_build_free(build);
140
141         if (!graft->node)
142                 graft = isl_ast_graft_free(graft);
143
144         return graft;
145 }
146
147 /* Generate an AST for a single domain based on
148  * the inverse schedule "executed".
149  *
150  * If there is more than one domain element associated to the current
151  * schedule "time", then we need to continue the generation process
152  * in generate_non_single_valued.
153  * Note that the inverse schedule being single-valued may depend
154  * on constraints that are only available in the original context
155  * domain specified by the user.  We therefore first introduce
156  * the constraints from data->build->domain.
157  * On the other hand, we only perform the test after having taken the gist
158  * of the domain as the resulting map is the one from which the call
159  * expression is constructed.  Using this map to construct the call
160  * expression usually yields simpler results.
161  * Because we perform the single-valuedness test on the gisted map,
162  * we may in rare cases fail to recognize that the inverse schedule
163  * is single-valued.  This becomes problematic if this happens
164  * from the recursive call through generate_non_single_valued
165  * as we would then end up in an infinite recursion.
166  * We therefore check if we are inside a call to generate_non_single_valued
167  * and revert to the ungisted map if the gisted map turns out not to be
168  * single-valued.
169  *
170  * Otherwise, we generate a call expression for the single executed
171  * domain element and put a guard around it based on the (simplified)
172  * domain of "executed".
173  *
174  * If the user has set an at_each_domain callback, it is called
175  * on the constructed call expression node.
176  */
177 static int generate_domain(__isl_take isl_map *executed, void *user)
178 {
179         struct isl_generate_domain_data *data = user;
180         isl_ast_graft *graft;
181         isl_ast_graft_list *list;
182         isl_set *guard;
183         isl_map *map;
184         int sv;
185
186         executed = isl_map_intersect_domain(executed,
187                                             isl_set_copy(data->build->domain));
188
189         executed = isl_map_coalesce(executed);
190         map = isl_map_copy(executed);
191         map = isl_ast_build_compute_gist_map_domain(data->build, map);
192         sv = isl_map_is_single_valued(map);
193         if (sv < 0)
194                 goto error;
195         if (!sv) {
196                 isl_map_free(map);
197                 if (data->build->single_valued)
198                         map = isl_map_copy(executed);
199                 else
200                         return generate_non_single_valued(executed, data);
201         }
202         guard = isl_map_domain(isl_map_copy(map));
203         guard = isl_set_coalesce(guard);
204         guard = isl_ast_build_compute_gist(data->build, guard);
205         graft = isl_ast_graft_alloc_domain(map, data->build);
206         graft = at_each_domain(graft, executed, data->build);
207
208         isl_map_free(executed);
209         graft = isl_ast_graft_add_guard(graft, guard, data->build);
210
211         list = isl_ast_graft_list_from_ast_graft(graft);
212         data->list = isl_ast_graft_list_concat(data->list, list);
213
214         return 0;
215 error:
216         isl_map_free(map);
217         isl_map_free(executed);
218         return -1;
219 }
220
221 /* Call build->create_leaf to a create "leaf" node in the AST,
222  * encapsulate the result in an isl_ast_graft and return the result
223  * as a 1-element list.
224  *
225  * Note that the node returned by the user may be an entire tree.
226  *
227  * Before we pass control to the user, we first clear some information
228  * from the build that is (presumbably) only meaningful
229  * for the current code generation.
230  * This includes the create_leaf callback itself, so we make a copy
231  * of the build first.
232  */
233 static __isl_give isl_ast_graft_list *call_create_leaf(
234         __isl_take isl_union_map *executed, __isl_take isl_ast_build *build)
235 {
236         isl_ast_node *node;
237         isl_ast_graft *graft;
238         isl_ast_build *user_build;
239
240         user_build = isl_ast_build_copy(build);
241         user_build = isl_ast_build_set_executed(user_build, executed);
242         user_build = isl_ast_build_clear_local_info(user_build);
243         if (!user_build)
244                 node = NULL;
245         else
246                 node = build->create_leaf(user_build, build->create_leaf_user);
247         graft = isl_ast_graft_alloc(node, build);
248         isl_ast_build_free(build);
249         return isl_ast_graft_list_from_ast_graft(graft);
250 }
251
252 /* Generate an AST after having handled the complete schedule
253  * of this call to the code generator.
254  *
255  * If the user has specified a create_leaf callback, control
256  * is passed to the user in call_create_leaf.
257  *
258  * Otherwise, we generate one or more calls for each individual
259  * domain in generate_domain.
260  */
261 static __isl_give isl_ast_graft_list *generate_inner_level(
262         __isl_take isl_union_map *executed, __isl_take isl_ast_build *build)
263 {
264         isl_ctx *ctx;
265         struct isl_generate_domain_data data = { build };
266
267         if (!build || !executed)
268                 goto error;
269
270         if (build->create_leaf)
271                 return call_create_leaf(executed, build);
272
273         ctx = isl_union_map_get_ctx(executed);
274         data.list = isl_ast_graft_list_alloc(ctx, 0);
275         if (isl_union_map_foreach_map(executed, &generate_domain, &data) < 0)
276                 data.list = isl_ast_graft_list_free(data.list);
277
278         if (0)
279 error:          data.list = NULL;
280         isl_ast_build_free(build);
281         isl_union_map_free(executed);
282         return data.list;
283 }
284
285 /* Call the before_each_for callback, if requested by the user.
286  */
287 static __isl_give isl_ast_node *before_each_for(__isl_take isl_ast_node *node,
288         __isl_keep isl_ast_build *build)
289 {
290         isl_id *id;
291
292         if (!node || !build)
293                 return isl_ast_node_free(node);
294         if (!build->before_each_for)
295                 return node;
296         id = build->before_each_for(build, build->before_each_for_user);
297         node = isl_ast_node_set_annotation(node, id);
298         return node;
299 }
300
301 /* Call the after_each_for callback, if requested by the user.
302  */
303 static __isl_give isl_ast_graft *after_each_for(__isl_keep isl_ast_graft *graft,
304         __isl_keep isl_ast_build *build)
305 {
306         if (!graft || !build)
307                 return isl_ast_graft_free(graft);
308         if (!build->after_each_for)
309                 return graft;
310         graft->node = build->after_each_for(graft->node, build,
311                                                 build->after_each_for_user);
312         if (!graft->node)
313                 return isl_ast_graft_free(graft);
314         return graft;
315 }
316
317 /* Plug in all the know values of the current and outer dimensions
318  * in the domain of "executed".  In principle, we only need to plug
319  * in the known value of the current dimension since the values of
320  * outer dimensions have been plugged in already.
321  * However, it turns out to be easier to just plug in all known values.
322  */
323 static __isl_give isl_union_map *plug_in_values(
324         __isl_take isl_union_map *executed, __isl_keep isl_ast_build *build)
325 {
326         return isl_ast_build_substitute_values_union_map_domain(build,
327                                                                     executed);
328 }
329
330 /* Check if the constraint "c" is a lower bound on dimension "pos",
331  * an upper bound, or independent of dimension "pos".
332  */
333 static int constraint_type(isl_constraint *c, int pos)
334 {
335         if (isl_constraint_is_lower_bound(c, isl_dim_set, pos))
336                 return 1;
337         if (isl_constraint_is_upper_bound(c, isl_dim_set, pos))
338                 return 2;
339         return 0;
340 }
341
342 /* Compare the types of the constraints "a" and "b",
343  * resulting in constraints that are independent of "depth"
344  * to be sorted before the lower bounds on "depth", which in
345  * turn are sorted before the upper bounds on "depth".
346  */
347 static int cmp_constraint(__isl_keep isl_constraint *a,
348         __isl_keep isl_constraint *b, void *user)
349 {
350         int *depth = user;
351         int t1 = constraint_type(a, *depth);
352         int t2 = constraint_type(b, *depth);
353
354         return t1 - t2;
355 }
356
357 /* Extract a lower bound on dimension "pos" from constraint "c".
358  *
359  * If the constraint is of the form
360  *
361  *      a x + f(...) >= 0
362  *
363  * then we essentially return
364  *
365  *      l = ceil(-f(...)/a)
366  *
367  * However, if the current dimension is strided, then we need to make
368  * sure that the lower bound we construct is of the form
369  *
370  *      f + s a
371  *
372  * with f the offset and s the stride.
373  * We therefore compute
374  *
375  *      f + s * ceil((l - f)/s)
376  */
377 static __isl_give isl_aff *lower_bound(__isl_keep isl_constraint *c,
378         int pos, __isl_keep isl_ast_build *build)
379 {
380         isl_aff *aff;
381
382         aff = isl_constraint_get_bound(c, isl_dim_set, pos);
383         aff = isl_aff_ceil(aff);
384
385         if (isl_ast_build_has_stride(build, pos)) {
386                 isl_aff *offset;
387                 isl_int stride;
388
389                 isl_int_init(stride);
390
391                 offset = isl_ast_build_get_offset(build, pos);
392                 isl_ast_build_get_stride(build, pos, &stride);
393
394                 aff = isl_aff_sub(aff, isl_aff_copy(offset));
395                 aff = isl_aff_scale_down(aff, stride);
396                 aff = isl_aff_ceil(aff);
397                 aff = isl_aff_scale(aff, stride);
398                 aff = isl_aff_add(aff, offset);
399
400                 isl_int_clear(stride);
401         }
402
403         aff = isl_ast_build_compute_gist_aff(build, aff);
404
405         return aff;
406 }
407
408 /* Return the exact lower bound (or upper bound if "upper" is set)
409  * of "domain" as a piecewise affine expression.
410  *
411  * If we are computing a lower bound (of a strided dimension), then
412  * we need to make sure it is of the form
413  *
414  *      f + s a
415  *
416  * where f is the offset and s is the stride.
417  * We therefore need to include the stride constraint before computing
418  * the minimum.
419  */
420 static __isl_give isl_pw_aff *exact_bound(__isl_keep isl_set *domain,
421         __isl_keep isl_ast_build *build, int upper)
422 {
423         isl_set *stride;
424         isl_map *it_map;
425         isl_pw_aff *pa;
426         isl_pw_multi_aff *pma;
427
428         domain = isl_set_copy(domain);
429         if (!upper) {
430                 stride = isl_ast_build_get_stride_constraint(build);
431                 domain = isl_set_intersect(domain, stride);
432         }
433         it_map = isl_ast_build_map_to_iterator(build, domain);
434         if (upper)
435                 pma = isl_map_lexmax_pw_multi_aff(it_map);
436         else
437                 pma = isl_map_lexmin_pw_multi_aff(it_map);
438         pa = isl_pw_multi_aff_get_pw_aff(pma, 0);
439         isl_pw_multi_aff_free(pma);
440         pa = isl_ast_build_compute_gist_pw_aff(build, pa);
441         pa = isl_pw_aff_coalesce(pa);
442
443         return pa;
444 }
445
446 /* Extract a lower bound on dimension "pos" from each constraint
447  * in "constraints" and return the list of lower bounds.
448  * If "constraints" has zero elements, then we extract a lower bound
449  * from "domain" instead.
450  */
451 static __isl_give isl_pw_aff_list *lower_bounds(
452         __isl_keep isl_constraint_list *constraints, int pos,
453         __isl_keep isl_set *domain, __isl_keep isl_ast_build *build)
454 {
455         isl_ctx *ctx;
456         isl_pw_aff_list *list;
457         int i, n;
458
459         if (!build)
460                 return NULL;
461
462         n = isl_constraint_list_n_constraint(constraints);
463         if (n == 0) {
464                 isl_pw_aff *pa;
465                 pa = exact_bound(domain, build, 0);
466                 return isl_pw_aff_list_from_pw_aff(pa);
467         }
468
469         ctx = isl_ast_build_get_ctx(build);
470         list = isl_pw_aff_list_alloc(ctx,n);
471
472         for (i = 0; i < n; ++i) {
473                 isl_aff *aff;
474                 isl_constraint *c;
475
476                 c = isl_constraint_list_get_constraint(constraints, i);
477                 aff = lower_bound(c, pos, build);
478                 isl_constraint_free(c);
479                 list = isl_pw_aff_list_add(list, isl_pw_aff_from_aff(aff));
480         }
481
482         return list;
483 }
484
485 /* Extract an upper bound on dimension "pos" from each constraint
486  * in "constraints" and return the list of upper bounds.
487  * If "constraints" has zero elements, then we extract an upper bound
488  * from "domain" instead.
489  */
490 static __isl_give isl_pw_aff_list *upper_bounds(
491         __isl_keep isl_constraint_list *constraints, int pos,
492         __isl_keep isl_set *domain, __isl_keep isl_ast_build *build)
493 {
494         isl_ctx *ctx;
495         isl_pw_aff_list *list;
496         int i, n;
497
498         n = isl_constraint_list_n_constraint(constraints);
499         if (n == 0) {
500                 isl_pw_aff *pa;
501                 pa = exact_bound(domain, build, 1);
502                 return isl_pw_aff_list_from_pw_aff(pa);
503         }
504
505         ctx = isl_ast_build_get_ctx(build);
506         list = isl_pw_aff_list_alloc(ctx,n);
507
508         for (i = 0; i < n; ++i) {
509                 isl_aff *aff;
510                 isl_constraint *c;
511
512                 c = isl_constraint_list_get_constraint(constraints, i);
513                 aff = isl_constraint_get_bound(c, isl_dim_set, pos);
514                 isl_constraint_free(c);
515                 aff = isl_aff_floor(aff);
516                 list = isl_pw_aff_list_add(list, isl_pw_aff_from_aff(aff));
517         }
518
519         return list;
520 }
521
522 /* Return an isl_ast_expr that performs the reduction of type "type"
523  * on AST expressions corresponding to the elements in "list".
524  *
525  * The list is assumed to contain at least one element.
526  * If the list contains exactly one element, then the returned isl_ast_expr
527  * simply computes that affine expression.
528  */
529 static __isl_give isl_ast_expr *reduce_list(enum isl_ast_op_type type,
530         __isl_keep isl_pw_aff_list *list, __isl_keep isl_ast_build *build)
531 {
532         int i, n;
533         isl_ctx *ctx;
534         isl_ast_expr *expr;
535
536         if (!list)
537                 return NULL;
538
539         n = isl_pw_aff_list_n_pw_aff(list);
540
541         if (n == 1)
542                 return isl_ast_build_expr_from_pw_aff_internal(build,
543                                 isl_pw_aff_list_get_pw_aff(list, 0));
544
545         ctx = isl_pw_aff_list_get_ctx(list);
546         expr = isl_ast_expr_alloc_op(ctx, type, n);
547         if (!expr)
548                 return NULL;
549
550         for (i = 0; i < n; ++i) {
551                 isl_ast_expr *expr_i;
552
553                 expr_i = isl_ast_build_expr_from_pw_aff_internal(build,
554                                 isl_pw_aff_list_get_pw_aff(list, i));
555                 if (!expr_i)
556                         return isl_ast_expr_free(expr);
557                 expr->u.op.args[i] = expr_i;
558         }
559
560         return expr;
561 }
562
563 /* Add a guard to "graft" based on "bound" in the case of a degenerate
564  * level (including the special case of an eliminated level).
565  *
566  * We eliminate the current dimension, simplify the result in the current
567  * build and add the result as guards to the graft.
568  *
569  * Note that we cannot simply drop the constraints on the current dimension
570  * even in the eliminated case, because the single affine expression may
571  * not be explicitly available in "bounds".  Moreover, the single affine
572  * expression may only be defined on a subset of the build domain,
573  * so we do in some cases need to insert a guard even in the eliminated case.
574  */
575 static __isl_give isl_ast_graft *add_degenerate_guard(
576         __isl_take isl_ast_graft *graft, __isl_keep isl_basic_set *bounds,
577         __isl_keep isl_ast_build *build)
578 {
579         int depth;
580         isl_set *dom;
581
582         depth = isl_ast_build_get_depth(build);
583
584         dom = isl_set_from_basic_set(isl_basic_set_copy(bounds));
585         if (isl_ast_build_has_stride(build, depth)) {
586                 isl_set *stride;
587
588                 stride = isl_ast_build_get_stride_constraint(build);
589                 dom = isl_set_intersect(dom, stride);
590         }
591         dom = isl_set_eliminate(dom, isl_dim_set, depth, 1);
592         dom = isl_ast_build_compute_gist(build, dom);
593
594         graft = isl_ast_graft_add_guard(graft, dom, build);
595
596         return graft;
597 }
598
599 /* Update "graft" based on "bounds" for the eliminated case.
600  *
601  * In the eliminated case, no for node is created, so we only need
602  * to check if "bounds" imply any guards that need to be inserted.
603  */
604 static __isl_give isl_ast_graft *refine_eliminated(
605         __isl_take isl_ast_graft *graft, __isl_keep isl_basic_set *bounds,
606         __isl_keep isl_ast_build *build)
607 {
608         return add_degenerate_guard(graft, bounds, build);
609 }
610
611 /* Update "graft" based on "bounds" and "sub_build" for the degenerate case.
612  *
613  * "build" is the build in which graft->node was created
614  * "sub_build" contains information about the current level itself,
615  * including the single value attained.
616  *
617  * We first set the initialization part of the for loop to the single
618  * value attained by the current dimension.
619  * The increment and condition are not strictly needed as the are known
620  * to be "1" and "iterator <= value" respectively.
621  * Then we set the size of the iterator and
622  * check if "bounds" imply any guards that need to be inserted.
623  */
624 static __isl_give isl_ast_graft *refine_degenerate(
625         __isl_take isl_ast_graft *graft, __isl_keep isl_basic_set *bounds,
626         __isl_keep isl_ast_build *build,
627         __isl_keep isl_ast_build *sub_build)
628 {
629         isl_pw_aff *value;
630
631         if (!graft || !sub_build)
632                 return isl_ast_graft_free(graft);
633
634         value = isl_pw_aff_copy(sub_build->value);
635
636         graft->node->u.f.init = isl_ast_build_expr_from_pw_aff_internal(build,
637                                                 value);
638         if (!graft->node->u.f.init)
639                 return isl_ast_graft_free(graft);
640
641         graft = add_degenerate_guard(graft, bounds, build);
642
643         return graft;
644 }
645
646 /* Return the intersection of constraints in "list" as a set.
647  */
648 static __isl_give isl_set *intersect_constraints(
649         __isl_keep isl_constraint_list *list)
650 {
651         int i, n;
652         isl_basic_set *bset;
653
654         n = isl_constraint_list_n_constraint(list);
655         if (n < 1)
656                 isl_die(isl_constraint_list_get_ctx(list), isl_error_internal,
657                         "expecting at least one constraint", return NULL);
658
659         bset = isl_basic_set_from_constraint(
660                                 isl_constraint_list_get_constraint(list, 0));
661         for (i = 1; i < n; ++i) {
662                 isl_basic_set *bset_i;
663
664                 bset_i = isl_basic_set_from_constraint(
665                                 isl_constraint_list_get_constraint(list, i));
666                 bset = isl_basic_set_intersect(bset, bset_i);
667         }
668
669         return isl_set_from_basic_set(bset);
670 }
671
672 /* Compute the constraints on the outer dimensions enforced by
673  * graft->node and add those constraints to graft->enforced,
674  * in case the upper bound is expressed as a set "upper".
675  *
676  * In particular, if l(...) is a lower bound in "lower", and
677  *
678  *      -a i + f(...) >= 0              or      a i <= f(...)
679  *
680  * is an upper bound ocnstraint on the current dimension i,
681  * then the for loop enforces the constraint
682  *
683  *      -a l(...) + f(...) >= 0         or      a l(...) <= f(...)
684  *
685  * We therefore simply take each lower bound in turn, plug it into
686  * the upper bounds and compute the intersection over all lower bounds.
687  *
688  * If a lower bound is a rational expression, then
689  * isl_basic_set_preimage_multi_aff will force this rational
690  * expression to have only integer values.  However, the loop
691  * itself does not enforce this integrality constraint.  We therefore
692  * use the ceil of the lower bounds instead of the lower bounds themselves.
693  * Other constraints will make sure that the for loop is only executed
694  * when each of the lower bounds attains an integral value.
695  * In particular, potentially rational values only occur in
696  * lower_bound if the offset is a (seemingly) rational expression,
697  * but then outer conditions will make sure that this rational expression
698  * only attains integer values.
699  */
700 static __isl_give isl_ast_graft *set_enforced_from_set(
701         __isl_take isl_ast_graft *graft,
702         __isl_keep isl_pw_aff_list *lower, int pos, __isl_keep isl_set *upper)
703 {
704         isl_space *space;
705         isl_basic_set *enforced;
706         isl_pw_multi_aff *pma;
707         int i, n;
708
709         if (!graft || !lower)
710                 return isl_ast_graft_free(graft);
711
712         space = isl_set_get_space(upper);
713         enforced = isl_basic_set_universe(isl_space_copy(space));
714
715         space = isl_space_map_from_set(space);
716         pma = isl_pw_multi_aff_identity(space);
717
718         n = isl_pw_aff_list_n_pw_aff(lower);
719         for (i = 0; i < n; ++i) {
720                 isl_pw_aff *pa;
721                 isl_set *enforced_i;
722                 isl_basic_set *hull;
723                 isl_pw_multi_aff *pma_i;
724
725                 pa = isl_pw_aff_list_get_pw_aff(lower, i);
726                 pa = isl_pw_aff_ceil(pa);
727                 pma_i = isl_pw_multi_aff_copy(pma);
728                 pma_i = isl_pw_multi_aff_set_pw_aff(pma_i, pos, pa);
729                 enforced_i = isl_set_copy(upper);
730                 enforced_i = isl_set_preimage_pw_multi_aff(enforced_i, pma_i);
731                 hull = isl_set_simple_hull(enforced_i);
732                 enforced = isl_basic_set_intersect(enforced, hull);
733         }
734
735         isl_pw_multi_aff_free(pma);
736
737         graft = isl_ast_graft_enforce(graft, enforced);
738
739         return graft;
740 }
741
742 /* Compute the constraints on the outer dimensions enforced by
743  * graft->node and add those constraints to graft->enforced,
744  * in case the upper bound is expressed as
745  * a list of affine expressions "upper".
746  *
747  * The enforced condition is that each lower bound expression is less
748  * than or equal to each upper bound expression.
749  */
750 static __isl_give isl_ast_graft *set_enforced_from_list(
751         __isl_take isl_ast_graft *graft,
752         __isl_keep isl_pw_aff_list *lower, __isl_keep isl_pw_aff_list *upper)
753 {
754         isl_set *cond;
755         isl_basic_set *enforced;
756
757         lower = isl_pw_aff_list_copy(lower);
758         upper = isl_pw_aff_list_copy(upper);
759         cond = isl_pw_aff_list_le_set(lower, upper);
760         enforced = isl_set_simple_hull(cond);
761         graft = isl_ast_graft_enforce(graft, enforced);
762
763         return graft;
764 }
765
766 /* Does "aff" have a negative constant term?
767  */
768 static int aff_constant_is_negative(__isl_take isl_set *set,
769         __isl_take isl_aff *aff, void *user)
770 {
771         int *neg = user;
772         isl_int v;
773
774         isl_int_init(v);
775         isl_aff_get_constant(aff, &v);
776         *neg = isl_int_is_neg(v);
777         isl_int_clear(v);
778         isl_set_free(set);
779         isl_aff_free(aff);
780
781         return *neg ? 0 : -1;
782 }
783
784 /* Does "pa" have a negative constant term over its entire domain?
785  */
786 static int pw_aff_constant_is_negative(__isl_take isl_pw_aff *pa, void *user)
787 {
788         int r;
789         int *neg = user;
790
791         r = isl_pw_aff_foreach_piece(pa, &aff_constant_is_negative, user);
792         isl_pw_aff_free(pa);
793
794         return *neg ? 0 : -1;
795 }
796
797 /* Does each element in "list" have a negative constant term?
798  *
799  * The callback terminates the iteration as soon an element has been
800  * found that does not have a negative constant term.
801  */
802 static int list_constant_is_negative(__isl_keep isl_pw_aff_list *list)
803 {
804         int neg = 1;
805
806         if (isl_pw_aff_list_foreach(list,
807                                 &pw_aff_constant_is_negative, &neg) < 0 && neg)
808                 return -1;
809
810         return neg;
811 }
812
813 /* Add 1 to each of the elements in "list", where each of these elements
814  * is defined over the internal schedule space of "build".
815  */
816 static __isl_give isl_pw_aff_list *list_add_one(
817         __isl_take isl_pw_aff_list *list, __isl_keep isl_ast_build *build)
818 {
819         int i, n;
820         isl_space *space;
821         isl_aff *aff;
822         isl_pw_aff *one;
823
824         space = isl_ast_build_get_space(build, 1);
825         aff = isl_aff_zero_on_domain(isl_local_space_from_space(space));
826         aff = isl_aff_add_constant_si(aff, 1);
827         one = isl_pw_aff_from_aff(aff);
828
829         n = isl_pw_aff_list_n_pw_aff(list);
830         for (i = 0; i < n; ++i) {
831                 isl_pw_aff *pa;
832                 pa = isl_pw_aff_list_get_pw_aff(list, i);
833                 pa = isl_pw_aff_add(pa, isl_pw_aff_copy(one));
834                 list = isl_pw_aff_list_set_pw_aff(list, i, pa);
835         }
836
837         isl_pw_aff_free(one);
838
839         return list;
840 }
841
842 /* Set the condition part of the for node graft->node in case
843  * the upper bound is represented as a list of piecewise affine expressions.
844  *
845  * In particular, set the condition to
846  *
847  *      iterator <= min(list of upper bounds)
848  *
849  * If each of the upper bounds has a negative constant term, then
850  * set the condition to
851  *
852  *      iterator < min(list of (upper bound + 1)s)
853  *
854  */
855 static __isl_give isl_ast_graft *set_for_cond_from_list(
856         __isl_take isl_ast_graft *graft, __isl_keep isl_pw_aff_list *list,
857         __isl_keep isl_ast_build *build)
858 {
859         int neg;
860         isl_ast_expr *bound, *iterator, *cond;
861         enum isl_ast_op_type type = isl_ast_op_le;
862
863         if (!graft || !list)
864                 return isl_ast_graft_free(graft);
865
866         neg = list_constant_is_negative(list);
867         if (neg < 0)
868                 return isl_ast_graft_free(graft);
869         list = isl_pw_aff_list_copy(list);
870         if (neg) {
871                 list = list_add_one(list, build);
872                 type = isl_ast_op_lt;
873         }
874
875         bound = reduce_list(isl_ast_op_min, list, build);
876         iterator = isl_ast_expr_copy(graft->node->u.f.iterator);
877         cond = isl_ast_expr_alloc_binary(type, iterator, bound);
878         graft->node->u.f.cond = cond;
879
880         isl_pw_aff_list_free(list);
881         if (!graft->node->u.f.cond)
882                 return isl_ast_graft_free(graft);
883         return graft;
884 }
885
886 /* Set the condition part of the for node graft->node in case
887  * the upper bound is represented as a set.
888  */
889 static __isl_give isl_ast_graft *set_for_cond_from_set(
890         __isl_take isl_ast_graft *graft, __isl_keep isl_set *set,
891         __isl_keep isl_ast_build *build)
892 {
893         isl_ast_expr *cond;
894
895         if (!graft)
896                 return NULL;
897
898         cond = isl_ast_build_expr_from_set(build, isl_set_copy(set));
899         graft->node->u.f.cond = cond;
900         if (!graft->node->u.f.cond)
901                 return isl_ast_graft_free(graft);
902         return graft;
903 }
904
905 /* Construct an isl_ast_expr for the increment (i.e., stride) of
906  * the current dimension.
907  */
908 static __isl_give isl_ast_expr *for_inc(__isl_keep isl_ast_build *build)
909 {
910         int depth;
911         isl_int v;
912         isl_ctx *ctx;
913         isl_ast_expr *inc;
914
915         if (!build)
916                 return NULL;
917         ctx = isl_ast_build_get_ctx(build);
918         depth = isl_ast_build_get_depth(build);
919
920         if (!isl_ast_build_has_stride(build, depth))
921                 return isl_ast_expr_alloc_int_si(ctx, 1);
922
923         isl_int_init(v);
924         isl_ast_build_get_stride(build, depth, &v);
925         inc = isl_ast_expr_alloc_int(ctx, v);
926         isl_int_clear(v);
927
928         return inc;
929 }
930
931 /* Should we express the loop condition as
932  *
933  *      iterator <= min(list of upper bounds)
934  *
935  * or as a conjunction of constraints?
936  *
937  * The first is constructed from a list of upper bounds.
938  * The second is constructed from a set.
939  *
940  * If there are no upper bounds in "constraints", then this could mean
941  * that "domain" simply doesn't have an upper bound or that we didn't
942  * pick any upper bound.  In the first case, we want to generate the
943  * loop condition as a(n empty) conjunction of constraints
944  * In the second case, we will compute
945  * a single upper bound from "domain" and so we use the list form.
946  *
947  * If there are upper bounds in "constraints",
948  * then we use the list form iff the atomic_upper_bound option is set.
949  */
950 static int use_upper_bound_list(isl_ctx *ctx, int n_upper,
951         __isl_keep isl_set *domain, int depth)
952 {
953         if (n_upper > 0)
954                 return isl_options_get_ast_build_atomic_upper_bound(ctx);
955         else
956                 return isl_set_dim_has_upper_bound(domain, isl_dim_set, depth);
957 }
958
959 /* Fill in the expressions of the for node in graft->node.
960  *
961  * In particular,
962  * - set the initialization part of the loop to the maximum of the lower bounds
963  * - set the size of the iterator based on the values attained by the iterator
964  * - extract the increment from the stride of the current dimension
965  * - construct the for condition either based on a list of upper bounds
966  *      or on a set of upper bound constraints.
967  */
968 static __isl_give isl_ast_graft *set_for_node_expressions(
969         __isl_take isl_ast_graft *graft, __isl_keep isl_pw_aff_list *lower,
970         int use_list, __isl_keep isl_pw_aff_list *upper_list,
971         __isl_keep isl_set *upper_set, __isl_keep isl_ast_build *build)
972 {
973         isl_ast_node *node;
974
975         if (!graft)
976                 return NULL;
977
978         build = isl_ast_build_copy(build);
979         build = isl_ast_build_set_enforced(build,
980                                         isl_ast_graft_get_enforced(graft));
981
982         node = graft->node;
983         node->u.f.init = reduce_list(isl_ast_op_max, lower, build);
984         node->u.f.inc = for_inc(build);
985
986         if (use_list)
987                 graft = set_for_cond_from_list(graft, upper_list, build);
988         else
989                 graft = set_for_cond_from_set(graft, upper_set, build);
990
991         isl_ast_build_free(build);
992
993         if (!node->u.f.iterator || !node->u.f.init ||
994             !node->u.f.cond || !node->u.f.inc)
995                 return isl_ast_graft_free(graft);
996
997         return graft;
998 }
999
1000 /* Update "graft" based on "bounds" and "domain" for the generic,
1001  * non-degenerate, case.
1002  *
1003  * "c_lower" and "c_upper" contain the lower and upper bounds
1004  * that the loop node should express.
1005  * "domain" is the subset of the intersection of the constraints
1006  * for which some code is executed.
1007  *
1008  * There may be zero lower bounds or zero upper bounds in "constraints"
1009  * in case the list of constraints was created
1010  * based on the atomic option or based on separation with explicit bounds.
1011  * In that case, we use "domain" to derive lower and/or upper bounds.
1012  *
1013  * We first compute a list of one or more lower bounds.
1014  *
1015  * Then we decide if we want to express the condition as
1016  *
1017  *      iterator <= min(list of upper bounds)
1018  *
1019  * or as a conjunction of constraints.
1020  *
1021  * The set of enforced constraints is then computed either based on
1022  * a list of upper bounds or on a set of upper bound constraints.
1023  * We do not compute any enforced constraints if we were forced
1024  * to compute a lower or upper bound using exact_bound.  The domains
1025  * of the resulting expressions may imply some bounds on outer dimensions
1026  * that we do not want to appear in the enforced constraints since
1027  * they are not actually enforced by the corresponding code.
1028  *
1029  * Finally, we fill in the expressions of the for node.
1030  */
1031 static __isl_give isl_ast_graft *refine_generic_bounds(
1032         __isl_take isl_ast_graft *graft,
1033         __isl_take isl_constraint_list *c_lower,
1034         __isl_take isl_constraint_list *c_upper,
1035         __isl_keep isl_set *domain, __isl_keep isl_ast_build *build)
1036 {
1037         int depth;
1038         isl_ctx *ctx;
1039         isl_pw_aff_list *lower;
1040         int use_list;
1041         isl_set *upper_set = NULL;
1042         isl_pw_aff_list *upper_list = NULL;
1043         int n_lower, n_upper;
1044
1045         if (!graft || !c_lower || !c_upper || !build)
1046                 goto error;
1047
1048         depth = isl_ast_build_get_depth(build);
1049         ctx = isl_ast_graft_get_ctx(graft);
1050
1051         n_lower = isl_constraint_list_n_constraint(c_lower);
1052         n_upper = isl_constraint_list_n_constraint(c_upper);
1053
1054         use_list = use_upper_bound_list(ctx, n_upper, domain, depth);
1055
1056         lower = lower_bounds(c_lower, depth, domain, build);
1057
1058         if (use_list)
1059                 upper_list = upper_bounds(c_upper, depth, domain, build);
1060         else if (n_upper > 0)
1061                 upper_set = intersect_constraints(c_upper);
1062         else
1063                 upper_set = isl_set_universe(isl_set_get_space(domain));
1064
1065         if (n_lower == 0 || n_upper == 0)
1066                 ;
1067         else if (use_list)
1068                 graft = set_enforced_from_list(graft, lower, upper_list);
1069         else
1070                 graft = set_enforced_from_set(graft, lower, depth, upper_set);
1071
1072         graft = set_for_node_expressions(graft, lower, use_list, upper_list,
1073                                         upper_set, build);
1074
1075         isl_pw_aff_list_free(lower);
1076         isl_pw_aff_list_free(upper_list);
1077         isl_set_free(upper_set);
1078         isl_constraint_list_free(c_lower);
1079         isl_constraint_list_free(c_upper);
1080
1081         return graft;
1082 error:
1083         isl_constraint_list_free(c_lower);
1084         isl_constraint_list_free(c_upper);
1085         return isl_ast_graft_free(graft);
1086 }
1087
1088 /* Internal data structure used inside count_constraints to keep
1089  * track of the number of constraints that are independent of dimension "pos",
1090  * the lower bounds in "pos" and the upper bounds in "pos".
1091  */
1092 struct isl_ast_count_constraints_data {
1093         int pos;
1094
1095         int n_indep;
1096         int n_lower;
1097         int n_upper;
1098 };
1099
1100 /* Increment data->n_indep, data->lower or data->upper depending
1101  * on whether "c" is independenct of dimensions data->pos,
1102  * a lower bound or an upper bound.
1103  */
1104 static int count_constraints(__isl_take isl_constraint *c, void *user)
1105 {
1106         struct isl_ast_count_constraints_data *data = user;
1107
1108         if (isl_constraint_is_lower_bound(c, isl_dim_set, data->pos))
1109                 data->n_lower++;
1110         else if (isl_constraint_is_upper_bound(c, isl_dim_set, data->pos))
1111                 data->n_upper++;
1112         else
1113                 data->n_indep++;
1114
1115         isl_constraint_free(c);
1116
1117         return 0;
1118 }
1119
1120 /* Update "graft" based on "bounds" and "domain" for the generic,
1121  * non-degenerate, case.
1122  *
1123  * "list" respresent the list of bounds that need to be encoded by
1124  * the for loop (or a guard around the for loop).
1125  * "domain" is the subset of the intersection of the constraints
1126  * for which some code is executed.
1127  * "build" is the build in which graft->node was created.
1128  *
1129  * We separate lower bounds, upper bounds and constraints that
1130  * are independent of the loop iterator.
1131  *
1132  * The actual for loop bounds are generated in refine_generic_bounds.
1133  * If there are any constraints that are independent of the loop iterator,
1134  * we need to put a guard around the for loop (which may get hoisted up
1135  * to higher levels) and we call refine_generic_bounds in a build
1136  * where this guard is enforced.
1137  */
1138 static __isl_give isl_ast_graft *refine_generic_split(
1139         __isl_take isl_ast_graft *graft, __isl_take isl_constraint_list *list,
1140         __isl_keep isl_set *domain, __isl_keep isl_ast_build *build)
1141 {
1142         isl_ast_build *for_build;
1143         isl_set *guard;
1144         struct isl_ast_count_constraints_data data;
1145         isl_constraint_list *lower;
1146         isl_constraint_list *upper;
1147
1148         if (!list)
1149                 return isl_ast_graft_free(graft);
1150
1151         data.pos = isl_ast_build_get_depth(build);
1152
1153         list = isl_constraint_list_sort(list, &cmp_constraint, &data.pos);
1154         if (!list)
1155                 return isl_ast_graft_free(graft);
1156
1157         data.n_indep = data.n_lower = data.n_upper = 0;
1158         if (isl_constraint_list_foreach(list, &count_constraints, &data) < 0) {
1159                 isl_constraint_list_free(list);
1160                 return isl_ast_graft_free(graft);
1161         }
1162
1163         lower = isl_constraint_list_copy(list);
1164         lower = isl_constraint_list_drop(lower, 0, data.n_indep);
1165         upper = isl_constraint_list_copy(lower);
1166         lower = isl_constraint_list_drop(lower, data.n_lower, data.n_upper);
1167         upper = isl_constraint_list_drop(upper, 0, data.n_lower);
1168
1169         if (data.n_indep == 0) {
1170                 isl_constraint_list_free(list);
1171                 return refine_generic_bounds(graft, lower, upper,
1172                                                 domain, build);
1173         }
1174
1175         list = isl_constraint_list_drop(list, data.n_indep,
1176                                         data.n_lower + data.n_upper);
1177         guard = intersect_constraints(list);
1178         isl_constraint_list_free(list);
1179
1180         for_build = isl_ast_build_copy(build);
1181         for_build = isl_ast_build_restrict_pending(for_build,
1182                                                 isl_set_copy(guard));
1183         graft = refine_generic_bounds(graft, lower, upper, domain, for_build);
1184         isl_ast_build_free(for_build);
1185
1186         graft = isl_ast_graft_add_guard(graft, guard, build);
1187
1188         return graft;
1189 }
1190
1191 /* Add the guard implied by the current stride constraint (if any),
1192  * but not (necessarily) enforced by the generated AST to "graft".
1193  */
1194 static __isl_give isl_ast_graft *add_stride_guard(
1195         __isl_take isl_ast_graft *graft, __isl_keep isl_ast_build *build)
1196 {
1197         int depth;
1198         isl_set *dom;
1199
1200         depth = isl_ast_build_get_depth(build);
1201         if (!isl_ast_build_has_stride(build, depth))
1202                 return graft;
1203
1204         dom = isl_ast_build_get_stride_constraint(build);
1205         dom = isl_set_eliminate(dom, isl_dim_set, depth, 1);
1206         dom = isl_ast_build_compute_gist(build, dom);
1207
1208         graft = isl_ast_graft_add_guard(graft, dom, build);
1209
1210         return graft;
1211 }
1212
1213 /* Update "graft" based on "bounds" and "domain" for the generic,
1214  * non-degenerate, case.
1215  *
1216  * "bounds" respresent the bounds that need to be encoded by
1217  * the for loop (or a guard around the for loop).
1218  * "domain" is the subset of "bounds" for which some code is executed.
1219  * "build" is the build in which graft->node was created.
1220  *
1221  * We break up "bounds" into a list of constraints and continue with
1222  * refine_generic_split.
1223  */
1224 static __isl_give isl_ast_graft *refine_generic(
1225         __isl_take isl_ast_graft *graft,
1226         __isl_keep isl_basic_set *bounds, __isl_keep isl_set *domain,
1227         __isl_keep isl_ast_build *build)
1228 {
1229         isl_constraint_list *list;
1230
1231         if (!build || !graft)
1232                 return isl_ast_graft_free(graft);
1233
1234         bounds = isl_basic_set_copy(bounds);
1235         bounds = isl_ast_build_compute_gist_basic_set(build, bounds);
1236         list = isl_constraint_list_from_basic_set(bounds);
1237
1238         graft = refine_generic_split(graft, list, domain, build);
1239         graft = add_stride_guard(graft, build);
1240
1241         return graft;
1242 }
1243
1244 /* Create a for node for the current level.
1245  *
1246  * Mark the for node degenerate if "degenerate" is set.
1247  */
1248 static __isl_give isl_ast_node *create_for(__isl_keep isl_ast_build *build,
1249         int degenerate)
1250 {
1251         int depth;
1252         isl_id *id;
1253         isl_ast_node *node;
1254
1255         if (!build)
1256                 return NULL;
1257
1258         depth = isl_ast_build_get_depth(build);
1259         id = isl_ast_build_get_iterator_id(build, depth);
1260         node = isl_ast_node_alloc_for(id);
1261         if (degenerate)
1262                 node = isl_ast_node_for_mark_degenerate(node);
1263
1264         return node;
1265 }
1266
1267 /* Create an AST node for the current dimension based on
1268  * the schedule domain "bounds" and return the node encapsulated
1269  * in an isl_ast_graft.
1270  *
1271  * "executed" is the current inverse schedule, taking into account
1272  * the bounds in "bounds"
1273  * "domain" is the domain of "executed", with inner dimensions projected out.
1274  * It may be a strict subset of "bounds" in case "bounds" was created
1275  * based on the atomic option or based on separation with explicit bounds.
1276  *
1277  * "domain" may satisfy additional equalities that result
1278  * from intersecting "executed" with "bounds" in add_node.
1279  * It may also satisfy some global constraints that were dropped out because
1280  * we performed separation with explicit bounds.
1281  * The very first step is then to copy these constraints to "bounds".
1282  *
1283  * Since we may be calling before_each_for and after_each_for
1284  * callbacks, we record the current inverse schedule in the build.
1285  *
1286  * We consider three builds,
1287  * "build" is the one in which the current level is created,
1288  * "body_build" is the build in which the next level is created,
1289  * "sub_build" is essentially the same as "body_build", except that
1290  * the depth has not been increased yet.
1291  *
1292  * "build" already contains information (in strides and offsets)
1293  * about the strides at the current level, but this information is not
1294  * reflected in the build->domain.
1295  * We first add this information and the "bounds" to the sub_build->domain.
1296  * isl_ast_build_set_loop_bounds checks whether the current dimension attains
1297  * only a single value and whether this single value can be represented using
1298  * a single affine expression.
1299  * In the first case, the current level is considered "degenerate".
1300  * In the second, sub-case, the current level is considered "eliminated".
1301  * Eliminated level don't need to be reflected in the AST since we can
1302  * simply plug in the affine expression.  For degenerate, but non-eliminated,
1303  * levels, we do introduce a for node, but mark is as degenerate so that
1304  * it can be printed as an assignment of the single value to the loop
1305  * "iterator".
1306  *
1307  * If the current level is eliminated, we explicitly plug in the value
1308  * for the current level found by isl_ast_build_set_loop_bounds in the
1309  * inverse schedule.  This ensures that if we are working on a slice
1310  * of the domain based on information available in the inverse schedule
1311  * and the build domain, that then this information is also reflected
1312  * in the inverse schedule.  This operation also eliminates the current
1313  * dimension from the inverse schedule making sure no inner dimensions depend
1314  * on the current dimension.  Otherwise, we create a for node, marking
1315  * it degenerate if appropriate.  The initial for node is still incomplete
1316  * and will be completed in either refine_degenerate or refine_generic.
1317  *
1318  * We then generate a sequence of grafts for the next level,
1319  * create a surrounding graft for the current level and insert
1320  * the for node we created (if the current level is not eliminated).
1321  *
1322  * Finally, we set the bounds of the for loop and insert guards
1323  * (either in the AST or in the graft) in one of
1324  * refine_eliminated, refine_degenerate or refine_generic.
1325  */
1326 static __isl_give isl_ast_graft *create_node_scaled(
1327         __isl_take isl_union_map *executed,
1328         __isl_take isl_basic_set *bounds, __isl_take isl_set *domain,
1329         __isl_take isl_ast_build *build)
1330 {
1331         int depth;
1332         int degenerate, eliminated;
1333         isl_basic_set *hull;
1334         isl_ast_node *node = NULL;
1335         isl_ast_graft *graft;
1336         isl_ast_graft_list *children;
1337         isl_ast_build *sub_build;
1338         isl_ast_build *body_build;
1339
1340         domain = isl_ast_build_eliminate_divs(build, domain);
1341         domain = isl_set_detect_equalities(domain);
1342         hull = isl_set_unshifted_simple_hull(isl_set_copy(domain));
1343         bounds = isl_basic_set_intersect(bounds, hull);
1344         build = isl_ast_build_set_executed(build, isl_union_map_copy(executed));
1345
1346         depth = isl_ast_build_get_depth(build);
1347         sub_build = isl_ast_build_copy(build);
1348         sub_build = isl_ast_build_include_stride(sub_build);
1349         sub_build = isl_ast_build_set_loop_bounds(sub_build,
1350                                                 isl_basic_set_copy(bounds));
1351         degenerate = isl_ast_build_has_value(sub_build);
1352         eliminated = isl_ast_build_has_affine_value(sub_build, depth);
1353         if (degenerate < 0 || eliminated < 0)
1354                 executed = isl_union_map_free(executed);
1355         if (eliminated)
1356                 executed = plug_in_values(executed, sub_build);
1357         else
1358                 node = create_for(build, degenerate);
1359
1360         body_build = isl_ast_build_copy(sub_build);
1361         body_build = isl_ast_build_increase_depth(body_build);
1362         if (!eliminated)
1363                 node = before_each_for(node, body_build);
1364         children = generate_next_level(executed,
1365                                     isl_ast_build_copy(body_build));
1366
1367         graft = isl_ast_graft_alloc_level(children, build, sub_build);
1368         if (!eliminated)
1369                 graft = isl_ast_graft_insert_for(graft, node);
1370         if (eliminated)
1371                 graft = refine_eliminated(graft, bounds, build);
1372         else if (degenerate)
1373                 graft = refine_degenerate(graft, bounds, build, sub_build);
1374         else
1375                 graft = refine_generic(graft, bounds, domain, build);
1376         if (!eliminated)
1377                 graft = after_each_for(graft, body_build);
1378
1379         isl_ast_build_free(body_build);
1380         isl_ast_build_free(sub_build);
1381         isl_ast_build_free(build);
1382         isl_basic_set_free(bounds);
1383         isl_set_free(domain);
1384
1385         return graft;
1386 }
1387
1388 /* Internal data structure for checking if all constraints involving
1389  * the input dimension "depth" are such that the other coefficients
1390  * are multiples of "m", reducing "m" if they are not.
1391  * If "m" is reduced all the way down to "1", then the check has failed
1392  * and we break out of the iteration.
1393  * "d" is an initialized isl_int that can be used internally.
1394  */
1395 struct isl_check_scaled_data {
1396         int depth;
1397         isl_int m, d;
1398 };
1399
1400 /* If constraint "c" involves the input dimension data->depth,
1401  * then make sure that all the other coefficients are multiples of data->m,
1402  * reducing data->m if needed.
1403  * Break out of the iteration if data->m has become equal to "1".
1404  */
1405 static int constraint_check_scaled(__isl_take isl_constraint *c, void *user)
1406 {
1407         struct isl_check_scaled_data *data = user;
1408         int i, j, n;
1409         enum isl_dim_type t[] = { isl_dim_param, isl_dim_in, isl_dim_out,
1410                                     isl_dim_div };
1411
1412         if (!isl_constraint_involves_dims(c, isl_dim_in, data->depth, 1)) {
1413                 isl_constraint_free(c);
1414                 return 0;
1415         }
1416
1417         for (i = 0; i < 4; ++i) {
1418                 n = isl_constraint_dim(c, t[i]);
1419                 for (j = 0; j < n; ++j) {
1420                         if (t[i] == isl_dim_in && j == data->depth)
1421                                 continue;
1422                         if (!isl_constraint_involves_dims(c, t[i], j, 1))
1423                                 continue;
1424                         isl_constraint_get_coefficient(c, t[i], j, &data->d);
1425                         isl_int_gcd(data->m, data->m, data->d);
1426                         if (isl_int_is_one(data->m))
1427                                 break;
1428                 }
1429                 if (j < n)
1430                         break;
1431         }
1432
1433         isl_constraint_free(c);
1434
1435         return i < 4 ? -1 : 0;
1436 }
1437
1438 /* For each constraint of "bmap" that involves the input dimension data->depth,
1439  * make sure that all the other coefficients are multiples of data->m,
1440  * reducing data->m if needed.
1441  * Break out of the iteration if data->m has become equal to "1".
1442  */
1443 static int basic_map_check_scaled(__isl_take isl_basic_map *bmap, void *user)
1444 {
1445         int r;
1446
1447         r = isl_basic_map_foreach_constraint(bmap,
1448                                                 &constraint_check_scaled, user);
1449         isl_basic_map_free(bmap);
1450
1451         return r;
1452 }
1453
1454 /* For each constraint of "map" that involves the input dimension data->depth,
1455  * make sure that all the other coefficients are multiples of data->m,
1456  * reducing data->m if needed.
1457  * Break out of the iteration if data->m has become equal to "1".
1458  */
1459 static int map_check_scaled(__isl_take isl_map *map, void *user)
1460 {
1461         int r;
1462
1463         r = isl_map_foreach_basic_map(map, &basic_map_check_scaled, user);
1464         isl_map_free(map);
1465
1466         return r;
1467 }
1468
1469 /* Create an AST node for the current dimension based on
1470  * the schedule domain "bounds" and return the node encapsulated
1471  * in an isl_ast_graft.
1472  *
1473  * "executed" is the current inverse schedule, taking into account
1474  * the bounds in "bounds"
1475  * "domain" is the domain of "executed", with inner dimensions projected out.
1476  *
1477  *
1478  * Before moving on to the actual AST node construction in create_node_scaled,
1479  * we first check if the current dimension is strided and if we can scale
1480  * down this stride.  Note that we only do this if the ast_build_scale_strides
1481  * option is set.
1482  *
1483  * In particular, let the current dimension take on values
1484  *
1485  *      f + s a
1486  *
1487  * with a an integer.  We check if we can find an integer m that (obviouly)
1488  * divides both f and s.
1489  *
1490  * If so, we check if the current dimension only appears in constraints
1491  * where the coefficients of the other variables are multiples of m.
1492  * We perform this extra check to avoid the risk of introducing
1493  * divisions by scaling down the current dimension.
1494  *
1495  * If so, we scale the current dimension down by a factor of m.
1496  * That is, we plug in
1497  *
1498  *      i = m i'                                                        (1)
1499  *
1500  * Note that in principle we could always scale down strided loops
1501  * by plugging in
1502  *
1503  *      i = f + s i'
1504  *
1505  * but this may result in i' taking on larger values than the original i,
1506  * due to the shift by "f".
1507  * By constrast, the scaling in (1) can only reduce the (absolute) value "i".
1508  */
1509 static __isl_give isl_ast_graft *create_node(__isl_take isl_union_map *executed,
1510         __isl_take isl_basic_set *bounds, __isl_take isl_set *domain,
1511         __isl_take isl_ast_build *build)
1512 {
1513         struct isl_check_scaled_data data;
1514         isl_ctx *ctx;
1515         isl_aff *offset;
1516
1517         ctx = isl_ast_build_get_ctx(build);
1518         if (!isl_options_get_ast_build_scale_strides(ctx))
1519                 return create_node_scaled(executed, bounds, domain, build);
1520
1521         data.depth = isl_ast_build_get_depth(build);
1522         if (!isl_ast_build_has_stride(build, data.depth))
1523                 return create_node_scaled(executed, bounds, domain, build);
1524
1525         isl_int_init(data.m);
1526         isl_int_init(data.d);
1527
1528         offset = isl_ast_build_get_offset(build, data.depth);
1529         if (isl_ast_build_get_stride(build, data.depth, &data.m) < 0)
1530                 offset = isl_aff_free(offset);
1531         offset = isl_aff_scale_down(offset, data.m);
1532         if (isl_aff_get_denominator(offset, &data.d) < 0)
1533                 executed = isl_union_map_free(executed);
1534
1535         if (executed && isl_int_is_divisible_by(data.m, data.d))
1536                 isl_int_divexact(data.m, data.m, data.d);
1537         else
1538                 isl_int_set_si(data.m, 1);
1539
1540         if (!isl_int_is_one(data.m)) {
1541                 if (isl_union_map_foreach_map(executed, &map_check_scaled,
1542                                                 &data) < 0 &&
1543                     !isl_int_is_one(data.m))
1544                         executed = isl_union_map_free(executed);
1545         }
1546
1547         if (!isl_int_is_one(data.m)) {
1548                 isl_space *space;
1549                 isl_multi_aff *ma;
1550                 isl_aff *aff;
1551                 isl_map *map;
1552                 isl_union_map *umap;
1553
1554                 space = isl_ast_build_get_space(build, 1);
1555                 space = isl_space_map_from_set(space);
1556                 ma = isl_multi_aff_identity(space);
1557                 aff = isl_multi_aff_get_aff(ma, data.depth);
1558                 aff = isl_aff_scale(aff, data.m);
1559                 ma = isl_multi_aff_set_aff(ma, data.depth, aff);
1560
1561                 bounds = isl_basic_set_preimage_multi_aff(bounds,
1562                                                 isl_multi_aff_copy(ma));
1563                 domain = isl_set_preimage_multi_aff(domain,
1564                                                 isl_multi_aff_copy(ma));
1565                 map = isl_map_reverse(isl_map_from_multi_aff(ma));
1566                 umap = isl_union_map_from_map(map);
1567                 executed = isl_union_map_apply_domain(executed,
1568                                                 isl_union_map_copy(umap));
1569                 build = isl_ast_build_scale_down(build, data.m, umap);
1570         }
1571         isl_aff_free(offset);
1572
1573         isl_int_clear(data.d);
1574         isl_int_clear(data.m);
1575
1576         return create_node_scaled(executed, bounds, domain, build);
1577 }
1578
1579 /* Add the basic set to the list that "user" points to.
1580  */
1581 static int collect_basic_set(__isl_take isl_basic_set *bset, void *user)
1582 {
1583         isl_basic_set_list **list = user;
1584
1585         *list = isl_basic_set_list_add(*list, bset);
1586
1587         return 0;
1588 }
1589
1590 /* Extract the basic sets of "set" and collect them in an isl_basic_set_list.
1591  */
1592 static __isl_give isl_basic_set_list *isl_basic_set_list_from_set(
1593         __isl_take isl_set *set)
1594 {
1595         int n;
1596         isl_ctx *ctx;
1597         isl_basic_set_list *list;
1598
1599         if (!set)
1600                 return NULL;
1601
1602         ctx = isl_set_get_ctx(set);
1603
1604         n = isl_set_n_basic_set(set);
1605         list = isl_basic_set_list_alloc(ctx, n);
1606         if (isl_set_foreach_basic_set(set, &collect_basic_set, &list) < 0)
1607                 list = isl_basic_set_list_free(list);
1608
1609         isl_set_free(set);
1610         return list;
1611 }
1612
1613 /* Generate code for the schedule domain "bounds"
1614  * and add the result to "list".
1615  *
1616  * We mainly detect strides and additional equalities here
1617  * and then pass over control to create_node.
1618  *
1619  * "bounds" reflects the bounds on the current dimension and possibly
1620  * some extra conditions on outer dimensions.
1621  * It does not, however, include any divs involving the current dimension,
1622  * so it does not capture any stride constraints.
1623  * We therefore need to compute that part of the schedule domain that
1624  * intersects with "bounds" and derive the strides from the result.
1625  */
1626 static __isl_give isl_ast_graft_list *add_node(
1627         __isl_take isl_ast_graft_list *list, __isl_take isl_union_map *executed,
1628         __isl_take isl_basic_set *bounds, __isl_take isl_ast_build *build)
1629 {
1630         isl_ast_graft *graft;
1631         isl_set *domain = NULL;
1632         isl_union_set *uset;
1633         int empty;
1634
1635         uset = isl_union_set_from_basic_set(isl_basic_set_copy(bounds));
1636         executed = isl_union_map_intersect_domain(executed, uset);
1637         empty = isl_union_map_is_empty(executed);
1638         if (empty < 0)
1639                 goto error;
1640         if (empty)
1641                 goto done;
1642
1643         uset = isl_union_map_domain(isl_union_map_copy(executed));
1644         domain = isl_set_from_union_set(uset);
1645         domain = isl_ast_build_compute_gist(build, domain);
1646         empty = isl_set_is_empty(domain);
1647         if (empty < 0)
1648                 goto error;
1649         if (empty)
1650                 goto done;
1651
1652         domain = isl_ast_build_eliminate_inner(build, domain);
1653         build = isl_ast_build_detect_strides(build, isl_set_copy(domain));
1654
1655         graft = create_node(executed, bounds, domain,
1656                                 isl_ast_build_copy(build));
1657         list = isl_ast_graft_list_add(list, graft);
1658         isl_ast_build_free(build);
1659         return list;
1660 error:
1661         list = isl_ast_graft_list_free(list);
1662 done:
1663         isl_set_free(domain);
1664         isl_basic_set_free(bounds);
1665         isl_union_map_free(executed);
1666         isl_ast_build_free(build);
1667         return list;
1668 }
1669
1670 /* Does any element of i follow or coincide with any element of j
1671  * at the current depth for equal values of the outer dimensions?
1672  */
1673 static int domain_follows_at_depth(__isl_keep isl_basic_set *i,
1674         __isl_keep isl_basic_set *j, void *user)
1675 {
1676         int depth = *(int *) user;
1677         isl_basic_map *test;
1678         int empty;
1679         int l;
1680
1681         test = isl_basic_map_from_domain_and_range(isl_basic_set_copy(i),
1682                                                     isl_basic_set_copy(j));
1683         for (l = 0; l < depth; ++l)
1684                 test = isl_basic_map_equate(test, isl_dim_in, l,
1685                                                 isl_dim_out, l);
1686         test = isl_basic_map_order_ge(test, isl_dim_in, depth,
1687                                         isl_dim_out, depth);
1688         empty = isl_basic_map_is_empty(test);
1689         isl_basic_map_free(test);
1690
1691         return empty < 0 ? -1 : !empty;
1692 }
1693
1694 static __isl_give isl_ast_graft_list *generate_sorted_domains(
1695         __isl_keep isl_basic_set_list *domain_list,
1696         __isl_keep isl_union_map *executed,
1697         __isl_keep isl_ast_build *build);
1698
1699 /* Internal data structure for add_nodes.
1700  *
1701  * "executed" and "build" are extra arguments to be passed to add_node.
1702  * "list" collects the results.
1703  */
1704 struct isl_add_nodes_data {
1705         isl_union_map *executed;
1706         isl_ast_build *build;
1707
1708         isl_ast_graft_list *list;
1709 };
1710
1711 /* Generate code for the schedule domains in "scc"
1712  * and add the results to "list".
1713  *
1714  * The domains in "scc" form a strongly connected component in the ordering.
1715  * If the number of domains in "scc" is larger than 1, then this means
1716  * that we cannot determine a valid ordering for the domains in the component.
1717  * This should be fairly rare because the individual domains
1718  * have been made disjoint first.
1719  * The problem is that the domains may be integrally disjoint but not
1720  * rationally disjoint.  For example, we may have domains
1721  *
1722  *      { [i,i] : 0 <= i <= 1 }         and     { [i,1-i] : 0 <= i <= 1 }
1723  *
1724  * These two domains have an empty intersection, but their rational
1725  * relaxations do intersect.  It is impossible to order these domains
1726  * in the second dimension because the first should be ordered before
1727  * the second for outer dimension equal to 0, while it should be ordered
1728  * after for outer dimension equal to 1.
1729  *
1730  * This may happen in particular in case of unrolling since the domain
1731  * of each slice is replaced by its simple hull.
1732  *
1733  * We collect the basic sets in the component, call isl_set_make_disjoint
1734  * and try again.  Note that we rely here on isl_set_make_disjoint also
1735  * making the basic sets rationally disjoint.  If the basic sets
1736  * are rationally disjoint, then the ordering problem does not occur.
1737  * To see this, there can only be a problem if there are points
1738  * (i,a) and (j,b) in one set and (i,c) and (j,d) in the other with
1739  * a < c and b > d.  This means that either the interval spanned
1740  * by a en b lies inside that spanned by c and or the other way around.
1741  * In either case, there is a point inside both intervals with the
1742  * convex combination in terms of a and b and in terms of c and d.
1743  * Taking the same combination of i and j gives a point in the intersection.
1744  */
1745 static int add_nodes(__isl_take isl_basic_set_list *scc, void *user)
1746 {
1747         struct isl_add_nodes_data *data = user;
1748         int i, n;
1749         isl_basic_set *bset;
1750         isl_set *set;
1751
1752         n = isl_basic_set_list_n_basic_set(scc);
1753         bset = isl_basic_set_list_get_basic_set(scc, 0);
1754         if (n == 1) {
1755                 isl_basic_set_list_free(scc);
1756                 data->list = add_node(data->list,
1757                                 isl_union_map_copy(data->executed), bset,
1758                                 isl_ast_build_copy(data->build));
1759                 return data->list ? 0 : -1;
1760         }
1761
1762         set = isl_set_from_basic_set(bset);
1763         for (i = 1; i < n; ++i) {
1764                 bset = isl_basic_set_list_get_basic_set(scc, i);
1765                 set = isl_set_union(set, isl_set_from_basic_set(bset));
1766         }
1767
1768         set = isl_set_make_disjoint(set);
1769         if (isl_set_n_basic_set(set) == n)
1770                 isl_die(isl_basic_set_list_get_ctx(scc), isl_error_internal,
1771                         "unable to separate loop parts",
1772                         set = isl_set_free(set));
1773         isl_basic_set_list_free(scc);
1774         scc = isl_basic_set_list_from_set(set);
1775         data->list = isl_ast_graft_list_concat(data->list,
1776                     generate_sorted_domains(scc, data->executed, data->build));
1777         isl_basic_set_list_free(scc);
1778
1779         return data->list ? 0 : -1;
1780 }
1781
1782 /* Sort the domains in "domain_list" according to the execution order
1783  * at the current depth (for equal values of the outer dimensions),
1784  * generate code for each of them, collecting the results in a list.
1785  * If no code is generated (because the intersection of the inverse schedule
1786  * with the domains turns out to be empty), then an empty list is returned.
1787  *
1788  * The caller is responsible for ensuring that the basic sets in "domain_list"
1789  * are pair-wise disjoint.  It can, however, in principle happen that
1790  * two basic sets should be ordered one way for one value of the outer
1791  * dimensions and the other way for some other value of the outer dimensions.
1792  * We therefore play safe and look for strongly connected components.
1793  * The function add_nodes takes care of handling non-trivial components.
1794  */
1795 static __isl_give isl_ast_graft_list *generate_sorted_domains(
1796         __isl_keep isl_basic_set_list *domain_list,
1797         __isl_keep isl_union_map *executed, __isl_keep isl_ast_build *build)
1798 {
1799         isl_ctx *ctx;
1800         struct isl_add_nodes_data data;
1801         int depth;
1802         int n;
1803
1804         if (!domain_list)
1805                 return NULL;
1806
1807         ctx = isl_basic_set_list_get_ctx(domain_list);
1808         n = isl_basic_set_list_n_basic_set(domain_list);
1809         data.list = isl_ast_graft_list_alloc(ctx, n);
1810         if (n == 0)
1811                 return data.list;
1812         if (n == 1)
1813                 return add_node(data.list, isl_union_map_copy(executed),
1814                         isl_basic_set_list_get_basic_set(domain_list, 0),
1815                         isl_ast_build_copy(build));
1816
1817         depth = isl_ast_build_get_depth(build);
1818         data.executed = executed;
1819         data.build = build;
1820         if (isl_basic_set_list_foreach_scc(domain_list,
1821                                         &domain_follows_at_depth, &depth,
1822                                         &add_nodes, &data) < 0)
1823                 data.list = isl_ast_graft_list_free(data.list);
1824
1825         return data.list;
1826 }
1827
1828 /* Do i and j share any values for the outer dimensions?
1829  */
1830 static int shared_outer(__isl_keep isl_basic_set *i,
1831         __isl_keep isl_basic_set *j, void *user)
1832 {
1833         int depth = *(int *) user;
1834         isl_basic_map *test;
1835         int empty;
1836         int l;
1837
1838         test = isl_basic_map_from_domain_and_range(isl_basic_set_copy(i),
1839                                                     isl_basic_set_copy(j));
1840         for (l = 0; l < depth; ++l)
1841                 test = isl_basic_map_equate(test, isl_dim_in, l,
1842                                                 isl_dim_out, l);
1843         empty = isl_basic_map_is_empty(test);
1844         isl_basic_map_free(test);
1845
1846         return empty < 0 ? -1 : !empty;
1847 }
1848
1849 /* Internal data structure for generate_sorted_domains_wrap.
1850  *
1851  * "n" is the total number of basic sets
1852  * "executed" and "build" are extra arguments to be passed
1853  *      to generate_sorted_domains.
1854  *
1855  * "single" is set to 1 by generate_sorted_domains_wrap if there
1856  * is only a single component.
1857  * "list" collects the results.
1858  */
1859 struct isl_ast_generate_parallel_domains_data {
1860         int n;
1861         isl_union_map *executed;
1862         isl_ast_build *build;
1863
1864         int single;
1865         isl_ast_graft_list *list;
1866 };
1867
1868 /* Call generate_sorted_domains on "scc", fuse the result into a list
1869  * with either zero or one graft and collect the these single element
1870  * lists into data->list.
1871  *
1872  * If there is only one component, i.e., if the number of basic sets
1873  * in the current component is equal to the total number of basic sets,
1874  * then data->single is set to 1 and the result of generate_sorted_domains
1875  * is not fused.
1876  */
1877 static int generate_sorted_domains_wrap(__isl_take isl_basic_set_list *scc,
1878         void *user)
1879 {
1880         struct isl_ast_generate_parallel_domains_data *data = user;
1881         isl_ast_graft_list *list;
1882
1883         list = generate_sorted_domains(scc, data->executed, data->build);
1884         data->single = isl_basic_set_list_n_basic_set(scc) == data->n;
1885         if (!data->single)
1886                 list = isl_ast_graft_list_fuse(list, data->build);
1887         if (!data->list)
1888                 data->list = list;
1889         else
1890                 data->list = isl_ast_graft_list_concat(data->list, list);
1891
1892         isl_basic_set_list_free(scc);
1893         if (!data->list)
1894                 return -1;
1895
1896         return 0;
1897 }
1898
1899 /* Look for any (weakly connected) components in the "domain_list"
1900  * of domains that share some values of the outer dimensions.
1901  * That is, domains in different components do not share any values
1902  * of the outer dimensions.  This means that these components
1903  * can be freely reordered.
1904  * Within each of the components, we sort the domains according
1905  * to the execution order at the current depth.
1906  *
1907  * If there is more than one component, then generate_sorted_domains_wrap
1908  * fuses the result of each call to generate_sorted_domains
1909  * into a list with either zero or one graft and collects these (at most)
1910  * single element lists into a bigger list. This means that the elements of the
1911  * final list can be freely reordered.  In particular, we sort them
1912  * according to an arbitrary but fixed ordering to ease merging of
1913  * graft lists from different components.
1914  */
1915 static __isl_give isl_ast_graft_list *generate_parallel_domains(
1916         __isl_keep isl_basic_set_list *domain_list,
1917         __isl_keep isl_union_map *executed, __isl_keep isl_ast_build *build)
1918 {
1919         int depth;
1920         struct isl_ast_generate_parallel_domains_data data;
1921
1922         if (!domain_list)
1923                 return NULL;
1924
1925         data.n = isl_basic_set_list_n_basic_set(domain_list);
1926         if (data.n <= 1)
1927                 return generate_sorted_domains(domain_list, executed, build);
1928
1929         depth = isl_ast_build_get_depth(build);
1930         data.list = NULL;
1931         data.executed = executed;
1932         data.build = build;
1933         data.single = 0;
1934         if (isl_basic_set_list_foreach_scc(domain_list, &shared_outer, &depth,
1935                                             &generate_sorted_domains_wrap,
1936                                             &data) < 0)
1937                 data.list = isl_ast_graft_list_free(data.list);
1938
1939         if (!data.single)
1940                 data.list = isl_ast_graft_list_sort_guard(data.list);
1941
1942         return data.list;
1943 }
1944
1945 /* Internal data for separate_domain.
1946  *
1947  * "explicit" is set if we only want to use explicit bounds.
1948  *
1949  * "domain" collects the separated domains.
1950  */
1951 struct isl_separate_domain_data {
1952         isl_ast_build *build;
1953         int explicit;
1954         isl_set *domain;
1955 };
1956
1957 /* Extract implicit bounds on the current dimension for the executed "map".
1958  *
1959  * The domain of "map" may involve inner dimensions, so we
1960  * need to eliminate them.
1961  */
1962 static __isl_give isl_set *implicit_bounds(__isl_take isl_map *map,
1963         __isl_keep isl_ast_build *build)
1964 {
1965         isl_set *domain;
1966
1967         domain = isl_map_domain(map);
1968         domain = isl_ast_build_eliminate(build, domain);
1969
1970         return domain;
1971 }
1972
1973 /* Extract explicit bounds on the current dimension for the executed "map".
1974  *
1975  * Rather than eliminating the inner dimensions as in implicit_bounds,
1976  * we simply drop any constraints involving those inner dimensions.
1977  * The idea is that most bounds that are implied by constraints on the
1978  * inner dimensions will be enforced by for loops and not by explicit guards.
1979  * There is then no need to separate along those bounds.
1980  */
1981 static __isl_give isl_set *explicit_bounds(__isl_take isl_map *map,
1982         __isl_keep isl_ast_build *build)
1983 {
1984         isl_set *domain;
1985         int depth, dim;
1986
1987         dim = isl_map_dim(map, isl_dim_out);
1988         map = isl_map_drop_constraints_involving_dims(map, isl_dim_out, 0, dim);
1989
1990         domain = isl_map_domain(map);
1991         depth = isl_ast_build_get_depth(build);
1992         dim = isl_set_dim(domain, isl_dim_set);
1993         domain = isl_set_detect_equalities(domain);
1994         domain = isl_set_drop_constraints_involving_dims(domain,
1995                                 isl_dim_set, depth + 1, dim - (depth + 1));
1996         domain = isl_set_remove_divs_involving_dims(domain,
1997                                 isl_dim_set, depth, 1);
1998         domain = isl_set_remove_unknown_divs(domain);
1999
2000         return domain;
2001 }
2002
2003 /* Split data->domain into pieces that intersect with the range of "map"
2004  * and pieces that do not intersect with the range of "map"
2005  * and then add that part of the range of "map" that does not intersect
2006  * with data->domain.
2007  */
2008 static int separate_domain(__isl_take isl_map *map, void *user)
2009 {
2010         struct isl_separate_domain_data *data = user;
2011         isl_set *domain;
2012         isl_set *d1, *d2;
2013
2014         if (data->explicit)
2015                 domain = explicit_bounds(map, data->build);
2016         else
2017                 domain = implicit_bounds(map, data->build);
2018
2019         domain = isl_set_coalesce(domain);
2020         domain = isl_set_make_disjoint(domain);
2021         d1 = isl_set_subtract(isl_set_copy(domain), isl_set_copy(data->domain));
2022         d2 = isl_set_subtract(isl_set_copy(data->domain), isl_set_copy(domain));
2023         data->domain = isl_set_intersect(data->domain, domain);
2024         data->domain = isl_set_union(data->domain, d1);
2025         data->domain = isl_set_union(data->domain, d2);
2026
2027         return 0;
2028 }
2029
2030 /* Separate the schedule domains of "executed".
2031  *
2032  * That is, break up the domain of "executed" into basic sets,
2033  * such that for each basic set S, every element in S is associated with
2034  * the same domain spaces.
2035  *
2036  * "space" is the (single) domain space of "executed".
2037  */
2038 static __isl_give isl_set *separate_schedule_domains(
2039         __isl_take isl_space *space, __isl_take isl_union_map *executed,
2040         __isl_keep isl_ast_build *build)
2041 {
2042         struct isl_separate_domain_data data = { build };
2043         isl_ctx *ctx;
2044
2045         ctx = isl_ast_build_get_ctx(build);
2046         data.explicit = isl_options_get_ast_build_separation_bounds(ctx) ==
2047                                     ISL_AST_BUILD_SEPARATION_BOUNDS_EXPLICIT;
2048         data.domain = isl_set_empty(space);
2049         if (isl_union_map_foreach_map(executed, &separate_domain, &data) < 0)
2050                 data.domain = isl_set_free(data.domain);
2051
2052         isl_union_map_free(executed);
2053         return data.domain;
2054 }
2055
2056 /* Temporary data used during the search for a lower bound for unrolling.
2057  *
2058  * "domain" is the original set for which to find a lower bound
2059  * "depth" is the dimension for which to find a lower boudn
2060  *
2061  * "lower" is the best lower bound found so far.  It is NULL if we have not
2062  * found any yet.
2063  * "n" is the corresponding size.  If lower is NULL, then the value of n
2064  * is undefined.
2065  *
2066  * "tmp" is a temporary initialized isl_int.
2067  */
2068 struct isl_find_unroll_data {
2069         isl_set *domain;
2070         int depth;
2071
2072         isl_aff *lower;
2073         int *n;
2074         isl_int tmp;
2075 };
2076
2077 /* Check if we can use "c" as a lower bound and if it is better than
2078  * any previously found lower bound.
2079  *
2080  * If "c" does not involve the dimension at the current depth,
2081  * then we cannot use it.
2082  * Otherwise, let "c" be of the form
2083  *
2084  *      i >= f(j)/a
2085  *
2086  * We compute the maximal value of
2087  *
2088  *      -ceil(f(j)/a)) + i + 1
2089  *
2090  * over the domain.  If there is such a value "n", then we know
2091  *
2092  *      -ceil(f(j)/a)) + i + 1 <= n
2093  *
2094  * or
2095  *
2096  *      i < ceil(f(j)/a)) + n
2097  *
2098  * meaning that we can use ceil(f(j)/a)) as a lower bound for unrolling.
2099  * We just need to check if we have found any lower bound before and
2100  * if the new lower bound is better (smaller n) than the previously found
2101  * lower bounds.
2102  */
2103 static int update_unrolling_lower_bound(struct isl_find_unroll_data *data,
2104         __isl_keep isl_constraint *c)
2105 {
2106         isl_aff *aff, *lower;
2107         enum isl_lp_result res;
2108
2109         if (!isl_constraint_is_lower_bound(c, isl_dim_set, data->depth))
2110                 return 0;
2111
2112         lower = isl_constraint_get_bound(c, isl_dim_set, data->depth);
2113         lower = isl_aff_ceil(lower);
2114         aff = isl_aff_copy(lower);
2115         aff = isl_aff_neg(aff);
2116         aff = isl_aff_add_coefficient_si(aff, isl_dim_in, data->depth, 1);
2117         aff = isl_aff_add_constant_si(aff, 1);
2118         res = isl_set_max(data->domain, aff, &data->tmp);
2119         isl_aff_free(aff);
2120
2121         if (res == isl_lp_error)
2122                 goto error;
2123         if (res == isl_lp_unbounded) {
2124                 isl_aff_free(lower);
2125                 return 0;
2126         }
2127
2128         if (isl_int_cmp_si(data->tmp, INT_MAX) <= 0 &&
2129             (!data->lower || isl_int_cmp_si(data->tmp, *data->n) < 0)) {
2130                 isl_aff_free(data->lower);
2131                 data->lower = lower;
2132                 *data->n = isl_int_get_si(data->tmp);
2133         } else
2134                 isl_aff_free(lower);
2135
2136         return 1;
2137 error:
2138         isl_aff_free(lower);
2139         return -1;
2140 }
2141
2142 /* Check if we can use "c" as a lower bound and if it is better than
2143  * any previously found lower bound.
2144  */
2145 static int constraint_find_unroll(__isl_take isl_constraint *c, void *user)
2146 {
2147         struct isl_find_unroll_data *data;
2148         int r;
2149
2150         data = (struct isl_find_unroll_data *) user;
2151         r = update_unrolling_lower_bound(data, c);
2152         isl_constraint_free(c);
2153
2154         return r;
2155 }
2156
2157 /* Look for a lower bound l(i) on the dimension at "depth"
2158  * and a size n such that "domain" is a subset of
2159  *
2160  *      { [i] : l(i) <= i_d < l(i) + n }
2161  *
2162  * where d is "depth" and l(i) depends only on earlier dimensions.
2163  * Furthermore, try and find a lower bound such that n is as small as possible.
2164  * In particular, "n" needs to be finite.
2165  *
2166  * Inner dimensions have been eliminated from "domain" by the caller.
2167  *
2168  * We first construct a collection of lower bounds on the input set
2169  * by computing its simple hull.  We then iterate through them,
2170  * discarding those that we cannot use (either because they do not
2171  * involve the dimension at "depth" or because they have no corresponding
2172  * upper bound, meaning that "n" would be unbounded) and pick out the
2173  * best from the remaining ones.
2174  *
2175  * If we cannot find a suitable lower bound, then we consider that
2176  * to be an error.
2177  */
2178 static __isl_give isl_aff *find_unroll_lower_bound(__isl_keep isl_set *domain,
2179         int depth, int *n)
2180 {
2181         struct isl_find_unroll_data data = { domain, depth, NULL, n };
2182         isl_basic_set *hull;
2183
2184         isl_int_init(data.tmp);
2185         hull = isl_set_simple_hull(isl_set_copy(domain));
2186
2187         if (isl_basic_set_foreach_constraint(hull,
2188                                             &constraint_find_unroll, &data) < 0)
2189                 goto error;
2190
2191         isl_basic_set_free(hull);
2192         isl_int_clear(data.tmp);
2193
2194         if (!data.lower)
2195                 isl_die(isl_set_get_ctx(domain), isl_error_invalid,
2196                         "cannot find lower bound for unrolling", return NULL);
2197
2198         return data.lower;
2199 error:
2200         isl_basic_set_free(hull);
2201         isl_int_clear(data.tmp);
2202         return isl_aff_free(data.lower);
2203 }
2204
2205 /* Return the constraint
2206  *
2207  *      i_"depth" = aff + offset
2208  */
2209 static __isl_give isl_constraint *at_offset(int depth, __isl_keep isl_aff *aff,
2210         int offset)
2211 {
2212         aff = isl_aff_copy(aff);
2213         aff = isl_aff_add_coefficient_si(aff, isl_dim_in, depth, -1);
2214         aff = isl_aff_add_constant_si(aff, offset);
2215         return isl_equality_from_aff(aff);
2216 }
2217
2218 /* Return a list of basic sets, one for each value of the current dimension
2219  * in "domain".
2220  * The divs that involve the current dimension have not been projected out
2221  * from this domain.
2222  *
2223  * Since we are going to be iterating over the individual values,
2224  * we first check if there are any strides on the current dimension.
2225  * If there is, we rewrite the current dimension i as
2226  *
2227  *              i = stride i' + offset
2228  *
2229  * and then iterate over individual values of i' instead.
2230  *
2231  * We then look for a lower bound on i' and a size such that the domain
2232  * is a subset of
2233  *
2234  *      { [j,i'] : l(j) <= i' < l(j) + n }
2235  *
2236  * and then take slices of the domain at values of i'
2237  * between l(j) and l(j) + n - 1.
2238  *
2239  * We compute the unshifted simple hull of each slice to ensure that
2240  * we have a single basic set per offset.  The slicing constraint
2241  * may get simplified away before the unshifted simple hull is taken
2242  * and may therefore in some rare cases disappear from the result.
2243  * We therefore explicitly add the constraint back after computing
2244  * the unshifted simple hull to ensure that the basic sets
2245  * remain disjoint.  The constraints that are dropped by taking the hull
2246  * will be taken into account at the next level, as in the case of the
2247  * atomic option.
2248  *
2249  * Finally, we map i' back to i and add each basic set to the list.
2250  */
2251 static __isl_give isl_basic_set_list *do_unroll(__isl_take isl_set *domain,
2252         __isl_keep isl_ast_build *build)
2253 {
2254         int i, n;
2255         int depth;
2256         isl_ctx *ctx;
2257         isl_aff *lower;
2258         isl_basic_set_list *list;
2259         isl_multi_aff *expansion;
2260         isl_basic_map *bmap;
2261
2262         if (!domain)
2263                 return NULL;
2264
2265         ctx = isl_set_get_ctx(domain);
2266         depth = isl_ast_build_get_depth(build);
2267         build = isl_ast_build_copy(build);
2268         domain = isl_ast_build_eliminate_inner(build, domain);
2269         build = isl_ast_build_detect_strides(build, isl_set_copy(domain));
2270         expansion = isl_ast_build_get_stride_expansion(build);
2271
2272         domain = isl_set_preimage_multi_aff(domain,
2273                                             isl_multi_aff_copy(expansion));
2274         domain = isl_ast_build_eliminate_divs(build, domain);
2275
2276         isl_ast_build_free(build);
2277
2278         list = isl_basic_set_list_alloc(ctx, 0);
2279
2280         lower = find_unroll_lower_bound(domain, depth, &n);
2281         if (!lower)
2282                 list = isl_basic_set_list_free(list);
2283
2284         bmap = isl_basic_map_from_multi_aff(expansion);
2285
2286         for (i = 0; list && i < n; ++i) {
2287                 isl_set *set;
2288                 isl_basic_set *bset;
2289                 isl_constraint *slice;
2290
2291                 slice = at_offset(depth, lower, i);
2292                 set = isl_set_copy(domain);
2293                 set = isl_set_add_constraint(set, isl_constraint_copy(slice));
2294                 bset = isl_set_unshifted_simple_hull(set);
2295                 bset = isl_basic_set_add_constraint(bset, slice);
2296                 bset = isl_basic_set_apply(bset, isl_basic_map_copy(bmap));
2297                 list = isl_basic_set_list_add(list, bset);
2298         }
2299
2300         isl_aff_free(lower);
2301         isl_set_free(domain);
2302         isl_basic_map_free(bmap);
2303
2304         return list;
2305 }
2306
2307 /* Data structure for storing the results and the intermediate objects
2308  * of compute_domains.
2309  *
2310  * "list" is the main result of the function and contains a list
2311  * of disjoint basic sets for which code should be generated.
2312  *
2313  * "executed" and "build" are inputs to compute_domains.
2314  * "schedule_domain" is the domain of "executed".
2315  *
2316  * "option" constains the domains at the current depth that should by
2317  * atomic, separated or unrolled.  These domains are as specified by
2318  * the user, except that inner dimensions have been eliminated and
2319  * that they have been made pair-wise disjoint.
2320  *
2321  * "sep_class" contains the user-specified split into separation classes
2322  * specialized to the current depth.
2323  * "done" contains the union of the separation domains that have already
2324  * been handled.
2325  * "atomic" contains the domain that has effectively been made atomic.
2326  * This domain may be larger than the intersection of option[atomic]
2327  * and the schedule domain.
2328  */
2329 struct isl_codegen_domains {
2330         isl_basic_set_list *list;
2331
2332         isl_union_map *executed;
2333         isl_ast_build *build;
2334         isl_set *schedule_domain;
2335
2336         isl_set *option[3];
2337
2338         isl_map *sep_class;
2339         isl_set *done;
2340         isl_set *atomic;
2341 };
2342
2343 /* Add domains to domains->list for each individual value of the current
2344  * dimension, for that part of the schedule domain that lies in the
2345  * intersection of the option domain and the class domain.
2346  *
2347  * "domain" is the intersection of the class domain and the schedule domain.
2348  * The divs that involve the current dimension have not been projected out
2349  * from this domain.
2350  *
2351  * We first break up the unroll option domain into individual pieces
2352  * and then handle each of them separately.  The unroll option domain
2353  * has been made disjoint in compute_domains_init_options,
2354  *
2355  * Note that we actively want to combine different pieces of the
2356  * schedule domain that have the same value at the current dimension.
2357  * We therefore need to break up the unroll option domain before
2358  * intersecting with class and schedule domain, hoping that the
2359  * unroll option domain specified by the user is relatively simple.
2360  */
2361 static int compute_unroll_domains(struct isl_codegen_domains *domains,
2362         __isl_keep isl_set *domain)
2363 {
2364         isl_set *unroll_domain;
2365         isl_basic_set_list *unroll_list;
2366         int i, n;
2367         int empty;
2368
2369         empty = isl_set_is_empty(domains->option[unroll]);
2370         if (empty < 0)
2371                 return -1;
2372         if (empty)
2373                 return 0;
2374
2375         unroll_domain = isl_set_copy(domains->option[unroll]);
2376         unroll_list = isl_basic_set_list_from_set(unroll_domain);
2377
2378         n = isl_basic_set_list_n_basic_set(unroll_list);
2379         for (i = 0; i < n; ++i) {
2380                 isl_basic_set *bset;
2381                 isl_basic_set_list *list;
2382
2383                 bset = isl_basic_set_list_get_basic_set(unroll_list, i);
2384                 unroll_domain = isl_set_from_basic_set(bset);
2385                 unroll_domain = isl_set_intersect(unroll_domain,
2386                                                     isl_set_copy(domain));
2387
2388                 empty = isl_set_is_empty(unroll_domain);
2389                 if (empty >= 0 && empty) {
2390                         isl_set_free(unroll_domain);
2391                         continue;
2392                 }
2393
2394                 list = do_unroll(unroll_domain, domains->build);
2395                 domains->list = isl_basic_set_list_concat(domains->list, list);
2396         }
2397
2398         isl_basic_set_list_free(unroll_list);
2399
2400         return 0;
2401 }
2402
2403 /* Construct a single basic set that includes the intersection of
2404  * the schedule domain, the atomic option domain and the class domain.
2405  * Add the resulting basic set to domains->list and save a copy
2406  * in domains->atomic for use in compute_partial_domains.
2407  *
2408  * We construct a single domain rather than trying to combine
2409  * the schedule domains of individual domains because we are working
2410  * within a single component so that non-overlapping schedule domains
2411  * should already have been separated.
2412  * Note, though, that this does not take into account the class domain.
2413  * So, it is possible for a class domain to carve out a piece of the
2414  * schedule domain with independent pieces and then we would only
2415  * generate a single domain for them.  If this proves to be problematic
2416  * for some users, then this function will have to be adjusted.
2417  *
2418  * "domain" is the intersection of the schedule domain and the class domain,
2419  * with inner dimensions projected out.
2420  */
2421 static int compute_atomic_domain(struct isl_codegen_domains *domains,
2422         __isl_keep isl_set *domain)
2423 {
2424         isl_basic_set *bset;
2425         isl_set *atomic_domain;
2426         int empty;
2427
2428         atomic_domain = isl_set_copy(domains->option[atomic]);
2429         atomic_domain = isl_set_intersect(atomic_domain, isl_set_copy(domain));
2430         empty = isl_set_is_empty(atomic_domain);
2431         if (empty < 0 || empty) {
2432                 domains->atomic = atomic_domain;
2433                 return empty < 0 ? -1 : 0;
2434         }
2435
2436         atomic_domain = isl_set_coalesce(atomic_domain);
2437         bset = isl_set_unshifted_simple_hull(atomic_domain);
2438         domains->atomic = isl_set_from_basic_set(isl_basic_set_copy(bset));
2439         domains->list = isl_basic_set_list_add(domains->list, bset);
2440
2441         return 0;
2442 }
2443
2444 /* Split up the schedule domain into uniform basic sets,
2445  * in the sense that each element in a basic set is associated to
2446  * elements of the same domains, and add the result to domains->list.
2447  * Do this for that part of the schedule domain that lies in the
2448  * intersection of "class_domain" and the separate option domain.
2449  *
2450  * "class_domain" may or may not include the constraints
2451  * of the schedule domain, but this does not make a difference
2452  * since we are going to intersect it with the domain of the inverse schedule.
2453  * If it includes schedule domain constraints, then they may involve
2454  * inner dimensions, but we will eliminate them in separation_domain.
2455  */
2456 static int compute_separate_domain(struct isl_codegen_domains *domains,
2457         __isl_keep isl_set *class_domain)
2458 {
2459         isl_space *space;
2460         isl_set *domain;
2461         isl_union_map *executed;
2462         isl_basic_set_list *list;
2463         int empty;
2464
2465         domain = isl_set_copy(domains->option[separate]);
2466         domain = isl_set_intersect(domain, isl_set_copy(class_domain));
2467         executed = isl_union_map_copy(domains->executed);
2468         executed = isl_union_map_intersect_domain(executed,
2469                                     isl_union_set_from_set(domain));
2470         empty = isl_union_map_is_empty(executed);
2471         if (empty < 0 || empty) {
2472                 isl_union_map_free(executed);
2473                 return empty < 0 ? -1 : 0;
2474         }
2475
2476         space = isl_set_get_space(class_domain);
2477         domain = separate_schedule_domains(space, executed, domains->build);
2478
2479         list = isl_basic_set_list_from_set(domain);
2480         domains->list = isl_basic_set_list_concat(domains->list, list);
2481
2482         return 0;
2483 }
2484
2485 /* Split up the domain at the current depth into disjoint
2486  * basic sets for which code should be generated separately
2487  * for the given separation class domain.
2488  *
2489  * If any separation classes have been defined, then "class_domain"
2490  * is the domain of the current class and does not refer to inner dimensions.
2491  * Otherwise, "class_domain" is the universe domain.
2492  *
2493  * We first make sure that the class domain is disjoint from
2494  * previously considered class domains.
2495  *
2496  * The separate domains can be computed directly from the "class_domain".
2497  *
2498  * The unroll, atomic and remainder domains need the constraints
2499  * from the schedule domain.
2500  *
2501  * For unrolling, the actual schedule domain is needed (with divs that
2502  * may refer to the current dimension) so that stride detection can be
2503  * performed.
2504  *
2505  * For atomic and remainder domains, inner dimensions and divs involving
2506  * the current dimensions should be eliminated.
2507  * In case we are working within a separation class, we need to intersect
2508  * the result with the current "class_domain" to ensure that the domains
2509  * are disjoint from those generated from other class domains.
2510  *
2511  * The domain that has been made atomic may be larger than specified
2512  * by the user since it needs to be representable as a single basic set.
2513  * This possibly larger domain is stored in domains->atomic by
2514  * compute_atomic_domain.
2515  *
2516  * If anything is left after handling separate, unroll and atomic,
2517  * we split it up into basic sets and append the basic sets to domains->list.
2518  */
2519 static int compute_partial_domains(struct isl_codegen_domains *domains,
2520         __isl_take isl_set *class_domain)
2521 {
2522         isl_basic_set_list *list;
2523         isl_set *domain;
2524
2525         class_domain = isl_set_subtract(class_domain,
2526                                         isl_set_copy(domains->done));
2527         domains->done = isl_set_union(domains->done,
2528                                         isl_set_copy(class_domain));
2529
2530         domain = isl_set_copy(class_domain);
2531
2532         if (compute_separate_domain(domains, domain) < 0)
2533                 goto error;
2534         domain = isl_set_subtract(domain,
2535                                     isl_set_copy(domains->option[separate]));
2536
2537         domain = isl_set_intersect(domain,
2538                                 isl_set_copy(domains->schedule_domain));
2539
2540         if (compute_unroll_domains(domains, domain) < 0)
2541                 goto error;
2542         domain = isl_set_subtract(domain,
2543                                     isl_set_copy(domains->option[unroll]));
2544
2545         domain = isl_ast_build_eliminate(domains->build, domain);
2546         domain = isl_set_intersect(domain, isl_set_copy(class_domain));
2547
2548         if (compute_atomic_domain(domains, domain) < 0)
2549                 domain = isl_set_free(domain);
2550         domain = isl_set_subtract(domain, domains->atomic);
2551
2552         domain = isl_set_coalesce(domain);
2553         domain = isl_set_make_disjoint(domain);
2554
2555         list = isl_basic_set_list_from_set(domain);
2556         domains->list = isl_basic_set_list_concat(domains->list, list);
2557
2558         isl_set_free(class_domain);
2559
2560         return 0;
2561 error:
2562         isl_set_free(domain);
2563         isl_set_free(class_domain);
2564         return -1;
2565 }
2566
2567 /* Split up the domain at the current depth into disjoint
2568  * basic sets for which code should be generated separately
2569  * for the separation class identified by "pnt".
2570  *
2571  * We extract the corresponding class domain from domains->sep_class,
2572  * eliminate inner dimensions and pass control to compute_partial_domains.
2573  */
2574 static int compute_class_domains(__isl_take isl_point *pnt, void *user)
2575 {
2576         struct isl_codegen_domains *domains = user;
2577         isl_set *class_set;
2578         isl_set *domain;
2579         int disjoint;
2580
2581         class_set = isl_set_from_point(pnt);
2582         domain = isl_map_domain(isl_map_intersect_range(
2583                                 isl_map_copy(domains->sep_class), class_set));
2584         domain = isl_ast_build_compute_gist(domains->build, domain);
2585         domain = isl_ast_build_eliminate(domains->build, domain);
2586
2587         disjoint = isl_set_plain_is_disjoint(domain, domains->schedule_domain);
2588         if (disjoint < 0)
2589                 return -1;
2590         if (disjoint) {
2591                 isl_set_free(domain);
2592                 return 0;
2593         }
2594
2595         return compute_partial_domains(domains, domain);
2596 }
2597
2598 /* Extract the domains at the current depth that should be atomic,
2599  * separated or unrolled and store them in option.
2600  *
2601  * The domains specified by the user might overlap, so we make
2602  * them disjoint by subtracting earlier domains from later domains.
2603  */
2604 static void compute_domains_init_options(isl_set *option[3],
2605         __isl_keep isl_ast_build *build)
2606 {
2607         enum isl_ast_build_domain_type type, type2;
2608
2609         for (type = atomic; type <= separate; ++type) {
2610                 option[type] = isl_ast_build_get_option_domain(build, type);
2611                 for (type2 = atomic; type2 < type; ++type2)
2612                         option[type] = isl_set_subtract(option[type],
2613                                                 isl_set_copy(option[type2]));
2614         }
2615
2616         option[unroll] = isl_set_coalesce(option[unroll]);
2617         option[unroll] = isl_set_make_disjoint(option[unroll]);
2618 }
2619
2620 /* Split up the domain at the current depth into disjoint
2621  * basic sets for which code should be generated separately,
2622  * based on the user-specified options.
2623  * Return the list of disjoint basic sets.
2624  *
2625  * There are three kinds of domains that we need to keep track of.
2626  * - the "schedule domain" is the domain of "executed"
2627  * - the "class domain" is the domain corresponding to the currrent
2628  *      separation class
2629  * - the "option domain" is the domain corresponding to one of the options
2630  *      atomic, unroll or separate
2631  *
2632  * We first consider the individial values of the separation classes
2633  * and split up the domain for each of them separately.
2634  * Finally, we consider the remainder.  If no separation classes were
2635  * specified, then we call compute_partial_domains with the universe
2636  * "class_domain".  Otherwise, we take the "schedule_domain" as "class_domain",
2637  * with inner dimensions removed.  We do this because we want to
2638  * avoid computing the complement of the class domains (i.e., the difference
2639  * between the universe and domains->done).
2640  */
2641 static __isl_give isl_basic_set_list *compute_domains(
2642         __isl_keep isl_union_map *executed, __isl_keep isl_ast_build *build)
2643 {
2644         struct isl_codegen_domains domains;
2645         isl_ctx *ctx;
2646         isl_set *domain;
2647         isl_union_set *schedule_domain;
2648         isl_set *classes;
2649         isl_space *space;
2650         int n_param;
2651         enum isl_ast_build_domain_type type;
2652         int empty;
2653
2654         if (!executed)
2655                 return NULL;
2656
2657         ctx = isl_union_map_get_ctx(executed);
2658         domains.list = isl_basic_set_list_alloc(ctx, 0);
2659
2660         schedule_domain = isl_union_map_domain(isl_union_map_copy(executed));
2661         domain = isl_set_from_union_set(schedule_domain);
2662
2663         compute_domains_init_options(domains.option, build);
2664
2665         domains.sep_class = isl_ast_build_get_separation_class(build);
2666         classes = isl_map_range(isl_map_copy(domains.sep_class));
2667         n_param = isl_set_dim(classes, isl_dim_param);
2668         classes = isl_set_project_out(classes, isl_dim_param, 0, n_param);
2669
2670         space = isl_set_get_space(domain);
2671         domains.build = build;
2672         domains.schedule_domain = isl_set_copy(domain);
2673         domains.executed = executed;
2674         domains.done = isl_set_empty(space);
2675
2676         if (isl_set_foreach_point(classes, &compute_class_domains, &domains) < 0)
2677                 domains.list = isl_basic_set_list_free(domains.list);
2678         isl_set_free(classes);
2679
2680         empty = isl_set_is_empty(domains.done);
2681         if (empty < 0) {
2682                 domains.list = isl_basic_set_list_free(domains.list);
2683                 domain = isl_set_free(domain);
2684         } else if (empty) {
2685                 isl_set_free(domain);
2686                 domain = isl_set_universe(isl_set_get_space(domains.done));
2687         } else {
2688                 domain = isl_ast_build_eliminate(build, domain);
2689         }
2690         if (compute_partial_domains(&domains, domain) < 0)
2691                 domains.list = isl_basic_set_list_free(domains.list);
2692
2693         isl_set_free(domains.schedule_domain);
2694         isl_set_free(domains.done);
2695         isl_map_free(domains.sep_class);
2696         for (type = atomic; type <= separate; ++type)
2697                 isl_set_free(domains.option[type]);
2698
2699         return domains.list;
2700 }
2701
2702 /* Generate code for a single component, after shifting (if any)
2703  * has been applied.
2704  *
2705  * We first split up the domain at the current depth into disjoint
2706  * basic sets based on the user-specified options.
2707  * Then we generated code for each of them and concatenate the results.
2708  */
2709 static __isl_give isl_ast_graft_list *generate_shifted_component(
2710         __isl_take isl_union_map *executed, __isl_take isl_ast_build *build)
2711 {
2712         isl_basic_set_list *domain_list;
2713         isl_ast_graft_list *list = NULL;
2714
2715         domain_list = compute_domains(executed, build);
2716         list = generate_parallel_domains(domain_list, executed, build);
2717
2718         isl_basic_set_list_free(domain_list);
2719         isl_union_map_free(executed);
2720         isl_ast_build_free(build);
2721
2722         return list;
2723 }
2724
2725 struct isl_set_map_pair {
2726         isl_set *set;
2727         isl_map *map;
2728 };
2729
2730 /* Given an array "domain" of isl_set_map_pairs and an array "order"
2731  * of indices into the "domain" array,
2732  * return the union of the "map" fields of the elements
2733  * indexed by the first "n" elements of "order".
2734  */
2735 static __isl_give isl_union_map *construct_component_executed(
2736         struct isl_set_map_pair *domain, int *order, int n)
2737 {
2738         int i;
2739         isl_map *map;
2740         isl_union_map *executed;
2741
2742         map = isl_map_copy(domain[order[0]].map);
2743         executed = isl_union_map_from_map(map);
2744         for (i = 1; i < n; ++i) {
2745                 map = isl_map_copy(domain[order[i]].map);
2746                 executed = isl_union_map_add_map(executed, map);
2747         }
2748
2749         return executed;
2750 }
2751
2752 /* Generate code for a single component, after shifting (if any)
2753  * has been applied.
2754  *
2755  * The component inverse schedule is specified as the "map" fields
2756  * of the elements of "domain" indexed by the first "n" elements of "order".
2757  */
2758 static __isl_give isl_ast_graft_list *generate_shifted_component_from_list(
2759         struct isl_set_map_pair *domain, int *order, int n,
2760         __isl_take isl_ast_build *build)
2761 {
2762         isl_union_map *executed;
2763
2764         executed = construct_component_executed(domain, order, n);
2765         return generate_shifted_component(executed, build);
2766 }
2767
2768 /* Given an array "domain" of isl_set_map_pairs and an array "order"
2769  * of indices into the "domain" array,
2770  * do all (except for at most one) of the "set" field of the elements
2771  * indexed by the first "n" elements of "order" have a fixed value
2772  * at position "depth"?
2773  */
2774 static int at_most_one_non_fixed(struct isl_set_map_pair *domain,
2775         int *order, int n, int depth)
2776 {
2777         int i;
2778         int non_fixed = -1;
2779
2780         for (i = 0; i < n; ++i) {
2781                 int f;
2782
2783                 f = isl_set_plain_is_fixed(domain[order[i]].set,
2784                                                 isl_dim_set, depth, NULL);
2785                 if (f < 0)
2786                         return -1;
2787                 if (f)
2788                         continue;
2789                 if (non_fixed >= 0)
2790                         return 0;
2791                 non_fixed = i;
2792         }
2793
2794         return 1;
2795 }
2796
2797 /* Given an array "domain" of isl_set_map_pairs and an array "order"
2798  * of indices into the "domain" array,
2799  * eliminate the inner dimensions from the "set" field of the elements
2800  * indexed by the first "n" elements of "order", provided the current
2801  * dimension does not have a fixed value.
2802  *
2803  * Return the index of the first element in "order" with a corresponding
2804  * "set" field that does not have an (obviously) fixed value.
2805  */
2806 static int eliminate_non_fixed(struct isl_set_map_pair *domain,
2807         int *order, int n, int depth, __isl_keep isl_ast_build *build)
2808 {
2809         int i;
2810         int base = -1;
2811
2812         for (i = n - 1; i >= 0; --i) {
2813                 int f;
2814                 f = isl_set_plain_is_fixed(domain[order[i]].set,
2815                                                 isl_dim_set, depth, NULL);
2816                 if (f < 0)
2817                         return -1;
2818                 if (f)
2819                         continue;
2820                 domain[order[i]].set = isl_ast_build_eliminate_inner(build,
2821                                                         domain[order[i]].set);
2822                 base = i;
2823         }
2824
2825         return base;
2826 }
2827
2828 /* Given an array "domain" of isl_set_map_pairs and an array "order"
2829  * of indices into the "domain" array,
2830  * find the element of "domain" (amongst those indexed by the first "n"
2831  * elements of "order") with the "set" field that has the smallest
2832  * value for the current iterator.
2833  *
2834  * Note that the domain with the smallest value may depend on the parameters
2835  * and/or outer loop dimension.  Since the result of this function is only
2836  * used as heuristic, we only make a reasonable attempt at finding the best
2837  * domain, one that should work in case a single domain provides the smallest
2838  * value for the current dimension over all values of the parameters
2839  * and outer dimensions.
2840  *
2841  * In particular, we compute the smallest value of the first domain
2842  * and replace it by that of any later domain if that later domain
2843  * has a smallest value that is smaller for at least some value
2844  * of the parameters and outer dimensions.
2845  */
2846 static int first_offset(struct isl_set_map_pair *domain, int *order, int n,
2847         __isl_keep isl_ast_build *build)
2848 {
2849         int i;
2850         isl_map *min_first;
2851         int first = 0;
2852
2853         min_first = isl_ast_build_map_to_iterator(build,
2854                                         isl_set_copy(domain[order[0]].set));
2855         min_first = isl_map_lexmin(min_first);
2856
2857         for (i = 1; i < n; ++i) {
2858                 isl_map *min, *test;
2859                 int empty;
2860
2861                 min = isl_ast_build_map_to_iterator(build,
2862                                         isl_set_copy(domain[order[i]].set));
2863                 min = isl_map_lexmin(min);
2864                 test = isl_map_copy(min);
2865                 test = isl_map_apply_domain(isl_map_copy(min_first), test);
2866                 test = isl_map_order_lt(test, isl_dim_in, 0, isl_dim_out, 0);
2867                 empty = isl_map_is_empty(test);
2868                 isl_map_free(test);
2869                 if (empty >= 0 && !empty) {
2870                         isl_map_free(min_first);
2871                         first = i;
2872                         min_first = min;
2873                 } else
2874                         isl_map_free(min);
2875
2876                 if (empty < 0)
2877                         break;
2878         }
2879
2880         isl_map_free(min_first);
2881
2882         return i < n ? -1 : first;
2883 }
2884
2885 /* Construct a shifted inverse schedule based on the original inverse schedule,
2886  * the stride and the offset.
2887  *
2888  * The original inverse schedule is specified as the "map" fields
2889  * of the elements of "domain" indexed by the first "n" elements of "order".
2890  *
2891  * "stride" and "offset" are such that the difference
2892  * between the values of the current dimension of domain "i"
2893  * and the values of the current dimension for some reference domain are
2894  * equal to
2895  *
2896  *      stride * integer + offset[i]
2897  *
2898  * Moreover, 0 <= offset[i] < stride.
2899  *
2900  * For each domain, we create a map
2901  *
2902  *      { [..., j, ...] -> [..., j - offset[i], offset[i], ....] }
2903  *
2904  * where j refers to the current dimension and the other dimensions are
2905  * unchanged, and apply this map to the original schedule domain.
2906  *
2907  * For example, for the original schedule
2908  *
2909  *      { A[i] -> [2i]: 0 <= i < 10; B[i] -> [2i+1] : 0 <= i < 10 }
2910  *
2911  * and assuming the offset is 0 for the A domain and 1 for the B domain,
2912  * we apply the mapping
2913  *
2914  *      { [j] -> [j, 0] }
2915  *
2916  * to the schedule of the "A" domain and the mapping
2917  *
2918  *      { [j - 1] -> [j, 1] }
2919  *
2920  * to the schedule of the "B" domain.
2921  *
2922  *
2923  * Note that after the transformation, the differences between pairs
2924  * of values of the current dimension over all domains are multiples
2925  * of stride and that we have therefore exposed the stride.
2926  *
2927  *
2928  * To see that the mapping preserves the lexicographic order,
2929  * first note that each of the individual maps above preserves the order.
2930  * If the value of the current iterator is j1 in one domain and j2 in another,
2931  * then if j1 = j2, we know that the same map is applied to both domains
2932  * and the order is preserved.
2933  * Otherwise, let us assume, without loss of generality, that j1 < j2.
2934  * If c1 >= c2 (with c1 and c2 the corresponding offsets), then
2935  *
2936  *      j1 - c1 < j2 - c2
2937  *
2938  * and the order is preserved.
2939  * If c1 < c2, then we know
2940  *
2941  *      0 <= c2 - c1 < s
2942  *
2943  * We also have
2944  *
2945  *      j2 - j1 = n * s + r
2946  *
2947  * with n >= 0 and 0 <= r < s.
2948  * In other words, r = c2 - c1.
2949  * If n > 0, then
2950  *
2951  *      j1 - c1 < j2 - c2
2952  *
2953  * If n = 0, then
2954  *
2955  *      j1 - c1 = j2 - c2
2956  *
2957  * and so
2958  *
2959  *      (j1 - c1, c1) << (j2 - c2, c2)
2960  *
2961  * with "<<" the lexicographic order, proving that the order is preserved
2962  * in all cases.
2963  */
2964 static __isl_give isl_union_map *contruct_shifted_executed(
2965         struct isl_set_map_pair *domain, int *order, int n, isl_int stride,
2966         __isl_keep isl_vec *offset, __isl_keep isl_ast_build *build)
2967 {
2968         int i;
2969         isl_int v;
2970         isl_union_map *executed;
2971         isl_space *space;
2972         isl_map *map;
2973         int depth;
2974         isl_constraint *c;
2975
2976         depth = isl_ast_build_get_depth(build);
2977         space = isl_ast_build_get_space(build, 1);
2978         executed = isl_union_map_empty(isl_space_copy(space));
2979         space = isl_space_map_from_set(space);
2980         map = isl_map_identity(isl_space_copy(space));
2981         map = isl_map_eliminate(map, isl_dim_out, depth, 1);
2982         map = isl_map_insert_dims(map, isl_dim_out, depth + 1, 1);
2983         space = isl_space_insert_dims(space, isl_dim_out, depth + 1, 1);
2984
2985         c = isl_equality_alloc(isl_local_space_from_space(space));
2986         c = isl_constraint_set_coefficient_si(c, isl_dim_in, depth, 1);
2987         c = isl_constraint_set_coefficient_si(c, isl_dim_out, depth, -1);
2988
2989         isl_int_init(v);
2990
2991         for (i = 0; i < n; ++i) {
2992                 isl_map *map_i;
2993
2994                 if (isl_vec_get_element(offset, i, &v) < 0)
2995                         break;
2996                 map_i = isl_map_copy(map);
2997                 map_i = isl_map_fix(map_i, isl_dim_out, depth + 1, v);
2998                 isl_int_neg(v, v);
2999                 c = isl_constraint_set_constant(c, v);
3000                 map_i = isl_map_add_constraint(map_i, isl_constraint_copy(c));
3001
3002                 map_i = isl_map_apply_domain(isl_map_copy(domain[order[i]].map),
3003                                                 map_i);
3004                 executed = isl_union_map_add_map(executed, map_i);
3005         }
3006
3007         isl_constraint_free(c);
3008         isl_map_free(map);
3009
3010         isl_int_clear(v);
3011
3012         if (i < n)
3013                 executed = isl_union_map_free(executed);
3014
3015         return executed;
3016 }
3017
3018 /* Generate code for a single component, after exposing the stride,
3019  * given that the schedule domain is "shifted strided".
3020  *
3021  * The component inverse schedule is specified as the "map" fields
3022  * of the elements of "domain" indexed by the first "n" elements of "order".
3023  *
3024  * The schedule domain being "shifted strided" means that the differences
3025  * between the values of the current dimension of domain "i"
3026  * and the values of the current dimension for some reference domain are
3027  * equal to
3028  *
3029  *      stride * integer + offset[i]
3030  *
3031  * We first look for the domain with the "smallest" value for the current
3032  * dimension and adjust the offsets such that the offset of the "smallest"
3033  * domain is equal to zero.  The other offsets are reduced modulo stride.
3034  *
3035  * Based on this information, we construct a new inverse schedule in
3036  * contruct_shifted_executed that exposes the stride.
3037  * Since this involves the introduction of a new schedule dimension,
3038  * the build needs to be changed accodingly.
3039  * After computing the AST, the newly introduced dimension needs
3040  * to be removed again from the list of grafts.  We do this by plugging
3041  * in a mapping that represents the new schedule domain in terms of the
3042  * old schedule domain.
3043  */
3044 static __isl_give isl_ast_graft_list *generate_shift_component(
3045         struct isl_set_map_pair *domain, int *order, int n, isl_int stride,
3046         __isl_keep isl_vec *offset, __isl_take isl_ast_build *build)
3047 {
3048         isl_ast_graft_list *list;
3049         int first;
3050         int depth;
3051         isl_ctx *ctx;
3052         isl_int val;
3053         isl_vec *v;
3054         isl_space *space;
3055         isl_multi_aff *ma, *zero;
3056         isl_union_map *executed;
3057
3058         ctx = isl_ast_build_get_ctx(build);
3059         depth = isl_ast_build_get_depth(build);
3060
3061         first = first_offset(domain, order, n, build);
3062         if (first < 0)
3063                 return isl_ast_build_free(build);
3064
3065         isl_int_init(val);
3066         v = isl_vec_alloc(ctx, n);
3067         if (isl_vec_get_element(offset, first, &val) < 0)
3068                 v = isl_vec_free(v);
3069         isl_int_neg(val, val);
3070         v = isl_vec_set(v, val);
3071         v = isl_vec_add(v, isl_vec_copy(offset));
3072         v = isl_vec_fdiv_r(v, stride);
3073
3074         executed = contruct_shifted_executed(domain, order, n, stride, v,
3075                                                 build);
3076         space = isl_ast_build_get_space(build, 1);
3077         space = isl_space_map_from_set(space);
3078         ma = isl_multi_aff_identity(isl_space_copy(space));
3079         space = isl_space_from_domain(isl_space_domain(space));
3080         space = isl_space_add_dims(space, isl_dim_out, 1);
3081         zero = isl_multi_aff_zero(space);
3082         ma = isl_multi_aff_range_splice(ma, depth + 1, zero);
3083         build = isl_ast_build_insert_dim(build, depth + 1);
3084         list = generate_shifted_component(executed, build);
3085
3086         list = isl_ast_graft_list_preimage_multi_aff(list, ma);
3087
3088         isl_vec_free(v);
3089         isl_int_clear(val);
3090
3091         return list;
3092 }
3093
3094 /* Generate code for a single component.
3095  *
3096  * The component inverse schedule is specified as the "map" fields
3097  * of the elements of "domain" indexed by the first "n" elements of "order".
3098  *
3099  * This function may modify the "set" fields of "domain".
3100  *
3101  * Before proceeding with the actual code generation for the component,
3102  * we first check if there are any "shifted" strides, meaning that
3103  * the schedule domains of the individual domains are all strided,
3104  * but that they have different offsets, resulting in the union
3105  * of schedule domains not being strided anymore.
3106  *
3107  * The simplest example is the schedule
3108  *
3109  *      { A[i] -> [2i]: 0 <= i < 10; B[i] -> [2i+1] : 0 <= i < 10 }
3110  *
3111  * Both schedule domains are strided, but their union is not.
3112  * This function detects such cases and then rewrites the schedule to
3113  *
3114  *      { A[i] -> [2i, 0]: 0 <= i < 10; B[i] -> [2i, 1] : 0 <= i < 10 }
3115  *
3116  * In the new schedule, the schedule domains have the same offset (modulo
3117  * the stride), ensuring that the union of schedule domains is also strided.
3118  *
3119  *
3120  * If there is only a single domain in the component, then there is
3121  * nothing to do.   Similarly, if the current schedule dimension has
3122  * a fixed value for almost all domains then there is nothing to be done.
3123  * In particular, we need at least two domains where the current schedule
3124  * dimension does not have a fixed value.
3125  * Finally, if any of the options refer to the current schedule dimension,
3126  * then we bail out as well.  It would be possible to reformulate the options
3127  * in terms of the new schedule domain, but that would introduce constraints
3128  * that separate the domains in the options and that is something we would
3129  * like to avoid.
3130  *
3131  *
3132  * To see if there is any shifted stride, we look at the differences
3133  * between the values of the current dimension in pairs of domains
3134  * for equal values of outer dimensions.  These differences should be
3135  * of the form
3136  *
3137  *      m x + r
3138  *
3139  * with "m" the stride and "r" a constant.  Note that we cannot perform
3140  * this analysis on individual domains as the lower bound in each domain
3141  * may depend on parameters or outer dimensions and so the current dimension
3142  * itself may not have a fixed remainder on division by the stride.
3143  *
3144  * In particular, we compare the first domain that does not have an
3145  * obviously fixed value for the current dimension to itself and all
3146  * other domains and collect the offsets and the gcd of the strides.
3147  * If the gcd becomes one, then we failed to find shifted strides.
3148  * If all the offsets are the same (for those domains that do not have
3149  * an obviously fixed value for the current dimension), then we do not
3150  * apply the transformation.
3151  * If none of the domains were skipped, then there is nothing to do.
3152  * If some of them were skipped, then if we apply separation, the schedule
3153  * domain should get split in pieces with a (non-shifted) stride.
3154  *
3155  * Otherwise, we apply a shift to expose the stride in
3156  * generate_shift_component.
3157  */
3158 static __isl_give isl_ast_graft_list *generate_component(
3159         struct isl_set_map_pair *domain, int *order, int n,
3160         __isl_take isl_ast_build *build)
3161 {
3162         int i, d;
3163         int depth;
3164         isl_ctx *ctx;
3165         isl_map *map;
3166         isl_set *deltas;
3167         isl_int m, r, gcd;
3168         isl_vec *v;
3169         int fixed, skip;
3170         int base;
3171         isl_ast_graft_list *list;
3172         int res = 0;
3173
3174         depth = isl_ast_build_get_depth(build);
3175
3176         skip = n == 1;
3177         if (skip >= 0 && !skip)
3178                 skip = at_most_one_non_fixed(domain, order, n, depth);
3179         if (skip >= 0 && !skip)
3180                 skip = isl_ast_build_options_involve_depth(build);
3181         if (skip < 0)
3182                 return isl_ast_build_free(build);
3183         if (skip)
3184                 return generate_shifted_component_from_list(domain,
3185                                                             order, n, build);
3186
3187         base = eliminate_non_fixed(domain, order, n, depth, build);
3188         if (base < 0)
3189                 return isl_ast_build_free(build);
3190
3191         ctx = isl_ast_build_get_ctx(build);
3192
3193         isl_int_init(m);
3194         isl_int_init(r);
3195         isl_int_init(gcd);
3196         v = isl_vec_alloc(ctx, n);
3197
3198         fixed = 1;
3199         for (i = 0; i < n; ++i) {
3200                 map = isl_map_from_domain_and_range(
3201                                         isl_set_copy(domain[order[base]].set),
3202                                         isl_set_copy(domain[order[i]].set));
3203                 for (d = 0; d < depth; ++d)
3204                         map = isl_map_equate(map, isl_dim_in, d,
3205                                                     isl_dim_out, d);
3206                 deltas = isl_map_deltas(map);
3207                 res = isl_set_dim_residue_class(deltas, depth, &m, &r);
3208                 isl_set_free(deltas);
3209                 if (res < 0)
3210                         break;
3211
3212                 if (i == 0)
3213                         isl_int_set(gcd, m);
3214                 else
3215                         isl_int_gcd(gcd, gcd, m);
3216                 if (isl_int_is_one(gcd))
3217                         break;
3218                 v = isl_vec_set_element(v, i, r);
3219
3220                 res = isl_set_plain_is_fixed(domain[order[i]].set,
3221                                                 isl_dim_set, depth, NULL);
3222                 if (res < 0)
3223                         break;
3224                 if (res)
3225                         continue;
3226
3227                 if (fixed && i > base) {
3228                         isl_vec_get_element(v, base, &m);
3229                         if (isl_int_ne(m, r))
3230                                 fixed = 0;
3231                 }
3232         }
3233
3234         if (res < 0) {
3235                 isl_ast_build_free(build);
3236                 list = NULL;
3237         } else if (i < n || fixed) {
3238                 list = generate_shifted_component_from_list(domain,
3239                                                             order, n, build);
3240         } else {
3241                 list = generate_shift_component(domain, order, n, gcd, v,
3242                                                 build);
3243         }
3244
3245         isl_vec_free(v);
3246         isl_int_clear(gcd);
3247         isl_int_clear(r);
3248         isl_int_clear(m);
3249
3250         return list;
3251 }
3252
3253 /* Store both "map" itself and its domain in the
3254  * structure pointed to by *next and advance to the next array element.
3255  */
3256 static int extract_domain(__isl_take isl_map *map, void *user)
3257 {
3258         struct isl_set_map_pair **next = user;
3259
3260         (*next)->map = isl_map_copy(map);
3261         (*next)->set = isl_map_domain(map);
3262         (*next)++;
3263
3264         return 0;
3265 }
3266
3267 /* Internal data for any_scheduled_after.
3268  *
3269  * "depth" is the number of loops that have already been generated
3270  * "group_coscheduled" is a local copy of options->ast_build_group_coscheduled
3271  * "domain" is an array of set-map pairs corresponding to the different
3272  * iteration domains.  The set is the schedule domain, i.e., the domain
3273  * of the inverse schedule, while the map is the inverse schedule itself.
3274  */
3275 struct isl_any_scheduled_after_data {
3276         int depth;
3277         int group_coscheduled;
3278         struct isl_set_map_pair *domain;
3279 };
3280
3281 /* Is any element of domain "i" scheduled after any element of domain "j"
3282  * (for a common iteration of the first data->depth loops)?
3283  *
3284  * data->domain[i].set contains the domain of the inverse schedule
3285  * for domain "i", i.e., elements in the schedule domain.
3286  *
3287  * If data->group_coscheduled is set, then we also return 1 if there
3288  * is any pair of elements in the two domains that are scheduled together.
3289  */
3290 static int any_scheduled_after(int i, int j, void *user)
3291 {
3292         struct isl_any_scheduled_after_data *data = user;
3293         int dim = isl_set_dim(data->domain[i].set, isl_dim_set);
3294         int pos;
3295
3296         for (pos = data->depth; pos < dim; ++pos) {
3297                 int follows;
3298
3299                 follows = isl_set_follows_at(data->domain[i].set,
3300                                                 data->domain[j].set, pos);
3301
3302                 if (follows < -1)
3303                         return -1;
3304                 if (follows > 0)
3305                         return 1;
3306                 if (follows < 0)
3307                         return 0;
3308         }
3309
3310         return data->group_coscheduled;
3311 }
3312
3313 /* Look for independent components at the current depth and generate code
3314  * for each component separately.  The resulting lists of grafts are
3315  * merged in an attempt to combine grafts with identical guards.
3316  *
3317  * Code for two domains can be generated separately if all the elements
3318  * of one domain are scheduled before (or together with) all the elements
3319  * of the other domain.  We therefore consider the graph with as nodes
3320  * the domains and an edge between two nodes if any element of the first
3321  * node is scheduled after any element of the second node.
3322  * If the ast_build_group_coscheduled is set, then we also add an edge if
3323  * there is any pair of elements in the two domains that are scheduled
3324  * together.
3325  * Code is then generated (by generate_component)
3326  * for each of the strongly connected components in this graph
3327  * in their topological order.
3328  *
3329  * Since the test is performed on the domain of the inverse schedules of
3330  * the different domains, we precompute these domains and store
3331  * them in data.domain.
3332  */
3333 static __isl_give isl_ast_graft_list *generate_components(
3334         __isl_take isl_union_map *executed, __isl_take isl_ast_build *build)
3335 {
3336         int i;
3337         isl_ctx *ctx = isl_ast_build_get_ctx(build);
3338         int n = isl_union_map_n_map(executed);
3339         struct isl_any_scheduled_after_data data;
3340         struct isl_set_map_pair *next;
3341         struct isl_tarjan_graph *g = NULL;
3342         isl_ast_graft_list *list = NULL;
3343         int n_domain = 0;
3344
3345         data.domain = isl_calloc_array(ctx, struct isl_set_map_pair, n);
3346         if (!data.domain)
3347                 goto error;
3348         n_domain = n;
3349
3350         next = data.domain;
3351         if (isl_union_map_foreach_map(executed, &extract_domain, &next) < 0)
3352                 goto error;
3353
3354         if (!build)
3355                 goto error;
3356         data.depth = isl_ast_build_get_depth(build);
3357         data.group_coscheduled = isl_options_get_ast_build_group_coscheduled(ctx);
3358         g = isl_tarjan_graph_init(ctx, n, &any_scheduled_after, &data);
3359
3360         list = isl_ast_graft_list_alloc(ctx, 0);
3361
3362         i = 0;
3363         while (list && n) {
3364                 isl_ast_graft_list *list_c;
3365                 int first = i;
3366
3367                 if (g->order[i] == -1)
3368                         isl_die(ctx, isl_error_internal, "cannot happen",
3369                                 goto error);
3370                 ++i; --n;
3371                 while (g->order[i] != -1) {
3372                         ++i; --n;
3373                 }
3374
3375                 list_c = generate_component(data.domain,
3376                                             g->order + first, i - first,
3377                                             isl_ast_build_copy(build));
3378                 list = isl_ast_graft_list_merge(list, list_c, build);
3379
3380                 ++i;
3381         }
3382
3383         if (0)
3384 error:          list = isl_ast_graft_list_free(list);
3385         isl_tarjan_graph_free(g);
3386         for (i = 0; i < n_domain; ++i) {
3387                 isl_map_free(data.domain[i].map);
3388                 isl_set_free(data.domain[i].set);
3389         }
3390         free(data.domain);
3391         isl_union_map_free(executed);
3392         isl_ast_build_free(build);
3393
3394         return list;
3395 }
3396
3397 /* Generate code for the next level (and all inner levels).
3398  *
3399  * If "executed" is empty, i.e., no code needs to be generated,
3400  * then we return an empty list.
3401  *
3402  * If we have already generated code for all loop levels, then we pass
3403  * control to generate_inner_level.
3404  *
3405  * If "executed" lives in a single space, i.e., if code needs to be
3406  * generated for a single domain, then there can only be a single
3407  * component and we go directly to generate_shifted_component.
3408  * Otherwise, we call generate_components to detect the components
3409  * and to call generate_component on each of them separately.
3410  */
3411 static __isl_give isl_ast_graft_list *generate_next_level(
3412         __isl_take isl_union_map *executed, __isl_take isl_ast_build *build)
3413 {
3414         int depth;
3415
3416         if (!build || !executed)
3417                 goto error;
3418
3419         if (isl_union_map_is_empty(executed)) {
3420                 isl_ctx *ctx = isl_ast_build_get_ctx(build);
3421                 isl_union_map_free(executed);
3422                 isl_ast_build_free(build);
3423                 return isl_ast_graft_list_alloc(ctx, 0);
3424         }
3425
3426         depth = isl_ast_build_get_depth(build);
3427         if (depth >= isl_set_dim(build->domain, isl_dim_set))
3428                 return generate_inner_level(executed, build);
3429
3430         if (isl_union_map_n_map(executed) == 1)
3431                 return generate_shifted_component(executed, build);
3432
3433         return generate_components(executed, build);
3434 error:
3435         isl_union_map_free(executed);
3436         isl_ast_build_free(build);
3437         return NULL;
3438 }
3439
3440 /* Internal data structure used by isl_ast_build_ast_from_schedule.
3441  * internal, executed and build are the inputs to generate_code.
3442  * list collects the output.
3443  */
3444 struct isl_generate_code_data {
3445         int internal;
3446         isl_union_map *executed;
3447         isl_ast_build *build;
3448
3449         isl_ast_graft_list *list;
3450 };
3451
3452 /* Given an inverse schedule in terms of the external build schedule, i.e.,
3453  *
3454  *      [E -> S] -> D
3455  *
3456  * with E the external build schedule and S the additional schedule "space",
3457  * reformulate the inverse schedule in terms of the internal schedule domain,
3458  * i.e., return
3459  *
3460  *      [I -> S] -> D
3461  *
3462  * We first obtain a mapping
3463  *
3464  *      I -> E
3465  *
3466  * take the inverse and the product with S -> S, resulting in
3467  *
3468  *      [I -> S] -> [E -> S]
3469  *
3470  * Applying the map to the input produces the desired result.
3471  */
3472 static __isl_give isl_union_map *internal_executed(
3473         __isl_take isl_union_map *executed, __isl_keep isl_space *space,
3474         __isl_keep isl_ast_build *build)
3475 {
3476         isl_map *id, *proj;
3477
3478         proj = isl_ast_build_get_schedule_map(build);
3479         proj = isl_map_reverse(proj);
3480         space = isl_space_map_from_set(isl_space_copy(space));
3481         id = isl_map_identity(space);
3482         proj = isl_map_product(proj, id);
3483         executed = isl_union_map_apply_domain(executed,
3484                                                 isl_union_map_from_map(proj));
3485         return executed;
3486 }
3487
3488 /* Generate an AST that visits the elements in the range of data->executed
3489  * in the relative order specified by the corresponding image element(s)
3490  * for those image elements that belong to "set".
3491  * Add the result to data->list.
3492  *
3493  * The caller ensures that "set" is a universe domain.
3494  * "space" is the space of the additional part of the schedule.
3495  * It is equal to the space of "set" if build->domain is parametric.
3496  * Otherwise, it is equal to the range of the wrapped space of "set".
3497  *
3498  * If the build space is not parametric and if isl_ast_build_ast_from_schedule
3499  * was called from an outside user (data->internal not set), then
3500  * the (inverse) schedule refers to the external build domain and needs to
3501  * be transformed to refer to the internal build domain.
3502  *
3503  * The build is extended to include the additional part of the schedule.
3504  * If the original build space was not parametric, then the options
3505  * in data->build refer only to the additional part of the schedule
3506  * and they need to be adjusted to refer to the complete AST build
3507  * domain.
3508  *
3509  * After having adjusted inverse schedule and build, we start generating
3510  * code with the outer loop of the current code generation
3511  * in generate_next_level.
3512  *
3513  * If the original build space was not parametric, we undo the embedding
3514  * on the resulting isl_ast_node_list so that it can be used within
3515  * the outer AST build.
3516  */
3517 static int generate_code_in_space(struct isl_generate_code_data *data,
3518         __isl_take isl_set *set, __isl_take isl_space *space)
3519 {
3520         isl_union_map *executed;
3521         isl_ast_build *build;
3522         isl_ast_graft_list *list;
3523         int embed;
3524
3525         executed = isl_union_map_copy(data->executed);
3526         executed = isl_union_map_intersect_domain(executed,
3527                                                  isl_union_set_from_set(set));
3528
3529         embed = !isl_set_is_params(data->build->domain);
3530         if (embed && !data->internal)
3531                 executed = internal_executed(executed, space, data->build);
3532
3533         build = isl_ast_build_copy(data->build);
3534         build = isl_ast_build_product(build, space);
3535
3536         list = generate_next_level(executed, build);
3537
3538         list = isl_ast_graft_list_unembed(list, embed);
3539
3540         data->list = isl_ast_graft_list_concat(data->list, list);
3541
3542         return 0;
3543 }
3544
3545 /* Generate an AST that visits the elements in the range of data->executed
3546  * in the relative order specified by the corresponding domain element(s)
3547  * for those domain elements that belong to "set".
3548  * Add the result to data->list.
3549  *
3550  * The caller ensures that "set" is a universe domain.
3551  *
3552  * If the build space S is not parametric, then the space of "set"
3553  * need to be a wrapped relation with S as domain.  That is, it needs
3554  * to be of the form
3555  *
3556  *      [S -> T]
3557  *
3558  * Check this property and pass control to generate_code_in_space
3559  * passing along T.
3560  * If the build space is not parametric, then T is the space of "set".
3561  */
3562 static int generate_code_set(__isl_take isl_set *set, void *user)
3563 {
3564         struct isl_generate_code_data *data = user;
3565         isl_space *space, *build_space;
3566         int is_domain;
3567
3568         space = isl_set_get_space(set);
3569
3570         if (isl_set_is_params(data->build->domain))
3571                 return generate_code_in_space(data, set, space);
3572
3573         build_space = isl_ast_build_get_space(data->build, data->internal);
3574         space = isl_space_unwrap(space);
3575         is_domain = isl_space_is_domain(build_space, space);
3576         isl_space_free(build_space);
3577         space = isl_space_range(space);
3578
3579         if (is_domain < 0)
3580                 goto error;
3581         if (!is_domain)
3582                 isl_die(isl_set_get_ctx(set), isl_error_invalid,
3583                         "invalid nested schedule space", goto error);
3584
3585         return generate_code_in_space(data, set, space);
3586 error:
3587         isl_set_free(set);
3588         isl_space_free(space);
3589         return -1;
3590 }
3591
3592 /* Generate an AST that visits the elements in the range of "executed"
3593  * in the relative order specified by the corresponding domain element(s).
3594  *
3595  * "build" is an isl_ast_build that has either been constructed by
3596  * isl_ast_build_from_context or passed to a callback set by
3597  * isl_ast_build_set_create_leaf.
3598  * In the first case, the space of the isl_ast_build is typically
3599  * a parametric space, although this is currently not enforced.
3600  * In the second case, the space is never a parametric space.
3601  * If the space S is not parametric, then the domain space(s) of "executed"
3602  * need to be wrapped relations with S as domain.
3603  *
3604  * If the domain of "executed" consists of several spaces, then an AST
3605  * is generated for each of them (in arbitrary order) and the results
3606  * are concatenated.
3607  *
3608  * If "internal" is set, then the domain "S" above refers to the internal
3609  * schedule domain representation.  Otherwise, it refers to the external
3610  * representation, as returned by isl_ast_build_get_schedule_space.
3611  *
3612  * We essentially run over all the spaces in the domain of "executed"
3613  * and call generate_code_set on each of them.
3614  */
3615 static __isl_give isl_ast_graft_list *generate_code(
3616         __isl_take isl_union_map *executed, __isl_take isl_ast_build *build,
3617         int internal)
3618 {
3619         isl_ctx *ctx;
3620         struct isl_generate_code_data data = { 0 };
3621         isl_space *space;
3622         isl_union_set *schedule_domain;
3623         isl_union_map *universe;
3624
3625         if (!build)
3626                 goto error;
3627         space = isl_ast_build_get_space(build, 1);
3628         space = isl_space_align_params(space,
3629                                     isl_union_map_get_space(executed));
3630         space = isl_space_align_params(space,
3631                                     isl_union_map_get_space(build->options));
3632         build = isl_ast_build_align_params(build, isl_space_copy(space));
3633         executed = isl_union_map_align_params(executed, space);
3634         if (!executed || !build)
3635                 goto error;
3636
3637         ctx = isl_ast_build_get_ctx(build);
3638
3639         data.internal = internal;
3640         data.executed = executed;
3641         data.build = build;
3642         data.list = isl_ast_graft_list_alloc(ctx, 0);
3643
3644         universe = isl_union_map_universe(isl_union_map_copy(executed));
3645         schedule_domain = isl_union_map_domain(universe);
3646         if (isl_union_set_foreach_set(schedule_domain, &generate_code_set,
3647                                         &data) < 0)
3648                 data.list = isl_ast_graft_list_free(data.list);
3649
3650         isl_union_set_free(schedule_domain);
3651         isl_union_map_free(executed);
3652
3653         isl_ast_build_free(build);
3654         return data.list;
3655 error:
3656         isl_union_map_free(executed);
3657         isl_ast_build_free(build);
3658         return NULL;
3659 }
3660
3661 /* Generate an AST that visits the elements in the domain of "schedule"
3662  * in the relative order specified by the corresponding image element(s).
3663  *
3664  * "build" is an isl_ast_build that has either been constructed by
3665  * isl_ast_build_from_context or passed to a callback set by
3666  * isl_ast_build_set_create_leaf.
3667  * In the first case, the space of the isl_ast_build is typically
3668  * a parametric space, although this is currently not enforced.
3669  * In the second case, the space is never a parametric space.
3670  * If the space S is not parametric, then the range space(s) of "schedule"
3671  * need to be wrapped relations with S as domain.
3672  *
3673  * If the range of "schedule" consists of several spaces, then an AST
3674  * is generated for each of them (in arbitrary order) and the results
3675  * are concatenated.
3676  *
3677  * We first initialize the local copies of the relevant options.
3678  * We do this here rather than when the isl_ast_build is created
3679  * because the options may have changed between the construction
3680  * of the isl_ast_build and the call to isl_generate_code.
3681  *
3682  * The main computation is performed on an inverse schedule (with
3683  * the schedule domain in the domain and the elements to be executed
3684  * in the range) called "executed".
3685  */
3686 __isl_give isl_ast_node *isl_ast_build_ast_from_schedule(
3687         __isl_keep isl_ast_build *build, __isl_take isl_union_map *schedule)
3688 {
3689         isl_ast_graft_list *list;
3690         isl_ast_node *node;
3691         isl_union_map *executed;
3692
3693         build = isl_ast_build_copy(build);
3694         build = isl_ast_build_set_single_valued(build, 0);
3695         executed = isl_union_map_reverse(schedule);
3696         list = generate_code(executed, isl_ast_build_copy(build), 0);
3697         node = isl_ast_node_from_graft_list(list, build);
3698         isl_ast_build_free(build);
3699
3700         return node;
3701 }