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