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