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