1 //===------ ISLTools.cpp ----------------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Tools, utilities, helpers and extensions useful in conjunction with the
10 // Integer Set Library (isl).
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "polly/Support/ISLTools.h"
15 #include "llvm/Support/raw_ostream.h"
16 #include <cassert>
17 #include <vector>
18 
19 using namespace polly;
20 
21 namespace {
22 /// Create a map that shifts one dimension by an offset.
23 ///
24 /// Example:
25 /// makeShiftDimAff({ [i0, i1] -> [o0, o1] }, 1, -2)
26 ///   = { [i0, i1] -> [i0, i1 - 1] }
27 ///
28 /// @param Space  The map space of the result. Must have equal number of in- and
29 ///               out-dimensions.
30 /// @param Pos    Position to shift.
31 /// @param Amount Value added to the shifted dimension.
32 ///
33 /// @return An isl_multi_aff for the map with this shifted dimension.
makeShiftDimAff(isl::space Space,int Pos,int Amount)34 isl::multi_aff makeShiftDimAff(isl::space Space, int Pos, int Amount) {
35   auto Identity = isl::multi_aff::identity(Space);
36   if (Amount == 0)
37     return Identity;
38   auto ShiftAff = Identity.get_aff(Pos);
39   ShiftAff = ShiftAff.set_constant_si(Amount);
40   return Identity.set_aff(Pos, ShiftAff);
41 }
42 
43 /// Construct a map that swaps two nested tuples.
44 ///
45 /// @param FromSpace1 { Space1[] }
46 /// @param FromSpace2 { Space2[] }
47 ///
48 /// @return { [Space1[] -> Space2[]] -> [Space2[] -> Space1[]] }
makeTupleSwapBasicMap(isl::space FromSpace1,isl::space FromSpace2)49 isl::basic_map makeTupleSwapBasicMap(isl::space FromSpace1,
50                                      isl::space FromSpace2) {
51   // Fast-path on out-of-quota.
52   if (!FromSpace1 || !FromSpace2)
53     return {};
54 
55   assert(FromSpace1.is_set());
56   assert(FromSpace2.is_set());
57 
58   unsigned Dims1 = FromSpace1.dim(isl::dim::set);
59   unsigned Dims2 = FromSpace2.dim(isl::dim::set);
60 
61   isl::space FromSpace =
62       FromSpace1.map_from_domain_and_range(FromSpace2).wrap();
63   isl::space ToSpace = FromSpace2.map_from_domain_and_range(FromSpace1).wrap();
64   isl::space MapSpace = FromSpace.map_from_domain_and_range(ToSpace);
65 
66   isl::basic_map Result = isl::basic_map::universe(MapSpace);
67   for (unsigned i = 0u; i < Dims1; i += 1)
68     Result = Result.equate(isl::dim::in, i, isl::dim::out, Dims2 + i);
69   for (unsigned i = 0u; i < Dims2; i += 1) {
70     Result = Result.equate(isl::dim::in, Dims1 + i, isl::dim::out, i);
71   }
72 
73   return Result;
74 }
75 
76 /// Like makeTupleSwapBasicMap(isl::space,isl::space), but returns
77 /// an isl_map.
makeTupleSwapMap(isl::space FromSpace1,isl::space FromSpace2)78 isl::map makeTupleSwapMap(isl::space FromSpace1, isl::space FromSpace2) {
79   isl::basic_map BMapResult = makeTupleSwapBasicMap(FromSpace1, FromSpace2);
80   return isl::map(BMapResult);
81 }
82 } // anonymous namespace
83 
beforeScatter(isl::map Map,bool Strict)84 isl::map polly::beforeScatter(isl::map Map, bool Strict) {
85   isl::space RangeSpace = Map.get_space().range();
86   isl::map ScatterRel =
87       Strict ? isl::map::lex_gt(RangeSpace) : isl::map::lex_ge(RangeSpace);
88   return Map.apply_range(ScatterRel);
89 }
90 
beforeScatter(isl::union_map UMap,bool Strict)91 isl::union_map polly::beforeScatter(isl::union_map UMap, bool Strict) {
92   isl::union_map Result = isl::union_map::empty(UMap.get_space());
93 
94   for (isl::map Map : UMap.get_map_list()) {
95     isl::map After = beforeScatter(Map, Strict);
96     Result = Result.add_map(After);
97   }
98 
99   return Result;
100 }
101 
afterScatter(isl::map Map,bool Strict)102 isl::map polly::afterScatter(isl::map Map, bool Strict) {
103   isl::space RangeSpace = Map.get_space().range();
104   isl::map ScatterRel =
105       Strict ? isl::map::lex_lt(RangeSpace) : isl::map::lex_le(RangeSpace);
106   return Map.apply_range(ScatterRel);
107 }
108 
afterScatter(const isl::union_map & UMap,bool Strict)109 isl::union_map polly::afterScatter(const isl::union_map &UMap, bool Strict) {
110   isl::union_map Result = isl::union_map::empty(UMap.get_space());
111   for (isl::map Map : UMap.get_map_list()) {
112     isl::map After = afterScatter(Map, Strict);
113     Result = Result.add_map(After);
114   }
115   return Result;
116 }
117 
betweenScatter(isl::map From,isl::map To,bool InclFrom,bool InclTo)118 isl::map polly::betweenScatter(isl::map From, isl::map To, bool InclFrom,
119                                bool InclTo) {
120   isl::map AfterFrom = afterScatter(From, !InclFrom);
121   isl::map BeforeTo = beforeScatter(To, !InclTo);
122 
123   return AfterFrom.intersect(BeforeTo);
124 }
125 
betweenScatter(isl::union_map From,isl::union_map To,bool InclFrom,bool InclTo)126 isl::union_map polly::betweenScatter(isl::union_map From, isl::union_map To,
127                                      bool InclFrom, bool InclTo) {
128   isl::union_map AfterFrom = afterScatter(From, !InclFrom);
129   isl::union_map BeforeTo = beforeScatter(To, !InclTo);
130 
131   return AfterFrom.intersect(BeforeTo);
132 }
133 
singleton(isl::union_map UMap,isl::space ExpectedSpace)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.get()) == 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 
singleton(isl::union_set USet,isl::space ExpectedSpace)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.get()) == 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 
getNumScatterDims(const isl::union_map & Schedule)160 unsigned polly::getNumScatterDims(const isl::union_map &Schedule) {
161   unsigned Dims = 0;
162   for (isl::map Map : Schedule.get_map_list()) {
163     // Map.dim would return UINT_MAX.
164     if (!Map)
165       continue;
166 
167     Dims = std::max(Dims, Map.dim(isl::dim::out));
168   }
169   return Dims;
170 }
171 
getScatterSpace(const isl::union_map & Schedule)172 isl::space polly::getScatterSpace(const isl::union_map &Schedule) {
173   if (!Schedule)
174     return nullptr;
175   unsigned Dims = getNumScatterDims(Schedule);
176   isl::space ScatterSpace = Schedule.get_space().set_from_params();
177   return ScatterSpace.add_dims(isl::dim::set, Dims);
178 }
179 
makeIdentityMap(const isl::union_set & USet,bool RestrictDomain)180 isl::union_map polly::makeIdentityMap(const isl::union_set &USet,
181                                       bool RestrictDomain) {
182   isl::union_map Result = isl::union_map::empty(USet.get_space());
183   for (isl::set Set : USet.get_set_list()) {
184     isl::map IdentityMap = isl::map::identity(Set.get_space().map_from_set());
185     if (RestrictDomain)
186       IdentityMap = IdentityMap.intersect_domain(Set);
187     Result = Result.add_map(IdentityMap);
188   }
189   return Result;
190 }
191 
reverseDomain(isl::map Map)192 isl::map polly::reverseDomain(isl::map Map) {
193   isl::space DomSpace = Map.get_space().domain().unwrap();
194   isl::space Space1 = DomSpace.domain();
195   isl::space Space2 = DomSpace.range();
196   isl::map Swap = makeTupleSwapMap(Space1, Space2);
197   return Map.apply_domain(Swap);
198 }
199 
reverseDomain(const isl::union_map & UMap)200 isl::union_map polly::reverseDomain(const isl::union_map &UMap) {
201   isl::union_map Result = isl::union_map::empty(UMap.get_space());
202   for (isl::map Map : UMap.get_map_list()) {
203     auto Reversed = reverseDomain(std::move(Map));
204     Result = Result.add_map(Reversed);
205   }
206   return Result;
207 }
208 
shiftDim(isl::set Set,int Pos,int Amount)209 isl::set polly::shiftDim(isl::set Set, int Pos, int Amount) {
210   int NumDims = Set.dim(isl::dim::set);
211   if (Pos < 0)
212     Pos = NumDims + Pos;
213   assert(Pos < NumDims && "Dimension index must be in range");
214   isl::space Space = Set.get_space();
215   Space = Space.map_from_domain_and_range(Space);
216   isl::multi_aff Translator = makeShiftDimAff(Space, Pos, Amount);
217   isl::map TranslatorMap = isl::map::from_multi_aff(Translator);
218   return Set.apply(TranslatorMap);
219 }
220 
shiftDim(isl::union_set USet,int Pos,int Amount)221 isl::union_set polly::shiftDim(isl::union_set USet, int Pos, int Amount) {
222   isl::union_set Result = isl::union_set::empty(USet.get_space());
223   for (isl::set Set : USet.get_set_list()) {
224     isl::set Shifted = shiftDim(Set, Pos, Amount);
225     Result = Result.add_set(Shifted);
226   }
227   return Result;
228 }
229 
shiftDim(isl::map Map,isl::dim Dim,int Pos,int Amount)230 isl::map polly::shiftDim(isl::map Map, isl::dim Dim, int Pos, int Amount) {
231   int NumDims = Map.dim(Dim);
232   if (Pos < 0)
233     Pos = NumDims + Pos;
234   assert(Pos < NumDims && "Dimension index must be in range");
235   isl::space Space = Map.get_space();
236   switch (Dim) {
237   case isl::dim::in:
238     Space = Space.domain();
239     break;
240   case isl::dim::out:
241     Space = Space.range();
242     break;
243   default:
244     llvm_unreachable("Unsupported value for 'dim'");
245   }
246   Space = Space.map_from_domain_and_range(Space);
247   isl::multi_aff Translator = makeShiftDimAff(Space, Pos, Amount);
248   isl::map TranslatorMap = isl::map::from_multi_aff(Translator);
249   switch (Dim) {
250   case isl::dim::in:
251     return Map.apply_domain(TranslatorMap);
252   case isl::dim::out:
253     return Map.apply_range(TranslatorMap);
254   default:
255     llvm_unreachable("Unsupported value for 'dim'");
256   }
257 }
258 
shiftDim(isl::union_map UMap,isl::dim Dim,int Pos,int Amount)259 isl::union_map polly::shiftDim(isl::union_map UMap, isl::dim Dim, int Pos,
260                                int Amount) {
261   isl::union_map Result = isl::union_map::empty(UMap.get_space());
262 
263   for (isl::map Map : UMap.get_map_list()) {
264     isl::map Shifted = shiftDim(Map, Dim, Pos, Amount);
265     Result = Result.add_map(Shifted);
266   }
267   return Result;
268 }
269 
simplify(isl::set & Set)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 
simplify(isl::union_set & USet)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 
simplify(isl::map & Map)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 
simplify(isl::union_map & UMap)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 
computeReachingWrite(isl::union_map Schedule,isl::union_map Writes,bool Reverse,bool InclPrevDef,bool InclNextDef)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
computeArrayUnused(isl::union_map Schedule,isl::union_map Writes,isl::union_map Reads,bool ReadEltInSameInst,bool IncludeLastRead,bool IncludeWrite)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 
convertZoneToTimepoints(isl::union_set Zone,bool InclStart,bool InclEnd)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 
convertZoneToTimepoints(isl::union_map Zone,isl::dim Dim,bool InclStart,bool InclEnd)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 
convertZoneToTimepoints(isl::map Zone,isl::dim Dim,bool InclStart,bool InclEnd)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 
distributeDomain(isl::map Map)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   if (!DomainSpace)
444     return {};
445   unsigned DomainDims = DomainSpace.dim(isl::dim::set);
446   isl::space RangeSpace = Space.range().unwrap();
447   isl::space Range1Space = RangeSpace.domain();
448   if (!Range1Space)
449     return {};
450   unsigned Range1Dims = Range1Space.dim(isl::dim::set);
451   isl::space Range2Space = RangeSpace.range();
452   if (!Range2Space)
453     return {};
454   unsigned Range2Dims = Range2Space.dim(isl::dim::set);
455 
456   isl::space OutputSpace =
457       DomainSpace.map_from_domain_and_range(Range1Space)
458           .wrap()
459           .map_from_domain_and_range(
460               DomainSpace.map_from_domain_and_range(Range2Space).wrap());
461 
462   isl::basic_map Translator = isl::basic_map::universe(
463       Space.wrap().map_from_domain_and_range(OutputSpace.wrap()));
464 
465   for (unsigned i = 0; i < DomainDims; i += 1) {
466     Translator = Translator.equate(isl::dim::in, i, isl::dim::out, i);
467     Translator = Translator.equate(isl::dim::in, i, isl::dim::out,
468                                    DomainDims + Range1Dims + i);
469   }
470   for (unsigned i = 0; i < Range1Dims; i += 1)
471     Translator = Translator.equate(isl::dim::in, DomainDims + i, isl::dim::out,
472                                    DomainDims + i);
473   for (unsigned i = 0; i < Range2Dims; i += 1)
474     Translator = Translator.equate(isl::dim::in, DomainDims + Range1Dims + i,
475                                    isl::dim::out,
476                                    DomainDims + Range1Dims + DomainDims + i);
477 
478   return Map.wrap().apply(Translator).unwrap();
479 }
480 
distributeDomain(isl::union_map UMap)481 isl::union_map polly::distributeDomain(isl::union_map UMap) {
482   isl::union_map Result = isl::union_map::empty(UMap.get_space());
483   for (isl::map Map : UMap.get_map_list()) {
484     auto Distributed = distributeDomain(Map);
485     Result = Result.add_map(Distributed);
486   }
487   return Result;
488 }
489 
liftDomains(isl::union_map UMap,isl::union_set Factor)490 isl::union_map polly::liftDomains(isl::union_map UMap, isl::union_set Factor) {
491 
492   // { Factor[] -> Factor[] }
493   isl::union_map Factors = makeIdentityMap(Factor, true);
494 
495   return Factors.product(UMap);
496 }
497 
applyDomainRange(isl::union_map UMap,isl::union_map Func)498 isl::union_map polly::applyDomainRange(isl::union_map UMap,
499                                        isl::union_map Func) {
500   // This implementation creates unnecessary cross products of the
501   // DomainDomain[] and Func. An alternative implementation could reverse
502   // domain+uncurry,apply Func to what now is the domain, then undo the
503   // preparing transformation. Another alternative implementation could create a
504   // translator map for each piece.
505 
506   // { DomainDomain[] }
507   isl::union_set DomainDomain = UMap.domain().unwrap().domain();
508 
509   // { [DomainDomain[] -> DomainRange[]] -> [DomainDomain[] -> NewDomainRange[]]
510   // }
511   isl::union_map LifetedFunc = liftDomains(std::move(Func), DomainDomain);
512 
513   return UMap.apply_domain(LifetedFunc);
514 }
515 
intersectRange(isl::map Map,isl::union_set Range)516 isl::map polly::intersectRange(isl::map Map, isl::union_set Range) {
517   isl::set RangeSet = Range.extract_set(Map.get_space().range());
518   return Map.intersect_range(RangeSet);
519 }
520 
subtractParams(isl::map Map,isl::set Params)521 isl::map polly::subtractParams(isl::map Map, isl::set Params) {
522   auto MapSpace = Map.get_space();
523   auto ParamsMap = isl::map::universe(MapSpace).intersect_params(Params);
524   return Map.subtract(ParamsMap);
525 }
526 
getConstant(isl::pw_aff PwAff,bool Max,bool Min)527 isl::val polly::getConstant(isl::pw_aff PwAff, bool Max, bool Min) {
528   assert(!Max || !Min); // Cannot return min and max at the same time.
529   isl::val Result;
530   isl::stat Stat = PwAff.foreach_piece(
531       [=, &Result](isl::set Set, isl::aff Aff) -> isl::stat {
532         if (Result && Result.is_nan())
533           return isl::stat::ok();
534 
535         // TODO: If Min/Max, we can also determine a minimum/maximum value if
536         // Set is constant-bounded.
537         if (!Aff.is_cst()) {
538           Result = isl::val::nan(Aff.get_ctx());
539           return isl::stat::error();
540         }
541 
542         isl::val ThisVal = Aff.get_constant_val();
543         if (!Result) {
544           Result = ThisVal;
545           return isl::stat::ok();
546         }
547 
548         if (Result.eq(ThisVal))
549           return isl::stat::ok();
550 
551         if (Max && ThisVal.gt(Result)) {
552           Result = ThisVal;
553           return isl::stat::ok();
554         }
555 
556         if (Min && ThisVal.lt(Result)) {
557           Result = ThisVal;
558           return isl::stat::ok();
559         }
560 
561         // Not compatible
562         Result = isl::val::nan(Aff.get_ctx());
563         return isl::stat::error();
564       });
565 
566   if (Stat.is_error())
567     return {};
568 
569   return Result;
570 }
571 
572 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
foreachPoint(const isl::set & Set,const std::function<void (isl::point P)> & F)573 static void foreachPoint(const isl::set &Set,
574                          const std::function<void(isl::point P)> &F) {
575   Set.foreach_point([&](isl::point P) -> isl::stat {
576     F(P);
577     return isl::stat::ok();
578   });
579 }
580 
foreachPoint(isl::basic_set BSet,const std::function<void (isl::point P)> & F)581 static void foreachPoint(isl::basic_set BSet,
582                          const std::function<void(isl::point P)> &F) {
583   foreachPoint(isl::set(BSet), F);
584 }
585 
586 /// Determine the sorting order of the sets @p A and @p B without considering
587 /// the space structure.
588 ///
589 /// Ordering is based on the lower bounds of the set's dimensions. First
590 /// dimensions are considered first.
flatCompare(const isl::basic_set & A,const isl::basic_set & B)591 static int flatCompare(const isl::basic_set &A, const isl::basic_set &B) {
592   // Quick bail-out on out-of-quota.
593   if (!A || !B)
594     return 0;
595 
596   unsigned ALen = A.dim(isl::dim::set);
597   unsigned BLen = B.dim(isl::dim::set);
598   unsigned Len = std::min(ALen, BLen);
599 
600   for (unsigned i = 0; i < Len; i += 1) {
601     isl::basic_set ADim =
602         A.project_out(isl::dim::param, 0, A.dim(isl::dim::param))
603             .project_out(isl::dim::set, i + 1, ALen - i - 1)
604             .project_out(isl::dim::set, 0, i);
605     isl::basic_set BDim =
606         B.project_out(isl::dim::param, 0, B.dim(isl::dim::param))
607             .project_out(isl::dim::set, i + 1, BLen - i - 1)
608             .project_out(isl::dim::set, 0, i);
609 
610     isl::basic_set AHull = isl::set(ADim).convex_hull();
611     isl::basic_set BHull = isl::set(BDim).convex_hull();
612 
613     bool ALowerBounded =
614         bool(isl::set(AHull).dim_has_any_lower_bound(isl::dim::set, 0));
615     bool BLowerBounded =
616         bool(isl::set(BHull).dim_has_any_lower_bound(isl::dim::set, 0));
617 
618     int BoundedCompare = BLowerBounded - ALowerBounded;
619     if (BoundedCompare != 0)
620       return BoundedCompare;
621 
622     if (!ALowerBounded || !BLowerBounded)
623       continue;
624 
625     isl::pw_aff AMin = isl::set(ADim).dim_min(0);
626     isl::pw_aff BMin = isl::set(BDim).dim_min(0);
627 
628     isl::val AMinVal = polly::getConstant(AMin, false, true);
629     isl::val BMinVal = polly::getConstant(BMin, false, true);
630 
631     int MinCompare = AMinVal.sub(BMinVal).sgn();
632     if (MinCompare != 0)
633       return MinCompare;
634   }
635 
636   // If all the dimensions' lower bounds are equal or incomparable, sort based
637   // on the number of dimensions.
638   return ALen - BLen;
639 }
640 
641 /// Compare the sets @p A and @p B according to their nested space structure.
642 /// Returns 0 if the structure is considered equal.
643 /// If @p ConsiderTupleLen is false, the number of dimensions in a tuple are
644 /// ignored, i.e. a tuple with the same name but different number of dimensions
645 /// are considered equal.
structureCompare(const isl::space & ASpace,const isl::space & BSpace,bool ConsiderTupleLen)646 static int structureCompare(const isl::space &ASpace, const isl::space &BSpace,
647                             bool ConsiderTupleLen) {
648   int WrappingCompare = bool(ASpace.is_wrapping()) - bool(BSpace.is_wrapping());
649   if (WrappingCompare != 0)
650     return WrappingCompare;
651 
652   if (ASpace.is_wrapping() && BSpace.is_wrapping()) {
653     isl::space AMap = ASpace.unwrap();
654     isl::space BMap = BSpace.unwrap();
655 
656     int FirstResult =
657         structureCompare(AMap.domain(), BMap.domain(), ConsiderTupleLen);
658     if (FirstResult != 0)
659       return FirstResult;
660 
661     return structureCompare(AMap.range(), BMap.range(), ConsiderTupleLen);
662   }
663 
664   std::string AName;
665   if (ASpace.has_tuple_name(isl::dim::set))
666     AName = ASpace.get_tuple_name(isl::dim::set);
667 
668   std::string BName;
669   if (BSpace.has_tuple_name(isl::dim::set))
670     BName = BSpace.get_tuple_name(isl::dim::set);
671 
672   int NameCompare = AName.compare(BName);
673   if (NameCompare != 0)
674     return NameCompare;
675 
676   if (ConsiderTupleLen) {
677     int LenCompare = BSpace.dim(isl::dim::set) - ASpace.dim(isl::dim::set);
678     if (LenCompare != 0)
679       return LenCompare;
680   }
681 
682   return 0;
683 }
684 
685 /// Compare the sets @p A and @p B according to their nested space structure. If
686 /// the structure is the same, sort using the dimension lower bounds.
687 /// Returns an std::sort compatible bool.
orderComparer(const isl::basic_set & A,const isl::basic_set & B)688 static bool orderComparer(const isl::basic_set &A, const isl::basic_set &B) {
689   isl::space ASpace = A.get_space();
690   isl::space BSpace = B.get_space();
691 
692   // Ignoring number of dimensions first ensures that structures with same tuple
693   // names, but different number of dimensions are still sorted close together.
694   int TupleNestingCompare = structureCompare(ASpace, BSpace, false);
695   if (TupleNestingCompare != 0)
696     return TupleNestingCompare < 0;
697 
698   int TupleCompare = structureCompare(ASpace, BSpace, true);
699   if (TupleCompare != 0)
700     return TupleCompare < 0;
701 
702   return flatCompare(A, B) < 0;
703 }
704 
705 /// Print a string representation of @p USet to @p OS.
706 ///
707 /// The pieces of @p USet are printed in a sorted order. Spaces with equal or
708 /// similar nesting structure are printed together. Compared to isl's own
709 /// printing function the uses the structure itself as base of the sorting, not
710 /// a hash of it. It ensures that e.g. maps spaces with same domain structure
711 /// are printed together. Set pieces with same structure are printed in order of
712 /// their lower bounds.
713 ///
714 /// @param USet     Polyhedra to print.
715 /// @param OS       Target stream.
716 /// @param Simplify Whether to simplify the polyhedron before printing.
717 /// @param IsMap    Whether @p USet is a wrapped map. If true, sets are
718 ///                 unwrapped before printing to again appear as a map.
printSortedPolyhedra(isl::union_set USet,llvm::raw_ostream & OS,bool Simplify,bool IsMap)719 static void printSortedPolyhedra(isl::union_set USet, llvm::raw_ostream &OS,
720                                  bool Simplify, bool IsMap) {
721   if (!USet) {
722     OS << "<null>\n";
723     return;
724   }
725 
726   if (Simplify)
727     simplify(USet);
728 
729   // Get all the polyhedra.
730   std::vector<isl::basic_set> BSets;
731 
732   for (isl::set Set : USet.get_set_list()) {
733     for (isl::basic_set BSet : Set.get_basic_set_list()) {
734       BSets.push_back(BSet);
735     }
736   }
737 
738   if (BSets.empty()) {
739     OS << "{\n}\n";
740     return;
741   }
742 
743   // Sort the polyhedra.
744   llvm::sort(BSets, orderComparer);
745 
746   // Print the polyhedra.
747   bool First = true;
748   for (const isl::basic_set &BSet : BSets) {
749     std::string Str;
750     if (IsMap)
751       Str = isl::map(BSet.unwrap()).to_str();
752     else
753       Str = isl::set(BSet).to_str();
754     size_t OpenPos = Str.find_first_of('{');
755     assert(OpenPos != std::string::npos);
756     size_t ClosePos = Str.find_last_of('}');
757     assert(ClosePos != std::string::npos);
758 
759     if (First)
760       OS << llvm::StringRef(Str).substr(0, OpenPos + 1) << "\n ";
761     else
762       OS << ";\n ";
763 
764     OS << llvm::StringRef(Str).substr(OpenPos + 1, ClosePos - OpenPos - 2);
765     First = false;
766   }
767   assert(!First);
768   OS << "\n}\n";
769 }
770 
recursiveExpand(isl::basic_set BSet,int Dim,isl::set & Expanded)771 static void recursiveExpand(isl::basic_set BSet, int Dim, isl::set &Expanded) {
772   int Dims = BSet.dim(isl::dim::set);
773   if (Dim >= Dims) {
774     Expanded = Expanded.unite(BSet);
775     return;
776   }
777 
778   isl::basic_set DimOnly =
779       BSet.project_out(isl::dim::param, 0, BSet.dim(isl::dim::param))
780           .project_out(isl::dim::set, Dim + 1, Dims - Dim - 1)
781           .project_out(isl::dim::set, 0, Dim);
782   if (!DimOnly.is_bounded()) {
783     recursiveExpand(BSet, Dim + 1, Expanded);
784     return;
785   }
786 
787   foreachPoint(DimOnly, [&, Dim](isl::point P) {
788     isl::val Val = P.get_coordinate_val(isl::dim::set, 0);
789     isl::basic_set FixBSet = BSet.fix_val(isl::dim::set, Dim, Val);
790     recursiveExpand(FixBSet, Dim + 1, Expanded);
791   });
792 }
793 
794 /// Make each point of a set explicit.
795 ///
796 /// "Expanding" makes each point a set contains explicit. That is, the result is
797 /// a set of singleton polyhedra. Unbounded dimensions are not expanded.
798 ///
799 /// Example:
800 ///   { [i] : 0 <= i < 2 }
801 /// is expanded to:
802 ///   { [0]; [1] }
expand(const isl::set & Set)803 static isl::set expand(const isl::set &Set) {
804   isl::set Expanded = isl::set::empty(Set.get_space());
805   for (isl::basic_set BSet : Set.get_basic_set_list())
806     recursiveExpand(BSet, 0, Expanded);
807   return Expanded;
808 }
809 
810 /// Expand all points of a union set explicit.
811 ///
812 /// @see expand(const isl::set)
expand(const isl::union_set & USet)813 static isl::union_set expand(const isl::union_set &USet) {
814   isl::union_set Expanded = isl::union_set::empty(USet.get_space());
815   for (isl::set Set : USet.get_set_list()) {
816     isl::set SetExpanded = expand(Set);
817     Expanded = Expanded.add_set(SetExpanded);
818   }
819   return Expanded;
820 }
821 
dumpPw(const isl::set & Set)822 LLVM_DUMP_METHOD void polly::dumpPw(const isl::set &Set) {
823   printSortedPolyhedra(Set, llvm::errs(), true, false);
824 }
825 
dumpPw(const isl::map & Map)826 LLVM_DUMP_METHOD void polly::dumpPw(const isl::map &Map) {
827   printSortedPolyhedra(Map.wrap(), llvm::errs(), true, true);
828 }
829 
dumpPw(const isl::union_set & USet)830 LLVM_DUMP_METHOD void polly::dumpPw(const isl::union_set &USet) {
831   printSortedPolyhedra(USet, llvm::errs(), true, false);
832 }
833 
dumpPw(const isl::union_map & UMap)834 LLVM_DUMP_METHOD void polly::dumpPw(const isl::union_map &UMap) {
835   printSortedPolyhedra(UMap.wrap(), llvm::errs(), true, true);
836 }
837 
dumpPw(__isl_keep isl_set * Set)838 LLVM_DUMP_METHOD void polly::dumpPw(__isl_keep isl_set *Set) {
839   dumpPw(isl::manage_copy(Set));
840 }
841 
dumpPw(__isl_keep isl_map * Map)842 LLVM_DUMP_METHOD void polly::dumpPw(__isl_keep isl_map *Map) {
843   dumpPw(isl::manage_copy(Map));
844 }
845 
dumpPw(__isl_keep isl_union_set * USet)846 LLVM_DUMP_METHOD void polly::dumpPw(__isl_keep isl_union_set *USet) {
847   dumpPw(isl::manage_copy(USet));
848 }
849 
dumpPw(__isl_keep isl_union_map * UMap)850 LLVM_DUMP_METHOD void polly::dumpPw(__isl_keep isl_union_map *UMap) {
851   dumpPw(isl::manage_copy(UMap));
852 }
853 
dumpExpanded(const isl::set & Set)854 LLVM_DUMP_METHOD void polly::dumpExpanded(const isl::set &Set) {
855   printSortedPolyhedra(expand(Set), llvm::errs(), false, false);
856 }
857 
dumpExpanded(const isl::map & Map)858 LLVM_DUMP_METHOD void polly::dumpExpanded(const isl::map &Map) {
859   printSortedPolyhedra(expand(Map.wrap()), llvm::errs(), false, true);
860 }
861 
dumpExpanded(const isl::union_set & USet)862 LLVM_DUMP_METHOD void polly::dumpExpanded(const isl::union_set &USet) {
863   printSortedPolyhedra(expand(USet), llvm::errs(), false, false);
864 }
865 
dumpExpanded(const isl::union_map & UMap)866 LLVM_DUMP_METHOD void polly::dumpExpanded(const isl::union_map &UMap) {
867   printSortedPolyhedra(expand(UMap.wrap()), llvm::errs(), false, true);
868 }
869 
dumpExpanded(__isl_keep isl_set * Set)870 LLVM_DUMP_METHOD void polly::dumpExpanded(__isl_keep isl_set *Set) {
871   dumpExpanded(isl::manage_copy(Set));
872 }
873 
dumpExpanded(__isl_keep isl_map * Map)874 LLVM_DUMP_METHOD void polly::dumpExpanded(__isl_keep isl_map *Map) {
875   dumpExpanded(isl::manage_copy(Map));
876 }
877 
dumpExpanded(__isl_keep isl_union_set * USet)878 LLVM_DUMP_METHOD void polly::dumpExpanded(__isl_keep isl_union_set *USet) {
879   dumpExpanded(isl::manage_copy(USet));
880 }
881 
dumpExpanded(__isl_keep isl_union_map * UMap)882 LLVM_DUMP_METHOD void polly::dumpExpanded(__isl_keep isl_union_map *UMap) {
883   dumpExpanded(isl::manage_copy(UMap));
884 }
885 #endif
886