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