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