1 //===------ ISLTools.cpp ----------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Tools, utilities, helpers and extensions useful in conjunction with the
11 // Integer Set Library (isl).
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "polly/Support/ISLTools.h"
16 #include "llvm/ADT/StringRef.h"
17 
18 using namespace polly;
19 
20 namespace {
21 /// Create a map that shifts one dimension by an offset.
22 ///
23 /// Example:
24 /// makeShiftDimAff({ [i0, i1] -> [o0, o1] }, 1, -2)
25 ///   = { [i0, i1] -> [i0, i1 - 1] }
26 ///
27 /// @param Space  The map space of the result. Must have equal number of in- and
28 ///               out-dimensions.
29 /// @param Pos    Position to shift.
30 /// @param Amount Value added to the shifted dimension.
31 ///
32 /// @return An isl_multi_aff for the map with this shifted dimension.
33 isl::multi_aff makeShiftDimAff(isl::space Space, int Pos, int Amount) {
34   auto Identity = give(isl_multi_aff_identity(Space.take()));
35   if (Amount == 0)
36     return Identity;
37   auto ShiftAff = give(isl_multi_aff_get_aff(Identity.keep(), Pos));
38   ShiftAff = give(isl_aff_set_constant_si(ShiftAff.take(), Amount));
39   return give(isl_multi_aff_set_aff(Identity.take(), Pos, ShiftAff.take()));
40 }
41 
42 /// Construct a map that swaps two nested tuples.
43 ///
44 /// @param FromSpace1 { Space1[] }
45 /// @param FromSpace2 { Space2[] }
46 ///
47 /// @return { [Space1[] -> Space2[]] -> [Space2[] -> Space1[]] }
48 isl::basic_map makeTupleSwapBasicMap(isl::space FromSpace1,
49                                      isl::space FromSpace2) {
50   assert(isl_space_is_set(FromSpace1.keep()) != isl_bool_false);
51   assert(isl_space_is_set(FromSpace2.keep()) != isl_bool_false);
52 
53   auto Dims1 = isl_space_dim(FromSpace1.keep(), isl_dim_set);
54   auto Dims2 = isl_space_dim(FromSpace2.keep(), isl_dim_set);
55   auto FromSpace = give(isl_space_wrap(isl_space_map_from_domain_and_range(
56       FromSpace1.copy(), FromSpace2.copy())));
57   auto ToSpace = give(isl_space_wrap(isl_space_map_from_domain_and_range(
58       FromSpace2.take(), FromSpace1.take())));
59   auto MapSpace = give(
60       isl_space_map_from_domain_and_range(FromSpace.take(), ToSpace.take()));
61 
62   auto Result = give(isl_basic_map_universe(MapSpace.take()));
63   for (auto i = Dims1 - Dims1; i < Dims1; i += 1) {
64     Result = give(isl_basic_map_equate(Result.take(), isl_dim_in, i,
65                                        isl_dim_out, Dims2 + i));
66   }
67   for (auto i = Dims2 - Dims2; i < Dims2; i += 1) {
68     Result = give(isl_basic_map_equate(Result.take(), isl_dim_in, Dims1 + i,
69                                        isl_dim_out, i));
70   }
71 
72   return Result;
73 }
74 
75 /// Like makeTupleSwapBasicMap(isl::space,isl::space), but returns
76 /// an isl_map.
77 isl::map makeTupleSwapMap(isl::space FromSpace1, isl::space FromSpace2) {
78   auto BMapResult =
79       makeTupleSwapBasicMap(std::move(FromSpace1), std::move(FromSpace2));
80   return give(isl_map_from_basic_map(BMapResult.take()));
81 }
82 } // anonymous namespace
83 
84 isl::map polly::beforeScatter(isl::map Map, bool Strict) {
85   auto RangeSpace = give(isl_space_range(isl_map_get_space(Map.keep())));
86   auto ScatterRel = give(Strict ? isl_map_lex_gt(RangeSpace.take())
87                                 : isl_map_lex_ge(RangeSpace.take()));
88   return give(isl_map_apply_range(Map.take(), ScatterRel.take()));
89 }
90 
91 isl::union_map polly::beforeScatter(isl::union_map UMap, bool Strict) {
92   auto Result = give(isl_union_map_empty(isl_union_map_get_space(UMap.keep())));
93   UMap.foreach_map([=, &Result](isl::map Map) -> isl::stat {
94     auto After = beforeScatter(Map, Strict);
95     Result = give(isl_union_map_add_map(Result.take(), After.take()));
96     return isl::stat::ok;
97   });
98   return Result;
99 }
100 
101 isl::map polly::afterScatter(isl::map Map, bool Strict) {
102   auto RangeSpace = give(isl_space_range(isl_map_get_space(Map.keep())));
103   auto ScatterRel = give(Strict ? isl_map_lex_lt(RangeSpace.take())
104                                 : isl_map_lex_le(RangeSpace.take()));
105   return give(isl_map_apply_range(Map.take(), ScatterRel.take()));
106 }
107 
108 isl::union_map polly::afterScatter(const isl::union_map &UMap, bool Strict) {
109   auto Result = give(isl_union_map_empty(isl_union_map_get_space(UMap.keep())));
110   UMap.foreach_map([=, &Result](isl::map Map) -> isl::stat {
111     auto After = afterScatter(Map, Strict);
112     Result = give(isl_union_map_add_map(Result.take(), After.take()));
113     return isl::stat::ok;
114   });
115   return Result;
116 }
117 
118 isl::map polly::betweenScatter(isl::map From, isl::map To, bool InclFrom,
119                                bool InclTo) {
120   auto AfterFrom = afterScatter(From, !InclFrom);
121   auto BeforeTo = beforeScatter(To, !InclTo);
122 
123   return give(isl_map_intersect(AfterFrom.take(), BeforeTo.take()));
124 }
125 
126 isl::union_map polly::betweenScatter(isl::union_map From, isl::union_map To,
127                                      bool InclFrom, bool InclTo) {
128   auto AfterFrom = afterScatter(From, !InclFrom);
129   auto BeforeTo = beforeScatter(To, !InclTo);
130 
131   return give(isl_union_map_intersect(AfterFrom.take(), BeforeTo.take()));
132 }
133 
134 isl::map polly::singleton(isl::union_map UMap, isl::space ExpectedSpace) {
135   if (!UMap)
136     return nullptr;
137 
138   if (isl_union_map_n_map(UMap.keep()) == 0)
139     return isl::map::empty(ExpectedSpace);
140 
141   isl::map Result = isl::map::from_union_map(UMap);
142   assert(!Result || Result.get_space().has_equal_tuples(ExpectedSpace));
143 
144   return Result;
145 }
146 
147 isl::set polly::singleton(isl::union_set USet, isl::space ExpectedSpace) {
148   if (!USet)
149     return nullptr;
150 
151   if (isl_union_set_n_set(USet.keep()) == 0)
152     return isl::set::empty(ExpectedSpace);
153 
154   isl::set Result(USet);
155   assert(!Result || Result.get_space().has_equal_tuples(ExpectedSpace));
156 
157   return Result;
158 }
159 
160 unsigned polly::getNumScatterDims(const isl::union_map &Schedule) {
161   unsigned Dims = 0;
162   Schedule.foreach_map([&Dims](isl::map Map) -> isl::stat {
163     Dims = std::max(Dims, isl_map_dim(Map.keep(), isl_dim_out));
164     return isl::stat::ok;
165   });
166   return Dims;
167 }
168 
169 isl::space polly::getScatterSpace(const isl::union_map &Schedule) {
170   if (!Schedule)
171     return nullptr;
172   auto Dims = getNumScatterDims(Schedule);
173   auto ScatterSpace =
174       give(isl_space_set_from_params(isl_union_map_get_space(Schedule.keep())));
175   return give(isl_space_add_dims(ScatterSpace.take(), isl_dim_set, Dims));
176 }
177 
178 isl::union_map polly::makeIdentityMap(const isl::union_set &USet,
179                                       bool RestrictDomain) {
180   auto Result = give(isl_union_map_empty(isl_union_set_get_space(USet.keep())));
181   USet.foreach_set([=, &Result](isl::set Set) -> isl::stat {
182     auto IdentityMap = give(isl_map_identity(
183         isl_space_map_from_set(isl_set_get_space(Set.keep()))));
184     if (RestrictDomain)
185       IdentityMap =
186           give(isl_map_intersect_domain(IdentityMap.take(), Set.take()));
187     Result = give(isl_union_map_add_map(Result.take(), IdentityMap.take()));
188     return isl::stat::ok;
189   });
190   return Result;
191 }
192 
193 isl::map polly::reverseDomain(isl::map Map) {
194   auto DomSpace =
195       give(isl_space_unwrap(isl_space_domain(isl_map_get_space(Map.keep()))));
196   auto Space1 = give(isl_space_domain(DomSpace.copy()));
197   auto Space2 = give(isl_space_range(DomSpace.take()));
198   auto Swap = makeTupleSwapMap(std::move(Space1), std::move(Space2));
199   return give(isl_map_apply_domain(Map.take(), Swap.take()));
200 }
201 
202 isl::union_map polly::reverseDomain(const isl::union_map &UMap) {
203   auto Result = give(isl_union_map_empty(isl_union_map_get_space(UMap.keep())));
204   UMap.foreach_map([=, &Result](isl::map Map) -> isl::stat {
205     auto Reversed = reverseDomain(std::move(Map));
206     Result = give(isl_union_map_add_map(Result.take(), Reversed.take()));
207     return isl::stat::ok;
208   });
209   return Result;
210 }
211 
212 isl::set polly::shiftDim(isl::set Set, int Pos, int Amount) {
213   int NumDims = isl_set_dim(Set.keep(), isl_dim_set);
214   if (Pos < 0)
215     Pos = NumDims + Pos;
216   assert(Pos < NumDims && "Dimension index must be in range");
217   auto Space = give(isl_set_get_space(Set.keep()));
218   Space = give(isl_space_map_from_domain_and_range(Space.copy(), Space.copy()));
219   auto Translator = makeShiftDimAff(std::move(Space), Pos, Amount);
220   auto TranslatorMap = give(isl_map_from_multi_aff(Translator.take()));
221   return give(isl_set_apply(Set.take(), TranslatorMap.take()));
222 }
223 
224 isl::union_set polly::shiftDim(isl::union_set USet, int Pos, int Amount) {
225   auto Result = give(isl_union_set_empty(isl_union_set_get_space(USet.keep())));
226   USet.foreach_set([=, &Result](isl::set Set) -> isl::stat {
227     auto Shifted = shiftDim(Set, Pos, Amount);
228     Result = give(isl_union_set_add_set(Result.take(), Shifted.take()));
229     return isl::stat::ok;
230   });
231   return Result;
232 }
233 
234 isl::map polly::shiftDim(isl::map Map, isl::dim Dim, int Pos, int Amount) {
235   int NumDims = Map.dim(Dim);
236   if (Pos < 0)
237     Pos = NumDims + Pos;
238   assert(Pos < NumDims && "Dimension index must be in range");
239   auto Space = give(isl_map_get_space(Map.keep()));
240   switch (Dim) {
241   case isl::dim::in:
242     Space = std::move(Space).domain();
243     break;
244   case isl::dim::out:
245     Space = give(isl_space_range(Space.take()));
246     break;
247   default:
248     llvm_unreachable("Unsupported value for 'dim'");
249   }
250   Space = give(isl_space_map_from_domain_and_range(Space.copy(), Space.copy()));
251   auto Translator = makeShiftDimAff(std::move(Space), Pos, Amount);
252   auto TranslatorMap = give(isl_map_from_multi_aff(Translator.take()));
253   switch (Dim) {
254   case isl::dim::in:
255     return Map.apply_domain(TranslatorMap);
256   case isl::dim::out:
257     return Map.apply_range(TranslatorMap);
258   default:
259     llvm_unreachable("Unsupported value for 'dim'");
260   }
261 }
262 
263 isl::union_map polly::shiftDim(isl::union_map UMap, isl::dim Dim, int Pos,
264                                int Amount) {
265   auto Result = isl::union_map::empty(UMap.get_space());
266 
267   UMap.foreach_map([=, &Result](isl::map Map) -> isl::stat {
268     auto Shifted = shiftDim(Map, Dim, Pos, Amount);
269     Result = std::move(Result).add_map(Shifted);
270     return isl::stat::ok;
271   });
272   return Result;
273 }
274 
275 void polly::simplify(isl::set &Set) {
276   Set = give(isl_set_compute_divs(Set.take()));
277   Set = give(isl_set_detect_equalities(Set.take()));
278   Set = give(isl_set_coalesce(Set.take()));
279 }
280 
281 void polly::simplify(isl::union_set &USet) {
282   USet = give(isl_union_set_compute_divs(USet.take()));
283   USet = give(isl_union_set_detect_equalities(USet.take()));
284   USet = give(isl_union_set_coalesce(USet.take()));
285 }
286 
287 void polly::simplify(isl::map &Map) {
288   Map = give(isl_map_compute_divs(Map.take()));
289   Map = give(isl_map_detect_equalities(Map.take()));
290   Map = give(isl_map_coalesce(Map.take()));
291 }
292 
293 void polly::simplify(isl::union_map &UMap) {
294   UMap = give(isl_union_map_compute_divs(UMap.take()));
295   UMap = give(isl_union_map_detect_equalities(UMap.take()));
296   UMap = give(isl_union_map_coalesce(UMap.take()));
297 }
298 
299 isl::union_map polly::computeReachingWrite(isl::union_map Schedule,
300                                            isl::union_map Writes, bool Reverse,
301                                            bool InclPrevDef, bool InclNextDef) {
302 
303   // { Scatter[] }
304   isl::space ScatterSpace = getScatterSpace(Schedule);
305 
306   // { ScatterRead[] -> ScatterWrite[] }
307   isl::map Relation;
308   if (Reverse)
309     Relation = InclPrevDef ? isl::map::lex_lt(ScatterSpace)
310                            : isl::map::lex_le(ScatterSpace);
311   else
312     Relation = InclNextDef ? isl::map::lex_gt(ScatterSpace)
313                            : isl::map::lex_ge(ScatterSpace);
314 
315   // { ScatterWrite[] -> [ScatterRead[] -> ScatterWrite[]] }
316   isl::map RelationMap = Relation.range_map().reverse();
317 
318   // { Element[] -> ScatterWrite[] }
319   isl::union_map WriteAction = Schedule.apply_domain(Writes);
320 
321   // { ScatterWrite[] -> Element[] }
322   isl::union_map WriteActionRev = WriteAction.reverse();
323 
324   // { Element[] -> [ScatterUse[] -> ScatterWrite[]] }
325   isl::union_map DefSchedRelation =
326       isl::union_map(RelationMap).apply_domain(WriteActionRev);
327 
328   // For each element, at every point in time, map to the times of previous
329   // definitions. { [Element[] -> ScatterRead[]] -> ScatterWrite[] }
330   isl::union_map ReachableWrites = DefSchedRelation.uncurry();
331   if (Reverse)
332     ReachableWrites = ReachableWrites.lexmin();
333   else
334     ReachableWrites = ReachableWrites.lexmax();
335 
336   // { [Element[] -> ScatterWrite[]] -> ScatterWrite[] }
337   isl::union_map SelfUse = WriteAction.range_map();
338 
339   if (InclPrevDef && InclNextDef) {
340     // Add the Def itself to the solution.
341     ReachableWrites = ReachableWrites.unite(SelfUse).coalesce();
342   } else if (!InclPrevDef && !InclNextDef) {
343     // Remove Def itself from the solution.
344     ReachableWrites = ReachableWrites.subtract(SelfUse);
345   }
346 
347   // { [Element[] -> ScatterRead[]] -> Domain[] }
348   return ReachableWrites.apply_range(Schedule.reverse());
349 }
350 
351 isl::union_map
352 polly::computeArrayUnused(isl::union_map Schedule, isl::union_map Writes,
353                           isl::union_map Reads, bool ReadEltInSameInst,
354                           bool IncludeLastRead, bool IncludeWrite) {
355   // { Element[] -> Scatter[] }
356   auto ReadActions =
357       give(isl_union_map_apply_domain(Schedule.copy(), Reads.take()));
358   auto WriteActions =
359       give(isl_union_map_apply_domain(Schedule.copy(), Writes.copy()));
360 
361   // { [Element[] -> DomainWrite[]] -> Scatter[] }
362   auto EltDomWrites = give(isl_union_map_apply_range(
363       isl_union_map_range_map(isl_union_map_reverse(Writes.copy())),
364       Schedule.copy()));
365 
366   // { [Element[] -> Scatter[]] -> DomainWrite[] }
367   auto ReachingOverwrite = computeReachingWrite(
368       Schedule, Writes, true, ReadEltInSameInst, !ReadEltInSameInst);
369 
370   // { [Element[] -> Scatter[]] -> DomainWrite[] }
371   auto ReadsOverwritten = give(isl_union_map_intersect_domain(
372       ReachingOverwrite.take(), isl_union_map_wrap(ReadActions.take())));
373 
374   // { [Element[] -> DomainWrite[]] -> Scatter[] }
375   auto ReadsOverwrittenRotated = give(isl_union_map_reverse(
376       isl_union_map_curry(reverseDomain(ReadsOverwritten).take())));
377   auto LastOverwrittenRead =
378       give(isl_union_map_lexmax(ReadsOverwrittenRotated.copy()));
379 
380   // { [Element[] -> DomainWrite[]] -> Scatter[] }
381   auto BetweenLastReadOverwrite = betweenScatter(
382       LastOverwrittenRead, EltDomWrites, IncludeLastRead, IncludeWrite);
383 
384   // { [Element[] -> Scatter[]] -> DomainWrite[] }
385   isl::union_map ReachingOverwriteZone = computeReachingWrite(
386       Schedule, Writes, true, IncludeLastRead, IncludeWrite);
387 
388   // { [Element[] -> DomainWrite[]] -> Scatter[] }
389   isl::union_map ReachingOverwriteRotated =
390       reverseDomain(ReachingOverwriteZone).curry().reverse();
391 
392   // { [Element[] -> DomainWrite[]] -> Scatter[] }
393   isl::union_map WritesWithoutReads = ReachingOverwriteRotated.subtract_domain(
394       ReadsOverwrittenRotated.domain());
395 
396   return BetweenLastReadOverwrite.unite(WritesWithoutReads)
397       .domain_factor_domain();
398 }
399 
400 isl::union_set polly::convertZoneToTimepoints(isl::union_set Zone,
401                                               bool InclStart, bool InclEnd) {
402   if (!InclStart && InclEnd)
403     return Zone;
404 
405   auto ShiftedZone = shiftDim(Zone, -1, -1);
406   if (InclStart && !InclEnd)
407     return ShiftedZone;
408   else if (!InclStart && !InclEnd)
409     return give(isl_union_set_intersect(Zone.take(), ShiftedZone.take()));
410 
411   assert(InclStart && InclEnd);
412   return give(isl_union_set_union(Zone.take(), ShiftedZone.take()));
413 }
414 
415 isl::union_map polly::convertZoneToTimepoints(isl::union_map Zone, isl::dim Dim,
416                                               bool InclStart, bool InclEnd) {
417   if (!InclStart && InclEnd)
418     return Zone;
419 
420   auto ShiftedZone = shiftDim(Zone, Dim, -1, -1);
421   if (InclStart && !InclEnd)
422     return ShiftedZone;
423   else if (!InclStart && !InclEnd)
424     return give(isl_union_map_intersect(Zone.take(), ShiftedZone.take()));
425 
426   assert(InclStart && InclEnd);
427   return give(isl_union_map_union(Zone.take(), ShiftedZone.take()));
428 }
429 
430 isl::map polly::convertZoneToTimepoints(isl::map Zone, isl::dim Dim,
431                                         bool InclStart, bool InclEnd) {
432   if (!InclStart && InclEnd)
433     return Zone;
434 
435   auto ShiftedZone = shiftDim(Zone, Dim, -1, -1);
436   if (InclStart && !InclEnd)
437     return ShiftedZone;
438   else if (!InclStart && !InclEnd)
439     return give(isl_map_intersect(Zone.take(), ShiftedZone.take()));
440 
441   assert(InclStart && InclEnd);
442   return give(isl_map_union(Zone.take(), ShiftedZone.take()));
443 }
444 
445 isl::map polly::distributeDomain(isl::map Map) {
446   // Note that we cannot take Map apart into { Domain[] -> Range1[] } and {
447   // Domain[] -> Range2[] } and combine again. We would loose any relation
448   // between Range1[] and Range2[] that is not also a constraint to Domain[].
449 
450   auto Space = give(isl_map_get_space(Map.keep()));
451   auto DomainSpace = give(isl_space_domain(Space.copy()));
452   auto DomainDims = isl_space_dim(DomainSpace.keep(), isl_dim_set);
453   auto RangeSpace = give(isl_space_unwrap(isl_space_range(Space.copy())));
454   auto Range1Space = give(isl_space_domain(RangeSpace.copy()));
455   auto Range1Dims = isl_space_dim(Range1Space.keep(), isl_dim_set);
456   auto Range2Space = give(isl_space_range(RangeSpace.copy()));
457   auto Range2Dims = isl_space_dim(Range2Space.keep(), isl_dim_set);
458 
459   auto OutputSpace = give(isl_space_map_from_domain_and_range(
460       isl_space_wrap(isl_space_map_from_domain_and_range(DomainSpace.copy(),
461                                                          Range1Space.copy())),
462       isl_space_wrap(isl_space_map_from_domain_and_range(DomainSpace.copy(),
463                                                          Range2Space.copy()))));
464 
465   auto Translator =
466       give(isl_basic_map_universe(isl_space_map_from_domain_and_range(
467           isl_space_wrap(Space.copy()), isl_space_wrap(OutputSpace.copy()))));
468 
469   for (unsigned i = 0; i < DomainDims; i += 1) {
470     Translator = give(
471         isl_basic_map_equate(Translator.take(), isl_dim_in, i, isl_dim_out, i));
472     Translator =
473         give(isl_basic_map_equate(Translator.take(), isl_dim_in, i, isl_dim_out,
474                                   DomainDims + Range1Dims + i));
475   }
476   for (unsigned i = 0; i < Range1Dims; i += 1) {
477     Translator =
478         give(isl_basic_map_equate(Translator.take(), isl_dim_in, DomainDims + i,
479                                   isl_dim_out, DomainDims + i));
480   }
481   for (unsigned i = 0; i < Range2Dims; i += 1) {
482     Translator = give(isl_basic_map_equate(
483         Translator.take(), isl_dim_in, DomainDims + Range1Dims + i, isl_dim_out,
484         DomainDims + Range1Dims + DomainDims + i));
485   }
486 
487   return give(isl_set_unwrap(isl_set_apply(
488       isl_map_wrap(Map.copy()), isl_map_from_basic_map(Translator.copy()))));
489 }
490 
491 isl::union_map polly::distributeDomain(isl::union_map UMap) {
492   auto Result = give(isl_union_map_empty(isl_union_map_get_space(UMap.keep())));
493   isl::stat Success = UMap.foreach_map([=, &Result](isl::map Map) {
494     auto Distributed = distributeDomain(Map);
495     Result = give(isl_union_map_add_map(Result.take(), Distributed.copy()));
496     return isl::stat::ok;
497   });
498   if (Success != isl::stat::ok)
499     return {};
500   return Result;
501 }
502 
503 isl::union_map polly::liftDomains(isl::union_map UMap, isl::union_set Factor) {
504 
505   // { Factor[] -> Factor[] }
506   auto Factors = makeIdentityMap(std::move(Factor), true);
507 
508   return std::move(Factors).product(std::move(UMap));
509 }
510 
511 isl::union_map polly::applyDomainRange(isl::union_map UMap,
512                                        isl::union_map Func) {
513   // This implementation creates unnecessary cross products of the
514   // DomainDomain[] and Func. An alternative implementation could reverse
515   // domain+uncurry,apply Func to what now is the domain, then undo the
516   // preparing transformation. Another alternative implementation could create a
517   // translator map for each piece.
518 
519   // { DomainDomain[] }
520   auto DomainDomain = UMap.domain().unwrap().domain();
521 
522   // { [DomainDomain[] -> DomainRange[]] -> [DomainDomain[] -> NewDomainRange[]]
523   // }
524   auto LifetedFunc = liftDomains(std::move(Func), DomainDomain);
525 
526   return std::move(UMap).apply_domain(std::move(LifetedFunc));
527 }
528 
529 isl::map polly::intersectRange(isl::map Map, isl::union_set Range) {
530   isl::set RangeSet = Range.extract_set(Map.get_space().range());
531   return Map.intersect_range(RangeSet);
532 }
533 
534 isl::val polly::getConstant(isl::pw_aff PwAff, bool Max, bool Min) {
535   assert(!Max || !Min); // Cannot return min and max at the same time.
536   isl::val Result;
537   PwAff.foreach_piece([=, &Result](isl::set Set, isl::aff Aff) -> isl::stat {
538     if (Result && Result.is_nan())
539       return isl::stat::ok;
540 
541     // TODO: If Min/Max, we can also determine a minimum/maximum value if
542     // Set is constant-bounded.
543     if (!Aff.is_cst()) {
544       Result = isl::val::nan(Aff.get_ctx());
545       return isl::stat::error;
546     }
547 
548     isl::val ThisVal = Aff.get_constant_val();
549     if (!Result) {
550       Result = ThisVal;
551       return isl::stat::ok;
552     }
553 
554     if (Result.eq(ThisVal))
555       return isl::stat::ok;
556 
557     if (Max && ThisVal.gt(Result)) {
558       Result = ThisVal;
559       return isl::stat::ok;
560     }
561 
562     if (Min && ThisVal.lt(Result)) {
563       Result = ThisVal;
564       return isl::stat::ok;
565     }
566 
567     // Not compatible
568     Result = isl::val::nan(Aff.get_ctx());
569     return isl::stat::error;
570   });
571   return Result;
572 }
573 
574 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
575 static void foreachPoint(const isl::set &Set,
576                          const std::function<void(isl::point P)> &F) {
577   isl_set_foreach_point(
578       Set.keep(),
579       [](__isl_take isl_point *p, void *User) -> isl_stat {
580         auto &F = *static_cast<const std::function<void(isl::point)> *>(User);
581         F(give(p));
582         return isl_stat_ok;
583       },
584       const_cast<void *>(static_cast<const void *>(&F)));
585 }
586 
587 static void foreachPoint(isl::basic_set BSet,
588                          const std::function<void(isl::point P)> &F) {
589   foreachPoint(give(isl_set_from_basic_set(BSet.take())), F);
590 }
591 
592 /// Determine the sorting order of the sets @p A and @p B without considering
593 /// the space structure.
594 ///
595 /// Ordering is based on the lower bounds of the set's dimensions. First
596 /// dimensions are considered first.
597 static int flatCompare(const isl::basic_set &A, const isl::basic_set &B) {
598   int ALen = A.dim(isl::dim::set);
599   int BLen = B.dim(isl::dim::set);
600   int Len = std::min(ALen, BLen);
601 
602   for (int i = 0; i < Len; i += 1) {
603     isl::basic_set ADim =
604         A.project_out(isl::dim::param, 0, A.dim(isl::dim::param))
605             .project_out(isl::dim::set, i + 1, ALen - i - 1)
606             .project_out(isl::dim::set, 0, i);
607     isl::basic_set BDim =
608         B.project_out(isl::dim::param, 0, B.dim(isl::dim::param))
609             .project_out(isl::dim::set, i + 1, BLen - i - 1)
610             .project_out(isl::dim::set, 0, i);
611 
612     isl::basic_set AHull = isl::set(ADim).convex_hull();
613     isl::basic_set BHull = isl::set(BDim).convex_hull();
614 
615     bool ALowerBounded =
616         bool(isl::set(AHull).dim_has_any_lower_bound(isl::dim::set, 0));
617     bool BLowerBounded =
618         bool(isl::set(BHull).dim_has_any_lower_bound(isl::dim::set, 0));
619 
620     int BoundedCompare = BLowerBounded - ALowerBounded;
621     if (BoundedCompare != 0)
622       return BoundedCompare;
623 
624     if (!ALowerBounded || !BLowerBounded)
625       continue;
626 
627     isl::pw_aff AMin = isl::set(ADim).dim_min(0);
628     isl::pw_aff BMin = isl::set(BDim).dim_min(0);
629 
630     isl::val AMinVal = polly::getConstant(AMin, false, true);
631     isl::val BMinVal = polly::getConstant(BMin, false, true);
632 
633     int MinCompare = AMinVal.sub(BMinVal).sgn();
634     if (MinCompare != 0)
635       return MinCompare;
636   }
637 
638   // If all the dimensions' lower bounds are equal or incomparable, sort based
639   // on the number of dimensions.
640   return ALen - BLen;
641 }
642 
643 /// Compare the sets @p A and @p B according to their nested space structure. If
644 /// the structure is the same, sort using the dimension lower bounds.
645 static int recursiveCompare(const isl::basic_set &A, const isl::basic_set &B) {
646   isl::space ASpace = A.get_space();
647   isl::space BSpace = B.get_space();
648 
649   int WrappingCompare = bool(ASpace.is_wrapping()) - bool(BSpace.is_wrapping());
650   if (WrappingCompare != 0)
651     return WrappingCompare;
652 
653   if (ASpace.is_wrapping() && B.is_wrapping()) {
654     isl::basic_map AMap = A.unwrap();
655     isl::basic_map BMap = B.unwrap();
656 
657     int FirstResult = recursiveCompare(AMap.domain(), BMap.domain());
658     if (FirstResult != 0)
659       return FirstResult;
660 
661     return recursiveCompare(AMap.range(), BMap.range());
662   }
663 
664   std::string AName = ASpace.has_tuple_name(isl::dim::set)
665                           ? ASpace.get_tuple_name(isl::dim::set)
666                           : std::string();
667   std::string BName = BSpace.has_tuple_name(isl::dim::set)
668                           ? BSpace.get_tuple_name(isl::dim::set)
669                           : std::string();
670 
671   int NameCompare = AName.compare(BName);
672   if (NameCompare != 0)
673     return NameCompare;
674 
675   return flatCompare(A, B);
676 }
677 
678 /// Wrapper for recursiveCompare, convert a {-1,0,1} compare result to what
679 /// std::sort expects.
680 static bool orderComparer(const isl::basic_set &A, const isl::basic_set &B) {
681   return recursiveCompare(A, B) < 0;
682 }
683 
684 /// Print a string representation of @p USet to @p OS.
685 ///
686 /// The pieces of @p USet are printed in a sorted order. Spaces with equal or
687 /// similar nesting structure are printed together. Compared to isl's own
688 /// printing function the uses the structure itself as base of the sorting, not
689 /// a hash of it. It ensures that e.g. maps spaces with same domain structure
690 /// are printed together. Set pieces with same structure are printed in order of
691 /// their lower bounds.
692 ///
693 /// @param USet     Polyhedra to print.
694 /// @param OS       Target stream.
695 /// @param Simplify Whether to simplify the polyhedron before printing.
696 /// @param IsMap    Whether @p USet is a wrapped map. If true, sets are
697 ///                 unwrapped before printing to again appear as a map.
698 static void printSortedPolyhedra(isl::union_set USet, llvm::raw_ostream &OS,
699                                  bool Simplify, bool IsMap) {
700   if (!USet) {
701     OS << "<null>\n";
702     return;
703   }
704 
705   if (Simplify)
706     simplify(USet);
707 
708   // Get all the polyhedra.
709   std::vector<isl::basic_set> BSets;
710   USet.foreach_set([&BSets](isl::set Set) -> isl::stat {
711     Set.foreach_basic_set([&BSets](isl::basic_set BSet) -> isl::stat {
712       BSets.push_back(BSet);
713       return isl::stat::ok;
714     });
715     return isl::stat::ok;
716   });
717 
718   if (BSets.empty()) {
719     OS << "{\n}\n";
720     return;
721   }
722 
723   // Sort the polyhedra.
724   std::sort(BSets.begin(), BSets.end(), orderComparer);
725 
726   // Print the polyhedra.
727   bool First = true;
728   for (const isl::basic_set &BSet : BSets) {
729     std::string Str;
730     if (IsMap)
731       Str = isl::map(BSet.unwrap()).to_str();
732     else
733       Str = isl::set(BSet).to_str();
734     size_t OpenPos = Str.find_first_of('{');
735     assert(OpenPos != std::string::npos);
736     size_t ClosePos = Str.find_last_of('}');
737     assert(ClosePos != std::string::npos);
738 
739     if (First)
740       OS << llvm::StringRef(Str).substr(0, OpenPos + 1) << "\n ";
741     else
742       OS << ";\n ";
743 
744     OS << llvm::StringRef(Str).substr(OpenPos + 1, ClosePos - OpenPos - 2);
745     First = false;
746   }
747   assert(!First);
748   OS << "\n}\n";
749 }
750 
751 static void recursiveExpand(isl::basic_set BSet, int Dim, isl::set &Expanded) {
752   int Dims = BSet.dim(isl::dim::set);
753   if (Dim >= Dims) {
754     Expanded = Expanded.unite(BSet);
755     return;
756   }
757 
758   isl::basic_set DimOnly =
759       BSet.project_out(isl::dim::param, 0, BSet.dim(isl::dim::param))
760           .project_out(isl::dim::set, Dim + 1, Dims - Dim - 1)
761           .project_out(isl::dim::set, 0, Dim);
762   if (!DimOnly.is_bounded()) {
763     recursiveExpand(BSet, Dim + 1, Expanded);
764     return;
765   }
766 
767   foreachPoint(DimOnly, [&, Dim](isl::point P) {
768     isl::val Val = P.get_coordinate_val(isl::dim::set, 0);
769     isl::basic_set FixBSet = BSet.fix_val(isl::dim::set, Dim, Val);
770     recursiveExpand(FixBSet, Dim + 1, Expanded);
771   });
772 }
773 
774 /// Make each point of a set explicit.
775 ///
776 /// "Expanding" makes each point a set contains explicit. That is, the result is
777 /// a set of singleton polyhedra. Unbounded dimensions are not expanded.
778 ///
779 /// Example:
780 ///   { [i] : 0 <= i < 2 }
781 /// is expanded to:
782 ///   { [0]; [1] }
783 static isl::set expand(const isl::set &Set) {
784   isl::set Expanded = isl::set::empty(Set.get_space());
785   Set.foreach_basic_set([&](isl::basic_set BSet) -> isl::stat {
786     recursiveExpand(BSet, 0, Expanded);
787     return isl::stat::ok;
788   });
789   return Expanded;
790 }
791 
792 /// Expand all points of a union set explicit.
793 ///
794 /// @see expand(const isl::set)
795 static isl::union_set expand(const isl::union_set &USet) {
796   isl::union_set Expanded =
797       give(isl_union_set_empty(isl_union_set_get_space(USet.keep())));
798   USet.foreach_set([&](isl::set Set) -> isl::stat {
799     isl::set SetExpanded = expand(Set);
800     Expanded = Expanded.add_set(SetExpanded);
801     return isl::stat::ok;
802   });
803   return Expanded;
804 }
805 
806 LLVM_DUMP_METHOD void polly::dumpPw(const isl::set &Set) {
807   printSortedPolyhedra(Set, llvm::errs(), true, false);
808 }
809 
810 LLVM_DUMP_METHOD void polly::dumpPw(const isl::map &Map) {
811   printSortedPolyhedra(Map.wrap(), llvm::errs(), true, true);
812 }
813 
814 LLVM_DUMP_METHOD void polly::dumpPw(const isl::union_set &USet) {
815   printSortedPolyhedra(USet, llvm::errs(), true, false);
816 }
817 
818 LLVM_DUMP_METHOD void polly::dumpPw(const isl::union_map &UMap) {
819   printSortedPolyhedra(UMap.wrap(), llvm::errs(), true, true);
820 }
821 
822 LLVM_DUMP_METHOD void polly::dumpPw(__isl_keep isl_set *Set) {
823   dumpPw(isl::manage(isl_set_copy(Set)));
824 }
825 
826 LLVM_DUMP_METHOD void polly::dumpPw(__isl_keep isl_map *Map) {
827   dumpPw(isl::manage(isl_map_copy(Map)));
828 }
829 
830 LLVM_DUMP_METHOD void polly::dumpPw(__isl_keep isl_union_set *USet) {
831   dumpPw(isl::manage(isl_union_set_copy(USet)));
832 }
833 
834 LLVM_DUMP_METHOD void polly::dumpPw(__isl_keep isl_union_map *UMap) {
835   dumpPw(isl::manage(isl_union_map_copy(UMap)));
836 }
837 
838 LLVM_DUMP_METHOD void polly::dumpExpanded(const isl::set &Set) {
839   printSortedPolyhedra(expand(Set), llvm::errs(), false, false);
840 }
841 
842 LLVM_DUMP_METHOD void polly::dumpExpanded(const isl::map &Map) {
843   printSortedPolyhedra(expand(Map.wrap()), llvm::errs(), false, true);
844 }
845 
846 LLVM_DUMP_METHOD void polly::dumpExpanded(const isl::union_set &USet) {
847   printSortedPolyhedra(expand(USet), llvm::errs(), false, false);
848 }
849 
850 LLVM_DUMP_METHOD void polly::dumpExpanded(const isl::union_map &UMap) {
851   printSortedPolyhedra(expand(UMap.wrap()), llvm::errs(), false, true);
852 }
853 
854 LLVM_DUMP_METHOD void polly::dumpExpanded(__isl_keep isl_set *Set) {
855   dumpExpanded(isl::manage(isl_set_copy(Set)));
856 }
857 
858 LLVM_DUMP_METHOD void polly::dumpExpanded(__isl_keep isl_map *Map) {
859   dumpExpanded(isl::manage(isl_map_copy(Map)));
860 }
861 
862 LLVM_DUMP_METHOD void polly::dumpExpanded(__isl_keep isl_union_set *USet) {
863   dumpExpanded(isl::manage(isl_union_set_copy(USet)));
864 }
865 
866 LLVM_DUMP_METHOD void polly::dumpExpanded(__isl_keep isl_union_map *UMap) {
867   dumpExpanded(isl::manage(isl_union_map_copy(UMap)));
868 }
869 #endif
870