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